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.65 by root, Fri Jan 25 09:26:13 2002 UTC vs.
Revision 1.82 by root, Sat Dec 2 03:31:42 2006 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines