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.58 by root, Mon Dec 3 21:32:35 2001 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 ();
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;
187
166 $self->{time} = $::NOW; 188 $self->{time} = $::NOW;
167 189
168 weaken ($Coro::current->{conn} = $self); 190 weaken ($Coro::current->{conn} = $self);
169 191
170 $::conns++; 192 ++$::conns;
171 $::maxconns = $::conns if $::conns > $::maxconns; 193 $::maxconns = $::conns if $::conns > $::maxconns;
172 194
173 $self; 195 $self
174} 196}
175 197
176sub DESTROY { 198sub DESTROY {
177 #my $self = shift; 199 my $self = shift;
200
178 $::conns--; 201 --$::conns;
179} 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;
180 227
181sub slog { 228sub slog {
182 my $self = shift; 229 my $self = shift;
183 main::slog($_[0], "$self->{remote_id}> $_[1]"); 230 main::slog($_[0], "$self->{remote_id}> $_[1]");
184} 231}
185 232
186sub response { 233sub response {
187 my ($self, $code, $msg, $hdr, $content) = @_; 234 my ($self, $code, $msg, $hdr, $content) = @_;
188 my $res = "HTTP/1.1 $code $msg\015\012"; 235 my $res = "HTTP/1.1 $code $msg\015\012";
236 my $GZ = "";
189 237
190 if (exists $hdr->{Connection}) { 238 if (exists $hdr->{Connection}) {
191 if ($hdr->{Connection} =~ /close/) { 239 if ($hdr->{Connection} =~ /close/) {
192 $self->{h}{connection} = "close" 240 $self->{h}{connection} = "close"
193 } 241 }
199 $self->{h}{connection} = "close" 247 $self->{h}{connection} = "close"
200 } 248 }
201 } 249 }
202 } 250 }
203 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
204 $res .= "Date: $HTTP_NOW\015\012"; 265 $res .= "Date: $HTTP_NOW\015\012";
266 $res .= "Server: $::NAME\015\012";
205 267
206 while (my ($h, $v) = each %$hdr) { 268 while (my ($h, $v) = each %$hdr) {
207 $res .= "$h: $v\015\012" 269 $res .= "$h: $v\015\012"
208 } 270 }
209 $res .= "\015\012"; 271 $res .= "\015\012";
210 272
211 $res .= $content if defined $content and $self->{method} ne "HEAD"; 273 $res .= $content if defined $content and $self->{method} ne "HEAD";
212 274
213 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).
214 " $self->{remote_id} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}. 276 " $self->{remote_id} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}.$GZ.
215 " \"$self->{h}{referer}\"\n"; 277 " \"$self->{h}{referer}\"\n";
216 278
217 print $accesslog $log if $accesslog; 279 print $::accesslog $log if $::accesslog;
218 print STDERR $log; 280 print STDERR $log;
219 281
220 $self->{written} += 282 $tbf_top->request(length $res, 1e6);
221 print {$self->{fh}} $res; 283 $self->{written} += print {$self->{fh}} $res;
222} 284}
223 285
224sub err { 286sub err {
225 my $self = shift; 287 my $self = shift;
226 my ($code, $msg, $hdr, $content) = @_; 288 my ($code, $msg, $hdr, $content) = @_;
230 $hdr->{"Content-Type"} = "text/plain"; 292 $hdr->{"Content-Type"} = "text/plain";
231 $hdr->{"Content-Length"} = length $content; 293 $hdr->{"Content-Length"} = length $content;
232 } 294 }
233 $hdr->{"Connection"} = "close"; 295 $hdr->{"Connection"} = "close";
234 296
235 $self->response($code, $msg, $hdr, $content); 297 $self->response ($code, $msg, $hdr, $content);
236 298
237 die bless {}, err::; 299 die bless {}, err::
238} 300}
239 301
240sub handle { 302sub handle {
241 my $self = shift; 303 my $self = shift;
242 my $fh = $self->{fh}; 304 my $fh = $self->{fh};
243 305
244 my $host; 306 my $host;
245 307
246 $fh->timeout($::REQ_TIMEOUT); 308 $fh->timeout($::REQ_TIMEOUT);
247 while() { 309 while () {
248 $self->{reqs}++; 310 $self->{reqs}++;
249 311
250 # read request and parse first line 312 # read request and parse first line
251 my $req = $fh->readline("\015\012\015\012"); 313 my $req = $fh->readline("\015\012\015\012");
252 314
281 my (%hdr, $h, $v); 343 my (%hdr, $h, $v);
282 344
283 $hdr{lc $1} .= ",$2" 345 $hdr{lc $1} .= ",$2"
284 while $req =~ /\G 346 while $req =~ /\G
285 ([^:\000-\040]+): 347 ([^:\000-\040]+):
286 [\008\040]* 348 [\011\040]*
287 ((?: [^\015\012]+ | \015\012[\008\040] )*) 349 ((?: [^\015\012]+ | \015\012[\011\040] )*)
288 \015\012 350 \015\012
289 /gxc; 351 /gxc;
290 352
291 $req =~ /\G\015\012$/ 353 $req =~ /\G\015\012$/
292 or $self->err(400, "bad request"); 354 or $self->err(400, "bad request");
361# uri => path mapping 423# uri => path mapping
362sub map_uri { 424sub map_uri {
363 my $self = shift; 425 my $self = shift;
364 my $host = $self->{server_name}; 426 my $host = $self->{server_name};
365 my $uri = $self->{uri}; 427 my $uri = $self->{uri};
428
429 $host =~ /[\/\\]/
430 and $self->err(400, "bad request");
366 431
367 # some massaging, also makes it more secure 432 # some massaging, also makes it more secure
368 $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;
369 $uri =~ s%//+%/%g; 434 $uri =~ s%//+%/%g;
370 $uri =~ s%/\.(?=/|$)%%g; 435 $uri =~ s%/\.(?=/|$)%%g;
414 479
415 if ($self->{name} =~ s%^/internal/([^/]+)%%) { 480 if ($self->{name} =~ s%^/internal/([^/]+)%%) {
416 if ($::internal{$1}) { 481 if ($::internal{$1}) {
417 $::internal{$1}->($self); 482 $::internal{$1}->($self);
418 } else { 483 } else {
419 $self->err(404, "not found"); 484 $self->err (404, "not found");
420 } 485 }
421 } else { 486 } else {
422 487
423 stat $path 488 stat $path
424 or $self->err(404, "not found"); 489 or $self->err (404, "not found");
425 490
426 $self->{stat} = [stat _]; 491 $self->{stat} = [stat _];
427 492
428 # idiotic netscape sends idiotic headers AGAIN 493 # idiotic netscape sends idiotic headers AGAIN
429 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/ 494 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
432 if (-d _ && -r _) { 497 if (-d _ && -r _) {
433 # directory 498 # directory
434 if ($path !~ /\/$/) { 499 if ($path !~ /\/$/) {
435 # create a redirect to get the trailing "/" 500 # create a redirect to get the trailing "/"
436 # we don't try to avoid the :80 501 # we don't try to avoid the :80
437 $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}/" });
438 } else { 503 } else {
439 $ims < $self->{stat}[9] 504 $ims < $self->{stat}[9]
440 or $self->err(304, "not modified"); 505 or $self->err (304, "not modified");
441 506
442 if (-r "$path/index.html") { 507 if (-r "$path/index.html") {
443 # replace directory "size" by index.html filesize 508 # replace directory "size" by index.html filesize
444 $self->{stat} = [stat ($self->{path} .= "/index.html")]; 509 $self->{stat} = [stat ($self->{path} .= "/index.html")];
445 $self->handle_file($queue_index); 510 $self->handle_file ($queue_index, $tbf_top);
446 } else { 511 } else {
447 $self->handle_dir; 512 $self->handle_dir;
448 } 513 }
449 } 514 }
450 } elsif (-f _ && -r _) { 515 } elsif (-f _ && -r _) {
451 -x _ and $self->err(403, "forbidden"); 516 -x _ and $self->err (403, "forbidden");
452 517
453 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 518 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
454 my $timeout = $::NOW + 10; 519 my $timeout = $::NOW + 10;
455 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 520 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
456 if ($timeout < $::NOW) { 521 if ($timeout < $::NOW) {
459 $httpevent->wait; 524 $httpevent->wait;
460 } 525 }
461 } 526 }
462 } 527 }
463 528
464 $self->handle_file($queue_file); 529 $self->handle_file ($queue_file, $tbf_top);
465 } else { 530 } else {
466 $self->err(404, "not found"); 531 $self->err (404, "not found");
467 } 532 }
468 } 533 }
469} 534}
470 535
471sub handle_dir { 536sub handle_dir {
472 my $self = shift; 537 my $self = shift;
473 my $idx = $self->diridx; 538 my $idx = $self->diridx;
474 539
475 $self->response(200, "ok", 540 $self->response (200, "ok",
476 { 541 {
477 "Content-Type" => "text/html", 542 "Content-Type" => "text/html; charset=utf-8",
478 "Content-Length" => length $idx, 543 "Content-Length" => length $idx,
479 "Last-Modified" => time2str ($self->{stat}[9]), 544 "Last-Modified" => time2str ($self->{stat}[9]),
480 }, 545 },
481 $idx); 546 $idx);
482} 547}
483 548
484sub handle_file { 549sub handle_file {
485 my ($self, $queue) = @_; 550 my ($self, $queue, $tbf) = @_;
486 my $length = $self->{stat}[7]; 551 my $length = $self->{stat}[7];
487 my $hdr = { 552 my $hdr = {
488 "Last-Modified" => time2str ((stat _)[9]), 553 "Last-Modified" => time2str ((stat _)[9]),
554 "Accept-Ranges" => "bytes",
489 }; 555 };
490 556
491 my @code = (200, "ok"); 557 my @code = (200, "ok");
492 my ($l, $h); 558 my ($l, $h);
493 559
494 if ($self->{h}{range} =~ /^bytes=(.*)$/) { 560 if ($self->{h}{range} =~ /^bytes=(.*)$/i) {
495 for (split /,/, $1) { 561 for (split /,/, $1) {
496 if (/^-(\d+)$/) { 562 if (/^-(\d+)$/) {
497 ($l, $h) = ($length - $1, $length - 1); 563 ($l, $h) = ($length - $1, $length - 1);
498 } elsif (/^(\d+)-(\d*)$/) { 564 } elsif (/^(\d+)-(\d*)$/) {
499 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1); 565 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1);
503 } 569 }
504 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; 570 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
505 } 571 }
506 $hdr->{"Content-Range"} = "bytes */$length"; 572 $hdr->{"Content-Range"} = "bytes */$length";
507 $hdr->{"Content-Length"} = $length; 573 $hdr->{"Content-Length"} = $length;
508 $self->err(416, "not satisfiable", $hdr, ""); 574 $self->err (416, "not satisfiable", $hdr, "");
509 575
510satisfiable: 576satisfiable:
511 # check for segmented downloads 577 # check for segmented downloads
512 if ($l && $::NO_SEGMENTED) { 578 if ($l && $::NO_SEGMENTED) {
513 my $timeout = $::NOW + 15; 579 my $timeout = $::NOW + 15;
514 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) { 580 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
515 if ($timeout <= $::NOW) { 581 if ($timeout <= $::NOW) {
516 $self->block($::BLOCKTIME, "segmented downloads are forbidden"); 582 $self->block ($::BLOCKTIME, "segmented downloads are forbidden");
517 #$self->err_segmented_download; 583 #$self->err_segmented_download;
518 } else { 584 } else {
519 $httpevent->wait; 585 $httpevent->wait;
520 } 586 }
521 } 587 }
532 598
533 $self->{path} =~ /\.([^.]+)$/; 599 $self->{path} =~ /\.([^.]+)$/;
534 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream"; 600 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream";
535 $hdr->{"Content-Length"} = $length; 601 $hdr->{"Content-Length"} = $length;
536 602
537 $self->response(@code, $hdr, ""); 603 $self->response (@code, $hdr, "");
538 604
539 if ($self->{method} eq "GET") { 605 if ($self->{method} eq "GET") {
540 $self->{time} = $::NOW; 606 $self->{time} = $::NOW;
607 $self->{written} = 0;
541 608
542 my $current = $Coro::current;
543
544 my ($fh, $buf, $r);
545
546 open $fh, "<", $self->{path} 609 open my $fh, "<", $self->{path}
547 or die "$self->{path}: late open failure ($!)"; 610 or die "$self->{path}: late open failure ($!)";
548 611
549 $h -= $l - 1; 612 $h -= $l - 1;
550 613
551 if (0) { # !AIO
552 if ($l) {
553 sysseek $fh, $l, 0;
554 }
555 }
556
557 my $transfer = $queue->start_transfer($h); 614 my $transfer = $queue->start_transfer ($h);
558 my $locked; 615 my $locked;
559 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size 616 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size
560 617
561 while ($h > 0) { 618 while ($h > 0) {
562 unless ($locked) { 619 unless ($locked) {
563 if ($locked ||= $transfer->try($::WAIT_INTERVAL)) { 620 if ($locked ||= $transfer->try ($::WAIT_INTERVAL)) {
564 $bufsize = $::BUFSIZE; 621 $bufsize = $::BUFSIZE;
565 $self->{time} = $::NOW; 622 $self->{time} = $::NOW;
623 $self->{written} = 0;
566 } 624 }
567 } 625 }
568 626
569 if ($blocked{$self->{remote_id}}) { 627 if ($blocked{$self->{remote_id}}) {
570 $self->{h}{connection} = "close"; 628 $self->{h}{connection} = "close";
571 die bless {}, err:: 629 die bless {}, err::;
572 } 630 }
573 631
574 if (0) { # !AIO 632 Coro::AIO::aio_read $fh, $l, ($h > $bufsize ? $bufsize : $h), my $buf, 0
575 sysread $fh, $buf, $h > $bufsize ? $bufsize : $h
576 or last; 633 or last;
577 } else { 634
578 aio_read($fh, $l, ($h > $bufsize ? $bufsize : $h), 635 $tbf->request (length $buf);
579 $buf, 0, sub { 636 my $w = $self->{fh}->syswrite ($buf)
580 $r = $_[0];
581 Coro::ready($current);
582 });
583 &Coro::schedule;
584 last unless $r;
585 }
586 my $w = syswrite $self->{fh}, $buf
587 or last; 637 or last;
588 $::written += $w; 638 $::written += $w;
589 $self->{written} += $w; 639 $self->{written} += $w;
590 $l += $r; 640 $l += $w;
591 } 641 }
592 642
593 close $fh; 643 close $fh;
594 } 644 }
595} 645}
596 646
5971; 6471
648

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines