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

Comparing cvsroot/Coro/myhttpd/httpd.pl (file contents):
Revision 1.63 by root, Wed Jan 23 03:07:05 2002 UTC vs.
Revision 1.87 by root, Wed Nov 19 11:41:06 2008 UTC

1use Coro; 1use Coro;
2use Coro::Semaphore; 2use Coro::Semaphore;
3use Coro::Event; 3use Coro::EV;
4use Coro::Socket; 4use Coro::Socket;
5use Coro::Signal; 5use Coro::Signal;
6use Coro::AIO ();
6 7
7use HTTP::Date; 8use HTTP::Date;
8use POSIX (); 9use POSIX ();
9 10
10use Compress::Zlib (); 11use Compress::Zlib ();
22our $errorlog; 23our $errorlog;
23 24
24our $NOW; 25our $NOW;
25our $HTTP_NOW; 26our $HTTP_NOW;
26 27
27Event->timer(interval => 1, hard => 1, cb => sub { 28our $ERROR_LOG;
29our $ACCESS_LOG;
30
31our $update_time = EV::periodic 0, 1, undef, sub {
28 $NOW = time; 32 $NOW = time;
29 $HTTP_NOW = time2str $NOW; 33 $HTTP_NOW = time2str $NOW;
30})->now; 34};
35$update_time->invoke;
31 36
32if ($ERROR_LOG) { 37if ($ERROR_LOG) {
33 use IO::Handle; 38 use IO::Handle;
34 open $errorlog, ">>$ERROR_LOG" 39 open $errorlog, ">>$ERROR_LOG"
35 or die "$ERROR_LOG: $!"; 40 or die "$ERROR_LOG: $!";
55our $httpevent = new Coro::Signal; 60our $httpevent = new Coro::Signal;
56 61
57our $queue_file = new transferqueue $MAX_TRANSFERS; 62our $queue_file = new transferqueue $MAX_TRANSFERS;
58our $queue_index = new transferqueue 10; 63our $queue_index = new transferqueue 10;
59 64
65our $tbf_top = new tbf rate => $TBF_RATE || 100000;
66
67my $unused_bytes = 0;
68my $unused_last = time;
69
70sub unused_bandwidth {
71 $unused_bytes += $_[0];
72 if ($unused_last < $NOW - 30 && $unused_bytes / ($NOW - $unused_last) > 50000) {
73 $unused_last = $NOW;
74 $unused_bytes = 0;
75 $queue_file->force_wake_next;
76 slog 1, "forced filetransfer due to unused bandwidth";
77 }
78}
79
60my @newcons; 80my @newcons;
61my @pool; 81my @pool;
62 82
63# one "execution thread" 83# one "execution thread"
64sub handler { 84sub handler {
65 while () { 85 while () {
66 if (@newcons) { 86 if (@newcons) {
67 eval { 87 eval {
68 conn->new(@{pop @newcons})->handle; 88 conn->new (@{pop @newcons})->handle;
69 }; 89 };
70 slog 1, "$@" if $@ && !ref $@; 90 slog 1, "$@" if $@ && !ref $@;
71 91
72 $httpevent->broadcast; # only for testing, but doesn't matter much 92 $httpevent->broadcast; # only for testing, but doesn't matter much
73 93
95 if (@pool) { 115 if (@pool) {
96 (pop @pool)->ready; 116 (pop @pool)->ready;
97 } else { 117 } else {
98 async \&handler; 118 async \&handler;
99 } 119 }
100
101 } 120 }
102 }; 121 };
103} 122}
104 123
105my $http_port = new Coro::Socket 124my $http_port = new Coro::Socket
106 LocalAddr => $SERVER_HOST, 125 LocalAddr => $SERVER_HOST,
107 LocalPort => $SERVER_PORT, 126 LocalPort => $SERVER_PORT,
108 ReuseAddr => 1, 127 ReuseAddr => 1,
109 Listen => 50, 128 Listen => 50,
110 or die "unable to start server"; 129 or die "unable to start server";
111 130
112listen_on $http_port; 131listen_on $http_port;
113 132
114if ($SERVER_PORT2) { 133if ($SERVER_PORT2) {
115 my $http_port = new Coro::Socket 134 my $http_port = new Coro::Socket
116 LocalAddr => $SERVER_HOST, 135 LocalAddr => $SERVER_HOST,
117 LocalPort => $SERVER_PORT2, 136 LocalPort => $SERVER_PORT2,
118 ReuseAddr => 1, 137 ReuseAddr => 1,
119 Listen => 50, 138 Listen => 50,
120 or die "unable to start server"; 139 or die "unable to start server";
121 140
122 listen_on $http_port; 141 listen_on $http_port;
123} 142}
124 143
125package conn; 144package conn;
145
146use strict;
147use bytes;
126 148
127use Socket; 149use Socket;
128use HTTP::Date; 150use HTTP::Date;
129use Convert::Scalar 'weaken'; 151use Convert::Scalar 'weaken';
130use Linux::AIO; 152use IO::AIO;
131 153
132Linux::AIO::min_parallel $::AIO_PARALLEL; 154IO::AIO::min_parallel $::AIO_PARALLEL;
133 155
134Event->io(fd => Linux::AIO::poll_fileno, 156our $AIO_WATCHER = EV::io IO::AIO::poll_fileno, EV::READ, \&IO::AIO::poll_cb;
135 poll => 'r', async => 1,
136 cb => \&Linux::AIO::poll_cb);
137 157
138our %conn; # $conn{ip}{self} => connobj 158our %conn; # $conn{ip}{self} => connobj
139our %uri; # $uri{ip}{uri}{self} 159our %uri; # $uri{ip}{uri}{self}
140our %blocked; 160our %blocked;
141our %mimetype; 161our %mimetype;
142 162
143sub read_mimetypes { 163sub read_mimetypes {
144 local *M;
145 if (open M, "<mime_types") { 164 if (open my $fh, "<mime_types") {
146 while (<M>) { 165 while (<$fh>) {
147 if (/^([^#]\S+)\t+(\S+)$/) { 166 if (/^([^#]\S+)\t+(\S+)$/) {
148 $mimetype{lc $1} = $2; 167 $mimetype{lc $1} = $2;
149 } 168 }
150 } 169 }
151 } else { 170 } else {
159 my $class = shift; 178 my $class = shift;
160 my $fh = shift; 179 my $fh = shift;
161 my $peername = shift; 180 my $peername = shift;
162 my $self = bless { fh => $fh }, $class; 181 my $self = bless { fh => $fh }, $class;
163 my (undef, $iaddr) = unpack_sockaddr_in $peername 182 my (undef, $iaddr) = unpack_sockaddr_in $peername
164 or $self->err(500, "unable to decode peername"); 183 or $self->err (500, "unable to decode peername");
165 184
166 $self->{remote_addr} = 185 $self->{remote_addr} =
167 $self->{remote_id} = inet_ntoa $iaddr; 186 $self->{remote_id} = inet_ntoa $iaddr;
168 187
169 $self->{time} = $::NOW; 188 $self->{time} = $::NOW;
170 189
171 weaken ($Coro::current->{conn} = $self); 190 weaken ($Coro::current->{conn} = $self);
172 191
173 $::conns++; 192 ++$::conns;
174 $::maxconns = $::conns if $::conns > $::maxconns; 193 $::maxconns = $::conns if $::conns > $::maxconns;
175 194
176 $self; 195 $self
177} 196}
178 197
179sub DESTROY { 198sub DESTROY {
180 #my $self = shift; 199 my $self = shift;
200
181 $::conns--; 201 --$::conns;
182} 202}
203
204sub prune_cache {
205 my $hash = $_[0];
206
207 for (keys %$hash) {
208 if (ref $hash->{$_} eq HASH::) {
209 prune_cache($hash->{$_});
210 unless (scalar keys %{$hash->{$_}}) {
211 delete $hash->{$_};
212 }
213 }
214 }
215}
216
217sub prune_caches {
218 prune_cache \%conn;
219 prune_cache \%uri;
220
221 for (keys %blocked) {
222 delete $blocked{$_} unless $blocked{$_}[0] > $::NOW;
223 }
224}
225
226our $PRUNE_WATCHER = EV::timer 60, 60, \&prune_caches;
183 227
184sub slog { 228sub slog {
185 my $self = shift; 229 my $self = shift;
186 main::slog($_[0], "$self->{remote_id}> $_[1]"); 230 main::slog($_[0], "$self->{remote_id}> $_[1]");
187} 231}
205 } 249 }
206 } 250 }
207 251
208 if ($self->{method} ne "HEAD" 252 if ($self->{method} ne "HEAD"
209 && $self->{h}{"accept-encoding"} =~ /\bgzip\b/ 253 && $self->{h}{"accept-encoding"} =~ /\bgzip\b/
254 && 400 < length $content
210 && $hdr->{"Content-Length"} == length $content 255 && $hdr->{"Content-Length"} == length $content
211 && !exists $hdr->{"Content-Encoding"} 256 && !exists $hdr->{"Content-Encoding"}
212 ) { 257 ) {
213 my $orig = length $content; 258 my $orig = length $content;
214 $hdr->{"Content-Encoding"} = "gzip"; 259 $hdr->{"Content-Encoding"} = "gzip";
216 $hdr->{"Content-Length"} = length $content; 261 $hdr->{"Content-Length"} = length $content;
217 $GZ = sprintf "GZ%02d", 100 - 100*((length $content) / $orig); 262 $GZ = sprintf "GZ%02d", 100 - 100*((length $content) / $orig);
218 } 263 }
219 264
220 $res .= "Date: $HTTP_NOW\015\012"; 265 $res .= "Date: $HTTP_NOW\015\012";
266 $res .= "Server: $::NAME\015\012";
221 267
222 while (my ($h, $v) = each %$hdr) { 268 while (my ($h, $v) = each %$hdr) {
223 $res .= "$h: $v\015\012" 269 $res .= "$h: $v\015\012"
224 } 270 }
225 $res .= "\015\012"; 271 $res .= "\015\012";
226 272
227 $res .= $content if defined $content and $self->{method} ne "HEAD"; 273 $res .= $content if defined $content and $self->{method} ne "HEAD";
228 274
229 my $log = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $NOW). 275 my $log = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $::NOW).
230 " $self->{remote_id} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}.$GZ. 276 " $self->{remote_id} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}.$GZ.
231 " \"$self->{h}{referer}\"\n"; 277 " \"$self->{h}{referer}\"\n";
232 278
233 print $accesslog $log if $accesslog; 279 print $::accesslog $log if $::accesslog;
234 print STDERR $log; 280 print STDERR $log;
235 281
236 $self->{written} += 282 $tbf_top->request(length $res, 1e6);
237 print {$self->{fh}} $res; 283 $self->{written} += print {$self->{fh}} $res;
238} 284}
239 285
240sub err { 286sub err {
241 my $self = shift; 287 my $self = shift;
242 my ($code, $msg, $hdr, $content) = @_; 288 my ($code, $msg, $hdr, $content) = @_;
246 $hdr->{"Content-Type"} = "text/plain"; 292 $hdr->{"Content-Type"} = "text/plain";
247 $hdr->{"Content-Length"} = length $content; 293 $hdr->{"Content-Length"} = length $content;
248 } 294 }
249 $hdr->{"Connection"} = "close"; 295 $hdr->{"Connection"} = "close";
250 296
251 $self->response($code, $msg, $hdr, $content); 297 $self->response ($code, $msg, $hdr, $content);
252 298
253 die bless {}, err::; 299 die bless {}, err::
254} 300}
255 301
256sub handle { 302sub handle {
257 my $self = shift; 303 my $self = shift;
258 my $fh = $self->{fh}; 304 my $fh = $self->{fh};
259 305
260 my $host; 306 my $host;
261 307
262 $fh->timeout($::REQ_TIMEOUT); 308 $fh->timeout($::REQ_TIMEOUT);
263 while() { 309 while () {
264 $self->{reqs}++; 310 $self->{reqs}++;
265 311
266 # read request and parse first line 312 # read request and parse first line
267 my $req = $fh->readline("\015\012\015\012"); 313 my $req = $fh->readline("\015\012\015\012");
268 314
297 my (%hdr, $h, $v); 343 my (%hdr, $h, $v);
298 344
299 $hdr{lc $1} .= ",$2" 345 $hdr{lc $1} .= ",$2"
300 while $req =~ /\G 346 while $req =~ /\G
301 ([^:\000-\040]+): 347 ([^:\000-\040]+):
302 [\010\040]* 348 [\011\040]*
303 ((?: [^\015\012]+ | \015\012[\010\040] )*) 349 ((?: [^\015\012]+ | \015\012[\011\040] )*)
304 \015\012 350 \015\012
305 /gxc; 351 /gxc;
306 352
307 $req =~ /\G\015\012$/ 353 $req =~ /\G\015\012$/
308 or $self->err(400, "bad request"); 354 or $self->err(400, "bad request");
377# uri => path mapping 423# uri => path mapping
378sub map_uri { 424sub map_uri {
379 my $self = shift; 425 my $self = shift;
380 my $host = $self->{server_name}; 426 my $host = $self->{server_name};
381 my $uri = $self->{uri}; 427 my $uri = $self->{uri};
428
429 $host =~ /[\/\\]/
430 and $self->err(400, "bad request");
382 431
383 # some massaging, also makes it more secure 432 # some massaging, also makes it more secure
384 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge; 433 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge;
385 $uri =~ s%//+%/%g; 434 $uri =~ s%//+%/%g;
386 $uri =~ s%/\.(?=/|$)%%g; 435 $uri =~ s%/\.(?=/|$)%%g;
430 479
431 if ($self->{name} =~ s%^/internal/([^/]+)%%) { 480 if ($self->{name} =~ s%^/internal/([^/]+)%%) {
432 if ($::internal{$1}) { 481 if ($::internal{$1}) {
433 $::internal{$1}->($self); 482 $::internal{$1}->($self);
434 } else { 483 } else {
435 $self->err(404, "not found"); 484 $self->err (404, "not found");
436 } 485 }
437 } else { 486 } else {
438 487
439 stat $path 488 stat $path
440 or $self->err(404, "not found"); 489 or $self->err (404, "not found");
441 490
442 $self->{stat} = [stat _]; 491 $self->{stat} = [stat _];
443 492
444 # idiotic netscape sends idiotic headers AGAIN 493 # idiotic netscape sends idiotic headers AGAIN
445 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/ 494 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
448 if (-d _ && -r _) { 497 if (-d _ && -r _) {
449 # directory 498 # directory
450 if ($path !~ /\/$/) { 499 if ($path !~ /\/$/) {
451 # create a redirect to get the trailing "/" 500 # create a redirect to get the trailing "/"
452 # we don't try to avoid the :80 501 # we don't try to avoid the :80
453 $self->err(301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" }); 502 $self->err (301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" });
454 } else { 503 } else {
455 $ims < $self->{stat}[9] 504 $ims < $self->{stat}[9]
456 or $self->err(304, "not modified"); 505 or $self->err (304, "not modified");
457 506
458 if (-r "$path/index.html") { 507 if (-r "$path/index.html") {
459 # replace directory "size" by index.html filesize 508 # replace directory "size" by index.html filesize
460 $self->{stat} = [stat ($self->{path} .= "/index.html")]; 509 $self->{stat} = [stat ($self->{path} .= "/index.html")];
461 $self->handle_file($queue_index); 510 $self->handle_file ($queue_index, $tbf_top);
462 } else { 511 } else {
463 $self->handle_dir; 512 $self->handle_dir;
464 } 513 }
465 } 514 }
466 } elsif (-f _ && -r _) { 515 } elsif (-f _ && -r _) {
467 -x _ and $self->err(403, "forbidden"); 516 -x _ and $self->err (403, "forbidden");
468 517
469 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 518 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
470 my $timeout = $::NOW + 10; 519 my $timeout = $::NOW + 10;
471 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 520 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
472 if ($timeout < $::NOW) { 521 if ($timeout < $::NOW) {
475 $httpevent->wait; 524 $httpevent->wait;
476 } 525 }
477 } 526 }
478 } 527 }
479 528
480 $self->handle_file($queue_file); 529 $self->handle_file ($queue_file, $tbf_top);
481 } else { 530 } else {
482 $self->err(404, "not found"); 531 $self->err (404, "not found");
483 } 532 }
484 } 533 }
485} 534}
486 535
487sub handle_dir { 536sub handle_dir {
488 my $self = shift; 537 my $self = shift;
489 my $idx = $self->diridx; 538 my $idx = $self->diridx;
490 539
491 $self->response(200, "ok", 540 $self->response (200, "ok",
492 { 541 {
493 "Content-Type" => "text/html", 542 "Content-Type" => "text/html; charset=utf-8",
494 "Content-Length" => length $idx, 543 "Content-Length" => length $idx,
495 "Last-Modified" => time2str ($self->{stat}[9]), 544 "Last-Modified" => time2str ($self->{stat}[9]),
496 }, 545 },
497 $idx); 546 $idx);
498} 547}
499 548
500sub handle_file { 549sub handle_file {
501 my ($self, $queue) = @_; 550 my ($self, $queue, $tbf) = @_;
502 my $length = $self->{stat}[7]; 551 my $length = $self->{stat}[7];
503 my $hdr = { 552 my $hdr = {
504 "Last-Modified" => time2str ((stat _)[9]), 553 "Last-Modified" => time2str ((stat _)[9]),
554 "Accept-Ranges" => "bytes",
505 }; 555 };
506 556
507 my @code = (200, "ok"); 557 my @code = (200, "ok");
508 my ($l, $h); 558 my ($l, $h);
509 559
510 if ($self->{h}{range} =~ /^bytes=(.*)$/) { 560 if ($self->{h}{range} =~ /^bytes=(.*)$/i) {
511 for (split /,/, $1) { 561 for (split /,/, $1) {
512 if (/^-(\d+)$/) { 562 if (/^-(\d+)$/) {
513 ($l, $h) = ($length - $1, $length - 1); 563 ($l, $h) = ($length - $1, $length - 1);
514 } elsif (/^(\d+)-(\d*)$/) { 564 } elsif (/^(\d+)-(\d*)$/) {
515 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1); 565 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1);
519 } 569 }
520 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; 570 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
521 } 571 }
522 $hdr->{"Content-Range"} = "bytes */$length"; 572 $hdr->{"Content-Range"} = "bytes */$length";
523 $hdr->{"Content-Length"} = $length; 573 $hdr->{"Content-Length"} = $length;
524 $self->err(416, "not satisfiable", $hdr, ""); 574 $self->err (416, "not satisfiable", $hdr, "");
525 575
526satisfiable: 576satisfiable:
527 # check for segmented downloads 577 # check for segmented downloads
528 if ($l && $::NO_SEGMENTED) { 578 if ($l && $::NO_SEGMENTED) {
529 my $timeout = $::NOW + 15; 579 my $timeout = $::NOW + 15;
530 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) { 580 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
531 if ($timeout <= $::NOW) { 581 if ($timeout <= $::NOW) {
532 $self->block($::BLOCKTIME, "segmented downloads are forbidden"); 582 $self->block ($::BLOCKTIME, "segmented downloads are forbidden");
533 #$self->err_segmented_download; 583 #$self->err_segmented_download;
534 } else { 584 } else {
535 $httpevent->wait; 585 $httpevent->wait;
536 } 586 }
537 } 587 }
548 598
549 $self->{path} =~ /\.([^.]+)$/; 599 $self->{path} =~ /\.([^.]+)$/;
550 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream"; 600 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream";
551 $hdr->{"Content-Length"} = $length; 601 $hdr->{"Content-Length"} = $length;
552 602
553 $self->response(@code, $hdr, ""); 603 $self->response (@code, $hdr, "");
554 604
555 if ($self->{method} eq "GET") { 605 if ($self->{method} eq "GET") {
556 $self->{time} = $::NOW; 606 $self->{time} = $::NOW;
607 $self->{written} = 0;
557 608
558 my $current = $Coro::current;
559
560 my ($fh, $buf, $r);
561
562 open $fh, "<", $self->{path} 609 open my $fh, "<", $self->{path}
563 or die "$self->{path}: late open failure ($!)"; 610 or die "$self->{path}: late open failure ($!)";
564 611
565 $h -= $l - 1; 612 $h -= $l - 1;
566 613
567 if (0) { # !AIO
568 if ($l) {
569 sysseek $fh, $l, 0;
570 }
571 }
572
573 my $transfer = $queue->start_transfer($h); 614 my $transfer = $queue->start_transfer ($h);
574 my $locked; 615 my $locked;
575 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size 616 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size
576 617
577 while ($h > 0) { 618 while ($h > 0) {
578 unless ($locked) { 619 unless ($locked) {
579 if ($locked ||= $transfer->try($::WAIT_INTERVAL)) { 620 if ($locked ||= $transfer->try ($::WAIT_INTERVAL)) {
580 $bufsize = $::BUFSIZE; 621 $bufsize = $::BUFSIZE;
581 $self->{time} = $::NOW; 622 $self->{time} = $::NOW;
623 $self->{written} = 0;
582 } 624 }
583 } 625 }
584 626
585 if ($blocked{$self->{remote_id}}) { 627 if ($blocked{$self->{remote_id}}) {
586 $self->{h}{connection} = "close"; 628 $self->{h}{connection} = "close";
587 die bless {}, err::; 629 die bless {}, err::;
588 } 630 }
589 631
590 if (0) { # !AIO 632 Coro::AIO::aio_read $fh, $l, ($h > $bufsize ? $bufsize : $h), my $buf, 0
591 sysread $fh, $buf, $h > $bufsize ? $bufsize : $h
592 or last; 633 or last;
593 } else { 634
594 aio_read($fh, $l, ($h > $bufsize ? $bufsize : $h), 635 $tbf->request (length $buf);
595 $buf, 0, sub { 636 my $w = $self->{fh}->syswrite ($buf)
596 $r = $_[0];
597 Coro::ready($current);
598 });
599 &Coro::schedule;
600 last unless $r;
601 }
602 my $w = syswrite $self->{fh}, $buf
603 or last; 637 or last;
604 $::written += $w; 638 $::written += $w;
605 $self->{written} += $w; 639 $self->{written} += $w;
606 $l += $r; 640 $l += $w;
607 } 641 }
608 642
609 close $fh; 643 close $fh;
610 } 644 }
611} 645}
612 646
6131; 6471
648

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines