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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines