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.33 by root, Wed Aug 29 01:40:44 2001 UTC vs.
Revision 1.46 by root, Sat Nov 17 04:15:23 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;
5 6
6use HTTP::Date; 7use HTTP::Date;
7 8
8no utf8; 9no utf8;
9use bytes; 10use bytes;
10
11our @wait_time = (); # used to calculcate avg. waiting time
12our $wait_time_length = 25;
13 11
14# at least on my machine, this thingy serves files 12# at least on my machine, this thingy serves files
15# quite a bit faster than apache, ;) 13# quite a bit faster than apache, ;)
16# and quite a bit slower than thttpd :( 14# and quite a bit slower than thttpd :(
17 15
31 my $format = shift; 29 my $format = shift;
32 printf "---: $format\n", @_; 30 printf "---: $format\n", @_;
33} 31}
34 32
35our $connections = new Coro::Semaphore $MAX_CONNECTS || 250; 33our $connections = new Coro::Semaphore $MAX_CONNECTS || 250;
36our $transfers = new Coro::Semaphore $MAX_TRANSFER || 50; 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);
37 42
38my @newcons; 43my @newcons;
39my @pool; 44my @pool;
40 45
41# one "execution thread" 46# one "execution thread"
42sub handler { 47sub handler {
43 while () { 48 while () {
44 my $new = pop @newcons;
45 if ($new) { 49 if (@newcons) {
46 eval { 50 eval {
47 conn->new(@$new)->handle; 51 conn->new(@{pop @newcons})->handle;
48 }; 52 };
49 slog 1, "$@" if $@ && !ref $@; 53 slog 1, "$@" if $@ && !ref $@;
50 $connections->up; 54 $connections->up;
51 } else { 55 } else {
52 last if @pool >= $MAX_POOL; 56 last if @pool >= $MAX_POOL;
54 schedule; 58 schedule;
55 } 59 }
56 } 60 }
57} 61}
58 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
59my $http_port = new Coro::Socket 85my $http_port = new Coro::Socket
60 LocalAddr => $SERVER_HOST, 86 LocalAddr => $SERVER_HOST,
61 LocalPort => $SERVER_PORT, 87 LocalPort => $SERVER_PORT,
62 ReuseAddr => 1, 88 ReuseAddr => 1,
63 Listen => 50, 89 Listen => 50,
64 or die "unable to start server"; 90 or die "unable to start server";
65 91
66push @listen_sockets, $http_port; 92listen_on $http_port;
93
94if ($SERVER_PORT2) {
95 my $http_port = new Coro::Socket
96 LocalAddr => $SERVER_HOST,
97 LocalPort => $SERVER_PORT2,
98 ReuseAddr => 1,
99 Listen => 50,
100 or die "unable to start server";
101
102 listen_on $http_port;
103}
67 104
68our $NOW; 105our $NOW;
69our $HTTP_NOW; 106our $HTTP_NOW;
70 107
71Event->timer(interval => 1, hard => 1, cb => sub { 108Event->timer(interval => 1, hard => 1, cb => sub {
72 $NOW = time; 109 $NOW = time;
73 $HTTP_NOW = time2str $NOW; 110 $HTTP_NOW = time2str $NOW;
74}); 111})->now;
75
76# the "main thread"
77async {
78 slog 1, "accepting connections";
79 while () {
80 $connections->down;
81 push @newcons, [$http_port->accept];
82 #slog 3, "accepted @$connections ".scalar(@pool);
83 if (@pool) {
84 (pop @pool)->ready;
85 } else {
86 async \&handler;
87 }
88
89 }
90};
91 112
92package conn; 113package conn;
93 114
94use Socket; 115use Socket;
95use HTTP::Date; 116use HTTP::Date;
96use Convert::Scalar 'weaken'; 117use Convert::Scalar 'weaken';
97use Linux::AIO; 118use Linux::AIO;
98 119
99Linux::AIO::min_parallel $::AIO_PARALLEL; 120Linux::AIO::min_parallel $::AIO_PARALLEL;
100
101my $aio_requests = new Coro::Semaphore $::AIO_PARALLEL * 4;
102 121
103Event->io(fd => Linux::AIO::poll_fileno, 122Event->io(fd => Linux::AIO::poll_fileno,
104 poll => 'r', async => 1, 123 poll => 'r', async => 1,
105 cb => \&Linux::AIO::poll_cb); 124 cb => \&Linux::AIO::poll_cb);
106 125
124 143
125read_mimetypes; 144read_mimetypes;
126 145
127sub new { 146sub new {
128 my $class = shift; 147 my $class = shift;
148 my $fh = shift;
129 my $peername = shift; 149 my $peername = shift;
130 my $fh = shift;
131 my $self = bless { fh => $fh }, $class; 150 my $self = bless { fh => $fh }, $class;
132 my (undef, $iaddr) = unpack_sockaddr_in $peername 151 my (undef, $iaddr) = unpack_sockaddr_in $peername
133 or $self->err(500, "unable to decode peername"); 152 or $self->err(500, "unable to decode peername");
134 153
135 $self->{remote_addr} = inet_ntoa $iaddr; 154 $self->{remote_addr} = inet_ntoa $iaddr;
136 $self->{time} = $::NOW; 155 $self->{time} = $::NOW;
137 156
138 # enter ourselves into various lists
139 weaken ($conn{$self->{remote_addr}}{$self*1} = $self);
140
141 $::conns++; 157 $::conns++;
142 158
143 $self; 159 $self;
144} 160}
145 161
146sub DESTROY { 162sub DESTROY {
147 my $self = shift; 163 my $self = shift;
148
149 $::conns--; 164 $::conns--;
150
151 $self->eoconn; 165 $self->eoconn;
152 delete $conn{$self->{remote_addr}}{$self*1};
153} 166}
154 167
155# end of connection 168# end of connection
156sub eoconn { 169sub eoconn {
157 my $self = shift; 170 my $self = shift;
171
172 # clean up hints
173 delete $conn{$self->{remote_id}}{$self*1};
158 delete $uri{$self->{remote_addr}}{$self->{uri}}{$self*1}; 174 delete $uri{$self->{remote_id}}{$self->{uri}}{$self*1};
175
176 $httpevent->broadcast;
159} 177}
160 178
161sub slog { 179sub slog {
162 my $self = shift; 180 my $self = shift;
163 main::slog($_[0], ($self->{remote_id} || $self->{remote_addr}) ."> $_[1]"); 181 main::slog($_[0], ($self->{remote_id} || $self->{remote_addr}) ."> $_[1]");
165 183
166sub response { 184sub response {
167 my ($self, $code, $msg, $hdr, $content) = @_; 185 my ($self, $code, $msg, $hdr, $content) = @_;
168 my $res = "HTTP/1.1 $code $msg\015\012"; 186 my $res = "HTTP/1.1 $code $msg\015\012";
169 187
170 $self->{h}{connection} ||= $hdr->{Connection}; 188 if (exists $hdr->{Connection}) {
189 if ($hdr->{Connection} =~ /close/) {
190 $self->{h}{connection} = "close"
191 }
192 } else {
193 if ($self->{version} < 1.1) {
194 if ($self->{h}{connection} =~ /keep-alive/i) {
195 $hdr->{Connection} = "Keep-Alive";
196 } else {
197 $self->{h}{connection} = "close"
198 }
199 }
200 }
171 201
172 $res .= "Date: $HTTP_NOW\015\012"; 202 $res .= "Date: $HTTP_NOW\015\012";
173 203
174 while (my ($h, $v) = each %$hdr) { 204 while (my ($h, $v) = each %$hdr) {
175 $res .= "$h: $v\015\012" 205 $res .= "$h: $v\015\012"
190sub err { 220sub err {
191 my $self = shift; 221 my $self = shift;
192 my ($code, $msg, $hdr, $content) = @_; 222 my ($code, $msg, $hdr, $content) = @_;
193 223
194 unless (defined $content) { 224 unless (defined $content) {
195 $content = "$code $msg"; 225 $content = "$code $msg\n";
196 $hdr->{"Content-Type"} = "text/plain"; 226 $hdr->{"Content-Type"} = "text/plain";
197 $hdr->{"Content-Length"} = length $content; 227 $hdr->{"Content-Length"} = length $content;
198 } 228 }
199 $hdr->{"Connection"} = "close"; 229 $hdr->{"Connection"} = "close";
200 230
225 } 255 }
226 256
227 $self->{h} = {}; 257 $self->{h} = {};
228 258
229 $fh->timeout($::RES_TIMEOUT); 259 $fh->timeout($::RES_TIMEOUT);
230 my $ip = $self->{remote_addr};
231
232 if ($blocked{$ip}) {
233 $self->err_blocked($blocked{$ip})
234 if $blocked{$ip} > $::NOW;
235
236 delete $blocked{$ip};
237 }
238
239 if (%{$conn{$ip}} > $::MAX_CONN_IP) {
240 my $delay = 120;
241 while (%{$conn{$ip}} > $::MAX_CONN_IP) {
242 if ($delay <= 0) {
243 $self->slog(2, "blocked ip $ip");
244 $self->err_blocked;
245 } else {
246 Coro::Event::do_timer(after => 3);
247 $delay -= 3;
248 }
249 }
250 }
251 260
252 $req =~ /^(?:\015\012)? 261 $req =~ /^(?:\015\012)?
253 (GET|HEAD) \040+ 262 (GET|HEAD) \040+
254 ([^\040]+) \040+ 263 ([^\040]+) \040+
255 HTTP\/([0-9]+\.[0-9]+) 264 HTTP\/([0-9]+\.[0-9]+)
280 289
281 $self->{h}{$h} = substr $v, 1 290 $self->{h}{$h} = substr $v, 1
282 while ($h, $v) = each %hdr; 291 while ($h, $v) = each %hdr;
283 } 292 }
284 293
294 # remote id should be unique per user
295 my $id = $self->{remote_addr};
296
297 if (exists $self->{h}{"client-ip"}) {
298 $id .= "[".$self->{h}{"client-ip"}."]";
299 } elsif (exists $self->{h}{"x-forwarded-for"}) {
300 $id .= "[".$self->{h}{"x-forwarded-for"}."]";
301 }
302
303 $self->{remote_id} = $id;
304
305 if ($blocked{$id}) {
306 $self->err_blocked($blocked{$id})
307 if $blocked{$id} > $::NOW;
308
309 delete $blocked{$id};
310 }
311
312 if (%{$conn{$id}} >= $::MAX_CONN_IP) {
313 my $delay = $::PER_TIMEOUT + $::NOW + 15;
314 while (%{$conn{$id}} >= $::MAX_CONN_IP) {
315 if ($delay < $::NOW) {
316 $self->slog(2, "blocked ip $id");
317 $self->err_blocked;
318 } else {
319 $httpevent->wait;
320 }
321 }
322 }
323
285 # find out server name and port 324 # find out server name and port
286 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) { 325 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) {
287 $host = $1; 326 $host = $1;
288 } else { 327 } else {
289 $host = $self->{h}{host}; 328 $host = $self->{h}{host};
291 330
292 if (defined $host) { 331 if (defined $host) {
293 $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80; 332 $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80;
294 } else { 333 } else {
295 ($self->{server_port}, $host) 334 ($self->{server_port}, $host)
296 = unpack_sockaddr_in $self->{fh}->getsockname 335 = unpack_sockaddr_in $self->{fh}->sockname
297 or $self->err(500, "unable to get socket name"); 336 or $self->err(500, "unable to get socket name");
298 $host = inet_ntoa $host; 337 $host = inet_ntoa $host;
299 } 338 }
300 339
301 $self->{server_name} = $host; 340 $self->{server_name} = $host;
302 341
303 # remote id should be unique per user 342 # enter ourselves into various lists
304 $self->{remote_id} = $self->{remote_addr}; 343 weaken ($conn{$id}{$self*1} = $self);
305
306 if (exists $self->{h}{"client-ip"}) {
307 $self->{remote_id} .= "[".$self->{h}{"client-ip"}."]";
308 } elsif (exists $self->{h}{"x-forwarded-for"}) {
309 $self->{remote_id} .= "[".$self->{h}{"x-forwarded-for"}."]";
310 }
311
312 weaken ($uri{$self->{remote_addr}}{$self->{uri}}{$self*1} = $self); 344 weaken ($uri{$id}{$self->{uri}}{$self*1} = $self);
313 345
314 eval { 346 eval {
315 $self->map_uri; 347 $self->map_uri;
316 $self->respond; 348 $self->respond;
317 }; 349 };
318 350
319 $self->eoconn; 351 $self->eoconn;
320 352
321 die if $@ && !ref $@; 353 die if $@ && !ref $@;
322 354
323 last if $self->{h}{connection} =~ /close/ || $self->{version} < 1.1; 355 last if $self->{h}{connection} =~ /close/;
356
357 $httpevent->broadcast;
324 358
325 $fh->timeout($::PER_TIMEOUT); 359 $fh->timeout($::PER_TIMEOUT);
326 } 360 }
327} 361}
328 362
398 } else { 432 } else {
399 $ims < $self->{stat}[9] 433 $ims < $self->{stat}[9]
400 or $self->err(304, "not modified"); 434 or $self->err(304, "not modified");
401 435
402 if (-r "$path/index.html") { 436 if (-r "$path/index.html") {
403 $self->{path} .= "/index.html"; 437 # replace directory "size" by index.html filesize
438 $self->{stat}[7] = (stat ($self->{path} .= "/index.html"))[7];
404 $self->handle_file; 439 $self->handle_file;
405 } else { 440 } else {
406 $self->handle_dir; 441 $self->handle_dir;
407 } 442 }
408 } 443 }
426 $idx); 461 $idx);
427} 462}
428 463
429sub handle_file { 464sub handle_file {
430 my $self = shift; 465 my $self = shift;
431 my $length = -s _; 466 my $length = $self->{stat}[7];
467 my $queue = $::transfers[$length >= $::TRANSFER_SMALL];
432 my $hdr = { 468 my $hdr = {
433 "Last-Modified" => time2str ((stat _)[9]), 469 "Last-Modified" => time2str ((stat _)[9]),
434 }; 470 };
435 471
436 my @code = (200, "ok"); 472 my @code = (200, "ok");
448 } 484 }
449 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; 485 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
450 } 486 }
451 $hdr->{"Content-Range"} = "bytes */$length"; 487 $hdr->{"Content-Range"} = "bytes */$length";
452 $hdr->{"Content-Length"} = $length; 488 $hdr->{"Content-Length"} = $length;
453 $self->slog(9, "not satisfiable($self->{h}{range}|".$self->{h}{"user-agent"}.")");
454 $self->err(416, "not satisfiable", $hdr, ""); 489 $self->err(416, "not satisfiable", $hdr, "");
455 490
456satisfiable: 491satisfiable:
457 # check for segmented downloads 492 # check for segmented downloads
458 if ($l && $::NO_SEGMENTED) { 493 if ($l && $::NO_SEGMENTED) {
459 my $delay = 180; 494 my $delay = $::NOW + $::PER_TIMEOUT + 15;
460 while (%{$uri{$self->{remote_addr}}{$self->{uri}}} > 1) { 495 while (%{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
461 if ($delay <= 0) { 496 if ($delay <= $::NOW) {
462 $self->err_segmented_download; 497 $self->err_segmented_download;
463 } else { 498 } else {
464 Coro::Event::do_timer(after => 3); $delay -= 3; 499 $httpevent->wait;
465 } 500 }
466 } 501 }
467 } 502 }
468 503
469 $hdr->{"Content-Range"} = "bytes $l-$h/$length"; 504 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
482 $self->response(@code, $hdr, ""); 517 $self->response(@code, $hdr, "");
483 518
484 if ($self->{method} eq "GET") { 519 if ($self->{method} eq "GET") {
485 $self->{time} = $::NOW; 520 $self->{time} = $::NOW;
486 521
522 my $fudge = $queue->[0]->waiters;
523 $fudge = $fudge ? ($fudge+1)/$fudge : 1;
524
525 $queue->[1] *= $fudge;
487 my $transfer = $::transfers->guard; 526 my $transfer = $queue->[0]->guard;
527
528 if ($fudge != 1) {
529 $queue->[1] /= $fudge;
530 $queue->[1] = $queue->[1] * $::wait_factor
531 + ($::NOW - $self->{time}) * (1 - $::wait_factor);
532 }
533 $self->{time} = $::NOW;
534
488 $self->{fh}->writable or return; 535 $self->{fh}->writable or return;
489
490 push @::wait_time, $::NOW - $self->{time};
491 shift @::wait_time if @wait_time > $wait_time_length;
492 $self->{time} = $::NOW;
493 536
494 my ($fh, $buf, $r); 537 my ($fh, $buf, $r);
495 my $current = $Coro::current; 538 my $current = $Coro::current;
496 open $fh, "<", $self->{path} 539 open $fh, "<", $self->{path}
497 or die "$self->{path}: late open failure ($!)"; 540 or die "$self->{path}: late open failure ($!)";
507 while ($h > 0) { 550 while ($h > 0) {
508 if (0) { 551 if (0) {
509 sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h 552 sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h
510 or last; 553 or last;
511 } else { 554 } else {
512 undef $buf;
513 $aio_requests->down;
514 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h), 555 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h),
515 $buf, 0, sub { 556 $buf, 0, sub {
516 $r = $_[0]; 557 $r = $_[0];
517 $current->ready; 558 Coro::ready($current);
518 }); 559 });
519 &Coro::schedule; 560 &Coro::schedule;
520 $aio_requests->up;
521 last unless $r; 561 last unless $r;
522 } 562 }
523 my $w = $self->{fh}->syswrite($buf) 563 my $w = syswrite $self->{fh}, $buf
524 or last; 564 or last;
525 $::written += $w; 565 $::written += $w;
526 $self->{written} += $w; 566 $self->{written} += $w;
527 $l += $r; 567 $l += $r;
528 } 568 }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines