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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines