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.66 by root, Mon Feb 25 03:21:09 2002 UTC vs.
Revision 1.84 by root, Sat Dec 8 21:01:16 2007 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}
217 $hdr->{"Content-Length"} = length $content; 261 $hdr->{"Content-Length"} = length $content;
218 $GZ = sprintf "GZ%02d", 100 - 100*((length $content) / $orig); 262 $GZ = sprintf "GZ%02d", 100 - 100*((length $content) / $orig);
219 } 263 }
220 264
221 $res .= "Date: $HTTP_NOW\015\012"; 265 $res .= "Date: $HTTP_NOW\015\012";
266 $res .= "Server: $::NAME\015\012";
222 267
223 while (my ($h, $v) = each %$hdr) { 268 while (my ($h, $v) = each %$hdr) {
224 $res .= "$h: $v\015\012" 269 $res .= "$h: $v\015\012"
225 } 270 }
226 $res .= "\015\012"; 271 $res .= "\015\012";
232 " \"$self->{h}{referer}\"\n"; 277 " \"$self->{h}{referer}\"\n";
233 278
234 print $::accesslog $log if $::accesslog; 279 print $::accesslog $log if $::accesslog;
235 print STDERR $log; 280 print STDERR $log;
236 281
237 $self->{written} += 282 $tbf_top->request(length $res, 1e6);
238 print {$self->{fh}} $res; 283 $self->{written} += print {$self->{fh}} $res;
239} 284}
240 285
241sub err { 286sub err {
242 my $self = shift; 287 my $self = shift;
243 my ($code, $msg, $hdr, $content) = @_; 288 my ($code, $msg, $hdr, $content) = @_;
247 $hdr->{"Content-Type"} = "text/plain"; 292 $hdr->{"Content-Type"} = "text/plain";
248 $hdr->{"Content-Length"} = length $content; 293 $hdr->{"Content-Length"} = length $content;
249 } 294 }
250 $hdr->{"Connection"} = "close"; 295 $hdr->{"Connection"} = "close";
251 296
252 $self->response($code, $msg, $hdr, $content); 297 $self->response ($code, $msg, $hdr, $content);
253 298
254 die bless {}, err::; 299 die bless {}, err::
255} 300}
256 301
257sub handle { 302sub handle {
258 my $self = shift; 303 my $self = shift;
259 my $fh = $self->{fh}; 304 my $fh = $self->{fh};
260 305
261 my $host; 306 my $host;
262 307
263 $fh->timeout($::REQ_TIMEOUT); 308 $fh->timeout($::REQ_TIMEOUT);
264 while() { 309 while () {
265 $self->{reqs}++; 310 $self->{reqs}++;
266 311
267 # read request and parse first line 312 # read request and parse first line
268 my $req = $fh->readline("\015\012\015\012"); 313 my $req = $fh->readline("\015\012\015\012");
269 314
431 476
432 if ($self->{name} =~ s%^/internal/([^/]+)%%) { 477 if ($self->{name} =~ s%^/internal/([^/]+)%%) {
433 if ($::internal{$1}) { 478 if ($::internal{$1}) {
434 $::internal{$1}->($self); 479 $::internal{$1}->($self);
435 } else { 480 } else {
436 $self->err(404, "not found"); 481 $self->err (404, "not found");
437 } 482 }
438 } else { 483 } else {
439 484
440 stat $path 485 stat $path
441 or $self->err(404, "not found"); 486 or $self->err (404, "not found");
442 487
443 $self->{stat} = [stat _]; 488 $self->{stat} = [stat _];
444 489
445 # idiotic netscape sends idiotic headers AGAIN 490 # idiotic netscape sends idiotic headers AGAIN
446 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/ 491 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
449 if (-d _ && -r _) { 494 if (-d _ && -r _) {
450 # directory 495 # directory
451 if ($path !~ /\/$/) { 496 if ($path !~ /\/$/) {
452 # create a redirect to get the trailing "/" 497 # create a redirect to get the trailing "/"
453 # we don't try to avoid the :80 498 # we don't try to avoid the :80
454 $self->err(301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" }); 499 $self->err (301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" });
455 } else { 500 } else {
456 $ims < $self->{stat}[9] 501 $ims < $self->{stat}[9]
457 or $self->err(304, "not modified"); 502 or $self->err (304, "not modified");
458 503
459 if (-r "$path/index.html") { 504 if (-r "$path/index.html") {
460 # replace directory "size" by index.html filesize 505 # replace directory "size" by index.html filesize
461 $self->{stat} = [stat ($self->{path} .= "/index.html")]; 506 $self->{stat} = [stat ($self->{path} .= "/index.html")];
462 $self->handle_file($queue_index); 507 $self->handle_file ($queue_index, $tbf_top);
463 } else { 508 } else {
464 $self->handle_dir; 509 $self->handle_dir;
465 } 510 }
466 } 511 }
467 } elsif (-f _ && -r _) { 512 } elsif (-f _ && -r _) {
468 -x _ and $self->err(403, "forbidden"); 513 -x _ and $self->err (403, "forbidden");
469 514
470 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 515 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
471 my $timeout = $::NOW + 10; 516 my $timeout = $::NOW + 10;
472 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 517 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
473 if ($timeout < $::NOW) { 518 if ($timeout < $::NOW) {
476 $httpevent->wait; 521 $httpevent->wait;
477 } 522 }
478 } 523 }
479 } 524 }
480 525
481 $self->handle_file($queue_file); 526 $self->handle_file ($queue_file, $tbf_top);
482 } else { 527 } else {
483 $self->err(404, "not found"); 528 $self->err (404, "not found");
484 } 529 }
485 } 530 }
486} 531}
487 532
488sub handle_dir { 533sub handle_dir {
489 my $self = shift; 534 my $self = shift;
490 my $idx = $self->diridx; 535 my $idx = $self->diridx;
491 536
492 $self->response(200, "ok", 537 $self->response (200, "ok",
493 { 538 {
494 "Content-Type" => "text/html", 539 "Content-Type" => "text/html; charset=utf-8",
495 "Content-Length" => length $idx, 540 "Content-Length" => length $idx,
496 "Last-Modified" => time2str ($self->{stat}[9]), 541 "Last-Modified" => time2str ($self->{stat}[9]),
497 }, 542 },
498 $idx); 543 $idx);
499} 544}
500 545
501sub handle_file { 546sub handle_file {
502 my ($self, $queue) = @_; 547 my ($self, $queue, $tbf) = @_;
503 my $length = $self->{stat}[7]; 548 my $length = $self->{stat}[7];
504 my $hdr = { 549 my $hdr = {
505 "Last-Modified" => time2str ((stat _)[9]), 550 "Last-Modified" => time2str ((stat _)[9]),
551 "Accept-Ranges" => "bytes",
506 }; 552 };
507 553
508 my @code = (200, "ok"); 554 my @code = (200, "ok");
509 my ($l, $h); 555 my ($l, $h);
510 556
520 } 566 }
521 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; 567 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
522 } 568 }
523 $hdr->{"Content-Range"} = "bytes */$length"; 569 $hdr->{"Content-Range"} = "bytes */$length";
524 $hdr->{"Content-Length"} = $length; 570 $hdr->{"Content-Length"} = $length;
525 $self->err(416, "not satisfiable", $hdr, ""); 571 $self->err (416, "not satisfiable", $hdr, "");
526 572
527satisfiable: 573satisfiable:
528 # check for segmented downloads 574 # check for segmented downloads
529 if ($l && $::NO_SEGMENTED) { 575 if ($l && $::NO_SEGMENTED) {
530 my $timeout = $::NOW + 15; 576 my $timeout = $::NOW + 15;
531 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) { 577 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
532 if ($timeout <= $::NOW) { 578 if ($timeout <= $::NOW) {
533 $self->block($::BLOCKTIME, "segmented downloads are forbidden"); 579 $self->block ($::BLOCKTIME, "segmented downloads are forbidden");
534 #$self->err_segmented_download; 580 #$self->err_segmented_download;
535 } else { 581 } else {
536 $httpevent->wait; 582 $httpevent->wait;
537 } 583 }
538 } 584 }
549 595
550 $self->{path} =~ /\.([^.]+)$/; 596 $self->{path} =~ /\.([^.]+)$/;
551 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream"; 597 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream";
552 $hdr->{"Content-Length"} = $length; 598 $hdr->{"Content-Length"} = $length;
553 599
554 $self->response(@code, $hdr, ""); 600 $self->response (@code, $hdr, "");
555 601
556 if ($self->{method} eq "GET") { 602 if ($self->{method} eq "GET") {
557 $self->{time} = $::NOW; 603 $self->{time} = $::NOW;
604 $self->{written} = 0;
558 605
559 my $current = $Coro::current;
560
561 my ($fh, $buf, $r);
562
563 open $fh, "<", $self->{path} 606 open my $fh, "<", $self->{path}
564 or die "$self->{path}: late open failure ($!)"; 607 or die "$self->{path}: late open failure ($!)";
565 608
566 $h -= $l - 1; 609 $h -= $l - 1;
567 610
568 if (0) { # !AIO
569 if ($l) {
570 sysseek $fh, $l, 0;
571 }
572 }
573
574 my $transfer = $queue->start_transfer($h); 611 my $transfer = $queue->start_transfer ($h);
575 my $locked; 612 my $locked;
576 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size 613 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size
577 614
578 while ($h > 0) { 615 while ($h > 0) {
579 unless ($locked) { 616 unless ($locked) {
580 if ($locked ||= $transfer->try($::WAIT_INTERVAL)) { 617 if ($locked ||= $transfer->try ($::WAIT_INTERVAL)) {
581 $bufsize = $::BUFSIZE; 618 $bufsize = $::BUFSIZE;
582 $self->{time} = $::NOW; 619 $self->{time} = $::NOW;
620 $self->{written} = 0;
583 } 621 }
584 } 622 }
585 623
586 if ($blocked{$self->{remote_id}}) { 624 if ($blocked{$self->{remote_id}}) {
587 $self->{h}{connection} = "close"; 625 $self->{h}{connection} = "close";
588 die bless {}, err::; 626 die bless {}, err::;
589 } 627 }
590 628
591 if (0) { # !AIO 629 Coro::AIO::aio_read $fh, $l, ($h > $bufsize ? $bufsize : $h), my $buf, 0
592 sysread $fh, $buf, $h > $bufsize ? $bufsize : $h
593 or last; 630 or last;
594 } else { 631
595 aio_read($fh, $l, ($h > $bufsize ? $bufsize : $h), 632 $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 633 my $w = syswrite $self->{fh}, $buf
604 or last; 634 or last;
605 $::written += $w; 635 $::written += $w;
606 $self->{written} += $w; 636 $self->{written} += $w;
607 $l += $r; 637 $l += $w;
608 } 638 }
609 639
610 close $fh; 640 close $fh;
611 } 641 }
612} 642}
613 643
6141; 6441
645

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines