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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines