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.62 by root, Sun Jan 6 05:29:39 2002 UTC vs.
Revision 1.84 by root, Sat Dec 8 21:01:16 2007 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: $!";
50} 57}
51 58
52our $connections = new Coro::Semaphore $MAX_CONNECTS || 250; 59our $connections = new Coro::Semaphore $MAX_CONNECTS || 250;
53our $httpevent = new Coro::Signal; 60our $httpevent = new Coro::Signal;
54 61
55our $queue_file = new transferqueue slots => $MAX_TRANSFERS, maxsize => 250_000_000; 62our $queue_file = new transferqueue $MAX_TRANSFERS;
56our $queue_index = new transferqueue slots => 10; 63our $queue_index = new transferqueue 10;
57 64
58our $requests; 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}
59 79
60my @newcons; 80my @newcons;
61my @pool; 81my @pool;
62 82
63# one "execution thread" 83# one "execution thread"
64sub handler { 84sub handler {
65 while () { 85 while () {
66 if (@newcons) { 86 if (@newcons) {
67 eval { 87 eval {
68 conn->new(@{pop @newcons})->handle; 88 conn->new (@{pop @newcons})->handle;
69 }; 89 };
70 slog 1, "$@" if $@ && !ref $@; 90 slog 1, "$@" if $@ && !ref $@;
71 91
72 $httpevent->broadcast; # only for testing, but doesn't matter much 92 $httpevent->broadcast; # only for testing, but doesn't matter much
73 93
95 if (@pool) { 115 if (@pool) {
96 (pop @pool)->ready; 116 (pop @pool)->ready;
97 } else { 117 } else {
98 async \&handler; 118 async \&handler;
99 } 119 }
100
101 } 120 }
102 }; 121 };
103} 122}
104 123
105my $http_port = new Coro::Socket 124my $http_port = new Coro::Socket
106 LocalAddr => $SERVER_HOST, 125 LocalAddr => $SERVER_HOST,
107 LocalPort => $SERVER_PORT, 126 LocalPort => $SERVER_PORT,
108 ReuseAddr => 1, 127 ReuseAddr => 1,
109 Listen => 50, 128 Listen => 50,
110 or die "unable to start server"; 129 or die "unable to start server";
111 130
112listen_on $http_port; 131listen_on $http_port;
113 132
114if ($SERVER_PORT2) { 133if ($SERVER_PORT2) {
115 my $http_port = new Coro::Socket 134 my $http_port = new Coro::Socket
116 LocalAddr => $SERVER_HOST, 135 LocalAddr => $SERVER_HOST,
117 LocalPort => $SERVER_PORT2, 136 LocalPort => $SERVER_PORT2,
118 ReuseAddr => 1, 137 ReuseAddr => 1,
119 Listen => 50, 138 Listen => 50,
120 or die "unable to start server"; 139 or die "unable to start server";
121 140
122 listen_on $http_port; 141 listen_on $http_port;
123} 142}
124 143
125package conn; 144package conn;
145
146use strict;
147use bytes;
126 148
127use Socket; 149use Socket;
128use HTTP::Date; 150use HTTP::Date;
129use Convert::Scalar 'weaken'; 151use Convert::Scalar 'weaken';
130use Linux::AIO; 152use IO::AIO;
131 153
132Linux::AIO::min_parallel $::AIO_PARALLEL; 154IO::AIO::min_parallel $::AIO_PARALLEL;
133 155
134Event->io(fd => Linux::AIO::poll_fileno, 156our $AIO_WATCHER = EV::io IO::AIO::poll_fileno, EV::READ, \&IO::AIO::poll_cb;
135 poll => 'r', async => 1,
136 cb => \&Linux::AIO::poll_cb);
137 157
138our %conn; # $conn{ip}{self} => connobj 158our %conn; # $conn{ip}{self} => connobj
139our %uri; # $uri{ip}{uri}{self} 159our %uri; # $uri{ip}{uri}{self}
140our %blocked; 160our %blocked;
141our %mimetype; 161our %mimetype;
142 162
143sub read_mimetypes { 163sub read_mimetypes {
144 local *M;
145 if (open M, "<mime_types") { 164 if (open my $fh, "<mime_types") {
146 while (<M>) { 165 while (<$fh>) {
147 if (/^([^#]\S+)\t+(\S+)$/) { 166 if (/^([^#]\S+)\t+(\S+)$/) {
148 $mimetype{lc $1} = $2; 167 $mimetype{lc $1} = $2;
149 } 168 }
150 } 169 }
151 } else { 170 } else {
159 my $class = shift; 178 my $class = shift;
160 my $fh = shift; 179 my $fh = shift;
161 my $peername = shift; 180 my $peername = shift;
162 my $self = bless { fh => $fh }, $class; 181 my $self = bless { fh => $fh }, $class;
163 my (undef, $iaddr) = unpack_sockaddr_in $peername 182 my (undef, $iaddr) = unpack_sockaddr_in $peername
164 or $self->err(500, "unable to decode peername"); 183 or $self->err (500, "unable to decode peername");
165 184
166 $self->{remote_addr} = 185 $self->{remote_addr} =
167 $self->{remote_id} = inet_ntoa $iaddr; 186 $self->{remote_id} = inet_ntoa $iaddr;
168 187
169 $self->{time} = $::NOW; 188 $self->{time} = $::NOW;
170 189
171 weaken ($Coro::current->{conn} = $self); 190 weaken ($Coro::current->{conn} = $self);
172 191
173 $::conns++; 192 ++$::conns;
174 $::maxconns = $::conns if $::conns > $::maxconns; 193 $::maxconns = $::conns if $::conns > $::maxconns;
175 194
176 $self; 195 $self
177} 196}
178 197
179sub DESTROY { 198sub DESTROY {
180 #my $self = shift; 199 my $self = shift;
200
181 $::conns--; 201 --$::conns;
182} 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;
183 227
184sub slog { 228sub slog {
185 my $self = shift; 229 my $self = shift;
186 main::slog($_[0], "$self->{remote_id}> $_[1]"); 230 main::slog($_[0], "$self->{remote_id}> $_[1]");
187} 231}
188 232
189sub response { 233sub response {
190 my ($self, $code, $msg, $hdr, $content) = @_; 234 my ($self, $code, $msg, $hdr, $content) = @_;
191 my $res = "HTTP/1.1 $code $msg\015\012"; 235 my $res = "HTTP/1.1 $code $msg\015\012";
236 my $GZ = "";
192 237
193 if (exists $hdr->{Connection}) { 238 if (exists $hdr->{Connection}) {
194 if ($hdr->{Connection} =~ /close/) { 239 if ($hdr->{Connection} =~ /close/) {
195 $self->{h}{connection} = "close" 240 $self->{h}{connection} = "close"
196 } 241 }
202 $self->{h}{connection} = "close" 247 $self->{h}{connection} = "close"
203 } 248 }
204 } 249 }
205 } 250 }
206 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
207 $res .= "Date: $HTTP_NOW\015\012"; 265 $res .= "Date: $HTTP_NOW\015\012";
266 $res .= "Server: $::NAME\015\012";
208 267
209 while (my ($h, $v) = each %$hdr) { 268 while (my ($h, $v) = each %$hdr) {
210 $res .= "$h: $v\015\012" 269 $res .= "$h: $v\015\012"
211 } 270 }
212 $res .= "\015\012"; 271 $res .= "\015\012";
213 272
214 $res .= $content if defined $content and $self->{method} ne "HEAD"; 273 $res .= $content if defined $content and $self->{method} ne "HEAD";
215 274
216 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).
217 " $self->{remote_id} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}. 276 " $self->{remote_id} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}.$GZ.
218 " \"$self->{h}{referer}\"\n"; 277 " \"$self->{h}{referer}\"\n";
219 278
220 print $accesslog $log if $accesslog; 279 print $::accesslog $log if $::accesslog;
221 print STDERR $log; 280 print STDERR $log;
222 281
223 $self->{written} += 282 $tbf_top->request(length $res, 1e6);
224 print {$self->{fh}} $res; 283 $self->{written} += print {$self->{fh}} $res;
225} 284}
226 285
227sub err { 286sub err {
228 my $self = shift; 287 my $self = shift;
229 my ($code, $msg, $hdr, $content) = @_; 288 my ($code, $msg, $hdr, $content) = @_;
233 $hdr->{"Content-Type"} = "text/plain"; 292 $hdr->{"Content-Type"} = "text/plain";
234 $hdr->{"Content-Length"} = length $content; 293 $hdr->{"Content-Length"} = length $content;
235 } 294 }
236 $hdr->{"Connection"} = "close"; 295 $hdr->{"Connection"} = "close";
237 296
238 $self->response($code, $msg, $hdr, $content); 297 $self->response ($code, $msg, $hdr, $content);
239 298
240 die bless {}, err::; 299 die bless {}, err::
241} 300}
242 301
243sub handle { 302sub handle {
244 my $self = shift; 303 my $self = shift;
245 my $fh = $self->{fh}; 304 my $fh = $self->{fh};
246 305
247 my $host; 306 my $host;
248 307
249 $fh->timeout($::REQ_TIMEOUT); 308 $fh->timeout($::REQ_TIMEOUT);
250 while() { 309 while () {
251 $self->{reqs}++; 310 $self->{reqs}++;
252 311
253 # read request and parse first line 312 # read request and parse first line
254 my $req = $fh->readline("\015\012\015\012"); 313 my $req = $fh->readline("\015\012\015\012");
255 314
284 my (%hdr, $h, $v); 343 my (%hdr, $h, $v);
285 344
286 $hdr{lc $1} .= ",$2" 345 $hdr{lc $1} .= ",$2"
287 while $req =~ /\G 346 while $req =~ /\G
288 ([^:\000-\040]+): 347 ([^:\000-\040]+):
289 [\008\040]* 348 [\011\040]*
290 ((?: [^\015\012]+ | \015\012[\008\040] )*) 349 ((?: [^\015\012]+ | \015\012[\011\040] )*)
291 \015\012 350 \015\012
292 /gxc; 351 /gxc;
293 352
294 $req =~ /\G\015\012$/ 353 $req =~ /\G\015\012$/
295 or $self->err(400, "bad request"); 354 or $self->err(400, "bad request");
296 355
297 $self->{h}{$h} = substr $v, 1 356 $self->{h}{$h} = substr $v, 1
298 while ($h, $v) = each %hdr; 357 while ($h, $v) = each %hdr;
299 } 358 }
300
301 $requests++;
302 359
303 # remote id should be unique per user 360 # remote id should be unique per user
304 my $id = $self->{remote_addr}; 361 my $id = $self->{remote_addr};
305 362
306 if (exists $self->{h}{"client-ip"}) { 363 if (exists $self->{h}{"client-ip"}) {
419 476
420 if ($self->{name} =~ s%^/internal/([^/]+)%%) { 477 if ($self->{name} =~ s%^/internal/([^/]+)%%) {
421 if ($::internal{$1}) { 478 if ($::internal{$1}) {
422 $::internal{$1}->($self); 479 $::internal{$1}->($self);
423 } else { 480 } else {
424 $self->err(404, "not found"); 481 $self->err (404, "not found");
425 } 482 }
426 } else { 483 } else {
427 484
428 stat $path 485 stat $path
429 or $self->err(404, "not found"); 486 or $self->err (404, "not found");
430 487
431 $self->{stat} = [stat _]; 488 $self->{stat} = [stat _];
432 489
433 # idiotic netscape sends idiotic headers AGAIN 490 # idiotic netscape sends idiotic headers AGAIN
434 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/ 491 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
437 if (-d _ && -r _) { 494 if (-d _ && -r _) {
438 # directory 495 # directory
439 if ($path !~ /\/$/) { 496 if ($path !~ /\/$/) {
440 # create a redirect to get the trailing "/" 497 # create a redirect to get the trailing "/"
441 # we don't try to avoid the :80 498 # we don't try to avoid the :80
442 $self->err(301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" }); 499 $self->err (301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" });
443 } else { 500 } else {
444 $ims < $self->{stat}[9] 501 $ims < $self->{stat}[9]
445 or $self->err(304, "not modified"); 502 or $self->err (304, "not modified");
446 503
447 if (-r "$path/index.html") { 504 if (-r "$path/index.html") {
448 # replace directory "size" by index.html filesize 505 # replace directory "size" by index.html filesize
449 $self->{stat} = [stat ($self->{path} .= "/index.html")]; 506 $self->{stat} = [stat ($self->{path} .= "/index.html")];
450 $self->handle_file($queue_index); 507 $self->handle_file ($queue_index, $tbf_top);
451 } else { 508 } else {
452 $self->handle_dir; 509 $self->handle_dir;
453 } 510 }
454 } 511 }
455 } elsif (-f _ && -r _) { 512 } elsif (-f _ && -r _) {
456 -x _ and $self->err(403, "forbidden"); 513 -x _ and $self->err (403, "forbidden");
457 514
458 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 515 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
459 my $timeout = $::NOW + 10; 516 my $timeout = $::NOW + 10;
460 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) { 517 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
461 if ($timeout < $::NOW) { 518 if ($timeout < $::NOW) {
464 $httpevent->wait; 521 $httpevent->wait;
465 } 522 }
466 } 523 }
467 } 524 }
468 525
469 $self->handle_file($queue_file); 526 $self->handle_file ($queue_file, $tbf_top);
470 } else { 527 } else {
471 $self->err(404, "not found"); 528 $self->err (404, "not found");
472 } 529 }
473 } 530 }
474} 531}
475 532
476sub handle_dir { 533sub handle_dir {
477 my $self = shift; 534 my $self = shift;
478 my $idx = $self->diridx; 535 my $idx = $self->diridx;
479 536
480 $self->response(200, "ok", 537 $self->response (200, "ok",
481 { 538 {
482 "Content-Type" => "text/html", 539 "Content-Type" => "text/html; charset=utf-8",
483 "Content-Length" => length $idx, 540 "Content-Length" => length $idx,
484 "Last-Modified" => time2str ($self->{stat}[9]), 541 "Last-Modified" => time2str ($self->{stat}[9]),
485 }, 542 },
486 $idx); 543 $idx);
487} 544}
488 545
489sub handle_file { 546sub handle_file {
490 my ($self, $queue) = @_; 547 my ($self, $queue, $tbf) = @_;
491 my $length = $self->{stat}[7]; 548 my $length = $self->{stat}[7];
492 my $hdr = { 549 my $hdr = {
493 "Last-Modified" => time2str ((stat _)[9]), 550 "Last-Modified" => time2str ((stat _)[9]),
551 "Accept-Ranges" => "bytes",
494 }; 552 };
495 553
496 my @code = (200, "ok"); 554 my @code = (200, "ok");
497 my ($l, $h); 555 my ($l, $h);
498 556
508 } 566 }
509 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; 567 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
510 } 568 }
511 $hdr->{"Content-Range"} = "bytes */$length"; 569 $hdr->{"Content-Range"} = "bytes */$length";
512 $hdr->{"Content-Length"} = $length; 570 $hdr->{"Content-Length"} = $length;
513 $self->err(416, "not satisfiable", $hdr, ""); 571 $self->err (416, "not satisfiable", $hdr, "");
514 572
515satisfiable: 573satisfiable:
516 # check for segmented downloads 574 # check for segmented downloads
517 if ($l && $::NO_SEGMENTED) { 575 if ($l && $::NO_SEGMENTED) {
518 my $timeout = $::NOW + 15; 576 my $timeout = $::NOW + 15;
519 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) { 577 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
520 if ($timeout <= $::NOW) { 578 if ($timeout <= $::NOW) {
521 $self->block($::BLOCKTIME, "segmented downloads are forbidden"); 579 $self->block ($::BLOCKTIME, "segmented downloads are forbidden");
522 #$self->err_segmented_download; 580 #$self->err_segmented_download;
523 } else { 581 } else {
524 $httpevent->wait; 582 $httpevent->wait;
525 } 583 }
526 } 584 }
537 595
538 $self->{path} =~ /\.([^.]+)$/; 596 $self->{path} =~ /\.([^.]+)$/;
539 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream"; 597 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream";
540 $hdr->{"Content-Length"} = $length; 598 $hdr->{"Content-Length"} = $length;
541 599
542 $self->response(@code, $hdr, ""); 600 $self->response (@code, $hdr, "");
543 601
544 if ($self->{method} eq "GET") { 602 if ($self->{method} eq "GET") {
545 $self->{time} = $::NOW; 603 $self->{time} = $::NOW;
604 $self->{written} = 0;
546 605
547 my $current = $Coro::current;
548
549 my ($fh, $buf, $r);
550
551 open $fh, "<", $self->{path} 606 open my $fh, "<", $self->{path}
552 or die "$self->{path}: late open failure ($!)"; 607 or die "$self->{path}: late open failure ($!)";
553 608
554 $h -= $l - 1; 609 $h -= $l - 1;
555 610
556 if (0) { # !AIO
557 if ($l) {
558 sysseek $fh, $l, 0;
559 }
560 }
561
562 my $transfer = $queue->start_transfer($h); 611 my $transfer = $queue->start_transfer ($h);
563 my $locked; 612 my $locked;
564 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size 613 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size
565 614
566 while ($h > 0) { 615 while ($h > 0) {
567 unless ($locked) { 616 unless ($locked) {
568 if ($locked ||= $transfer->try($::WAIT_INTERVAL)) { 617 if ($locked ||= $transfer->try ($::WAIT_INTERVAL)) {
569 $bufsize = $::BUFSIZE; 618 $bufsize = $::BUFSIZE;
570 $self->{time} = $::NOW; 619 $self->{time} = $::NOW;
620 $self->{written} = 0;
571 } 621 }
572 } 622 }
573 623
574 if ($blocked{$self->{remote_id}}) { 624 if ($blocked{$self->{remote_id}}) {
575 $self->{h}{connection} = "close"; 625 $self->{h}{connection} = "close";
576 die bless {}, err::; 626 die bless {}, err::;
577 } 627 }
578 628
579 if (0) { # !AIO 629 Coro::AIO::aio_read $fh, $l, ($h > $bufsize ? $bufsize : $h), my $buf, 0
580 sysread $fh, $buf, $h > $bufsize ? $bufsize : $h
581 or last; 630 or last;
582 } else { 631
583 aio_read($fh, $l, ($h > $bufsize ? $bufsize : $h), 632 $tbf->request (length $buf);
584 $buf, 0, sub {
585 $r = $_[0];
586 Coro::ready($current);
587 });
588 &Coro::schedule;
589 last unless $r;
590 }
591 my $w = syswrite $self->{fh}, $buf 633 my $w = syswrite $self->{fh}, $buf
592 or last; 634 or last;
593 $::written += $w; 635 $::written += $w;
594 $self->{written} += $w; 636 $self->{written} += $w;
595 $l += $r; 637 $l += $w;
596 } 638 }
597 639
598 close $fh; 640 close $fh;
599 } 641 }
600} 642}
601 643
6021; 6441
645

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines