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{/$}) {
33 $url_path .= 'index.html';
36 print STDERR "Method: ", $req->method, "\n";
37 print STDERR "Path: ", $url_path, "\n";
38 print STDERR "Available URLs: ", "\n";
39 foreach my $key (keys %$urls) {
40 print STDERR $key, "\n";
43 if (exists($urls->{$url_path})) {
44 print STDERR "Serving requested URL: ", $url_path, "\n" if $log;
45 next unless ($req->method eq "HEAD" || $req->method eq "GET");
48 my $tmp = $urls->{$url_path};
49 my $resp = HTTP::Response->new ($tmp->{code}, $tmp->{msg});
50 print STDERR "HTTP::Response: \n", $resp->as_string if $log;
52 #if (is_dynamic_url) { # dynamic resource
53 #} else { # static resource
55 while (my ($name, $value) = each %{$tmp->{headers}}) {
56 # print STDERR "setting header: $name = $value\n";
57 $resp->header($name => $value);
59 print STDERR "HTTP::Response with headers: \n", $resp->as_string if $log;
61 if ($req->method eq "GET") {
62 if (exists($tmp->{headers}{"Content-Length"})) {
63 # Content-Length and length($tmp->{content}) don't match
64 # manually prepare the HTTP response
65 $con->send_basic_header($tmp->{code}, $resp->message, $resp->protocol);
66 print $con $resp->headers_as_string($CRLF);
68 print $con $tmp->{content};
71 if ($req->header("Range")) {
72 $req->header("Range") =~ m/bytes=(\d*)-(\d*)/;
73 my $content_len = length($tmp->{content});
74 my $start = $1 ? $1 : 0;
75 my $end = $2 ? $2 : ($content_len - 1);
76 my $len = $2 ? ($2 - $start) : ($content_len - $start);
77 $resp->header("Accept-Ranges" => "bytes");
78 $resp->header("Content-Length" => $len);
79 $resp->header("Content-Range" => "bytes $start-$end/$content_len");
80 $resp->header("Keep-Alive" => "timeout=15, max=100");
81 $resp->header("Connection" => "Keep-Alive");
82 $con->send_basic_header(206, "Partial Content", $resp->protocol);
83 print $con $resp->headers_as_string($CRLF);
85 print $con substr($tmp->{content}, $start, $len);
89 $resp->content($tmp->{content});
90 print STDERR "HTTP::Response with content: \n", $resp->as_string if $log;
94 $con->send_response($resp);
95 print STDERR "HTTP::Response sent: \n", $resp->as_string if $log;
97 print STDERR "Requested wrong URL: ", $url_path, "\n" if $log;
98 $con->send_error($HTTP::Status::RC_FORBIDDEN);
102 print STDERR "Closing connection\n" if $log;