]> sjero.net Git - wget/blob - tests/HTTPServer.pm
Automated merge.
[wget] / tests / HTTPServer.pm
1 #!/usr/bin/perl -w
2
3 package HTTPServer;
4
5 use strict;
6
7 use HTTP::Daemon;
8 use HTTP::Status;
9 use HTTP::Headers;
10 use HTTP::Response;
11
12 our @ISA=qw(HTTP::Daemon);
13 my $VERSION = 0.01;
14
15 my $CRLF = "\015\012"; # "\r\n" is not portable
16 my $log = undef;
17
18 sub run {
19     my ($self, $urls, $synch_callback) = @_;
20     my $initialized = 0;
21
22     while (1) {
23         if (!$initialized) {
24             $synch_callback->();
25             $initialized = 1;
26         }        
27         my $con = $self->accept();
28         print STDERR "Accepted a new connection\n" if $log;
29         while (my $req = $con->get_request) {
30             my $url_path = $req->url->path;
31             if ($url_path =~ m{/$}) { # append 'index.html'
32                 $url_path .= 'index.html';
33             }
34             #if ($url_path =~ m{^/}) { # remove trailing '/'
35             #    $url_path = substr ($url_path, 1);
36             #}
37             if ($log) {
38                 print STDERR "Method: ", $req->method, "\n";
39                 print STDERR "Path: ", $url_path, "\n";
40                 print STDERR "Available URLs: ", "\n";
41                 foreach my $key (keys %$urls) {
42                     print STDERR $key, "\n";
43                 }
44             }
45             if (exists($urls->{$url_path})) {
46                 print STDERR "Serving requested URL: ", $url_path, "\n" if $log;
47                 next unless ($req->method eq "HEAD" || $req->method eq "GET");
48                 
49                 my $url_rec = $urls->{$url_path};
50                 $self->send_response($req, $url_rec, $con);
51             } else {
52                 print STDERR "Requested wrong URL: ", $url_path, "\n" if $log;
53                 $con->send_error($HTTP::Status::RC_FORBIDDEN);
54                 last;
55             }            
56         }
57         print STDERR "Closing connection\n" if $log;
58         $con->close;
59     }
60 }
61
62 sub send_response {
63     my ($self, $req, $url_rec, $con) = @_;
64
65     # create response
66     my ($code, $msg, $headers);
67     my $send_content = ($req->method eq "GET");
68     if (exists $url_rec->{'auth_method'}) {
69         ($send_content, $code, $msg, $headers) =
70             $self->handle_auth($req, $url_rec);
71     } else {
72         ($code, $msg) = @{$url_rec}{'code', 'msg'};
73         $headers = $url_rec->{headers};
74     }
75     my $resp = HTTP::Response->new ($code, $msg);
76     print STDERR "HTTP::Response: \n", $resp->as_string if $log;
77
78     while (my ($name, $value) = each %{$headers}) {
79         # print STDERR "setting header: $name = $value\n";
80         $resp->header($name => $value);
81     }
82     print STDERR "HTTP::Response with headers: \n", $resp->as_string if $log;
83
84     if ($send_content) {
85         my $content = $url_rec->{content};
86         if (exists($url_rec->{headers}{"Content-Length"})) {
87             # Content-Length and length($content) don't match
88             # manually prepare the HTTP response
89             $con->send_basic_header($url_rec->{code}, $resp->message, $resp->protocol);
90             print $con $resp->headers_as_string($CRLF);
91             print $con $CRLF;
92             print $con $content;
93             next;
94         }
95         if ($req->header("Range")) {
96             $req->header("Range") =~ m/bytes=(\d*)-(\d*)/;
97             my $content_len = length($content);
98             my $start = $1 ? $1 : 0;
99             my $end = $2 ? $2 : ($content_len - 1);
100             my $len = $2 ? ($2 - $start) : ($content_len - $start);
101             if ($len) {
102                 $resp->header("Accept-Ranges" => "bytes");
103                 $resp->header("Content-Length" => $len);
104                 $resp->header("Content-Range"
105                     => "bytes $start-$end/$content_len");
106                 $resp->header("Keep-Alive" => "timeout=15, max=100");
107                 $resp->header("Connection" => "Keep-Alive");
108                 $con->send_basic_header(206,
109                     "Partial Content", $resp->protocol);
110                 print $con $resp->headers_as_string($CRLF);
111                 print $con $CRLF;
112                 print $con substr($content, $start, $len);
113             } else {
114                 $con->send_basic_header(416, "Range Not Satisfiable",
115                     $resp->protocol);
116                 $resp->header("Keep-Alive" => "timeout=15, max=100");
117                 $resp->header("Connection" => "Keep-Alive");
118                 print $con $CRLF;
119             }
120             next;
121         }
122         # fill in content
123         $content = $self->_substitute_port($content);
124         $resp->content($content);
125         print STDERR "HTTP::Response with content: \n", $resp->as_string if $log;
126     }
127
128     $con->send_response($resp);
129     print STDERR "HTTP::Response sent: \n", $resp->as_string if $log;
130 }
131
132 # Generates appropriate response content based on the authentication
133 # status of the URL.
134 sub handle_auth {
135     my ($self, $req, $url_rec) = @_;
136     my ($send_content, $code, $msg, $headers);
137     # Catch failure to set code, msg:
138     $code = 500;
139     $msg  = "Didn't set response code in handle_auth";
140     # Most cases, we don't want to send content.
141     $send_content = 0;
142     # Initialize headers
143     $headers = {};
144     my $authhdr = $req->header('Authorization');
145
146     # Have we sent the challenge yet?
147     unless (defined $url_rec->{auth_challenged}
148         && $url_rec->{auth_challenged}) {
149         # Since we haven't challenged yet, we'd better not
150         # have received authentication (for our testing purposes).
151         if ($authhdr) {
152             $code = 400;
153             $msg  = "You sent auth before I sent challenge";
154         } else {
155             # Send challenge
156             $code = 401;
157             $msg  = "Authorization Required";
158             $headers->{'WWW-Authenticate'} = $url_rec->{'auth_method'}
159                 . " realm=\"wget-test\"";
160             $url_rec->{auth_challenged} = 1;
161         }
162     } elsif (!defined($authhdr)) {
163         # We've sent the challenge; we should have received valid
164         # authentication with this one. A normal server would just
165         # resend the challenge; but since this is a test, wget just
166         # failed it.
167         $code = 400;
168         $msg  = "You didn't send auth after I sent challenge";
169     } else {
170         my ($sent_method) = ($authhdr =~ /^(\S+)/g);
171         unless ($sent_method eq $url_rec->{'auth_method'}) {
172             # Not the authorization type we were expecting.
173             $code = 400;
174             $msg = "Expected auth type $url_rec->{'auth_method'} but got "
175                 . "$sent_method";
176         } elsif (($sent_method eq 'Digest'
177                   && &verify_auth_digest($authhdr, $url_rec, \$msg))
178                  ||
179                  ($sent_method eq 'Basic'
180                   && &verify_auth_basic($authhdr, $url_rec, \$msg))) {
181             # SUCCESSFUL AUTH: send expected message, headers, content.
182             ($code, $msg) = @{$url_rec}{'code', 'msg'};
183             $headers = $url_rec->{headers};
184             $send_content = 1;
185         } else {
186             $code = 400;
187         }
188     }
189
190     return ($send_content, $code, $msg, $headers);
191 }
192
193 sub verify_auth_digest {
194     return undef; # Not yet implemented.
195 }
196
197 sub verify_auth_basic {
198     require MIME::Base64;
199     my ($authhdr, $url_rec, $msgref) = @_;
200     my $expected = MIME::Base64::encode_base64($url_rec->{'user'} . ':'
201         . $url_rec->{'passwd'}, '');
202     my ($got) = $authhdr =~ /^Basic (.*)$/;
203     if ($got eq $expected) {
204         return 1;
205     } else {
206         $$msgref = "Wanted ${expected} got ${got}";
207         return undef;
208     }
209 }
210
211 sub _substitute_port {
212     my $self = shift;
213     my $ret = shift;
214     $ret =~ s/{{port}}/$self->sockport/eg;
215     return $ret;
216 }
217
218 1;
219
220 # vim: et ts=4 sw=4
221