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.95 by root, Wed Apr 24 23:49:34 2013 UTC

1use AnyEvent ();
2
1use Coro; 3use Coro;
2use Coro::Semaphore; 4use Coro::Semaphore;
5use Coro::SemaphoreSet;
3use Coro::Event; 6use Coro::EV;
4use Coro::Socket; 7use Coro::Socket;
5use Coro::Signal; 8use Coro::Signal;
6use Coro::AIO (); 9use Coro::AIO ();
7 10
11use Fcntl;
8use HTTP::Date; 12use HTTP::Date;
9use POSIX (); 13use POSIX ();
10 14
11use Compress::Zlib (); 15use Compress::Zlib ();
12 16
13no utf8; 17use common::sense;
14use bytes;
15 18
16# at least on my machine, this thingy serves files 19# at least on my machine, this thingy serves files
17# quite a bit faster than apache, ;) 20# quite a bit faster than apache, ;)
18# and quite a bit slower than thttpd :( 21# and quite a bit slower than thttpd :(
19 22
20$SIG{PIPE} = 'IGNORE'; 23$SIG{PIPE} = 'IGNORE';
21 24
22our $accesslog; 25our $accesslog;
23our $errorlog; 26our $errorlog;
27our @listen_sockets;
24 28
25our $NOW; 29our $NOW;
26our $HTTP_NOW; 30our $HTTP_NOW;
27 31
28our $ERROR_LOG; 32our $ERROR_LOG;
29our $ACCESS_LOG; 33our $ACCESS_LOG;
34our $TRANSFER_LOCK = new Coro::SemaphoreSet; # lock to be acquired per ip
30 35
31Event->timer(interval => 1, hard => 1, cb => sub { 36our $update_time = EV::periodic 0, 1, undef, sub {
32 $NOW = time; 37 $NOW = time;
33 $HTTP_NOW = time2str $NOW; 38 $HTTP_NOW = time2str $NOW;
34})->now; 39};
40$update_time->invoke;
35 41
36if ($ERROR_LOG) { 42if ($ERROR_LOG) {
37 use IO::Handle; 43 use IO::Handle;
38 open $errorlog, ">>$ERROR_LOG" 44 open $errorlog, ">>$ERROR_LOG"
39 or die "$ERROR_LOG: $!"; 45 or die "$ERROR_LOG: $!";
48} 54}
49 55
50sub slog { 56sub slog {
51 my $level = shift; 57 my $level = shift;
52 my $format = shift; 58 my $format = shift;
59
60 $format = sprintf $format, @_ if @_;
61
53 my $NOW = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $::NOW); 62 my $NOW = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $::NOW);
54 printf "$NOW: $format\n", @_; 63 print "$NOW: $format\n";
55 printf $errorlog "$NOW: $format\n", @_ if $errorlog; 64 print $errorlog "$NOW: $format\n", @_ if $errorlog;
56} 65}
57 66
58our $connections = new Coro::Semaphore $MAX_CONNECTS || 250; 67our $connections = new Coro::Semaphore $::MAX_CONNECTS || 250;
59our $httpevent = new Coro::Signal; 68our $httpevent = new Coro::Signal;
60 69
61our $queue_file = new transferqueue $MAX_TRANSFERS; 70our $queue_file = new transferqueue $::MAX_TRANSFERS;
62our $queue_index = new transferqueue 10; 71our $queue_index = new transferqueue 10;
63 72
64our $tbf_top = new tbf rate => $TBF_RATE || 100000; 73our $tbf_top = new tbf rate => $::TBF_RATE || 100000;
65 74
66my $unused_bytes = 0; 75my $unused_bytes = 0;
67my $unused_last = time; 76my $unused_last = time;
68 77
69sub unused_bandwidth { 78sub unused_bandwidth {
70 $unused_bytes += $_[0]; 79 $unused_bytes += $_[0];
71 if ($unused_last < $NOW - 30 && $unused_bytes / ($NOW - $unused_last) > 50000) { 80 if ($unused_last < $NOW - 30 && $unused_bytes / ($NOW - $unused_last) > 50000) {
72 $unused_last = $NOW; 81 $unused_last = $NOW;
73 $unused_bytes = 0; 82 $unused_bytes = 0;
74 $queue_file->force_wake_next; 83 $queue_file->force_wake_next
75 slog 1, "forced filetransfer due to unused bandwidth"; 84 and slog 1, "forced filetransfer due to unused bandwidth";
76 }
77}
78
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 } 85 }
100} 86}
101 87
102sub listen_on { 88sub listen_on {
103 my $listen = $_[0]; 89 my $listen = $_[0];
107 # the "main thread" 93 # the "main thread"
108 async { 94 async {
109 slog 1, "accepting connections"; 95 slog 1, "accepting connections";
110 while () { 96 while () {
111 $connections->down; 97 $connections->down;
112 push @newcons, [$listen->accept]; 98 my @conn = $listen->accept;
113 #slog 3, "accepted @$connections ".scalar(@pool); 99 #slog 3, "accepted @$connections ".scalar(@pool);
114 if (@pool) { 100
115 (pop @pool)->ready; 101 async_pool {
116 } else { 102 eval {
117 async \&handler; 103 conn->new (@conn)->handle;
104 };
105 slog 1, "$@" if $@ && !ref $@;
106
107 $httpevent->broadcast; # only for testing, but doesn't matter much
108
109 $connections->up;
118 } 110 }
119 } 111 }
120 }; 112 };
121} 113}
122 114
123my $http_port = new Coro::Socket 115my $http_port = new Coro::Socket
124 LocalAddr => $SERVER_HOST, 116 LocalAddr => $::SERVER_HOST,
125 LocalPort => $SERVER_PORT, 117 LocalPort => $::SERVER_PORT,
126 ReuseAddr => 1, 118 ReuseAddr => 1,
127 Listen => 50, 119 Listen => 50,
128 or die "unable to start server"; 120 or die "unable to start server";
129 121
130listen_on $http_port; 122listen_on $http_port;
131 123
132if ($SERVER_PORT2) { 124if ($::SERVER_PORT2) {
133 my $http_port = new Coro::Socket 125 my $http_port = new Coro::Socket
134 LocalAddr => $SERVER_HOST, 126 LocalAddr => $::SERVER_HOST,
135 LocalPort => $SERVER_PORT2, 127 LocalPort => $::SERVER_PORT2,
136 ReuseAddr => 1, 128 ReuseAddr => 1,
137 Listen => 50, 129 Listen => 50,
138 or die "unable to start server"; 130 or die "unable to start server";
139 131
140 listen_on $http_port; 132 listen_on $http_port;
141} 133}
142 134
143package conn; 135package conn;
144 136
145use strict; 137use common::sense;
146use bytes;
147 138
148use Socket; 139use Socket;
149use HTTP::Date; 140use HTTP::Date;
150use Convert::Scalar 'weaken'; 141use Convert::Scalar 'weaken';
151use IO::AIO; 142use IO::AIO;
143use AnyEvent::AIO;
152 144
153IO::AIO::min_parallel $::AIO_PARALLEL; 145IO::AIO::min_parallel $::AIO_PARALLEL;
154
155Event->io (fd => IO::AIO::poll_fileno,
156 poll => 'r', async => 1,
157 cb => \&IO::AIO::poll_cb);
158 146
159our %conn; # $conn{ip}{self} => connobj 147our %conn; # $conn{ip}{self} => connobj
160our %uri; # $uri{ip}{uri}{self} 148our %uri; # $uri{ip}{uri}{self}
161our %blocked; 149our %blocked;
162our %mimetype; 150our %mimetype;
163 151
164sub read_mimetypes { 152sub read_mimetypes {
165 local *M;
166 if (open M, "<mime_types") { 153 if (open my $fh, "<mime_types") {
167 while (<M>) { 154 while (<$fh>) {
168 if (/^([^#]\S+)\t+(\S+)$/) { 155 if (/^([^#]\S+)\t+(\S+)$/) {
169 $mimetype{lc $1} = $2; 156 $mimetype{lc $1} = $2;
170 } 157 }
171 } 158 }
172 } else { 159 } else {
180 my $class = shift; 167 my $class = shift;
181 my $fh = shift; 168 my $fh = shift;
182 my $peername = shift; 169 my $peername = shift;
183 my $self = bless { fh => $fh }, $class; 170 my $self = bless { fh => $fh }, $class;
184 my (undef, $iaddr) = unpack_sockaddr_in $peername 171 my (undef, $iaddr) = unpack_sockaddr_in $peername
185 or $self->err(500, "unable to decode peername"); 172 or $self->err (500, "unable to decode peername");
186 173
187 $self->{remote_addr} = 174 $self->{remote_addr} =
188 $self->{remote_id} = inet_ntoa $iaddr; 175 $self->{remote_id} = inet_ntoa $iaddr;
189 176
190 $self->{time} = $::NOW; 177 $self->{time} = $::NOW;
191 178
192 weaken ($Coro::current->{conn} = $self); 179 weaken ($Coro::current->{conn} = $self);
193 180
194 $::conns++; 181 ++$::conns;
195 $::maxconns = $::conns if $::conns > $::maxconns; 182 $::maxconns = $::conns if $::conns > $::maxconns;
196 183
197 $self; 184 $self
198} 185}
199 186
200sub DESTROY { 187sub DESTROY {
201 #my $self = shift; 188 my $self = shift;
189
202 $::conns--; 190 --$::conns;
203} 191}
204 192
205sub prune_cache { 193sub prune_cache {
206 my $hash = $_[0]; 194 my $hash = $_[0];
207 195
222 for (keys %blocked) { 210 for (keys %blocked) {
223 delete $blocked{$_} unless $blocked{$_}[0] > $::NOW; 211 delete $blocked{$_} unless $blocked{$_}[0] > $::NOW;
224 } 212 }
225} 213}
226 214
227Event->timer(interval => 60, cb => \&prune_caches); 215our $PRUNE_WATCHER = AE::timer 60, 60, \&prune_caches;
228 216
229sub slog { 217sub slog {
230 my $self = shift; 218 my $self = shift;
231 main::slog($_[0], "$self->{remote_id}> $_[1]"); 219 main::slog($_[0], "$self->{remote_id}> $_[1]");
232} 220}
293 $hdr->{"Content-Type"} = "text/plain"; 281 $hdr->{"Content-Type"} = "text/plain";
294 $hdr->{"Content-Length"} = length $content; 282 $hdr->{"Content-Length"} = length $content;
295 } 283 }
296 $hdr->{"Connection"} = "close"; 284 $hdr->{"Connection"} = "close";
297 285
298 $self->response($code, $msg, $hdr, $content); 286 $self->response ($code, $msg, $hdr, $content);
299 287
300 die bless {}, err::; 288 die bless {}, err::
301} 289}
302 290
303sub handle { 291sub handle {
304 my $self = shift; 292 my $self = shift;
305 my $fh = $self->{fh}; 293 my $fh = $self->{fh};
306 294
307 my $host; 295 my $host;
308 296
309 $fh->timeout($::REQ_TIMEOUT); 297 $fh->timeout($::REQ_TIMEOUT);
310 while() { 298 while () {
311 $self->{reqs}++; 299 $self->{reqs}++;
312 300
313 # read request and parse first line 301 # read request and parse first line
314 my $req = $fh->readline("\015\012\015\012"); 302 my $req = $fh->readline("\015\012\015\012");
315 303
424# uri => path mapping 412# uri => path mapping
425sub map_uri { 413sub map_uri {
426 my $self = shift; 414 my $self = shift;
427 my $host = $self->{server_name}; 415 my $host = $self->{server_name};
428 my $uri = $self->{uri}; 416 my $uri = $self->{uri};
417
418 $host =~ /[\/\\]/
419 and $self->err(400, "bad request");
429 420
430 # some massaging, also makes it more secure 421 # some massaging, also makes it more secure
431 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge; 422 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge;
432 $uri =~ s%//+%/%g; 423 $uri =~ s%//+%/%g;
433 $uri =~ s%/\.(?=/|$)%%g; 424 $uri =~ s%/\.(?=/|$)%%g;
477 468
478 if ($self->{name} =~ s%^/internal/([^/]+)%%) { 469 if ($self->{name} =~ s%^/internal/([^/]+)%%) {
479 if ($::internal{$1}) { 470 if ($::internal{$1}) {
480 $::internal{$1}->($self); 471 $::internal{$1}->($self);
481 } else { 472 } else {
482 $self->err(404, "not found"); 473 $self->err (404, "not found");
483 } 474 }
484 } else { 475 } else {
485 476
486 stat $path 477 Coro::AIO::aio_stat $path
487 or $self->err(404, "not found"); 478 and $self->err (404, "not found");
488 479
489 $self->{stat} = [stat _]; 480 $self->{stat} = [stat _];
490 481
491 # idiotic netscape sends idiotic headers AGAIN 482 # idiotic netscape sends idiotic headers AGAIN
492 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/ 483 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
495 if (-d _ && -r _) { 486 if (-d _ && -r _) {
496 # directory 487 # directory
497 if ($path !~ /\/$/) { 488 if ($path !~ /\/$/) {
498 # create a redirect to get the trailing "/" 489 # create a redirect to get the trailing "/"
499 # we don't try to avoid the :80 490 # we don't try to avoid the :80
500 $self->err(301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" }); 491 $self->err (301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" });
501 } else { 492 } else {
502 $ims < $self->{stat}[9] 493 $ims < $self->{stat}[9]
503 or $self->err(304, "not modified"); 494 or $self->err (304, "not modified");
504 495
505 if (-r "$path/index.html") { 496 if (-r "$path/index.html") {
506 # replace directory "size" by index.html filesize 497 # replace directory "size" by index.html filesize
507 $self->{stat} = [stat ($self->{path} .= "/index.html")]; 498 $self->{stat} = [stat ($self->{path} .= "/index.html")];
508 $self->handle_file($queue_index, $tbf_top); 499 $self->handle_file ($queue_index, $tbf_top);
509 } else { 500 } else {
510 $self->handle_dir; 501 $self->handle_dir;
511 } 502 }
512 } 503 }
513 } elsif (-f _ && -r _) { 504 } elsif (-f _ && -r _) {
514 -x _ and $self->err(403, "forbidden"); 505 -x _ and $self->err (403, "forbidden");
515 506
516 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 507 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
517 my $timeout = $::NOW + 10; 508 my $timeout = $::NOW + 10;
518 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 509 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
519 if ($timeout < $::NOW) { 510 if ($timeout < $::NOW) {
522 $httpevent->wait; 513 $httpevent->wait;
523 } 514 }
524 } 515 }
525 } 516 }
526 517
527 $self->handle_file($queue_file, $tbf_top); 518 $self->handle_file ($queue_file, $tbf_top);
528 } else { 519 } else {
529 $self->err(404, "not found"); 520 $self->err (404, "not found");
530 } 521 }
531 } 522 }
532} 523}
533 524
534sub handle_dir { 525sub handle_dir {
535 my $self = shift; 526 my $self = shift;
536 my $idx = $self->diridx; 527 my $idx = $self->diridx;
537 528
538 $self->response(200, "ok", 529 $self->response (200, "ok",
539 { 530 {
540 "Content-Type" => "text/html; charset=utf-8", 531 "Content-Type" => "text/html; charset=utf-8",
541 "Content-Length" => length $idx, 532 "Content-Length" => length $idx,
542 "Last-Modified" => time2str ($self->{stat}[9]), 533 "Last-Modified" => time2str ($self->{stat}[9]),
543 }, 534 },
553 }; 544 };
554 545
555 my @code = (200, "ok"); 546 my @code = (200, "ok");
556 my ($l, $h); 547 my ($l, $h);
557 548
558 if ($self->{h}{range} =~ /^bytes=(.*)$/) { 549 if ($self->{h}{range} =~ /^bytes=(.*)$/i) {
559 for (split /,/, $1) { 550 for (split /,/, $1) {
560 if (/^-(\d+)$/) { 551 if (/^-(\d+)$/) {
561 ($l, $h) = ($length - $1, $length - 1); 552 ($l, $h) = ($length - $1, $length - 1);
562 } elsif (/^(\d+)-(\d*)$/) { 553 } elsif (/^(\d+)-(\d*)$/) {
563 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1); 554 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1);
567 } 558 }
568 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; 559 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
569 } 560 }
570 $hdr->{"Content-Range"} = "bytes */$length"; 561 $hdr->{"Content-Range"} = "bytes */$length";
571 $hdr->{"Content-Length"} = $length; 562 $hdr->{"Content-Length"} = $length;
572 $self->err(416, "not satisfiable", $hdr, ""); 563 $self->err (416, "not satisfiable", $hdr, "");
573 564
574satisfiable: 565satisfiable:
575 # check for segmented downloads 566 # check for segmented downloads
576 if ($l && $::NO_SEGMENTED) { 567 if ($l && $::NO_SEGMENTED) {
577 my $timeout = $::NOW + 15; 568 my $timeout = $::NOW + 60;
578 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) { 569 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
579 if ($timeout <= $::NOW) { 570 if ($timeout <= $::NOW) {
580 $self->block($::BLOCKTIME, "segmented downloads are forbidden");
581 #$self->err_segmented_download; 571 $self->err_segmented_download;
582 } else { 572 } else {
583 $httpevent->wait; 573 $httpevent->wait;
584 } 574 }
585 } 575 }
586 } 576 }
596 586
597 $self->{path} =~ /\.([^.]+)$/; 587 $self->{path} =~ /\.([^.]+)$/;
598 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream"; 588 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream";
599 $hdr->{"Content-Length"} = $length; 589 $hdr->{"Content-Length"} = $length;
600 590
601 $self->response(@code, $hdr, ""); 591 $self->response (@code, $hdr, "");
602 592
603 if ($self->{method} eq "GET") { 593 if ($self->{method} eq "GET") {
604 $self->{time} = $::NOW; 594 $self->{time} = $::NOW;
605 $self->{written} = 0; 595 $self->{written} = 0;
606 596
607 my $fh; 597 my $fh = Coro::AIO::aio_open $self->{path}, Fcntl::O_RDONLY, 0
608
609 open $fh, "<", $self->{path}
610 or die "$self->{path}: late open failure ($!)"; 598 or die "$self->{path}: late open failure ($!)";
611 599
612 $h -= $l - 1; 600 $h -= $l - 1;
613 601
614 if (0) { # !AIO
615 if ($l) {
616 sysseek $fh, $l, 0;
617 }
618 }
619
620 my $transfer = $queue->start_transfer($h); 602 my $transfer = $queue->start_transfer ($h);
621 my $locked; 603 my $locked;
622 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size 604 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size
623 605
624 while ($h > 0) { 606 while ($h > 0) {
607 Coro::cede;
608 my $transfer_lock = $TRANSFER_LOCK->guard ($self->{remote_id});
609
625 unless ($locked) { 610 unless ($locked) {
626 if ($locked ||= $transfer->try($::WAIT_INTERVAL)) { 611 if ($locked ||= $transfer->try ($::WAIT_INTERVAL)) {
627 $bufsize = $::BUFSIZE; 612 $bufsize = $::BUFSIZE;
628 $self->{time} = $::NOW; 613 $self->{time} = $::NOW;
629 $self->{written} = 0; 614 $self->{written} = 0;
630 } 615 }
631 } 616 }
636 } 621 }
637 622
638 Coro::AIO::aio_read $fh, $l, ($h > $bufsize ? $bufsize : $h), my $buf, 0 623 Coro::AIO::aio_read $fh, $l, ($h > $bufsize ? $bufsize : $h), my $buf, 0
639 or last; 624 or last;
640 625
626 # readahead to work around rijk disk issues
627 IO::AIO::aio_readahead $fh, $l + $bufsize, $bufsize;
628
641 $tbf->request (length $buf); 629 $tbf->request (length $buf);
642 my $w = syswrite $self->{fh}, $buf 630 my $w = $self->{fh}->syswrite ($buf)
643 or last; 631 or last;
644 $::written += $w; 632 $::written += $w;
645 $self->{written} += $w; 633 $self->{written} += $w;
646 $l += $w; 634 $l += $w;
647 } 635 }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines