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.69 by root, Wed May 22 00:33:26 2002 UTC vs.
Revision 1.89 by root, Sun Jan 24 20:44:34 2010 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 => 150000; 65our $tbf_top = new tbf rate => $TBF_RATE || 100000;
61 66
62my $unused_bytes = 0; 67my $unused_bytes = 0;
63my $unused_last = time; 68my $unused_last = time;
64 69
65sub unused_bandwidth { 70sub unused_bandwidth {
70 $queue_file->force_wake_next; 75 $queue_file->force_wake_next;
71 slog 1, "forced filetransfer due to unused bandwidth"; 76 slog 1, "forced filetransfer due to unused bandwidth";
72 } 77 }
73} 78}
74 79
75my @newcons;
76my @pool;
77
78# one "execution thread"
79sub handler {
80 while () {
81 if (@newcons) {
82 eval {
83 conn->new(@{pop @newcons})->handle;
84 };
85 slog 1, "$@" if $@ && !ref $@;
86
87 $httpevent->broadcast; # only for testing, but doesn't matter much
88
89 $connections->up;
90 } else {
91 last if @pool >= $MAX_POOL;
92 push @pool, $Coro::current;
93 schedule;
94 }
95 }
96}
97
98sub listen_on { 80sub listen_on {
99 my $listen = $_[0]; 81 my $listen = $_[0];
100 82
101 push @listen_sockets, $listen; 83 push @listen_sockets, $listen;
102 84
103 # the "main thread" 85 # the "main thread"
104 async { 86 async {
105 slog 1, "accepting connections"; 87 slog 1, "accepting connections";
106 while () { 88 while () {
107 $connections->down; 89 $connections->down;
108 push @newcons, [$listen->accept]; 90 my @conn = $listen->accept;
109 #slog 3, "accepted @$connections ".scalar(@pool); 91 #slog 3, "accepted @$connections ".scalar(@pool);
110 if (@pool) { 92
111 (pop @pool)->ready; 93 async_pool {
112 } else { 94 eval {
113 async \&handler; 95 conn->new (@conn)->handle;
114 } 96 };
97 slog 1, "$@" if $@ && !ref $@;
115 98
99 $httpevent->broadcast; # only for testing, but doesn't matter much
100
101 $connections->up;
102 }
116 } 103 }
117 }; 104 };
118} 105}
119 106
120my $http_port = new Coro::Socket 107my $http_port = new Coro::Socket
121 LocalAddr => $SERVER_HOST, 108 LocalAddr => $SERVER_HOST,
122 LocalPort => $SERVER_PORT, 109 LocalPort => $SERVER_PORT,
123 ReuseAddr => 1, 110 ReuseAddr => 1,
124 Listen => 50, 111 Listen => 50,
125 or die "unable to start server"; 112 or die "unable to start server";
126 113
127listen_on $http_port; 114listen_on $http_port;
128 115
129if ($SERVER_PORT2) { 116if ($SERVER_PORT2) {
130 my $http_port = new Coro::Socket 117 my $http_port = new Coro::Socket
131 LocalAddr => $SERVER_HOST, 118 LocalAddr => $SERVER_HOST,
132 LocalPort => $SERVER_PORT2, 119 LocalPort => $SERVER_PORT2,
133 ReuseAddr => 1, 120 ReuseAddr => 1,
134 Listen => 50, 121 Listen => 50,
135 or die "unable to start server"; 122 or die "unable to start server";
136 123
137 listen_on $http_port; 124 listen_on $http_port;
138} 125}
139 126
140package conn; 127package conn;
128
129use strict;
130use bytes;
141 131
142use Socket; 132use Socket;
143use HTTP::Date; 133use HTTP::Date;
144use Convert::Scalar 'weaken'; 134use Convert::Scalar 'weaken';
145use Linux::AIO; 135use IO::AIO;
146 136
147Linux::AIO::min_parallel $::AIO_PARALLEL; 137IO::AIO::min_parallel $::AIO_PARALLEL;
148 138
149Event->io(fd => Linux::AIO::poll_fileno, 139our $AIO_WATCHER = EV::io IO::AIO::poll_fileno, EV::READ, \&IO::AIO::poll_cb;
150 poll => 'r', async => 1,
151 cb => \&Linux::AIO::poll_cb);
152 140
153our %conn; # $conn{ip}{self} => connobj 141our %conn; # $conn{ip}{self} => connobj
154our %uri; # $uri{ip}{uri}{self} 142our %uri; # $uri{ip}{uri}{self}
155our %blocked; 143our %blocked;
156our %mimetype; 144our %mimetype;
157 145
158sub read_mimetypes { 146sub read_mimetypes {
159 local *M;
160 if (open M, "<mime_types") { 147 if (open my $fh, "<mime_types") {
161 while (<M>) { 148 while (<$fh>) {
162 if (/^([^#]\S+)\t+(\S+)$/) { 149 if (/^([^#]\S+)\t+(\S+)$/) {
163 $mimetype{lc $1} = $2; 150 $mimetype{lc $1} = $2;
164 } 151 }
165 } 152 }
166 } else { 153 } else {
174 my $class = shift; 161 my $class = shift;
175 my $fh = shift; 162 my $fh = shift;
176 my $peername = shift; 163 my $peername = shift;
177 my $self = bless { fh => $fh }, $class; 164 my $self = bless { fh => $fh }, $class;
178 my (undef, $iaddr) = unpack_sockaddr_in $peername 165 my (undef, $iaddr) = unpack_sockaddr_in $peername
179 or $self->err(500, "unable to decode peername"); 166 or $self->err (500, "unable to decode peername");
180 167
181 $self->{remote_addr} = 168 $self->{remote_addr} =
182 $self->{remote_id} = inet_ntoa $iaddr; 169 $self->{remote_id} = inet_ntoa $iaddr;
183 170
184 $self->{time} = $::NOW; 171 $self->{time} = $::NOW;
185 172
186 weaken ($Coro::current->{conn} = $self); 173 weaken ($Coro::current->{conn} = $self);
187 174
188 $::conns++; 175 ++$::conns;
189 $::maxconns = $::conns if $::conns > $::maxconns; 176 $::maxconns = $::conns if $::conns > $::maxconns;
190 177
191 $self; 178 $self
192} 179}
193 180
194sub DESTROY { 181sub DESTROY {
195 #my $self = shift; 182 my $self = shift;
183
196 $::conns--; 184 --$::conns;
197} 185}
186
187sub prune_cache {
188 my $hash = $_[0];
189
190 for (keys %$hash) {
191 if (ref $hash->{$_} eq HASH::) {
192 prune_cache($hash->{$_});
193 unless (scalar keys %{$hash->{$_}}) {
194 delete $hash->{$_};
195 }
196 }
197 }
198}
199
200sub prune_caches {
201 prune_cache \%conn;
202 prune_cache \%uri;
203
204 for (keys %blocked) {
205 delete $blocked{$_} unless $blocked{$_}[0] > $::NOW;
206 }
207}
208
209our $PRUNE_WATCHER = EV::timer 60, 60, \&prune_caches;
198 210
199sub slog { 211sub slog {
200 my $self = shift; 212 my $self = shift;
201 main::slog($_[0], "$self->{remote_id}> $_[1]"); 213 main::slog($_[0], "$self->{remote_id}> $_[1]");
202} 214}
232 $hdr->{"Content-Length"} = length $content; 244 $hdr->{"Content-Length"} = length $content;
233 $GZ = sprintf "GZ%02d", 100 - 100*((length $content) / $orig); 245 $GZ = sprintf "GZ%02d", 100 - 100*((length $content) / $orig);
234 } 246 }
235 247
236 $res .= "Date: $HTTP_NOW\015\012"; 248 $res .= "Date: $HTTP_NOW\015\012";
249 $res .= "Server: $::NAME\015\012";
237 250
238 while (my ($h, $v) = each %$hdr) { 251 while (my ($h, $v) = each %$hdr) {
239 $res .= "$h: $v\015\012" 252 $res .= "$h: $v\015\012"
240 } 253 }
241 $res .= "\015\012"; 254 $res .= "\015\012";
262 $hdr->{"Content-Type"} = "text/plain"; 275 $hdr->{"Content-Type"} = "text/plain";
263 $hdr->{"Content-Length"} = length $content; 276 $hdr->{"Content-Length"} = length $content;
264 } 277 }
265 $hdr->{"Connection"} = "close"; 278 $hdr->{"Connection"} = "close";
266 279
267 $self->response($code, $msg, $hdr, $content); 280 $self->response ($code, $msg, $hdr, $content);
268 281
269 die bless {}, err::; 282 die bless {}, err::
270} 283}
271 284
272sub handle { 285sub handle {
273 my $self = shift; 286 my $self = shift;
274 my $fh = $self->{fh}; 287 my $fh = $self->{fh};
275 288
276 my $host; 289 my $host;
277 290
278 $fh->timeout($::REQ_TIMEOUT); 291 $fh->timeout($::REQ_TIMEOUT);
279 while() { 292 while () {
280 $self->{reqs}++; 293 $self->{reqs}++;
281 294
282 # read request and parse first line 295 # read request and parse first line
283 my $req = $fh->readline("\015\012\015\012"); 296 my $req = $fh->readline("\015\012\015\012");
284 297
393# uri => path mapping 406# uri => path mapping
394sub map_uri { 407sub map_uri {
395 my $self = shift; 408 my $self = shift;
396 my $host = $self->{server_name}; 409 my $host = $self->{server_name};
397 my $uri = $self->{uri}; 410 my $uri = $self->{uri};
411
412 $host =~ /[\/\\]/
413 and $self->err(400, "bad request");
398 414
399 # some massaging, also makes it more secure 415 # some massaging, also makes it more secure
400 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge; 416 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge;
401 $uri =~ s%//+%/%g; 417 $uri =~ s%//+%/%g;
402 $uri =~ s%/\.(?=/|$)%%g; 418 $uri =~ s%/\.(?=/|$)%%g;
446 462
447 if ($self->{name} =~ s%^/internal/([^/]+)%%) { 463 if ($self->{name} =~ s%^/internal/([^/]+)%%) {
448 if ($::internal{$1}) { 464 if ($::internal{$1}) {
449 $::internal{$1}->($self); 465 $::internal{$1}->($self);
450 } else { 466 } else {
451 $self->err(404, "not found"); 467 $self->err (404, "not found");
452 } 468 }
453 } else { 469 } else {
454 470
455 stat $path 471 Coro::AIO::aio_stat $path
456 or $self->err(404, "not found"); 472 and $self->err (404, "not found");
457 473
458 $self->{stat} = [stat _]; 474 $self->{stat} = [stat _];
459 475
460 # idiotic netscape sends idiotic headers AGAIN 476 # idiotic netscape sends idiotic headers AGAIN
461 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/ 477 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
464 if (-d _ && -r _) { 480 if (-d _ && -r _) {
465 # directory 481 # directory
466 if ($path !~ /\/$/) { 482 if ($path !~ /\/$/) {
467 # create a redirect to get the trailing "/" 483 # create a redirect to get the trailing "/"
468 # we don't try to avoid the :80 484 # we don't try to avoid the :80
469 $self->err(301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" }); 485 $self->err (301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" });
470 } else { 486 } else {
471 $ims < $self->{stat}[9] 487 $ims < $self->{stat}[9]
472 or $self->err(304, "not modified"); 488 or $self->err (304, "not modified");
473 489
474 if (-r "$path/index.html") { 490 if (-r "$path/index.html") {
475 # replace directory "size" by index.html filesize 491 # replace directory "size" by index.html filesize
476 $self->{stat} = [stat ($self->{path} .= "/index.html")]; 492 $self->{stat} = [stat ($self->{path} .= "/index.html")];
477 $self->handle_file($queue_index, $tbf_top); 493 $self->handle_file ($queue_index, $tbf_top);
478 } else { 494 } else {
479 $self->handle_dir; 495 $self->handle_dir;
480 } 496 }
481 } 497 }
482 } elsif (-f _ && -r _) { 498 } elsif (-f _ && -r _) {
483 -x _ and $self->err(403, "forbidden"); 499 -x _ and $self->err (403, "forbidden");
484 500
485 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 501 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
486 my $timeout = $::NOW + 10; 502 my $timeout = $::NOW + 10;
487 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 503 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
488 if ($timeout < $::NOW) { 504 if ($timeout < $::NOW) {
491 $httpevent->wait; 507 $httpevent->wait;
492 } 508 }
493 } 509 }
494 } 510 }
495 511
496 $self->handle_file($queue_file, $tbf_top); 512 $self->handle_file ($queue_file, $tbf_top);
497 } else { 513 } else {
498 $self->err(404, "not found"); 514 $self->err (404, "not found");
499 } 515 }
500 } 516 }
501} 517}
502 518
503sub handle_dir { 519sub handle_dir {
504 my $self = shift; 520 my $self = shift;
505 my $idx = $self->diridx; 521 my $idx = $self->diridx;
506 522
507 $self->response(200, "ok", 523 $self->response (200, "ok",
508 { 524 {
509 "Content-Type" => "text/html", 525 "Content-Type" => "text/html; charset=utf-8",
510 "Content-Length" => length $idx, 526 "Content-Length" => length $idx,
511 "Last-Modified" => time2str ($self->{stat}[9]), 527 "Last-Modified" => time2str ($self->{stat}[9]),
512 }, 528 },
513 $idx); 529 $idx);
514} 530}
515 531
516sub handle_file { 532sub handle_file {
517 my ($self, $queue, $tbf) = @_; 533 my ($self, $queue, $tbf) = @_;
518 my $length = $self->{stat}[7]; 534 my $length = $self->{stat}[7];
519 my $hdr = { 535 my $hdr = {
520 "Last-Modified" => time2str ((stat _)[9]), 536 "Last-Modified" => time2str ((stat _)[9]),
537 "Accept-Ranges" => "bytes",
521 }; 538 };
522 539
523 my @code = (200, "ok"); 540 my @code = (200, "ok");
524 my ($l, $h); 541 my ($l, $h);
525 542
526 if ($self->{h}{range} =~ /^bytes=(.*)$/) { 543 if ($self->{h}{range} =~ /^bytes=(.*)$/i) {
527 for (split /,/, $1) { 544 for (split /,/, $1) {
528 if (/^-(\d+)$/) { 545 if (/^-(\d+)$/) {
529 ($l, $h) = ($length - $1, $length - 1); 546 ($l, $h) = ($length - $1, $length - 1);
530 } elsif (/^(\d+)-(\d*)$/) { 547 } elsif (/^(\d+)-(\d*)$/) {
531 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1); 548 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1);
535 } 552 }
536 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; 553 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
537 } 554 }
538 $hdr->{"Content-Range"} = "bytes */$length"; 555 $hdr->{"Content-Range"} = "bytes */$length";
539 $hdr->{"Content-Length"} = $length; 556 $hdr->{"Content-Length"} = $length;
540 $self->err(416, "not satisfiable", $hdr, ""); 557 $self->err (416, "not satisfiable", $hdr, "");
541 558
542satisfiable: 559satisfiable:
543 # check for segmented downloads 560 # check for segmented downloads
544 if ($l && $::NO_SEGMENTED) { 561 if ($l && $::NO_SEGMENTED) {
545 my $timeout = $::NOW + 15; 562 my $timeout = $::NOW + 15;
546 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) { 563 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
547 if ($timeout <= $::NOW) { 564 if ($timeout <= $::NOW) {
548 $self->block($::BLOCKTIME, "segmented downloads are forbidden"); 565 $self->block ($::BLOCKTIME, "segmented downloads are forbidden");
549 #$self->err_segmented_download; 566 #$self->err_segmented_download;
550 } else { 567 } else {
551 $httpevent->wait; 568 $httpevent->wait;
552 } 569 }
553 } 570 }
564 581
565 $self->{path} =~ /\.([^.]+)$/; 582 $self->{path} =~ /\.([^.]+)$/;
566 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream"; 583 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream";
567 $hdr->{"Content-Length"} = $length; 584 $hdr->{"Content-Length"} = $length;
568 585
569 $self->response(@code, $hdr, ""); 586 $self->response (@code, $hdr, "");
570 587
571 if ($self->{method} eq "GET") { 588 if ($self->{method} eq "GET") {
572 $self->{time} = $::NOW; 589 $self->{time} = $::NOW;
590 $self->{written} = 0;
573 591
574 my $current = $Coro::current;
575
576 my ($fh, $buf, $r);
577
578 open $fh, "<", $self->{path} 592 open my $fh, "<", $self->{path}
579 or die "$self->{path}: late open failure ($!)"; 593 or die "$self->{path}: late open failure ($!)";
580 594
581 $h -= $l - 1; 595 $h -= $l - 1;
582 596
583 if (0) { # !AIO
584 if ($l) {
585 sysseek $fh, $l, 0;
586 }
587 }
588
589 my $transfer = $queue->start_transfer($h); 597 my $transfer = $queue->start_transfer ($h);
590 my $locked; 598 my $locked;
591 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size 599 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size
592 600
593 while ($h > 0) { 601 while ($h > 0) {
594 unless ($locked) { 602 unless ($locked) {
595 if ($locked ||= $transfer->try($::WAIT_INTERVAL)) { 603 if ($locked ||= $transfer->try ($::WAIT_INTERVAL)) {
596 $bufsize = $::BUFSIZE; 604 $bufsize = $::BUFSIZE;
597 $self->{time} = $::NOW; 605 $self->{time} = $::NOW;
606 $self->{written} = 0;
598 } 607 }
599 } 608 }
600 609
601 if ($blocked{$self->{remote_id}}) { 610 if ($blocked{$self->{remote_id}}) {
602 $self->{h}{connection} = "close"; 611 $self->{h}{connection} = "close";
603 die bless {}, err::; 612 die bless {}, err::;
604 } 613 }
605 614
606 if (0) { # !AIO 615 Coro::AIO::aio_read $fh, $l, ($h > $bufsize ? $bufsize : $h), my $buf, 0
607 sysread $fh, $buf, $h > $bufsize ? $bufsize : $h
608 or last; 616 or last;
609 } else {
610 aio_read($fh, $l, ($h > $bufsize ? $bufsize : $h),
611 $buf, 0, sub {
612 $r = $_[0];
613 Coro::ready($current);
614 });
615 &Coro::schedule;
616 last unless $r;
617 }
618 617
619 $tbf->request(length $buf); 618 $tbf->request (length $buf);
620 my $w = syswrite $self->{fh}, $buf 619 my $w = $self->{fh}->syswrite ($buf)
621 or last; 620 or last;
622 $::written += $w; 621 $::written += $w;
623 $self->{written} += $w; 622 $self->{written} += $w;
624 $l += $r; 623 $l += $w;
625 } 624 }
626 625
627 close $fh; 626 close $fh;
628 } 627 }
629} 628}
630 629
6311; 6301
631

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines