12 our @ISA=qw(HTTP::Daemon);
15 my $CRLF = "\015\012"; # "\r\n" is not portable
19 my ($self, $urls, $synch_callback) = @_;
28 my $con = $self->accept();
29 print STDERR "Accepted a new connection\n" if $log;
30 while (my $req = $con->get_request) {
31 my $url_path = $req->url->path;
32 if ($url_path =~ m{/$}) { # append 'index.html'
33 $url_path .= 'index.html';
35 if ($url_path =~ m{^/}) { # remove trailing '/'
36 $url_path = substr ($url_path, 1);
39 print STDERR "Method: ", $req->method, "\n";
40 print STDERR "Path: ", $url_path, "\n";
41 print STDERR "Available URLs: ", "\n";
42 foreach my $key (keys %$urls) {
43 print STDERR $key, "\n";
46 if (exists($urls->{$url_path})) {
47 print STDERR "Serving requested URL: ", $url_path, "\n" if $log;
48 next unless ($req->method eq "HEAD" || $req->method eq "GET");
51 my $tmp = $urls->{$url_path};
52 my $resp = HTTP::Response->new ($tmp->{code}, $tmp->{msg});
53 print STDERR "HTTP::Response: \n", $resp->as_string if $log;
55 #if (is_dynamic_url) { # dynamic resource
56 #} else { # static resource
58 while (my ($name, $value) = each %{$tmp->{headers}}) {
59 # print STDERR "setting header: $name = $value\n";
60 $resp->header($name => $value);
62 print STDERR "HTTP::Response with headers: \n", $resp->as_string if $log;
64 if ($req->method eq "GET") {
65 if (exists($tmp->{headers}{"Content-Length"})) {
66 # Content-Length and length($tmp->{content}) don't match
67 # manually prepare the HTTP response
68 $con->send_basic_header($tmp->{code}, $resp->message, $resp->protocol);
69 print $con $resp->headers_as_string($CRLF);
71 print $con $tmp->{content};
74 if ($req->header("Range")) {
75 $req->header("Range") =~ m/bytes=(\d*)-(\d*)/;
76 my $content_len = length($tmp->{content});
77 my $start = $1 ? $1 : 0;
78 my $end = $2 ? $2 : ($content_len - 1);
79 my $len = $2 ? ($2 - $start) : ($content_len - $start);
80 $resp->header("Accept-Ranges" => "bytes");
81 $resp->header("Content-Length" => $len);
82 $resp->header("Content-Range" => "bytes $start-$end/$content_len");
83 $resp->header("Keep-Alive" => "timeout=15, max=100");
84 $resp->header("Connection" => "Keep-Alive");
85 $con->send_basic_header(206, "Partial Content", $resp->protocol);
86 print $con $resp->headers_as_string($CRLF);
88 print $con substr($tmp->{content}, $start, $len);
92 $resp->content($tmp->{content});
93 print STDERR "HTTP::Response with content: \n", $resp->as_string if $log;
97 $con->send_response($resp);
98 print STDERR "HTTP::Response sent: \n", $resp->as_string if $log;
100 print STDERR "Requested wrong URL: ", $url_path, "\n" if $log;
101 $con->send_error($HTTP::Status::RC_FORBIDDEN);
105 print STDERR "Closing connection\n" if $log;