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.27 by root, Sun Aug 19 23:57:52 2001 UTC vs.
Revision 1.40 by root, Mon Sep 3 00:06:06 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;
48 schedule; 56 schedule;
49 } 57 }
50 } 58 }
51} 59}
52 60
61sub listen_on {
62 my $listen = $_[0];
63
64 push @listen_sockets, $listen;
65
66 # the "main thread"
67 async {
68 slog 1, "accepting connections";
69 while () {
70 $connections->down;
71 push @newcons, [$listen->accept];
72 #slog 3, "accepted @$connections ".scalar(@pool);
73 if (@pool) {
74 (pop @pool)->ready;
75 } else {
76 async \&handler;
77 }
78
79 }
80 };
81}
82
53my $http_port = new Coro::Socket 83my $http_port = new Coro::Socket
54 LocalAddr => $SERVER_HOST, 84 LocalAddr => $SERVER_HOST,
55 LocalPort => $SERVER_PORT, 85 LocalPort => $SERVER_PORT,
56 ReuseAddr => 1, 86 ReuseAddr => 1,
57 Listen => 50, 87 Listen => 50,
58 or die "unable to start server"; 88 or die "unable to start server";
59 89
60push @listen_sockets, $http_port; 90listen_on $http_port;
61 91
62# the "main thread" 92my $http_port = new Coro::Socket
63async { 93 LocalAddr => $SERVER_HOST,
64 slog 1, "accepting connections"; 94 LocalPort => $SERVER_PORT2,
65 while () { 95 ReuseAddr => 1,
66 $connections->down; 96 Listen => 50,
67 push @newcons, [$http_port->accept]; 97 or die "unable to start server";
68 #slog 3, "accepted @$connections ".scalar(@pool); 98
99listen_on $http_port;
100
101our $NOW;
102our $HTTP_NOW;
103
104Event->timer(interval => 1, hard => 1, cb => sub {
69 $::NOW = time; 105 $NOW = time;
70 if (@pool) { 106 $HTTP_NOW = time2str $NOW;
71 (pop @pool)->ready; 107})->now;
72 } else {
73 async \&handler;
74 }
75
76 }
77};
78 108
79package conn; 109package conn;
80 110
81use Socket; 111use Socket;
82use HTTP::Date; 112use HTTP::Date;
118 or $self->err(500, "unable to decode peername"); 148 or $self->err(500, "unable to decode peername");
119 149
120 $self->{remote_addr} = inet_ntoa $iaddr; 150 $self->{remote_addr} = inet_ntoa $iaddr;
121 $self->{time} = $::NOW; 151 $self->{time} = $::NOW;
122 152
123 # enter ourselves into various lists
124 weaken ($conn{$self->{remote_addr}}{$self*1} = $self);
125
126 $::conns++; 153 $::conns++;
127 154
128 $self; 155 $self;
129} 156}
130 157
131sub DESTROY { 158sub DESTROY {
132 my $self = shift; 159 my $self = shift;
133
134 $::conns--; 160 $::conns--;
135
136 $self->eoconn; 161 $self->eoconn;
137 delete $conn{$self->{remote_addr}}{$self*1};
138} 162}
139 163
140# end of connection 164# end of connection
141sub eoconn { 165sub eoconn {
142 my $self = shift; 166 my $self = shift;
167
168 # clean up hints
169 delete $conn{$self->{remote_id}}{$self*1};
143 delete $uri{$self->{remote_addr}}{$self->{uri}}{$self*1}; 170 delete $uri{$self->{remote_id}}{$self->{uri}}{$self*1};
144} 171}
145 172
146sub slog { 173sub slog {
147 my $self = shift; 174 my $self = shift;
148 main::slog($_[0], "$self->{remote_addr}> $_[1]"); 175 main::slog($_[0], ($self->{remote_id} || $self->{remote_addr}) ."> $_[1]");
149} 176}
150 177
151sub response { 178sub response {
152 my ($self, $code, $msg, $hdr, $content) = @_; 179 my ($self, $code, $msg, $hdr, $content) = @_;
153 my $res = "HTTP/1.1 $code $msg\015\012"; 180 my $res = "HTTP/1.1 $code $msg\015\012";
154 181
155 #$res .= "Connection: close\015\012"; 182 $self->{h}{connection} ||= $hdr->{Connection};
156 $res .= "Date: ".(time2str $::NOW)."\015\012"; # slow? nah. :( 183
184 $res .= "Date: $HTTP_NOW\015\012";
157 185
158 while (my ($h, $v) = each %$hdr) { 186 while (my ($h, $v) = each %$hdr) {
159 $res .= "$h: $v\015\012" 187 $res .= "$h: $v\015\012"
160 } 188 }
161 $res .= "\015\012"; 189 $res .= "\015\012";
174sub err { 202sub err {
175 my $self = shift; 203 my $self = shift;
176 my ($code, $msg, $hdr, $content) = @_; 204 my ($code, $msg, $hdr, $content) = @_;
177 205
178 unless (defined $content) { 206 unless (defined $content) {
179 $content = "$code $msg"; 207 $content = "$code $msg\n";
180 $hdr->{"Content-Type"} = "text/plain"; 208 $hdr->{"Content-Type"} = "text/plain";
181 $hdr->{"Content-Length"} = length $content; 209 $hdr->{"Content-Length"} = length $content;
182 } 210 }
183 $hdr->{"Connection"} = "close"; 211 $hdr->{"Connection"} = "close";
184 212
185 $self->response($code, $msg, $hdr, $content); 213 $self->response($code, $msg, $hdr, $content);
186 214
187 die bless {}, err::; 215 die bless {}, err::;
188} 216}
189 217
190sub err_blocked {
191 my $self = shift;
192 my $ip = $self->{remote_addr};
193 my $time = time2str $blocked{$ip} = $::NOW + $::BLOCKTIME;
194
195 Coro::Event::do_timer(after => 20*rand);
196
197 $self->err(401, "too many connections",
198 {
199 "Content-Type" => "text/html",
200 "Retry-After" => $::BLOCKTIME,
201 "Warning" => "Please do NOT retry, you have been blocked",
202 "WWW-Authenticate" => "Basic realm=\"Please do NOT retry, you have been blocked\"",
203 },
204 <<EOF);
205<html>
206<head>
207<title>Too many connections</title>
208</head>
209<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#000080" alink="#ff0000">
210
211<p>You have been blocked because you opened too many connections. You
212may retry at</p>
213
214 <p><blockquote>$time.</blockquote></p>
215
216<p>Until then, each new access will renew the block. You might want to have a
217look at the <a href="http://www.goof.com/pcg/marc/animefaq.html">FAQ</a>.</p>
218
219</body></html>
220EOF
221}
222
223sub handle { 218sub handle {
224 my $self = shift; 219 my $self = shift;
225 my $fh = $self->{fh}; 220 my $fh = $self->{fh};
221
222 my $host;
226 223
227 $fh->timeout($::REQ_TIMEOUT); 224 $fh->timeout($::REQ_TIMEOUT);
228 while() { 225 while() {
229 $self->{reqs}++; 226 $self->{reqs}++;
230 227
240 } 237 }
241 238
242 $self->{h} = {}; 239 $self->{h} = {};
243 240
244 $fh->timeout($::RES_TIMEOUT); 241 $fh->timeout($::RES_TIMEOUT);
245 my $ip = $self->{remote_addr};
246
247 if ($blocked{$ip}) {
248 $self->err_blocked($blocked{$ip})
249 if $blocked{$ip} > $::NOW;
250
251 delete $blocked{$ip};
252 }
253
254 if (%{$conn{$ip}} > $::MAX_CONN_IP) {
255 $self->slog(2, "blocked ip $ip");
256 $self->err_blocked;
257 }
258 242
259 $req =~ /^(?:\015\012)? 243 $req =~ /^(?:\015\012)?
260 (GET|HEAD) \040+ 244 (GET|HEAD) \040+
261 ([^\040]+) \040+ 245 ([^\040]+) \040+
262 HTTP\/([0-9]+\.[0-9]+) 246 HTTP\/([0-9]+\.[0-9]+)
287 271
288 $self->{h}{$h} = substr $v, 1 272 $self->{h}{$h} = substr $v, 1
289 while ($h, $v) = each %hdr; 273 while ($h, $v) = each %hdr;
290 } 274 }
291 275
276 # remote id should be unique per user
277 my $id = $self->{remote_addr};
278
279 if (exists $self->{h}{"client-ip"}) {
280 $id .= "[".$self->{h}{"client-ip"}."]";
281 } elsif (exists $self->{h}{"x-forwarded-for"}) {
282 $id .= "[".$self->{h}{"x-forwarded-for"}."]";
283 }
284
285 $self->{remote_id} = $id;
286
287 if ($blocked{$id}) {
288 $self->err_blocked($blocked{$id})
289 if $blocked{$id} > $::NOW;
290
291 delete $blocked{$id};
292 }
293
294 if (%{$conn{$id}} >= $::MAX_CONN_IP) {
295 my $delay = $::PER_TIMEOUT + 15;
296 while (%{$conn{$id}} >= $::MAX_CONN_IP) {
297 if ($delay <= 0) {
298 $self->slog(2, "blocked ip $id");
299 $self->err_blocked;
300 } else {
301 Coro::Event::do_timer(after => 4); $delay -= 4;
302 }
303 }
304 }
305
306 # find out server name and port
307 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) {
308 $host = $1;
309 } else {
310 $host = $self->{h}{host};
311 }
312
313 if (defined $host) {
292 $self->{server_port} = $self->{h}{host} =~ s/:([0-9]+)$// ? $1 : 80; 314 $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80;
315 } else {
316 ($self->{server_port}, $host)
317 = unpack_sockaddr_in $self->{fh}->getsockname
318 or $self->err(500, "unable to get socket name");
319 $host = inet_ntoa $host;
320 }
293 321
322 $self->{server_name} = $host;
323
324 # enter ourselves into various lists
325 weaken ($conn{$id}{$self*1} = $self);
294 weaken ($uri{$self->{remote_addr}}{$self->{uri}}{$self*1} = $self); 326 weaken ($uri{$id}{$self->{uri}}{$self*1} = $self);
295 327
296 eval { 328 eval {
297 $self->map_uri; 329 $self->map_uri;
298 $self->respond; 330 $self->respond;
299 }; 331 };
300 332
301 $self->eoconn; 333 $self->eoconn;
302 334
303 die if $@ && !ref $@; 335 die if $@ && !ref $@;
304 336
305 last if $self->{h}{connection} =~ /close/ || $self->{version} lt "1.1"; 337 last if $self->{h}{connection} =~ /close/ || $self->{version} < 1.1;
306 338
307 $self->slog(9, "persistent connection [".$self->{h}{"user-agent"}."][$self->{reqs}]");
308 $fh->timeout($::PER_TIMEOUT); 339 $fh->timeout($::PER_TIMEOUT);
309 } 340 }
310} 341}
311 342
312# uri => path mapping 343# uri => path mapping
313sub map_uri { 344sub map_uri {
314 my $self = shift; 345 my $self = shift;
315 my $host = $self->{h}{host} || "default"; 346 my $host = $self->{server_name};
316 my $uri = $self->{uri}; 347 my $uri = $self->{uri};
317 348
318 # some massaging, also makes it more secure 349 # some massaging, also makes it more secure
319 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge; 350 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge;
320 $uri =~ s%//+%/%g; 351 $uri =~ s%//+%/%g;
330 $self->{path} = "$::DOCROOT/$host$uri"; 361 $self->{path} = "$::DOCROOT/$host$uri";
331 362
332 $self->access_check; 363 $self->access_check;
333} 364}
334 365
335sub server_address {
336 my $self = shift;
337 my ($port, $iaddr) = unpack_sockaddr_in $self->{fh}->getsockname
338 or $self->err(500, "unable to get socket name");
339 ((inet_ntoa $iaddr), $port);
340}
341
342sub server_host {
343 my $self = shift;
344 if (exists $self->{h}{host}) {
345 return $self->{h}{host};
346 } else {
347 return (($self->server_address)[0]);
348 }
349}
350
351sub server_hostport {
352 my $self = shift;
353 my ($host, $port);
354 if (exists $self->{h}{host}) {
355 ($host, $port) = ($self->{h}{host}, $self->{server_port});
356 } else {
357 ($host, $port) = $self->server_address;
358 }
359 $port = $port == 80 ? "" : ":$port";
360 $host.$port;
361}
362
363sub _cgi { 366sub _cgi {
364 my $self = shift; 367 my $self = shift;
365 my $path = shift; 368 my $path = shift;
366 my $fh; 369 my $fh;
367 370
368 # no two-way xxx supported 371 # no two-way xxx supported
369 if (0 == fork) { 372 if (0 == fork) {
370 open STDOUT, ">&".fileno($self->{fh}); 373 open STDOUT, ">&".fileno($self->{fh});
371 if (chdir $::DOCROOT) { 374 if (chdir $::DOCROOT) {
372 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike 375 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike
373 $ENV{HTTP_HOST} = $self->server_host; 376 $ENV{HTTP_HOST} = $self->{server_name};
374 $ENV{HTTP_PORT} = $self->{server_host}; 377 $ENV{HTTP_PORT} = $self->{server_port};
375 $ENV{SCRIPT_NAME} = $self->{name}; 378 $ENV{SCRIPT_NAME} = $self->{name};
376 exec $path; 379 exec $path;
377 } 380 }
378 Coro::State::_exit(0); 381 Coro::State::_exit(0);
379 } else { 382 } else {
383 die;
380 } 384 }
385}
386
387sub server_hostport {
388 $_[0]{server_port} == 80
389 ? $_[0]{server_name}
390 : "$_[0]{server_name}:$_[0]{server_port}";
381} 391}
382 392
383sub respond { 393sub respond {
384 my $self = shift; 394 my $self = shift;
385 my $path = $self->{path}; 395 my $path = $self->{path};
395 405
396 if (-d _ && -r _) { 406 if (-d _ && -r _) {
397 # directory 407 # directory
398 if ($path !~ /\/$/) { 408 if ($path !~ /\/$/) {
399 # create a redirect to get the trailing "/" 409 # create a redirect to get the trailing "/"
400 my $host = $self->server_hostport; 410 # we don't try to avoid the :80
401 $self->err(301, "moved permanently", { Location => "http://$host$self->{uri}/" }); 411 $self->err(301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" });
402 } else { 412 } else {
403 $ims < $self->{stat}[9] 413 $ims < $self->{stat}[9]
404 or $self->err(304, "not modified"); 414 or $self->err(304, "not modified");
405 415
406 if (-r "$path/index.html") { 416 if (-r "$path/index.html") {
430 $idx); 440 $idx);
431} 441}
432 442
433sub handle_file { 443sub handle_file {
434 my $self = shift; 444 my $self = shift;
435 my $length = -s _; 445 my $length = $self->{stat}[7];
446 my $queue = $::transfers[$length >= $::TRANSFER_SMALL];
436 my $hdr = { 447 my $hdr = {
437 "Last-Modified" => time2str ((stat _)[9]), 448 "Last-Modified" => time2str ((stat _)[9]),
438 }; 449 };
439 450
440 my @code = (200, "ok"); 451 my @code = (200, "ok");
452 } 463 }
453 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; 464 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
454 } 465 }
455 $hdr->{"Content-Range"} = "bytes */$length"; 466 $hdr->{"Content-Range"} = "bytes */$length";
456 $hdr->{"Content-Length"} = $length; 467 $hdr->{"Content-Length"} = $length;
457 $self->slog(9, "not satisfiable($self->{h}{range}|".$self->{h}{"user-agent"}.")");
458 $self->err(416, "not satisfiable", $hdr, ""); 468 $self->err(416, "not satisfiable", $hdr, "");
459 469
460satisfiable: 470satisfiable:
461 # check for segmented downloads 471 # check for segmented downloads
462 if ($l && $::NO_SEGMENTED) { 472 if ($l && $::NO_SEGMENTED) {
473 my $delay = $::PER_TIMEOUT + 15;
463 if (%{$uri{$self->{remote_addr}}{$self->{uri}}} > 1) { 474 while (%{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
464 $self->err(400, "segmented downloads are not allowed"); 475 if ($delay <= 0) {
476 $self->err_segmented_download;
477 } else {
478 Coro::Event::do_timer(after => 4); $delay -= 4;
479 }
465 } 480 }
466 } 481 }
467 482
468 $hdr->{"Content-Range"} = "bytes $l-$h/$length"; 483 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
469 @code = (206, "partial content"); 484 @code = (206, "partial content");
479 $hdr->{"Content-Length"} = $length; 494 $hdr->{"Content-Length"} = $length;
480 495
481 $self->response(@code, $hdr, ""); 496 $self->response(@code, $hdr, "");
482 497
483 if ($self->{method} eq "GET") { 498 if ($self->{method} eq "GET") {
499 $self->{time} = $::NOW;
500
501 my $fudge = $queue->[0]->waiters;
502 $fudge = $fudge ? ($fudge+1)/$fudge : 1;
503
504 $queue->[1] *= $fudge;
505 my $transfer = $queue->[0]->guard;
506
507 if ($fudge != 1) {
508 $queue->[1] /= $fudge;
509 $queue->[1] = $queue->[1] * $::wait_factor
510 + ($::NOW - $self->{time}) * (1 - $::wait_factor);
511 }
512 $self->{time} = $::NOW;
513
514 $self->{fh}->writable or return;
515
484 my ($fh, $buf, $r); 516 my ($fh, $buf, $r);
485 my $current = $Coro::current; 517 my $current = $Coro::current;
486 open $fh, "<", $self->{path} 518 open $fh, "<", $self->{path}
487 or die "$self->{path}: late open failure ($!)"; 519 or die "$self->{path}: late open failure ($!)";
488 520
500 or last; 532 or last;
501 } else { 533 } else {
502 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h), 534 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h),
503 $buf, 0, sub { 535 $buf, 0, sub {
504 $r = $_[0]; 536 $r = $_[0];
505 $current->ready; 537 Coro::ready($current);
506 }); 538 });
507 &Coro::schedule; 539 &Coro::schedule;
508 last unless $r; 540 last unless $r;
509 } 541 }
510 my $w = $self->{fh}->syswrite($buf) 542 my $w = syswrite $self->{fh}, $buf
511 or last; 543 or last;
512 $::written += $w; 544 $::written += $w;
513 $self->{written} += $w; 545 $self->{written} += $w;
514 $l += $r; 546 $l += $r;
515 } 547 }
516 }
517 548
518 close $fh; 549 close $fh;
550 }
519} 551}
520 552
5211; 5531;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines