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.80 by root, Fri Dec 1 04:18:32 2006 UTC vs.
Revision 1.88 by root, Thu Nov 20 14:33:57 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 (); 6use Coro::AIO ();
7 7
8use HTTP::Date; 8use HTTP::Date;
26our $HTTP_NOW; 26our $HTTP_NOW;
27 27
28our $ERROR_LOG; 28our $ERROR_LOG;
29our $ACCESS_LOG; 29our $ACCESS_LOG;
30 30
31Event->timer(interval => 1, hard => 1, cb => sub { 31our $update_time = EV::periodic 0, 1, undef, sub {
32 $NOW = time; 32 $NOW = time;
33 $HTTP_NOW = time2str $NOW; 33 $HTTP_NOW = time2str $NOW;
34})->now; 34};
35$update_time->invoke;
35 36
36if ($ERROR_LOG) { 37if ($ERROR_LOG) {
37 use IO::Handle; 38 use IO::Handle;
38 open $errorlog, ">>$ERROR_LOG" 39 open $errorlog, ">>$ERROR_LOG"
39 or die "$ERROR_LOG: $!"; 40 or die "$ERROR_LOG: $!";
74 $queue_file->force_wake_next; 75 $queue_file->force_wake_next;
75 slog 1, "forced filetransfer due to unused bandwidth"; 76 slog 1, "forced filetransfer due to unused bandwidth";
76 } 77 }
77} 78}
78 79
79my @newcons;
80my @pool;
81
82# one "execution thread"
83sub handler {
84 while () {
85 if (@newcons) {
86 eval {
87 conn->new(@{pop @newcons})->handle;
88 };
89 slog 1, "$@" if $@ && !ref $@;
90
91 $httpevent->broadcast; # only for testing, but doesn't matter much
92
93 $connections->up;
94 } else {
95 last if @pool >= $MAX_POOL;
96 push @pool, $Coro::current;
97 schedule;
98 }
99 }
100}
101
102sub listen_on { 80sub listen_on {
103 my $listen = $_[0]; 81 my $listen = $_[0];
104 82
105 push @listen_sockets, $listen; 83 push @listen_sockets, $listen;
106 84
107 # the "main thread" 85 # the "main thread"
108 async { 86 async {
109 slog 1, "accepting connections"; 87 slog 1, "accepting connections";
110 while () { 88 while () {
111 $connections->down; 89 $connections->down;
112 push @newcons, [$listen->accept]; 90 my @conn = $listen->accept;
113 #slog 3, "accepted @$connections ".scalar(@pool); 91 #slog 3, "accepted @$connections ".scalar(@pool);
114 if (@pool) { 92
115 (pop @pool)->ready; 93 async_pool {
116 } else { 94 eval {
117 async \&handler; 95 conn->new (@conn)->handle;
96 };
97 slog 1, "$@" if $@ && !ref $@;
98
99 $httpevent->broadcast; # only for testing, but doesn't matter much
100
101 $connections->up;
118 } 102 }
119 } 103 }
120 }; 104 };
121} 105}
122 106
123my $http_port = new Coro::Socket 107my $http_port = new Coro::Socket
124 LocalAddr => $SERVER_HOST, 108 LocalAddr => $SERVER_HOST,
125 LocalPort => $SERVER_PORT, 109 LocalPort => $SERVER_PORT,
126 ReuseAddr => 1, 110 ReuseAddr => 1,
127 Listen => 50, 111 Listen => 50,
128 or die "unable to start server"; 112 or die "unable to start server";
129 113
130listen_on $http_port; 114listen_on $http_port;
131 115
132if ($SERVER_PORT2) { 116if ($SERVER_PORT2) {
133 my $http_port = new Coro::Socket 117 my $http_port = new Coro::Socket
134 LocalAddr => $SERVER_HOST, 118 LocalAddr => $SERVER_HOST,
135 LocalPort => $SERVER_PORT2, 119 LocalPort => $SERVER_PORT2,
136 ReuseAddr => 1, 120 ReuseAddr => 1,
137 Listen => 50, 121 Listen => 50,
138 or die "unable to start server"; 122 or die "unable to start server";
139 123
140 listen_on $http_port; 124 listen_on $http_port;
141} 125}
142 126
150use Convert::Scalar 'weaken'; 134use Convert::Scalar 'weaken';
151use IO::AIO; 135use IO::AIO;
152 136
153IO::AIO::min_parallel $::AIO_PARALLEL; 137IO::AIO::min_parallel $::AIO_PARALLEL;
154 138
155Event->io (fd => IO::AIO::poll_fileno, 139our $AIO_WATCHER = EV::io IO::AIO::poll_fileno, EV::READ, \&IO::AIO::poll_cb;
156 poll => 'r', async => 1,
157 cb => \&IO::AIO::poll_cb);
158 140
159our %conn; # $conn{ip}{self} => connobj 141our %conn; # $conn{ip}{self} => connobj
160our %uri; # $uri{ip}{uri}{self} 142our %uri; # $uri{ip}{uri}{self}
161our %blocked; 143our %blocked;
162our %mimetype; 144our %mimetype;
163 145
164sub read_mimetypes { 146sub read_mimetypes {
165 local *M;
166 if (open M, "<mime_types") { 147 if (open my $fh, "<mime_types") {
167 while (<M>) { 148 while (<$fh>) {
168 if (/^([^#]\S+)\t+(\S+)$/) { 149 if (/^([^#]\S+)\t+(\S+)$/) {
169 $mimetype{lc $1} = $2; 150 $mimetype{lc $1} = $2;
170 } 151 }
171 } 152 }
172 } else { 153 } else {
180 my $class = shift; 161 my $class = shift;
181 my $fh = shift; 162 my $fh = shift;
182 my $peername = shift; 163 my $peername = shift;
183 my $self = bless { fh => $fh }, $class; 164 my $self = bless { fh => $fh }, $class;
184 my (undef, $iaddr) = unpack_sockaddr_in $peername 165 my (undef, $iaddr) = unpack_sockaddr_in $peername
185 or $self->err(500, "unable to decode peername"); 166 or $self->err (500, "unable to decode peername");
186 167
187 $self->{remote_addr} = 168 $self->{remote_addr} =
188 $self->{remote_id} = inet_ntoa $iaddr; 169 $self->{remote_id} = inet_ntoa $iaddr;
189 170
190 $self->{time} = $::NOW; 171 $self->{time} = $::NOW;
191 172
192 weaken ($Coro::current->{conn} = $self); 173 weaken ($Coro::current->{conn} = $self);
193 174
194 $::conns++; 175 ++$::conns;
195 $::maxconns = $::conns if $::conns > $::maxconns; 176 $::maxconns = $::conns if $::conns > $::maxconns;
196 177
197 $self; 178 $self
198} 179}
199 180
200sub DESTROY { 181sub DESTROY {
201 #my $self = shift; 182 my $self = shift;
183
202 $::conns--; 184 --$::conns;
203} 185}
204 186
205sub prune_cache { 187sub prune_cache {
206 my $hash = $_[0]; 188 my $hash = $_[0];
207 189
222 for (keys %blocked) { 204 for (keys %blocked) {
223 delete $blocked{$_} unless $blocked{$_}[0] > $::NOW; 205 delete $blocked{$_} unless $blocked{$_}[0] > $::NOW;
224 } 206 }
225} 207}
226 208
227Event->timer(interval => 60, cb => \&prune_caches); 209our $PRUNE_WATCHER = EV::timer 60, 60, \&prune_caches;
228 210
229sub slog { 211sub slog {
230 my $self = shift; 212 my $self = shift;
231 main::slog($_[0], "$self->{remote_id}> $_[1]"); 213 main::slog($_[0], "$self->{remote_id}> $_[1]");
232} 214}
293 $hdr->{"Content-Type"} = "text/plain"; 275 $hdr->{"Content-Type"} = "text/plain";
294 $hdr->{"Content-Length"} = length $content; 276 $hdr->{"Content-Length"} = length $content;
295 } 277 }
296 $hdr->{"Connection"} = "close"; 278 $hdr->{"Connection"} = "close";
297 279
298 $self->response($code, $msg, $hdr, $content); 280 $self->response ($code, $msg, $hdr, $content);
299 281
300 die bless {}, err::; 282 die bless {}, err::
301} 283}
302 284
303sub handle { 285sub handle {
304 my $self = shift; 286 my $self = shift;
305 my $fh = $self->{fh}; 287 my $fh = $self->{fh};
306 288
307 my $host; 289 my $host;
308 290
309 $fh->timeout($::REQ_TIMEOUT); 291 $fh->timeout($::REQ_TIMEOUT);
310 while() { 292 while () {
311 $self->{reqs}++; 293 $self->{reqs}++;
312 294
313 # read request and parse first line 295 # read request and parse first line
314 my $req = $fh->readline("\015\012\015\012"); 296 my $req = $fh->readline("\015\012\015\012");
315 297
424# uri => path mapping 406# uri => path mapping
425sub map_uri { 407sub map_uri {
426 my $self = shift; 408 my $self = shift;
427 my $host = $self->{server_name}; 409 my $host = $self->{server_name};
428 my $uri = $self->{uri}; 410 my $uri = $self->{uri};
411
412 $host =~ /[\/\\]/
413 and $self->err(400, "bad request");
429 414
430 # some massaging, also makes it more secure 415 # some massaging, also makes it more secure
431 $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;
432 $uri =~ s%//+%/%g; 417 $uri =~ s%//+%/%g;
433 $uri =~ s%/\.(?=/|$)%%g; 418 $uri =~ s%/\.(?=/|$)%%g;
477 462
478 if ($self->{name} =~ s%^/internal/([^/]+)%%) { 463 if ($self->{name} =~ s%^/internal/([^/]+)%%) {
479 if ($::internal{$1}) { 464 if ($::internal{$1}) {
480 $::internal{$1}->($self); 465 $::internal{$1}->($self);
481 } else { 466 } else {
482 $self->err(404, "not found"); 467 $self->err (404, "not found");
483 } 468 }
484 } else { 469 } else {
485 470
486 stat $path 471 stat $path
487 or $self->err(404, "not found"); 472 or $self->err (404, "not found");
488 473
489 $self->{stat} = [stat _]; 474 $self->{stat} = [stat _];
490 475
491 # idiotic netscape sends idiotic headers AGAIN 476 # idiotic netscape sends idiotic headers AGAIN
492 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/ 477 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
495 if (-d _ && -r _) { 480 if (-d _ && -r _) {
496 # directory 481 # directory
497 if ($path !~ /\/$/) { 482 if ($path !~ /\/$/) {
498 # create a redirect to get the trailing "/" 483 # create a redirect to get the trailing "/"
499 # we don't try to avoid the :80 484 # we don't try to avoid the :80
500 $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}/" });
501 } else { 486 } else {
502 $ims < $self->{stat}[9] 487 $ims < $self->{stat}[9]
503 or $self->err(304, "not modified"); 488 or $self->err (304, "not modified");
504 489
505 if (-r "$path/index.html") { 490 if (-r "$path/index.html") {
506 # replace directory "size" by index.html filesize 491 # replace directory "size" by index.html filesize
507 $self->{stat} = [stat ($self->{path} .= "/index.html")]; 492 $self->{stat} = [stat ($self->{path} .= "/index.html")];
508 $self->handle_file($queue_index, $tbf_top); 493 $self->handle_file ($queue_index, $tbf_top);
509 } else { 494 } else {
510 $self->handle_dir; 495 $self->handle_dir;
511 } 496 }
512 } 497 }
513 } elsif (-f _ && -r _) { 498 } elsif (-f _ && -r _) {
514 -x _ and $self->err(403, "forbidden"); 499 -x _ and $self->err (403, "forbidden");
515 500
516 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 501 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
517 my $timeout = $::NOW + 10; 502 my $timeout = $::NOW + 10;
518 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 503 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
519 if ($timeout < $::NOW) { 504 if ($timeout < $::NOW) {
522 $httpevent->wait; 507 $httpevent->wait;
523 } 508 }
524 } 509 }
525 } 510 }
526 511
527 $self->handle_file($queue_file, $tbf_top); 512 $self->handle_file ($queue_file, $tbf_top);
528 } else { 513 } else {
529 $self->err(404, "not found"); 514 $self->err (404, "not found");
530 } 515 }
531 } 516 }
532} 517}
533 518
534sub handle_dir { 519sub handle_dir {
535 my $self = shift; 520 my $self = shift;
536 my $idx = $self->diridx; 521 my $idx = $self->diridx;
537 522
538 $self->response(200, "ok", 523 $self->response (200, "ok",
539 { 524 {
540 "Content-Type" => "text/html; charset=utf-8", 525 "Content-Type" => "text/html; charset=utf-8",
541 "Content-Length" => length $idx, 526 "Content-Length" => length $idx,
542 "Last-Modified" => time2str ($self->{stat}[9]), 527 "Last-Modified" => time2str ($self->{stat}[9]),
543 }, 528 },
553 }; 538 };
554 539
555 my @code = (200, "ok"); 540 my @code = (200, "ok");
556 my ($l, $h); 541 my ($l, $h);
557 542
558 if ($self->{h}{range} =~ /^bytes=(.*)$/) { 543 if ($self->{h}{range} =~ /^bytes=(.*)$/i) {
559 for (split /,/, $1) { 544 for (split /,/, $1) {
560 if (/^-(\d+)$/) { 545 if (/^-(\d+)$/) {
561 ($l, $h) = ($length - $1, $length - 1); 546 ($l, $h) = ($length - $1, $length - 1);
562 } elsif (/^(\d+)-(\d*)$/) { 547 } elsif (/^(\d+)-(\d*)$/) {
563 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1); 548 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1);
567 } 552 }
568 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; 553 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
569 } 554 }
570 $hdr->{"Content-Range"} = "bytes */$length"; 555 $hdr->{"Content-Range"} = "bytes */$length";
571 $hdr->{"Content-Length"} = $length; 556 $hdr->{"Content-Length"} = $length;
572 $self->err(416, "not satisfiable", $hdr, ""); 557 $self->err (416, "not satisfiable", $hdr, "");
573 558
574satisfiable: 559satisfiable:
575 # check for segmented downloads 560 # check for segmented downloads
576 if ($l && $::NO_SEGMENTED) { 561 if ($l && $::NO_SEGMENTED) {
577 my $timeout = $::NOW + 15; 562 my $timeout = $::NOW + 15;
578 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) { 563 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
579 if ($timeout <= $::NOW) { 564 if ($timeout <= $::NOW) {
580 $self->block($::BLOCKTIME, "segmented downloads are forbidden"); 565 $self->block ($::BLOCKTIME, "segmented downloads are forbidden");
581 #$self->err_segmented_download; 566 #$self->err_segmented_download;
582 } else { 567 } else {
583 $httpevent->wait; 568 $httpevent->wait;
584 } 569 }
585 } 570 }
596 581
597 $self->{path} =~ /\.([^.]+)$/; 582 $self->{path} =~ /\.([^.]+)$/;
598 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream"; 583 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream";
599 $hdr->{"Content-Length"} = $length; 584 $hdr->{"Content-Length"} = $length;
600 585
601 $self->response(@code, $hdr, ""); 586 $self->response (@code, $hdr, "");
602 587
603 if ($self->{method} eq "GET") { 588 if ($self->{method} eq "GET") {
604 $self->{time} = $::NOW; 589 $self->{time} = $::NOW;
605 $self->{written} = 0; 590 $self->{written} = 0;
606 591
607 my $fh;
608
609 open $fh, "<", $self->{path} 592 open my $fh, "<", $self->{path}
610 or die "$self->{path}: late open failure ($!)"; 593 or die "$self->{path}: late open failure ($!)";
611 594
612 $h -= $l - 1; 595 $h -= $l - 1;
613 596
614 if (0) { # !AIO
615 if ($l) {
616 sysseek $fh, $l, 0;
617 }
618 }
619
620 my $transfer = $queue->start_transfer($h); 597 my $transfer = $queue->start_transfer ($h);
621 my $locked; 598 my $locked;
622 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size 599 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size
623 600
624 while ($h > 0) { 601 while ($h > 0) {
625 unless ($locked) { 602 unless ($locked) {
626 if ($locked ||= $transfer->try($::WAIT_INTERVAL)) { 603 if ($locked ||= $transfer->try ($::WAIT_INTERVAL)) {
627 $bufsize = $::BUFSIZE; 604 $bufsize = $::BUFSIZE;
628 $self->{time} = $::NOW; 605 $self->{time} = $::NOW;
629 $self->{written} = 0; 606 $self->{written} = 0;
630 } 607 }
631 } 608 }
637 614
638 Coro::AIO::aio_read $fh, $l, ($h > $bufsize ? $bufsize : $h), my $buf, 0 615 Coro::AIO::aio_read $fh, $l, ($h > $bufsize ? $bufsize : $h), my $buf, 0
639 or last; 616 or last;
640 617
641 $tbf->request (length $buf); 618 $tbf->request (length $buf);
642 my $w = syswrite $self->{fh}, $buf 619 my $w = $self->{fh}->syswrite ($buf)
643 or last; 620 or last;
644 $::written += $w; 621 $::written += $w;
645 $self->{written} += $w; 622 $self->{written} += $w;
646 $l += $w; 623 $l += $w;
647 } 624 }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines