ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/myhttpd/httpd.pl
(Generate patch)

Comparing Coro/myhttpd/httpd.pl (file contents):
Revision 1.54 by root, Fri Nov 30 06:03:48 2001 UTC vs.
Revision 1.67 by root, Sun May 19 21:00:47 2002 UTC

5use Coro::Signal; 5use Coro::Signal;
6 6
7use HTTP::Date; 7use HTTP::Date;
8use POSIX (); 8use POSIX ();
9 9
10use Compress::Zlib ();
11
10no utf8; 12no utf8;
11use bytes; 13use bytes;
12 14
13# at least on my machine, this thingy serves files 15# at least on my machine, this thingy serves files
14# quite a bit faster than apache, ;) 16# quite a bit faster than apache, ;)
15# and quite a bit slower than thttpd :( 17# and quite a bit slower than thttpd :(
16 18
17$SIG{PIPE} = 'IGNORE'; 19$SIG{PIPE} = 'IGNORE';
18 20
19our $accesslog; 21our $accesslog;
22our $errorlog;
23
24our $NOW;
25our $HTTP_NOW;
26
27Event->timer(interval => 1, hard => 1, cb => sub {
28 $NOW = time;
29 $HTTP_NOW = time2str $NOW;
30})->now;
31
32if ($ERROR_LOG) {
33 use IO::Handle;
34 open $errorlog, ">>$ERROR_LOG"
35 or die "$ERROR_LOG: $!";
36 $errorlog->autoflush(1);
37}
20 38
21if ($ACCESS_LOG) { 39if ($ACCESS_LOG) {
22 use IO::Handle; 40 use IO::Handle;
23 open $accesslog, ">>$ACCESS_LOG" 41 open $accesslog, ">>$ACCESS_LOG"
24 or die "$ACCESS_LOG: $!"; 42 or die "$ACCESS_LOG: $!";
26} 44}
27 45
28sub slog { 46sub slog {
29 my $level = shift; 47 my $level = shift;
30 my $format = shift; 48 my $format = shift;
49 my $NOW = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $::NOW);
31 printf "---: $format\n", @_; 50 printf "$NOW: $format\n", @_;
51 printf $errorlog "$NOW: $format\n", @_ if $errorlog;
32} 52}
33 53
34our $connections = new Coro::Semaphore $MAX_CONNECTS || 250; 54our $connections = new Coro::Semaphore $MAX_CONNECTS || 250;
35our $httpevent = new Coro::Signal; 55our $httpevent = new Coro::Signal;
36 56
37our $wait_factor = 0.95;
38
39our $queue_small = new transferqueue $MAX_TRANSFERS_SMALL;
40our $queue_large = new transferqueue $MAX_TRANSFERS_LARGE; 57our $queue_file = new transferqueue $MAX_TRANSFERS;
41our $queue_index = new transferqueue 5; 58our $queue_index = new transferqueue 10;
59
60our $tbf_top = new tbf rate => 200000;
42 61
43my @newcons; 62my @newcons;
44my @pool; 63my @pool;
45 64
46# one "execution thread" 65# one "execution thread"
49 if (@newcons) { 68 if (@newcons) {
50 eval { 69 eval {
51 conn->new(@{pop @newcons})->handle; 70 conn->new(@{pop @newcons})->handle;
52 }; 71 };
53 slog 1, "$@" if $@ && !ref $@; 72 slog 1, "$@" if $@ && !ref $@;
73
74 $httpevent->broadcast; # only for testing, but doesn't matter much
75
54 $connections->up; 76 $connections->up;
55 } else { 77 } else {
56 last if @pool >= $MAX_POOL; 78 last if @pool >= $MAX_POOL;
57 push @pool, $Coro::current; 79 push @pool, $Coro::current;
58 schedule; 80 schedule;
100 or die "unable to start server"; 122 or die "unable to start server";
101 123
102 listen_on $http_port; 124 listen_on $http_port;
103} 125}
104 126
105our $NOW;
106our $HTTP_NOW;
107
108Event->timer(interval => 1, hard => 1, cb => sub {
109 $NOW = time;
110 $HTTP_NOW = time2str $NOW;
111})->now;
112
113package conn; 127package conn;
114 128
115use Socket; 129use Socket;
116use HTTP::Date; 130use HTTP::Date;
117use Convert::Scalar 'weaken'; 131use Convert::Scalar 'weaken';
151 my (undef, $iaddr) = unpack_sockaddr_in $peername 165 my (undef, $iaddr) = unpack_sockaddr_in $peername
152 or $self->err(500, "unable to decode peername"); 166 or $self->err(500, "unable to decode peername");
153 167
154 $self->{remote_addr} = 168 $self->{remote_addr} =
155 $self->{remote_id} = inet_ntoa $iaddr; 169 $self->{remote_id} = inet_ntoa $iaddr;
170
156 $self->{time} = $::NOW; 171 $self->{time} = $::NOW;
157 172
158 weaken ($Coro::current->{conn} = $self); 173 weaken ($Coro::current->{conn} = $self);
159 174
160 $::conns++; 175 $::conns++;
162 177
163 $self; 178 $self;
164} 179}
165 180
166sub DESTROY { 181sub DESTROY {
167 my $self = shift; 182 #my $self = shift;
168 $::conns--; 183 $::conns--;
169 $self->eoconn;
170}
171
172# end of connection
173sub eoconn {
174 my $self = shift;
175
176 # clean up hints
177 delete $conn{$self->{remote_id}}{$self*1};
178 delete $uri{$self->{remote_id}}{$self->{uri}}{$self*1};
179
180 $httpevent->broadcast;
181} 184}
182 185
183sub slog { 186sub slog {
184 my $self = shift; 187 my $self = shift;
185 main::slog($_[0], "$self->{remote_id}> $_[1]"); 188 main::slog($_[0], "$self->{remote_id}> $_[1]");
186} 189}
187 190
188sub response { 191sub response {
189 my ($self, $code, $msg, $hdr, $content) = @_; 192 my ($self, $code, $msg, $hdr, $content) = @_;
190 my $res = "HTTP/1.1 $code $msg\015\012"; 193 my $res = "HTTP/1.1 $code $msg\015\012";
194 my $GZ = "";
191 195
192 if (exists $hdr->{Connection}) { 196 if (exists $hdr->{Connection}) {
193 if ($hdr->{Connection} =~ /close/) { 197 if ($hdr->{Connection} =~ /close/) {
194 $self->{h}{connection} = "close" 198 $self->{h}{connection} = "close"
195 } 199 }
201 $self->{h}{connection} = "close" 205 $self->{h}{connection} = "close"
202 } 206 }
203 } 207 }
204 } 208 }
205 209
210 if ($self->{method} ne "HEAD"
211 && $self->{h}{"accept-encoding"} =~ /\bgzip\b/
212 && 400 < length $content
213 && $hdr->{"Content-Length"} == length $content
214 && !exists $hdr->{"Content-Encoding"}
215 ) {
216 my $orig = length $content;
217 $hdr->{"Content-Encoding"} = "gzip";
218 $content = Compress::Zlib::memGzip(\$content);
219 $hdr->{"Content-Length"} = length $content;
220 $GZ = sprintf "GZ%02d", 100 - 100*((length $content) / $orig);
221 }
222
206 $res .= "Date: $HTTP_NOW\015\012"; 223 $res .= "Date: $HTTP_NOW\015\012";
207 224
208 while (my ($h, $v) = each %$hdr) { 225 while (my ($h, $v) = each %$hdr) {
209 $res .= "$h: $v\015\012" 226 $res .= "$h: $v\015\012"
210 } 227 }
211 $res .= "\015\012"; 228 $res .= "\015\012";
212 229
213 $res .= $content if defined $content and $self->{method} ne "HEAD"; 230 $res .= $content if defined $content and $self->{method} ne "HEAD";
214 231
215 my $log = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $NOW). 232 my $log = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $::NOW).
216 " $self->{remote_id} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}. 233 " $self->{remote_id} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}.$GZ.
217 " \"$self->{h}{referer}\"\n"; 234 " \"$self->{h}{referer}\"\n";
218 235
219 print $accesslog $log if $accesslog; 236 print $::accesslog $log if $::accesslog;
220 print STDERR $log; 237 print STDERR $log;
221 238
222 $self->{written} += 239 $tbf_top->request(length $res, 1e6);
223 print {$self->{fh}} $res; 240 $self->{written} += print {$self->{fh}} $res;
224} 241}
225 242
226sub err { 243sub err {
227 my $self = shift; 244 my $self = shift;
228 my ($code, $msg, $hdr, $content) = @_; 245 my ($code, $msg, $hdr, $content) = @_;
283 my (%hdr, $h, $v); 300 my (%hdr, $h, $v);
284 301
285 $hdr{lc $1} .= ",$2" 302 $hdr{lc $1} .= ",$2"
286 while $req =~ /\G 303 while $req =~ /\G
287 ([^:\000-\040]+): 304 ([^:\000-\040]+):
288 [\008\040]* 305 [\011\040]*
289 ((?: [^\015\012]+ | \015\012[\008\040] )*) 306 ((?: [^\015\012]+ | \015\012[\011\040] )*)
290 \015\012 307 \015\012
291 /gxc; 308 /gxc;
292 309
293 $req =~ /\G\015\012$/ 310 $req =~ /\G\015\012$/
294 or $self->err(400, "bad request"); 311 or $self->err(400, "bad request");
306 $id .= "[".$self->{h}{"x-forwarded-for"}."]"; 323 $id .= "[".$self->{h}{"x-forwarded-for"}."]";
307 } 324 }
308 325
309 $self->{remote_id} = $id; 326 $self->{remote_id} = $id;
310 327
328 weaken (local $conn{$id}{$self*1} = $self);
329
311 if ($blocked{$id}) { 330 if ($blocked{$id}) {
312 $self->err_blocked($blocked{$id}) 331 $self->err_blocked
313 if $blocked{$id} > $::NOW; 332 if $blocked{$id}[0] > $::NOW;
314 333
315 delete $blocked{$id}; 334 delete $blocked{$id};
316 }
317
318 if (%{$conn{$id}} >= $::MAX_CONN_IP) {
319 my $delay = $::PER_TIMEOUT + $::NOW + 15;
320 while (%{$conn{$id}} >= $::MAX_CONN_IP) {
321 if ($delay < $::NOW) {
322 $self->slog(2, "blocked ip $id");
323 $self->err_blocked;
324 } else {
325 $httpevent->wait;
326 }
327 }
328 } 335 }
329 336
330 # find out server name and port 337 # find out server name and port
331 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) { 338 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) {
332 $host = $1; 339 $host = $1;
343 $host = inet_ntoa $host; 350 $host = inet_ntoa $host;
344 } 351 }
345 352
346 $self->{server_name} = $host; 353 $self->{server_name} = $host;
347 354
348 # enter ourselves into various lists
349 weaken ($conn{$id}{$self*1} = $self);
350 weaken ($uri{$id}{$self->{uri}}{$self*1} = $self); 355 weaken (local $uri{$id}{$self->{uri}}{$self*1} = $self);
351 356
352 eval { 357 eval {
353 $self->map_uri; 358 $self->map_uri;
354 $self->respond; 359 $self->respond;
355 }; 360 };
356 361
357 $self->eoconn;
358
359 die if $@ && !ref $@; 362 die if $@ && !ref $@;
360 363
361 last if $self->{h}{connection} =~ /close/; 364 last if $self->{h}{connection} =~ /close/i;
362 365
363 $httpevent->broadcast; 366 $httpevent->broadcast;
364 367
365 $fh->timeout($::PER_TIMEOUT); 368 $fh->timeout($::PER_TIMEOUT);
366 } 369 }
370}
371
372sub block {
373 my $self = shift;
374
375 $blocked{$self->{remote_id}} = [$::NOW + $_[0], $_[1]];
376 $self->slog(2, "blocked ip $self->{remote_id}");
377 $self->err_blocked;
367} 378}
368 379
369# uri => path mapping 380# uri => path mapping
370sub map_uri { 381sub map_uri {
371 my $self = shift; 382 my $self = shift;
447 $ims < $self->{stat}[9] 458 $ims < $self->{stat}[9]
448 or $self->err(304, "not modified"); 459 or $self->err(304, "not modified");
449 460
450 if (-r "$path/index.html") { 461 if (-r "$path/index.html") {
451 # replace directory "size" by index.html filesize 462 # replace directory "size" by index.html filesize
452 $self->{stat}[7] = (stat ($self->{path} .= "/index.html"))[7]; 463 $self->{stat} = [stat ($self->{path} .= "/index.html")];
453 $self->handle_file($queue_index); 464 $self->handle_file($queue_index, $tbf_top);
454 } else { 465 } else {
455 $self->handle_dir; 466 $self->handle_dir;
456 } 467 }
457 } 468 }
458 } elsif (-f _ && -r _) { 469 } elsif (-f _ && -r _) {
459 -x _ and $self->err(403, "forbidden"); 470 -x _ and $self->err(403, "forbidden");
460 $self->handle_file(-s _ >= $::TRANSFER_SMALL ? $queue_large : $queue_small); 471
472 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
473 my $timeout = $::NOW + 10;
474 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
475 if ($timeout < $::NOW) {
476 $self->block($::BLOCKTIME, "too many connections");
477 } else {
478 $httpevent->wait;
479 }
480 }
481 }
482
483 $self->handle_file($queue_file, $tbf_top);
461 } else { 484 } else {
462 $self->err(404, "not found"); 485 $self->err(404, "not found");
463 } 486 }
464 } 487 }
465} 488}
470 493
471 $self->response(200, "ok", 494 $self->response(200, "ok",
472 { 495 {
473 "Content-Type" => "text/html", 496 "Content-Type" => "text/html",
474 "Content-Length" => length $idx, 497 "Content-Length" => length $idx,
475 "Last-Modified" => time2str ((stat _)[9]), 498 "Last-Modified" => time2str ($self->{stat}[9]),
476 }, 499 },
477 $idx); 500 $idx);
478} 501}
479 502
480sub handle_file { 503sub handle_file {
481 my ($self, $queue) = @_; 504 my ($self, $queue, $tbf) = @_;
482 my $length = $self->{stat}[7]; 505 my $length = $self->{stat}[7];
483 my $hdr = { 506 my $hdr = {
484 "Last-Modified" => time2str ((stat _)[9]), 507 "Last-Modified" => time2str ((stat _)[9]),
485 }; 508 };
486 509
504 $self->err(416, "not satisfiable", $hdr, ""); 527 $self->err(416, "not satisfiable", $hdr, "");
505 528
506satisfiable: 529satisfiable:
507 # check for segmented downloads 530 # check for segmented downloads
508 if ($l && $::NO_SEGMENTED) { 531 if ($l && $::NO_SEGMENTED) {
509 my $delay = $::NOW + $::PER_TIMEOUT + 15; 532 my $timeout = $::NOW + 15;
510 while (%{$uri{$self->{remote_id}}{$self->{uri}}} > 1) { 533 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
511 if ($delay <= $::NOW) { 534 if ($timeout <= $::NOW) {
535 $self->block($::BLOCKTIME, "segmented downloads are forbidden");
512 $self->err_segmented_download; 536 #$self->err_segmented_download;
513 } else { 537 } else {
514 $httpevent->wait; 538 $httpevent->wait;
515 } 539 }
516 } 540 }
517 } 541 }
547 if ($l) { 571 if ($l) {
548 sysseek $fh, $l, 0; 572 sysseek $fh, $l, 0;
549 } 573 }
550 } 574 }
551 575
552 my $transfer = $queue->start_transfer; 576 my $transfer = $queue->start_transfer($h);
553 my $locked; 577 my $locked;
554 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size 578 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size
555 579
556 while ($h > 0) { 580 while ($h > 0) {
557 unless ($locked) { 581 unless ($locked) {
558 if ($locked ||= $transfer->try($::WAIT_INTERVAL)) { 582 if ($locked ||= $transfer->try($::WAIT_INTERVAL)) {
559 $bufsize = $::BUFSIZE; 583 $bufsize = $::BUFSIZE;
560 $self->{time} = $::NOW; 584 $self->{time} = $::NOW;
561 } 585 }
586 }
587
588 if ($blocked{$self->{remote_id}}) {
589 $self->{h}{connection} = "close";
590 die bless {}, err::;
562 } 591 }
563 592
564 if (0) { # !AIO 593 if (0) { # !AIO
565 sysread $fh, $buf, $h > $bufsize ? $bufsize : $h 594 sysread $fh, $buf, $h > $bufsize ? $bufsize : $h
566 or last; 595 or last;
571 Coro::ready($current); 600 Coro::ready($current);
572 }); 601 });
573 &Coro::schedule; 602 &Coro::schedule;
574 last unless $r; 603 last unless $r;
575 } 604 }
605
606 $tbf->request(length $buf);
576 my $w = syswrite $self->{fh}, $buf 607 my $w = syswrite $self->{fh}, $buf
577 or last; 608 or last;
578 $::written += $w; 609 $::written += $w;
579 $self->{written} += $w; 610 $self->{written} += $w;
580 $l += $r; 611 $l += $r;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines