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.29 by root, Sat Aug 25 15:14:03 2001 UTC vs.
Revision 1.44 by root, Fri Sep 14 12:38:18 2001 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;
6
7use HTTP::Date;
5 8
6no utf8; 9no utf8;
7use bytes; 10use bytes;
8 11
9# at least on my machine, this thingy serves files 12# at least on my machine, this thingy serves files
25 my $level = shift; 28 my $level = shift;
26 my $format = shift; 29 my $format = shift;
27 printf "---: $format\n", @_; 30 printf "---: $format\n", @_;
28} 31}
29 32
30my $connections = new Coro::Semaphore $MAX_CONNECTS; 33our $connections = new Coro::Semaphore $MAX_CONNECTS || 250;
34our $httpevent = new Coro::Signal;
35
36our $wait_factor = 0.95;
37
38our @transfers = (
39 [(new Coro::Semaphore $MAX_TRANSFERS_SMALL || 50), 1],
40 [(new Coro::Semaphore $MAX_TRANSFERS_LARGE || 50), 1],
41);
31 42
32my @newcons; 43my @newcons;
33my @pool; 44my @pool;
34 45
35# one "execution thread" 46# one "execution thread"
36sub handler { 47sub handler {
37 while () { 48 while () {
38 my $new = pop @newcons;
39 if ($new) { 49 if (@newcons) {
40 eval { 50 eval {
41 conn->new(@$new)->handle; 51 conn->new(@{pop @newcons})->handle;
42 }; 52 };
43 slog 1, "$@" if $@ && !ref $@; 53 slog 1, "$@" if $@ && !ref $@;
44 $connections->up; 54 $connections->up;
45 } else { 55 } else {
46 last if @pool >= $MAX_POOL; 56 last if @pool >= $MAX_POOL;
48 schedule; 58 schedule;
49 } 59 }
50 } 60 }
51} 61}
52 62
63sub listen_on {
64 my $listen = $_[0];
65
66 push @listen_sockets, $listen;
67
68 # the "main thread"
69 async {
70 slog 1, "accepting connections";
71 while () {
72 $connections->down;
73 push @newcons, [$listen->accept];
74 #slog 3, "accepted @$connections ".scalar(@pool);
75 if (@pool) {
76 (pop @pool)->ready;
77 } else {
78 async \&handler;
79 }
80
81 }
82 };
83}
84
53my $http_port = new Coro::Socket 85my $http_port = new Coro::Socket
54 LocalAddr => $SERVER_HOST, 86 LocalAddr => $SERVER_HOST,
55 LocalPort => $SERVER_PORT, 87 LocalPort => $SERVER_PORT,
56 ReuseAddr => 1, 88 ReuseAddr => 1,
57 Listen => 50, 89 Listen => 50,
58 or die "unable to start server"; 90 or die "unable to start server";
59 91
60push @listen_sockets, $http_port; 92listen_on $http_port;
61 93
62# the "main thread" 94if ($SERVER_PORT2) {
63async { 95 my $http_port = new Coro::Socket
64 slog 1, "accepting connections"; 96 LocalAddr => $SERVER_HOST,
65 while () { 97 LocalPort => $SERVER_PORT2,
66 $connections->down; 98 ReuseAddr => 1,
67 push @newcons, [$http_port->accept]; 99 Listen => 50,
68 #slog 3, "accepted @$connections ".scalar(@pool); 100 or die "unable to start server";
101
102 listen_on $http_port;
103}
104
105our $NOW;
106our $HTTP_NOW;
107
108Event->timer(interval => 1, hard => 1, cb => sub {
69 $::NOW = time; 109 $NOW = time;
70 if (@pool) { 110 $HTTP_NOW = time2str $NOW;
71 (pop @pool)->ready; 111})->now;
72 } else {
73 async \&handler;
74 }
75
76 }
77};
78 112
79package conn; 113package conn;
80 114
81use Socket; 115use Socket;
82use HTTP::Date; 116use HTTP::Date;
83use Convert::Scalar 'weaken'; 117use Convert::Scalar 'weaken';
84use Linux::AIO; 118use Linux::AIO;
85 119
86Linux::AIO::min_parallel $::AIO_PARALLEL; 120Linux::AIO::min_parallel $::AIO_PARALLEL;
87
88my $aio_requests = new Coro::Semaphore $::AIO_PARALLEL * 4;
89 121
90Event->io(fd => Linux::AIO::poll_fileno, 122Event->io(fd => Linux::AIO::poll_fileno,
91 poll => 'r', async => 1, 123 poll => 'r', async => 1,
92 cb => \&Linux::AIO::poll_cb); 124 cb => \&Linux::AIO::poll_cb);
93 125
111 143
112read_mimetypes; 144read_mimetypes;
113 145
114sub new { 146sub new {
115 my $class = shift; 147 my $class = shift;
148 my $fh = shift;
116 my $peername = shift; 149 my $peername = shift;
117 my $fh = shift;
118 my $self = bless { fh => $fh }, $class; 150 my $self = bless { fh => $fh }, $class;
119 my (undef, $iaddr) = unpack_sockaddr_in $peername 151 my (undef, $iaddr) = unpack_sockaddr_in $peername
120 or $self->err(500, "unable to decode peername"); 152 or $self->err(500, "unable to decode peername");
121 153
122 $self->{remote_addr} = inet_ntoa $iaddr; 154 $self->{remote_addr} = inet_ntoa $iaddr;
123 $self->{time} = $::NOW; 155 $self->{time} = $::NOW;
124 156
125 # enter ourselves into various lists
126 weaken ($conn{$self->{remote_addr}}{$self*1} = $self);
127
128 $::conns++; 157 $::conns++;
129 158
130 $self; 159 $self;
131} 160}
132 161
133sub DESTROY { 162sub DESTROY {
134 my $self = shift; 163 my $self = shift;
135
136 $::conns--; 164 $::conns--;
137
138 $self->eoconn; 165 $self->eoconn;
139 delete $conn{$self->{remote_addr}}{$self*1};
140} 166}
141 167
142# end of connection 168# end of connection
143sub eoconn { 169sub eoconn {
144 my $self = shift; 170 my $self = shift;
171
172 # clean up hints
173 delete $conn{$self->{remote_id}}{$self*1};
145 delete $uri{$self->{remote_addr}}{$self->{uri}}{$self*1}; 174 delete $uri{$self->{remote_id}}{$self->{uri}}{$self*1};
175
176 $httpevent->broadcast;
146} 177}
147 178
148sub slog { 179sub slog {
149 my $self = shift; 180 my $self = shift;
150 main::slog($_[0], ($self->{remote_id} || $self->{remote_addr}) ."> $_[1]"); 181 main::slog($_[0], ($self->{remote_id} || $self->{remote_addr}) ."> $_[1]");
152 183
153sub response { 184sub response {
154 my ($self, $code, $msg, $hdr, $content) = @_; 185 my ($self, $code, $msg, $hdr, $content) = @_;
155 my $res = "HTTP/1.1 $code $msg\015\012"; 186 my $res = "HTTP/1.1 $code $msg\015\012";
156 187
157 $self->{h}{connection} ||= $hdr->{Connection}; 188 $self->{h}{connection} = "close" if $hdr->{Connection} =~ /close/;
158 189
159 $res .= "Date: ".(time2str $::NOW)."\015\012"; # slow? nah. :( 190 $res .= "Date: $HTTP_NOW\015\012";
160 191
161 while (my ($h, $v) = each %$hdr) { 192 while (my ($h, $v) = each %$hdr) {
162 $res .= "$h: $v\015\012" 193 $res .= "$h: $v\015\012"
163 } 194 }
164 $res .= "\015\012"; 195 $res .= "\015\012";
177sub err { 208sub err {
178 my $self = shift; 209 my $self = shift;
179 my ($code, $msg, $hdr, $content) = @_; 210 my ($code, $msg, $hdr, $content) = @_;
180 211
181 unless (defined $content) { 212 unless (defined $content) {
182 $content = "$code $msg"; 213 $content = "$code $msg\n";
183 $hdr->{"Content-Type"} = "text/plain"; 214 $hdr->{"Content-Type"} = "text/plain";
184 $hdr->{"Content-Length"} = length $content; 215 $hdr->{"Content-Length"} = length $content;
185 } 216 }
186 $hdr->{"Connection"} = "close"; 217 $hdr->{"Connection"} = "close";
187 218
188 $self->response($code, $msg, $hdr, $content); 219 $self->response($code, $msg, $hdr, $content);
189 220
190 die bless {}, err::; 221 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} 222}
226 223
227sub handle { 224sub handle {
228 my $self = shift; 225 my $self = shift;
229 my $fh = $self->{fh}; 226 my $fh = $self->{fh};
246 } 243 }
247 244
248 $self->{h} = {}; 245 $self->{h} = {};
249 246
250 $fh->timeout($::RES_TIMEOUT); 247 $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 248
265 $req =~ /^(?:\015\012)? 249 $req =~ /^(?:\015\012)?
266 (GET|HEAD) \040+ 250 (GET|HEAD) \040+
267 ([^\040]+) \040+ 251 ([^\040]+) \040+
268 HTTP\/([0-9]+\.[0-9]+) 252 HTTP\/([0-9]+\.[0-9]+)
293 277
294 $self->{h}{$h} = substr $v, 1 278 $self->{h}{$h} = substr $v, 1
295 while ($h, $v) = each %hdr; 279 while ($h, $v) = each %hdr;
296 } 280 }
297 281
282 # remote id should be unique per user
283 my $id = $self->{remote_addr};
284
285 if (exists $self->{h}{"client-ip"}) {
286 $id .= "[".$self->{h}{"client-ip"}."]";
287 } elsif (exists $self->{h}{"x-forwarded-for"}) {
288 $id .= "[".$self->{h}{"x-forwarded-for"}."]";
289 }
290
291 $self->{remote_id} = $id;
292
293 if ($blocked{$id}) {
294 $self->err_blocked($blocked{$id})
295 if $blocked{$id} > $::NOW;
296
297 delete $blocked{$id};
298 }
299
300 if (%{$conn{$id}} >= $::MAX_CONN_IP) {
301 my $delay = $::PER_TIMEOUT + $::NOW + 15;
302 while (%{$conn{$id}} >= $::MAX_CONN_IP) {
303 if ($delay < $::NOW) {
304 $self->slog(2, "blocked ip $id");
305 $self->err_blocked;
306 } else {
307 $httpevent->wait;
308 }
309 }
310 }
311
298 # find out server name and port 312 # find out server name and port
299 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) { 313 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) {
300 $host = $1; 314 $host = $1;
301 } else { 315 } else {
302 $host = $self->{h}{host}; 316 $host = $self->{h}{host};
304 318
305 if (defined $host) { 319 if (defined $host) {
306 $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80; 320 $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80;
307 } else { 321 } else {
308 ($self->{server_port}, $host) 322 ($self->{server_port}, $host)
309 = unpack_sockaddr_in $self->{fh}->getsockname 323 = unpack_sockaddr_in $self->{fh}->sockname
310 or $self->err(500, "unable to get socket name"); 324 or $self->err(500, "unable to get socket name");
311 $host = inet_ntoa $host; 325 $host = inet_ntoa $host;
312 } 326 }
313 327
314 $self->{server_name} = $host; 328 $self->{server_name} = $host;
315 329
316 # remote id should be unique per user 330 # enter ourselves into various lists
317 $self->{remote_id} = $self->{remote_addr}; 331 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); 332 weaken ($uri{$id}{$self->{uri}}{$self*1} = $self);
326 333
327 eval { 334 eval {
328 $self->map_uri; 335 $self->map_uri;
329 $self->respond; 336 $self->respond;
330 }; 337 };
332 $self->eoconn; 339 $self->eoconn;
333 340
334 die if $@ && !ref $@; 341 die if $@ && !ref $@;
335 342
336 last if $self->{h}{connection} =~ /close/ || $self->{version} < 1.1; 343 last if $self->{h}{connection} =~ /close/ || $self->{version} < 1.1;
344
345 $httpevent->broadcast;
337 346
338 $fh->timeout($::PER_TIMEOUT); 347 $fh->timeout($::PER_TIMEOUT);
339 } 348 }
340} 349}
341 350
439 $idx); 448 $idx);
440} 449}
441 450
442sub handle_file { 451sub handle_file {
443 my $self = shift; 452 my $self = shift;
444 my $length = -s _; 453 my $length = $self->{stat}[7];
454 my $queue = $::transfers[$length >= $::TRANSFER_SMALL];
445 my $hdr = { 455 my $hdr = {
446 "Last-Modified" => time2str ((stat _)[9]), 456 "Last-Modified" => time2str ((stat _)[9]),
447 }; 457 };
448 458
449 my @code = (200, "ok"); 459 my @code = (200, "ok");
461 } 471 }
462 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; 472 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
463 } 473 }
464 $hdr->{"Content-Range"} = "bytes */$length"; 474 $hdr->{"Content-Range"} = "bytes */$length";
465 $hdr->{"Content-Length"} = $length; 475 $hdr->{"Content-Length"} = $length;
466 $self->slog(9, "not satisfiable($self->{h}{range}|".$self->{h}{"user-agent"}.")");
467 $self->err(416, "not satisfiable", $hdr, ""); 476 $self->err(416, "not satisfiable", $hdr, "");
468 477
469satisfiable: 478satisfiable:
470 # check for segmented downloads 479 # check for segmented downloads
471 if ($l && $::NO_SEGMENTED) { 480 if ($l && $::NO_SEGMENTED) {
472 my $delay = 60; 481 my $delay = $::NOW + $::PER_TIMEOUT + 15;
473 while (%{$uri{$self->{remote_addr}}{$self->{uri}}} > 1) { 482 while (%{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
474 if ($delay <= 0) { 483 if ($delay <= $::NOW) {
475 $self->err(400, "segmented downloads are not allowed", 484 $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 { 485 } else {
489 Coro::Event::do_timer(after => 3); $delay -= 3; 486 $httpevent->broadcast;
490 } 487 }
491 } 488 }
492 } 489 }
493 490
494 $hdr->{"Content-Range"} = "bytes $l-$h/$length"; 491 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
505 $hdr->{"Content-Length"} = $length; 502 $hdr->{"Content-Length"} = $length;
506 503
507 $self->response(@code, $hdr, ""); 504 $self->response(@code, $hdr, "");
508 505
509 if ($self->{method} eq "GET") { 506 if ($self->{method} eq "GET") {
507 $self->{time} = $::NOW;
508
509 my $fudge = $queue->[0]->waiters;
510 $fudge = $fudge ? ($fudge+1)/$fudge : 1;
511
512 $queue->[1] *= $fudge;
513 my $transfer = $queue->[0]->guard;
514
515 if ($fudge != 1) {
516 $queue->[1] /= $fudge;
517 $queue->[1] = $queue->[1] * $::wait_factor
518 + ($::NOW - $self->{time}) * (1 - $::wait_factor);
519 }
520 $self->{time} = $::NOW;
521
522 $self->{fh}->writable or return;
523
510 my ($fh, $buf, $r); 524 my ($fh, $buf, $r);
511 my $current = $Coro::current; 525 my $current = $Coro::current;
512 open $fh, "<", $self->{path} 526 open $fh, "<", $self->{path}
513 or die "$self->{path}: late open failure ($!)"; 527 or die "$self->{path}: late open failure ($!)";
514 528
523 while ($h > 0) { 537 while ($h > 0) {
524 if (0) { 538 if (0) {
525 sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h 539 sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h
526 or last; 540 or last;
527 } else { 541 } else {
528 undef $buf;
529 $aio_requests->down;
530 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h), 542 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h),
531 $buf, 0, sub { 543 $buf, 0, sub {
532 $r = $_[0]; 544 $r = $_[0];
533 $current->ready; 545 Coro::ready($current);
534 }); 546 });
535 &Coro::schedule; 547 &Coro::schedule;
536 $aio_requests->up;
537 last unless $r; 548 last unless $r;
538 } 549 }
539 my $w = $self->{fh}->syswrite($buf) 550 my $w = syswrite $self->{fh}, $buf
540 or last; 551 or last;
541 $::written += $w; 552 $::written += $w;
542 $self->{written} += $w; 553 $self->{written} += $w;
543 $l += $r; 554 $l += $r;
544 } 555 }
545 }
546 556
547 close $fh; 557 close $fh;
558 }
548} 559}
549 560
5501; 5611;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines