ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/myhttpd/httpd.pl
(Generate patch)

Comparing Coro/myhttpd/httpd.pl (file contents):
Revision 1.12 by root, Sat Aug 11 23:10:56 2001 UTC vs.
Revision 1.30 by root, Sun Aug 26 14:55:46 2001 UTC

9# at least on my machine, this thingy serves files 9# at least on my machine, this thingy serves files
10# quite a bit faster than apache, ;) 10# quite a bit faster than apache, ;)
11# and quite a bit slower than thttpd :( 11# and quite a bit slower than thttpd :(
12 12
13$SIG{PIPE} = 'IGNORE'; 13$SIG{PIPE} = 'IGNORE';
14 14
15our $accesslog;
16
17if ($ACCESS_LOG) {
18 use IO::Handle;
19 open $accesslog, ">>$ACCESS_LOG"
20 or die "$ACCESS_LOG: $!";
21 $accesslog->autoflush(1);
22}
23
15sub slog { 24sub slog {
16 my $level = shift; 25 my $level = shift;
17 my $format = shift; 26 my $format = shift;
18 printf "---: $format\n", @_; 27 printf "---: $format\n", @_;
19} 28}
43 52
44my $http_port = new Coro::Socket 53my $http_port = new Coro::Socket
45 LocalAddr => $SERVER_HOST, 54 LocalAddr => $SERVER_HOST,
46 LocalPort => $SERVER_PORT, 55 LocalPort => $SERVER_PORT,
47 ReuseAddr => 1, 56 ReuseAddr => 1,
48 Listen => 1, 57 Listen => 50,
49 or die "unable to start server"; 58 or die "unable to start server";
50 59
51push @listen_sockets, $http_port; 60push @listen_sockets, $http_port;
52 61
53# the "main thread" 62# the "main thread"
70package conn; 79package conn;
71 80
72use Socket; 81use Socket;
73use HTTP::Date; 82use HTTP::Date;
74use Convert::Scalar 'weaken'; 83use Convert::Scalar 'weaken';
84use Linux::AIO;
75 85
86Linux::AIO::min_parallel $::AIO_PARALLEL;
87
88my $aio_requests = new Coro::Semaphore $::AIO_PARALLEL * 4;
89
90Event->io(fd => Linux::AIO::poll_fileno,
91 poll => 'r', async => 1,
92 cb => \&Linux::AIO::poll_cb);
93
76our %conn; # $conn{ip}{fh} => connobj 94our %conn; # $conn{ip}{self} => connobj
95our %uri; # $uri{ip}{uri}{self}
77our %blocked; 96our %blocked;
78our %mimetype; 97our %mimetype;
79 98
80sub read_mimetypes { 99sub read_mimetypes {
81 local *M; 100 local *M;
104 $self->{time} = $::NOW; 123 $self->{time} = $::NOW;
105 124
106 # enter ourselves into various lists 125 # enter ourselves into various lists
107 weaken ($conn{$self->{remote_addr}}{$self*1} = $self); 126 weaken ($conn{$self->{remote_addr}}{$self*1} = $self);
108 127
128 $::conns++;
129
109 $self; 130 $self;
110} 131}
111 132
112sub DESTROY { 133sub DESTROY {
113 my $self = shift; 134 my $self = shift;
135
136 $::conns--;
137
138 $self->eoconn;
114 delete $conn{$self->{remote_addr}}{$self*1}; 139 delete $conn{$self->{remote_addr}}{$self*1};
140}
141
142# end of connection
143sub eoconn {
144 my $self = shift;
115 delete $uri{$self->{uri}}{$self*1}; 145 delete $uri{$self->{remote_addr}}{$self->{uri}}{$self*1};
116} 146}
117 147
118sub slog { 148sub slog {
119 my $self = shift; 149 my $self = shift;
120 main::slog($_[0], "$self->{remote_addr}> $_[1]"); 150 main::slog($_[0], ($self->{remote_id} || $self->{remote_addr}) ."> $_[1]");
121} 151}
122 152
123sub response { 153sub response {
124 my ($self, $code, $msg, $hdr, $content) = @_; 154 my ($self, $code, $msg, $hdr, $content) = @_;
125 my $res = "HTTP/1.0 $code $msg\015\012"; 155 my $res = "HTTP/1.1 $code $msg\015\012";
126 156
127 $res .= "Connection: close\015\012"; 157 $self->{h}{connection} ||= $hdr->{Connection};
158
128 $res .= "Date: ".(time2str $::NOW)."\015\012"; # slow? nah. :( 159 $res .= "Date: ".(time2str $::NOW)."\015\012"; # slow? nah. :(
129 160
130 while (my ($h, $v) = each %$hdr) { 161 while (my ($h, $v) = each %$hdr) {
131 $res .= "$h: $v\015\012" 162 $res .= "$h: $v\015\012"
132 } 163 }
133 $res .= "\015\012"; 164 $res .= "\015\012";
134 165
135 $res .= $content if defined $content and $self->{method} eq "GET"; 166 $res .= $content if defined $content and $self->{method} ne "HEAD";
136 167
137 print STDERR "$self->{remote_addr} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}." \"$self->{h}{referer}\"\n";#d# 168 my $log = "$self->{remote_addr} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}." \"$self->{h}{referer}\"\n";
169
170 print $accesslog $log if $accesslog;
171 print STDERR $log;
138 172
139 $self->{written} += 173 $self->{written} +=
140 print {$self->{fh}} $res; 174 print {$self->{fh}} $res;
141} 175}
142 176
147 unless (defined $content) { 181 unless (defined $content) {
148 $content = "$code $msg"; 182 $content = "$code $msg";
149 $hdr->{"Content-Type"} = "text/plain"; 183 $hdr->{"Content-Type"} = "text/plain";
150 $hdr->{"Content-Length"} = length $content; 184 $hdr->{"Content-Length"} = length $content;
151 } 185 }
186 $hdr->{"Connection"} = "close";
152 187
153 $self->response($code, $msg, $hdr, $content); 188 $self->response($code, $msg, $hdr, $content);
154 189
155 die bless {}, err::; 190 die bless {}, err::;
156} 191}
157 192
158sub err_blocked {
159 my $self = shift;
160 my $ip = $self->{remote_addr};
161 my $time = time2str $blocked{$ip} = $::NOW + $::BLOCKTIME;
162
163 Coro::Event::do_timer(after => 5);
164
165 $self->err(403, "too many connections",
166 {
167 "Content-Type" => "text/html",
168 "Retry-After" => $::BLOCKTIME
169 },
170 <<EOF);
171<html><p>
172You have been blocked because you opened too many connections. You
173may retry at</p>
174
175 <p><blockquote>$time.</blockquote></p>
176
177<p>Until then, each new access will renew the block. You might want to have a
178look at the <a href="http://www.goof.com/pcg/marc/animefaq.html">FAQ</a>.</p>
179</html>
180EOF
181}
182
183sub handle { 193sub handle {
184 my $self = shift; 194 my $self = shift;
185 my $fh = $self->{fh}; 195 my $fh = $self->{fh};
186 196
197 my $host;
198
199 $fh->timeout($::REQ_TIMEOUT);
187 #while() { 200 while() {
201 $self->{reqs}++;
202
203 # read request and parse first line
204 my $req = $fh->readline("\015\012\015\012");
205
206 unless (defined $req) {
207 if (exists $self->{version}) {
208 last;
209 } else {
210 $self->err(408, "request timeout");
211 }
212 }
213
188 $self->{h} = {}; 214 $self->{h} = {};
189 215
190 # read request and parse first line
191 $fh->timeout($::REQ_TIMEOUT);
192 my $req = $fh->readline("\015\012\015\012");
193 $fh->timeout($::RES_TIMEOUT); 216 $fh->timeout($::RES_TIMEOUT);
194
195 defined $req or
196 $self->err(408, "request timeout");
197
198 my $ip = $self->{remote_addr}; 217 my $ip = $self->{remote_addr};
199 218
200 if ($blocked{$ip}) { 219 if ($blocked{$ip}) {
201 $self->err_blocked($blocked{$ip}) 220 $self->err_blocked($blocked{$ip})
202 if $blocked{$ip} > $::NOW; 221 if $blocked{$ip} > $::NOW;
212 $req =~ /^(?:\015\012)? 231 $req =~ /^(?:\015\012)?
213 (GET|HEAD) \040+ 232 (GET|HEAD) \040+
214 ([^\040]+) \040+ 233 ([^\040]+) \040+
215 HTTP\/([0-9]+\.[0-9]+) 234 HTTP\/([0-9]+\.[0-9]+)
216 \015\012/gx 235 \015\012/gx
217 or $self->err(403, "method not allowed", { Allow => "GET,HEAD" }); 236 or $self->err(405, "method not allowed", { Allow => "GET,HEAD" });
218
219 $2 ne "1.0"
220 or $self->err(506, "http protocol version not supported");
221 237
222 $self->{method} = $1; 238 $self->{method} = $1;
223 $self->{uri} = $2; 239 $self->{uri} = $2;
240 $self->{version} = $3;
241
242 $3 =~ /^1\./
243 or $self->err(506, "http protocol version $3 not supported");
224 244
225 # parse headers 245 # parse headers
226 { 246 {
227 my (%hdr, $h, $v); 247 my (%hdr, $h, $v);
228 248
239 259
240 $self->{h}{$h} = substr $v, 1 260 $self->{h}{$h} = substr $v, 1
241 while ($h, $v) = each %hdr; 261 while ($h, $v) = each %hdr;
242 } 262 }
243 263
264 # find out server name and port
265 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) {
266 $host = $1;
267 } else {
268 $host = $self->{h}{host};
269 }
270
271 if (defined $host) {
244 $self->{server_port} = $self->{h}{host} =~ s/:([0-9]+)$// ? $1 : 80; 272 $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80;
273 } else {
274 ($self->{server_port}, $host)
275 = unpack_sockaddr_in $self->{fh}->getsockname
276 or $self->err(500, "unable to get socket name");
277 $host = inet_ntoa $host;
278 }
245 279
280 $self->{server_name} = $host;
281
282 # remote id should be unique per user
283 $self->{remote_id} = $self->{remote_addr};
284
285 if (exists $self->{h}{"client-ip"}) {
286 $self->{remote_id} .= "[".$self->{h}{"client-ip"}."]";
287 } elsif (exists $self->{h}{"x-forwarded-for"}) {
288 $self->{remote_id} .= "[".$self->{h}{"x-forwarded-for"}."]";
289 }
290
246 weaken ($uri{$self->{uri}}{$self*1} = $self); 291 weaken ($uri{$self->{remote_addr}}{$self->{uri}}{$self*1} = $self);
247 292
293 eval {
248 $self->map_uri; 294 $self->map_uri;
249 $self->respond; 295 $self->respond;
296 };
297
298 $self->eoconn;
299
300 die if $@ && !ref $@;
301
302 last if $self->{h}{connection} =~ /close/ || $self->{version} < 1.1;
303
304 $fh->timeout($::PER_TIMEOUT);
250 #} 305 }
251} 306}
252 307
253# uri => path mapping 308# uri => path mapping
254sub map_uri { 309sub map_uri {
255 my $self = shift; 310 my $self = shift;
256 my $host = $self->{h}{host} || "default"; 311 my $host = $self->{server_name};
257 my $uri = $self->{uri}; 312 my $uri = $self->{uri};
258 313
259 # some massaging, also makes it more secure 314 # some massaging, also makes it more secure
260 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge; 315 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge;
261 $uri =~ s%//+%/%g; 316 $uri =~ s%//+%/%g;
271 $self->{path} = "$::DOCROOT/$host$uri"; 326 $self->{path} = "$::DOCROOT/$host$uri";
272 327
273 $self->access_check; 328 $self->access_check;
274} 329}
275 330
276sub server_address {
277 my $self = shift;
278 my ($port, $iaddr) = unpack_sockaddr_in $self->{fh}->getsockname
279 or $self->err(500, "unable to get socket name");
280 ((inet_ntoa $iaddr), $port);
281}
282
283sub server_host {
284 my $self = shift;
285 if (exists $self->{h}{host}) {
286 return $self->{h}{host};
287 } else {
288 return (($self->server_address)[0]);
289 }
290}
291
292sub server_hostport {
293 my $self = shift;
294 my ($host, $port);
295 if (exists $self->{h}{host}) {
296 ($host, $port) = ($self->{h}{host}, $self->{server_port});
297 } else {
298 ($host, $port) = $self->server_address;
299 }
300 $port = $port == 80 ? "" : ":$port";
301 $host.$port;
302}
303
304sub _cgi { 331sub _cgi {
305 my $self = shift; 332 my $self = shift;
306 my $path = shift; 333 my $path = shift;
307 my $fh; 334 my $fh;
308 335
309 # no two-way xxx supported 336 # no two-way xxx supported
310 if (0 == fork) { 337 if (0 == fork) {
311 open STDOUT, ">&".fileno($self->{fh}); 338 open STDOUT, ">&".fileno($self->{fh});
312 if (chdir $::DOCROOT) { 339 if (chdir $::DOCROOT) {
313 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike 340 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike
314 $ENV{HTTP_HOST} = $self->server_host; 341 $ENV{HTTP_HOST} = $self->{server_name};
315 $ENV{HTTP_PORT} = $self->{server_host}; 342 $ENV{HTTP_PORT} = $self->{server_port};
316 $ENV{SCRIPT_NAME} = $self->{name}; 343 $ENV{SCRIPT_NAME} = $self->{name};
317 exec $path; 344 exec $path;
318 } 345 }
319 Coro::State::_exit(0); 346 Coro::State::_exit(0);
320 } else { 347 } else {
348 die;
321 } 349 }
350}
351
352sub server_hostport {
353 $_[0]{server_port} == 80
354 ? $_[0]{server_name}
355 : "$_[0]{server_name}:$_[0]{server_port}";
322} 356}
323 357
324sub respond { 358sub respond {
325 my $self = shift; 359 my $self = shift;
326 my $path = $self->{path}; 360 my $path = $self->{path};
336 370
337 if (-d _ && -r _) { 371 if (-d _ && -r _) {
338 # directory 372 # directory
339 if ($path !~ /\/$/) { 373 if ($path !~ /\/$/) {
340 # create a redirect to get the trailing "/" 374 # create a redirect to get the trailing "/"
341 my $host = $self->server_hostport; 375 # we don't try to avoid the :80
342 $self->err(301, "moved permanently", { Location => "http://$host$self->{uri}/" }); 376 $self->err(301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" });
343 } else { 377 } else {
344 $ims < $self->{stat}[9] 378 $ims < $self->{stat}[9]
345 or $self->err(304, "not modified"); 379 or $self->err(304, "not modified");
346 380
347 if ($self->{method} eq "GET") {
348 if (-r "$path/index.html") { 381 if (-r "$path/index.html") {
349 $self->{path} .= "/index.html"; 382 $self->{path} .= "/index.html";
350 $self->handle_file; 383 $self->handle_file;
351 } else { 384 } else {
352 $self->handle_dir; 385 $self->handle_dir;
353 }
354 } 386 }
355 } 387 }
356 } elsif (-f _ && -r _) { 388 } elsif (-f _ && -r _) {
357 -x _ and $self->err(403, "forbidden"); 389 -x _ and $self->err(403, "forbidden");
358 $self->handle_file; 390 $self->handle_file;
391 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1); 423 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1);
392 } else { 424 } else {
393 ($l, $h) = (0, $length - 1); 425 ($l, $h) = (0, $length - 1);
394 goto ignore; 426 goto ignore;
395 } 427 }
396 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h > $l; 428 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
397 } 429 }
398 $hdr->{"Content-Range"} = "bytes */$length"; 430 $hdr->{"Content-Range"} = "bytes */$length";
431 $hdr->{"Content-Length"} = $length;
432 $self->slog(9, "not satisfiable($self->{h}{range}|".$self->{h}{"user-agent"}.")");
399 $self->err(416, "not satisfiable", $hdr); 433 $self->err(416, "not satisfiable", $hdr, "");
400 434
401satisfiable: 435satisfiable:
402 # check for segmented downloads 436 # check for segmented downloads
403 if ($l && $::NO_SEGMENTED) { 437 if ($l && $::NO_SEGMENTED) {
404 if (%{$uri{$self->{uri}}} > 1) { 438 my $delay = 180;
405 $self->err(400, "segmented downloads are not allowed"); 439 while (%{$uri{$self->{remote_addr}}{$self->{uri}}} > 1) {
440 if ($delay <= 0) {
441 $self->err_segmented_download;
442 } else {
443 Coro::Event::do_timer(after => 3); $delay -= 3;
444 }
406 } 445 }
407 } 446 }
408 447
409 $hdr->{"Content-Range"} = "bytes $l-$h/$length"; 448 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
410 @code = (206, "partial content"); 449 @code = (206, "partial content");
420 $hdr->{"Content-Length"} = $length; 459 $hdr->{"Content-Length"} = $length;
421 460
422 $self->response(@code, $hdr, ""); 461 $self->response(@code, $hdr, "");
423 462
424 if ($self->{method} eq "GET") { 463 if ($self->{method} eq "GET") {
425 my ($fh, $buf); 464 my ($fh, $buf, $r);
465 my $current = $Coro::current;
426 open $fh, "<", $self->{path} 466 open $fh, "<", $self->{path}
427 or die "$self->{path}: late open failure ($!)"; 467 or die "$self->{path}: late open failure ($!)";
428 468
429 if ($l) {
430 sysseek $fh, $l, 0
431 or die "$self->{path}: cannot seek to $l ($!)";
432 }
433
434 $h -= $l - 1; 469 $h -= $l - 1;
435 470
471 if (0) {
472 if ($l) {
473 sysseek $fh, $l, 0;
474 }
475 }
476
436 while ($h > 0) { 477 while ($h > 0) {
478 if (0) {
437 $h -= sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h; 479 sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h
480 or last;
481 } else {
482 undef $buf;
483 $aio_requests->down;
484 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h),
485 $buf, 0, sub {
486 $r = $_[0];
487 $current->ready;
488 });
489 &Coro::schedule;
490 $aio_requests->up;
491 last unless $r;
492 }
438 my $w = $self->{fh}->syswrite($buf) 493 my $w = $self->{fh}->syswrite($buf)
439 or last; 494 or last;
440 $::written += $w; 495 $::written += $w;
441 $self->{written} += $w; 496 $self->{written} += $w;
497 $l += $r;
442 } 498 }
443 } 499 }
444 500
445 close $fh; 501 close $fh;
446} 502}

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines