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.83 by root, Sun Dec 3 17:49:22 2006 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines