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.29 by root, Sat Aug 25 15:14:03 2001 UTC vs.
Revision 1.39 by root, Sun Sep 2 12:23:04 2001 UTC

1use Coro; 1use Coro;
2use Coro::Semaphore; 2use Coro::Semaphore;
3use Coro::Event; 3use Coro::Event;
4use Coro::Socket; 4use Coro::Socket;
5
6use HTTP::Date;
5 7
6no utf8; 8no utf8;
7use bytes; 9use bytes;
8 10
9# at least on my machine, this thingy serves files 11# at least on my machine, this thingy serves files
25 my $level = shift; 27 my $level = shift;
26 my $format = shift; 28 my $format = shift;
27 printf "---: $format\n", @_; 29 printf "---: $format\n", @_;
28} 30}
29 31
30my $connections = new Coro::Semaphore $MAX_CONNECTS; 32our $connections = new Coro::Semaphore $MAX_CONNECTS || 250;
33
34our $wait_factor = 0.95;
35
36our @transfers = (
37 [(new Coro::Semaphore $MAX_TRANSFERS_SMALL || 50), 1],
38 [(new Coro::Semaphore $MAX_TRANSFERS_LARGE || 50), 1],
39);
31 40
32my @newcons; 41my @newcons;
33my @pool; 42my @pool;
34 43
35# one "execution thread" 44# one "execution thread"
36sub handler { 45sub handler {
37 while () { 46 while () {
38 my $new = pop @newcons;
39 if ($new) { 47 if (@newcons) {
40 eval { 48 eval {
41 conn->new(@$new)->handle; 49 conn->new(@{pop @newcons})->handle;
42 }; 50 };
43 slog 1, "$@" if $@ && !ref $@; 51 slog 1, "$@" if $@ && !ref $@;
44 $connections->up; 52 $connections->up;
45 } else { 53 } else {
46 last if @pool >= $MAX_POOL; 54 last if @pool >= $MAX_POOL;
57 Listen => 50, 65 Listen => 50,
58 or die "unable to start server"; 66 or die "unable to start server";
59 67
60push @listen_sockets, $http_port; 68push @listen_sockets, $http_port;
61 69
70our $NOW;
71our $HTTP_NOW;
72
73Event->timer(interval => 1, hard => 1, cb => sub {
74 $NOW = time;
75 $HTTP_NOW = time2str $NOW;
76})->now;
77
62# the "main thread" 78# the "main thread"
63async { 79async {
64 slog 1, "accepting connections"; 80 slog 1, "accepting connections";
65 while () { 81 while () {
66 $connections->down; 82 $connections->down;
67 push @newcons, [$http_port->accept]; 83 push @newcons, [$http_port->accept];
68 #slog 3, "accepted @$connections ".scalar(@pool); 84 #slog 3, "accepted @$connections ".scalar(@pool);
69 $::NOW = time;
70 if (@pool) { 85 if (@pool) {
71 (pop @pool)->ready; 86 (pop @pool)->ready;
72 } else { 87 } else {
73 async \&handler; 88 async \&handler;
74 } 89 }
82use HTTP::Date; 97use HTTP::Date;
83use Convert::Scalar 'weaken'; 98use Convert::Scalar 'weaken';
84use Linux::AIO; 99use Linux::AIO;
85 100
86Linux::AIO::min_parallel $::AIO_PARALLEL; 101Linux::AIO::min_parallel $::AIO_PARALLEL;
87
88my $aio_requests = new Coro::Semaphore $::AIO_PARALLEL * 4;
89 102
90Event->io(fd => Linux::AIO::poll_fileno, 103Event->io(fd => Linux::AIO::poll_fileno,
91 poll => 'r', async => 1, 104 poll => 'r', async => 1,
92 cb => \&Linux::AIO::poll_cb); 105 cb => \&Linux::AIO::poll_cb);
93 106
120 or $self->err(500, "unable to decode peername"); 133 or $self->err(500, "unable to decode peername");
121 134
122 $self->{remote_addr} = inet_ntoa $iaddr; 135 $self->{remote_addr} = inet_ntoa $iaddr;
123 $self->{time} = $::NOW; 136 $self->{time} = $::NOW;
124 137
125 # enter ourselves into various lists
126 weaken ($conn{$self->{remote_addr}}{$self*1} = $self);
127
128 $::conns++; 138 $::conns++;
129 139
130 $self; 140 $self;
131} 141}
132 142
133sub DESTROY { 143sub DESTROY {
134 my $self = shift; 144 my $self = shift;
135
136 $::conns--; 145 $::conns--;
137
138 $self->eoconn; 146 $self->eoconn;
139 delete $conn{$self->{remote_addr}}{$self*1};
140} 147}
141 148
142# end of connection 149# end of connection
143sub eoconn { 150sub eoconn {
144 my $self = shift; 151 my $self = shift;
152
153 # clean up hints
154 delete $conn{$self->{remote_id}}{$self*1};
145 delete $uri{$self->{remote_addr}}{$self->{uri}}{$self*1}; 155 delete $uri{$self->{remote_id}}{$self->{uri}}{$self*1};
146} 156}
147 157
148sub slog { 158sub slog {
149 my $self = shift; 159 my $self = shift;
150 main::slog($_[0], ($self->{remote_id} || $self->{remote_addr}) ."> $_[1]"); 160 main::slog($_[0], ($self->{remote_id} || $self->{remote_addr}) ."> $_[1]");
154 my ($self, $code, $msg, $hdr, $content) = @_; 164 my ($self, $code, $msg, $hdr, $content) = @_;
155 my $res = "HTTP/1.1 $code $msg\015\012"; 165 my $res = "HTTP/1.1 $code $msg\015\012";
156 166
157 $self->{h}{connection} ||= $hdr->{Connection}; 167 $self->{h}{connection} ||= $hdr->{Connection};
158 168
159 $res .= "Date: ".(time2str $::NOW)."\015\012"; # slow? nah. :( 169 $res .= "Date: $HTTP_NOW\015\012";
160 170
161 while (my ($h, $v) = each %$hdr) { 171 while (my ($h, $v) = each %$hdr) {
162 $res .= "$h: $v\015\012" 172 $res .= "$h: $v\015\012"
163 } 173 }
164 $res .= "\015\012"; 174 $res .= "\015\012";
177sub err { 187sub err {
178 my $self = shift; 188 my $self = shift;
179 my ($code, $msg, $hdr, $content) = @_; 189 my ($code, $msg, $hdr, $content) = @_;
180 190
181 unless (defined $content) { 191 unless (defined $content) {
182 $content = "$code $msg"; 192 $content = "$code $msg\n";
183 $hdr->{"Content-Type"} = "text/plain"; 193 $hdr->{"Content-Type"} = "text/plain";
184 $hdr->{"Content-Length"} = length $content; 194 $hdr->{"Content-Length"} = length $content;
185 } 195 }
186 $hdr->{"Connection"} = "close"; 196 $hdr->{"Connection"} = "close";
187 197
188 $self->response($code, $msg, $hdr, $content); 198 $self->response($code, $msg, $hdr, $content);
189 199
190 die bless {}, err::; 200 die bless {}, err::;
191}
192
193sub err_blocked {
194 my $self = shift;
195 my $ip = $self->{remote_addr};
196 my $time = time2str $blocked{$ip} = $::NOW + $::BLOCKTIME;
197
198 Coro::Event::do_timer(after => 20*rand);
199
200 $self->err(401, "too many connections",
201 {
202 "Content-Type" => "text/html",
203 "Retry-After" => $::BLOCKTIME,
204 "Warning" => "Please do NOT retry, you have been blocked",
205 "WWW-Authenticate" => "Basic realm=\"Please do NOT retry, you have been blocked\"",
206 "Connection" => "close",
207 },
208 <<EOF);
209<html>
210<head>
211<title>Too many connections</title>
212</head>
213<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#000080" alink="#ff0000">
214
215<p>You have been blocked because you opened too many connections. You
216may retry at</p>
217
218 <p><blockquote>$time.</blockquote></p>
219
220<p>Until then, each new access will renew the block. You might want to have a
221look at the <a href="http://www.goof.com/pcg/marc/animefaq.html#connectionlimit">FAQ</a>.</p>
222
223</body></html>
224EOF
225} 201}
226 202
227sub handle { 203sub handle {
228 my $self = shift; 204 my $self = shift;
229 my $fh = $self->{fh}; 205 my $fh = $self->{fh};
246 } 222 }
247 223
248 $self->{h} = {}; 224 $self->{h} = {};
249 225
250 $fh->timeout($::RES_TIMEOUT); 226 $fh->timeout($::RES_TIMEOUT);
251 my $ip = $self->{remote_addr};
252
253 if ($blocked{$ip}) {
254 $self->err_blocked($blocked{$ip})
255 if $blocked{$ip} > $::NOW;
256
257 delete $blocked{$ip};
258 }
259
260 if (%{$conn{$ip}} > $::MAX_CONN_IP) {
261 $self->slog(2, "blocked ip $ip");
262 $self->err_blocked;
263 }
264 227
265 $req =~ /^(?:\015\012)? 228 $req =~ /^(?:\015\012)?
266 (GET|HEAD) \040+ 229 (GET|HEAD) \040+
267 ([^\040]+) \040+ 230 ([^\040]+) \040+
268 HTTP\/([0-9]+\.[0-9]+) 231 HTTP\/([0-9]+\.[0-9]+)
293 256
294 $self->{h}{$h} = substr $v, 1 257 $self->{h}{$h} = substr $v, 1
295 while ($h, $v) = each %hdr; 258 while ($h, $v) = each %hdr;
296 } 259 }
297 260
261 # remote id should be unique per user
262 my $id = $self->{remote_addr};
263
264 if (exists $self->{h}{"client-ip"}) {
265 $id .= "[".$self->{h}{"client-ip"}."]";
266 } elsif (exists $self->{h}{"x-forwarded-for"}) {
267 $id .= "[".$self->{h}{"x-forwarded-for"}."]";
268 }
269
270 $self->{remote_id} = $id;
271
272 if ($blocked{$id}) {
273 $self->err_blocked($blocked{$id})
274 if $blocked{$id} > $::NOW;
275
276 delete $blocked{$id};
277 }
278
279 if (%{$conn{$id}} >= $::MAX_CONN_IP) {
280 my $delay = $::PER_TIMEOUT + 15;
281 while (%{$conn{$id}} >= $::MAX_CONN_IP) {
282 if ($delay <= 0) {
283 $self->slog(2, "blocked ip $id");
284 $self->err_blocked;
285 } else {
286 Coro::Event::do_timer(after => 4); $delay -= 4;
287 }
288 }
289 }
290
298 # find out server name and port 291 # find out server name and port
299 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) { 292 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) {
300 $host = $1; 293 $host = $1;
301 } else { 294 } else {
302 $host = $self->{h}{host}; 295 $host = $self->{h}{host};
311 $host = inet_ntoa $host; 304 $host = inet_ntoa $host;
312 } 305 }
313 306
314 $self->{server_name} = $host; 307 $self->{server_name} = $host;
315 308
316 # remote id should be unique per user 309 # enter ourselves into various lists
317 $self->{remote_id} = $self->{remote_addr}; 310 weaken ($conn{$id}{$self*1} = $self);
318
319 if (exists $self->{h}{"client-ip"}) {
320 $self->{remote_id} .= "[".$self->{h}{"client-ip"}."]";
321 } elsif (exists $self->{h}{"x-forwarded-for"}) {
322 $self->{remote_id} .= "[".$self->{h}{"x-forwarded-for"}."]";
323 }
324
325 weaken ($uri{$self->{remote_addr}}{$self->{uri}}{$self*1} = $self); 311 weaken ($uri{$id}{$self->{uri}}{$self*1} = $self);
326 312
327 eval { 313 eval {
328 $self->map_uri; 314 $self->map_uri;
329 $self->respond; 315 $self->respond;
330 }; 316 };
439 $idx); 425 $idx);
440} 426}
441 427
442sub handle_file { 428sub handle_file {
443 my $self = shift; 429 my $self = shift;
444 my $length = -s _; 430 my $length = $self->{stat}[7];
431 my $queue = $::transfers[$length >= $::TRANSFER_SMALL];
445 my $hdr = { 432 my $hdr = {
446 "Last-Modified" => time2str ((stat _)[9]), 433 "Last-Modified" => time2str ((stat _)[9]),
447 }; 434 };
448 435
449 my @code = (200, "ok"); 436 my @code = (200, "ok");
461 } 448 }
462 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; 449 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
463 } 450 }
464 $hdr->{"Content-Range"} = "bytes */$length"; 451 $hdr->{"Content-Range"} = "bytes */$length";
465 $hdr->{"Content-Length"} = $length; 452 $hdr->{"Content-Length"} = $length;
466 $self->slog(9, "not satisfiable($self->{h}{range}|".$self->{h}{"user-agent"}.")");
467 $self->err(416, "not satisfiable", $hdr, ""); 453 $self->err(416, "not satisfiable", $hdr, "");
468 454
469satisfiable: 455satisfiable:
470 # check for segmented downloads 456 # check for segmented downloads
471 if ($l && $::NO_SEGMENTED) { 457 if ($l && $::NO_SEGMENTED) {
472 my $delay = 60; 458 my $delay = $::PER_TIMEOUT + 15;
473 while (%{$uri{$self->{remote_addr}}{$self->{uri}}} > 1) { 459 while (%{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
474 if ($delay <= 0) { 460 if ($delay <= 0) {
475 $self->err(400, "segmented downloads are not allowed", 461 $self->err_segmented_download;
476 { "Content-Type" => "text/html", Connection => "close" }, <<EOF);
477<html>
478<head>
479<title>Segmented downloads are not allowed</title>
480</head>
481<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#000080" alink="#ff0000">
482
483<p>Segmented downloads are not allowed on this server. Please refer to the
484<a href="http://www.goof.com/pcg/marc/animefaq.html#segmented_downloads">FAQ</a>.</p>
485
486</body></html>
487EOF
488 } else { 462 } else {
489 Coro::Event::do_timer(after => 3); $delay -= 3; 463 Coro::Event::do_timer(after => 4); $delay -= 4;
490 } 464 }
491 } 465 }
492 } 466 }
493 467
494 $hdr->{"Content-Range"} = "bytes $l-$h/$length"; 468 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
505 $hdr->{"Content-Length"} = $length; 479 $hdr->{"Content-Length"} = $length;
506 480
507 $self->response(@code, $hdr, ""); 481 $self->response(@code, $hdr, "");
508 482
509 if ($self->{method} eq "GET") { 483 if ($self->{method} eq "GET") {
484 $self->{time} = $::NOW;
485
486 my $fudge = $queue->[0]->waiters;
487 $fudge = $fudge ? ($fudge+1)/$fudge : 1;
488
489 $queue->[1] *= $fudge;
490 my $transfer = $queue->[0]->guard;
491
492 if ($fudge != 1) {
493 $queue->[1] /= $fudge;
494 $queue->[1] = $queue->[1] * $::wait_factor
495 + ($::NOW - $self->{time}) * (1 - $::wait_factor);
496 }
497 $self->{time} = $::NOW;
498
499 $self->{fh}->writable or return;
500
510 my ($fh, $buf, $r); 501 my ($fh, $buf, $r);
511 my $current = $Coro::current; 502 my $current = $Coro::current;
512 open $fh, "<", $self->{path} 503 open $fh, "<", $self->{path}
513 or die "$self->{path}: late open failure ($!)"; 504 or die "$self->{path}: late open failure ($!)";
514 505
523 while ($h > 0) { 514 while ($h > 0) {
524 if (0) { 515 if (0) {
525 sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h 516 sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h
526 or last; 517 or last;
527 } else { 518 } else {
528 undef $buf;
529 $aio_requests->down;
530 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h), 519 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h),
531 $buf, 0, sub { 520 $buf, 0, sub {
532 $r = $_[0]; 521 $r = $_[0];
533 $current->ready; 522 Coro::ready($current);
534 }); 523 });
535 &Coro::schedule; 524 &Coro::schedule;
536 $aio_requests->up;
537 last unless $r; 525 last unless $r;
538 } 526 }
539 my $w = $self->{fh}->syswrite($buf) 527 my $w = syswrite $self->{fh}, $buf
540 or last; 528 or last;
541 $::written += $w; 529 $::written += $w;
542 $self->{written} += $w; 530 $self->{written} += $w;
543 $l += $r; 531 $l += $r;
544 } 532 }
545 }
546 533
547 close $fh; 534 close $fh;
535 }
548} 536}
549 537
5501; 5381;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines