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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines