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.39 by root, Sun Sep 2 12:23:04 2001 UTC vs.
Revision 1.82 by root, Sat Dec 2 03:31:42 2006 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;
6use Coro::AIO ();
5 7
6use HTTP::Date; 8use HTTP::Date;
9use POSIX ();
10
11use Compress::Zlib ();
7 12
8no utf8; 13no utf8;
9use bytes; 14use bytes;
10 15
11# at least on my machine, this thingy serves files 16# at least on my machine, this thingy serves files
13# and quite a bit slower than thttpd :( 18# and quite a bit slower than thttpd :(
14 19
15$SIG{PIPE} = 'IGNORE'; 20$SIG{PIPE} = 'IGNORE';
16 21
17our $accesslog; 22our $accesslog;
23our $errorlog;
24
25our $NOW;
26our $HTTP_NOW;
27
28our $ERROR_LOG;
29our $ACCESS_LOG;
30
31Event->timer(interval => 1, hard => 1, cb => sub {
32 $NOW = time;
33 $HTTP_NOW = time2str $NOW;
34})->now;
35
36if ($ERROR_LOG) {
37 use IO::Handle;
38 open $errorlog, ">>$ERROR_LOG"
39 or die "$ERROR_LOG: $!";
40 $errorlog->autoflush(1);
41}
18 42
19if ($ACCESS_LOG) { 43if ($ACCESS_LOG) {
20 use IO::Handle; 44 use IO::Handle;
21 open $accesslog, ">>$ACCESS_LOG" 45 open $accesslog, ">>$ACCESS_LOG"
22 or die "$ACCESS_LOG: $!"; 46 or die "$ACCESS_LOG: $!";
24} 48}
25 49
26sub slog { 50sub slog {
27 my $level = shift; 51 my $level = shift;
28 my $format = shift; 52 my $format = shift;
53 my $NOW = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $::NOW);
29 printf "---: $format\n", @_; 54 printf "$NOW: $format\n", @_;
55 printf $errorlog "$NOW: $format\n", @_ if $errorlog;
30} 56}
31 57
32our $connections = new Coro::Semaphore $MAX_CONNECTS || 250; 58our $connections = new Coro::Semaphore $MAX_CONNECTS || 250;
59our $httpevent = new Coro::Signal;
33 60
34our $wait_factor = 0.95; 61our $queue_file = new transferqueue $MAX_TRANSFERS;
62our $queue_index = new transferqueue 10;
35 63
36our @transfers = ( 64our $tbf_top = new tbf rate => $TBF_RATE || 100000;
37 [(new Coro::Semaphore $MAX_TRANSFERS_SMALL || 50), 1], 65
38 [(new Coro::Semaphore $MAX_TRANSFERS_LARGE || 50), 1], 66my $unused_bytes = 0;
39); 67my $unused_last = time;
68
69sub unused_bandwidth {
70 $unused_bytes += $_[0];
71 if ($unused_last < $NOW - 30 && $unused_bytes / ($NOW - $unused_last) > 50000) {
72 $unused_last = $NOW;
73 $unused_bytes = 0;
74 $queue_file->force_wake_next;
75 slog 1, "forced filetransfer due to unused bandwidth";
76 }
77}
40 78
41my @newcons; 79my @newcons;
42my @pool; 80my @pool;
43 81
44# one "execution thread" 82# one "execution thread"
45sub handler { 83sub handler {
46 while () { 84 while () {
47 if (@newcons) { 85 if (@newcons) {
48 eval { 86 eval {
49 conn->new(@{pop @newcons})->handle; 87 conn->new (@{pop @newcons})->handle;
50 }; 88 };
51 slog 1, "$@" if $@ && !ref $@; 89 slog 1, "$@" if $@ && !ref $@;
90
91 $httpevent->broadcast; # only for testing, but doesn't matter much
92
52 $connections->up; 93 $connections->up;
53 } else { 94 } else {
54 last if @pool >= $MAX_POOL; 95 last if @pool >= $MAX_POOL;
55 push @pool, $Coro::current; 96 push @pool, $Coro::current;
56 schedule; 97 schedule;
57 } 98 }
58 } 99 }
59} 100}
60 101
102sub listen_on {
103 my $listen = $_[0];
104
105 push @listen_sockets, $listen;
106
107 # the "main thread"
108 async {
109 slog 1, "accepting connections";
110 while () {
111 $connections->down;
112 push @newcons, [$listen->accept];
113 #slog 3, "accepted @$connections ".scalar(@pool);
114 if (@pool) {
115 (pop @pool)->ready;
116 } else {
117 async \&handler;
118 }
119 }
120 };
121}
122
61my $http_port = new Coro::Socket 123my $http_port = new Coro::Socket
62 LocalAddr => $SERVER_HOST, 124 LocalAddr => $SERVER_HOST,
63 LocalPort => $SERVER_PORT, 125 LocalPort => $SERVER_PORT,
64 ReuseAddr => 1, 126 ReuseAddr => 1,
65 Listen => 50, 127 Listen => 50,
66 or die "unable to start server"; 128 or die "unable to start server";
67 129
68push @listen_sockets, $http_port; 130listen_on $http_port;
69 131
70our $NOW; 132if ($SERVER_PORT2) {
71our $HTTP_NOW; 133 my $http_port = new Coro::Socket
134 LocalAddr => $SERVER_HOST,
135 LocalPort => $SERVER_PORT2,
136 ReuseAddr => 1,
137 Listen => 50,
138 or die "unable to start server";
72 139
73Event->timer(interval => 1, hard => 1, cb => sub { 140 listen_on $http_port;
74 $NOW = time; 141}
75 $HTTP_NOW = time2str $NOW;
76})->now;
77
78# the "main thread"
79async {
80 slog 1, "accepting connections";
81 while () {
82 $connections->down;
83 push @newcons, [$http_port->accept];
84 #slog 3, "accepted @$connections ".scalar(@pool);
85 if (@pool) {
86 (pop @pool)->ready;
87 } else {
88 async \&handler;
89 }
90
91 }
92};
93 142
94package conn; 143package conn;
144
145use strict;
146use bytes;
95 147
96use Socket; 148use Socket;
97use HTTP::Date; 149use HTTP::Date;
98use Convert::Scalar 'weaken'; 150use Convert::Scalar 'weaken';
99use Linux::AIO; 151use IO::AIO;
100 152
101Linux::AIO::min_parallel $::AIO_PARALLEL; 153IO::AIO::min_parallel $::AIO_PARALLEL;
102 154
103Event->io(fd => Linux::AIO::poll_fileno, 155Event->io (fd => IO::AIO::poll_fileno,
104 poll => 'r', async => 1, 156 poll => 'r', async => 1,
105 cb => \&Linux::AIO::poll_cb); 157 cb => \&IO::AIO::poll_cb);
106 158
107our %conn; # $conn{ip}{self} => connobj 159our %conn; # $conn{ip}{self} => connobj
108our %uri; # $uri{ip}{uri}{self} 160our %uri; # $uri{ip}{uri}{self}
109our %blocked; 161our %blocked;
110our %mimetype; 162our %mimetype;
111 163
112sub read_mimetypes { 164sub read_mimetypes {
113 local *M;
114 if (open M, "<mime_types") { 165 if (open my $fh, "<mime_types") {
115 while (<M>) { 166 while (<$fh>) {
116 if (/^([^#]\S+)\t+(\S+)$/) { 167 if (/^([^#]\S+)\t+(\S+)$/) {
117 $mimetype{lc $1} = $2; 168 $mimetype{lc $1} = $2;
118 } 169 }
119 } 170 }
120 } else { 171 } else {
124 175
125read_mimetypes; 176read_mimetypes;
126 177
127sub new { 178sub new {
128 my $class = shift; 179 my $class = shift;
180 my $fh = shift;
129 my $peername = shift; 181 my $peername = shift;
130 my $fh = shift;
131 my $self = bless { fh => $fh }, $class; 182 my $self = bless { fh => $fh }, $class;
132 my (undef, $iaddr) = unpack_sockaddr_in $peername 183 my (undef, $iaddr) = unpack_sockaddr_in $peername
133 or $self->err(500, "unable to decode peername"); 184 or $self->err (500, "unable to decode peername");
134 185
186 $self->{remote_addr} =
135 $self->{remote_addr} = inet_ntoa $iaddr; 187 $self->{remote_id} = inet_ntoa $iaddr;
188
136 $self->{time} = $::NOW; 189 $self->{time} = $::NOW;
137 190
191 weaken ($Coro::current->{conn} = $self);
192
138 $::conns++; 193 ++$::conns;
194 $::maxconns = $::conns if $::conns > $::maxconns;
139 195
140 $self; 196 $self
141} 197}
142 198
143sub DESTROY { 199sub DESTROY {
144 my $self = shift; 200 my $self = shift;
201
202 close $self->{fh}; # workaround
145 $::conns--; 203 --$::conns;
146 $self->eoconn;
147} 204}
148 205
149# end of connection 206sub prune_cache {
150sub eoconn { 207 my $hash = $_[0];
151 my $self = shift;
152 208
153 # clean up hints 209 for (keys %$hash) {
154 delete $conn{$self->{remote_id}}{$self*1}; 210 if (ref $hash->{$_} eq HASH::) {
155 delete $uri{$self->{remote_id}}{$self->{uri}}{$self*1}; 211 prune_cache($hash->{$_});
212 unless (scalar keys %{$hash->{$_}}) {
213 delete $hash->{$_};
214 }
215 }
216 }
156} 217}
218
219sub prune_caches {
220 prune_cache \%conn;
221 prune_cache \%uri;
222
223 for (keys %blocked) {
224 delete $blocked{$_} unless $blocked{$_}[0] > $::NOW;
225 }
226}
227
228Event->timer (interval => 60, cb => \&prune_caches);
157 229
158sub slog { 230sub slog {
159 my $self = shift; 231 my $self = shift;
160 main::slog($_[0], ($self->{remote_id} || $self->{remote_addr}) ."> $_[1]"); 232 main::slog($_[0], "$self->{remote_id}> $_[1]");
161} 233}
162 234
163sub response { 235sub response {
164 my ($self, $code, $msg, $hdr, $content) = @_; 236 my ($self, $code, $msg, $hdr, $content) = @_;
165 my $res = "HTTP/1.1 $code $msg\015\012"; 237 my $res = "HTTP/1.1 $code $msg\015\012";
238 my $GZ = "";
166 239
167 $self->{h}{connection} ||= $hdr->{Connection}; 240 if (exists $hdr->{Connection}) {
241 if ($hdr->{Connection} =~ /close/) {
242 $self->{h}{connection} = "close"
243 }
244 } else {
245 if ($self->{version} < 1.1) {
246 if ($self->{h}{connection} =~ /keep-alive/i) {
247 $hdr->{Connection} = "Keep-Alive";
248 } else {
249 $self->{h}{connection} = "close"
250 }
251 }
252 }
253
254 if ($self->{method} ne "HEAD"
255 && $self->{h}{"accept-encoding"} =~ /\bgzip\b/
256 && 400 < length $content
257 && $hdr->{"Content-Length"} == length $content
258 && !exists $hdr->{"Content-Encoding"}
259 ) {
260 my $orig = length $content;
261 $hdr->{"Content-Encoding"} = "gzip";
262 $content = Compress::Zlib::memGzip(\$content);
263 $hdr->{"Content-Length"} = length $content;
264 $GZ = sprintf "GZ%02d", 100 - 100*((length $content) / $orig);
265 }
168 266
169 $res .= "Date: $HTTP_NOW\015\012"; 267 $res .= "Date: $HTTP_NOW\015\012";
268 $res .= "Server: $::NAME\015\012";
170 269
171 while (my ($h, $v) = each %$hdr) { 270 while (my ($h, $v) = each %$hdr) {
172 $res .= "$h: $v\015\012" 271 $res .= "$h: $v\015\012"
173 } 272 }
174 $res .= "\015\012"; 273 $res .= "\015\012";
175 274
176 $res .= $content if defined $content and $self->{method} ne "HEAD"; 275 $res .= $content if defined $content and $self->{method} ne "HEAD";
177 276
178 my $log = "$self->{remote_addr} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}." \"$self->{h}{referer}\"\n"; 277 my $log = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $::NOW).
278 " $self->{remote_id} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}.$GZ.
279 " \"$self->{h}{referer}\"\n";
179 280
180 print $accesslog $log if $accesslog; 281 print $::accesslog $log if $::accesslog;
181 print STDERR $log; 282 print STDERR $log;
182 283
183 $self->{written} += 284 $tbf_top->request(length $res, 1e6);
184 print {$self->{fh}} $res; 285 $self->{written} += print {$self->{fh}} $res;
185} 286}
186 287
187sub err { 288sub err {
188 my $self = shift; 289 my $self = shift;
189 my ($code, $msg, $hdr, $content) = @_; 290 my ($code, $msg, $hdr, $content) = @_;
193 $hdr->{"Content-Type"} = "text/plain"; 294 $hdr->{"Content-Type"} = "text/plain";
194 $hdr->{"Content-Length"} = length $content; 295 $hdr->{"Content-Length"} = length $content;
195 } 296 }
196 $hdr->{"Connection"} = "close"; 297 $hdr->{"Connection"} = "close";
197 298
198 $self->response($code, $msg, $hdr, $content); 299 $self->response ($code, $msg, $hdr, $content);
199 300
200 die bless {}, err::; 301 die bless {}, err::
201} 302}
202 303
203sub handle { 304sub handle {
204 my $self = shift; 305 my $self = shift;
205 my $fh = $self->{fh}; 306 my $fh = $self->{fh};
206 307
207 my $host; 308 my $host;
208 309
209 $fh->timeout($::REQ_TIMEOUT); 310 $fh->timeout($::REQ_TIMEOUT);
210 while() { 311 while () {
211 $self->{reqs}++; 312 $self->{reqs}++;
212 313
213 # read request and parse first line 314 # read request and parse first line
214 my $req = $fh->readline("\015\012\015\012"); 315 my $req = $fh->readline("\015\012\015\012");
215 316
244 my (%hdr, $h, $v); 345 my (%hdr, $h, $v);
245 346
246 $hdr{lc $1} .= ",$2" 347 $hdr{lc $1} .= ",$2"
247 while $req =~ /\G 348 while $req =~ /\G
248 ([^:\000-\040]+): 349 ([^:\000-\040]+):
249 [\008\040]* 350 [\011\040]*
250 ((?: [^\015\012]+ | \015\012[\008\040] )*) 351 ((?: [^\015\012]+ | \015\012[\011\040] )*)
251 \015\012 352 \015\012
252 /gxc; 353 /gxc;
253 354
254 $req =~ /\G\015\012$/ 355 $req =~ /\G\015\012$/
255 or $self->err(400, "bad request"); 356 or $self->err(400, "bad request");
267 $id .= "[".$self->{h}{"x-forwarded-for"}."]"; 368 $id .= "[".$self->{h}{"x-forwarded-for"}."]";
268 } 369 }
269 370
270 $self->{remote_id} = $id; 371 $self->{remote_id} = $id;
271 372
373 weaken (local $conn{$id}{$self*1} = $self);
374
272 if ($blocked{$id}) { 375 if ($blocked{$id}) {
273 $self->err_blocked($blocked{$id}) 376 $self->err_blocked
274 if $blocked{$id} > $::NOW; 377 if $blocked{$id}[0] > $::NOW;
275 378
276 delete $blocked{$id}; 379 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 } 380 }
290 381
291 # find out server name and port 382 # find out server name and port
292 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) { 383 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) {
293 $host = $1; 384 $host = $1;
297 388
298 if (defined $host) { 389 if (defined $host) {
299 $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80; 390 $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80;
300 } else { 391 } else {
301 ($self->{server_port}, $host) 392 ($self->{server_port}, $host)
302 = unpack_sockaddr_in $self->{fh}->getsockname 393 = unpack_sockaddr_in $self->{fh}->sockname
303 or $self->err(500, "unable to get socket name"); 394 or $self->err(500, "unable to get socket name");
304 $host = inet_ntoa $host; 395 $host = inet_ntoa $host;
305 } 396 }
306 397
307 $self->{server_name} = $host; 398 $self->{server_name} = $host;
308 399
309 # enter ourselves into various lists
310 weaken ($conn{$id}{$self*1} = $self);
311 weaken ($uri{$id}{$self->{uri}}{$self*1} = $self); 400 weaken (local $uri{$id}{$self->{uri}}{$self*1} = $self);
312 401
313 eval { 402 eval {
314 $self->map_uri; 403 $self->map_uri;
315 $self->respond; 404 $self->respond;
316 }; 405 };
317 406
318 $self->eoconn;
319
320 die if $@ && !ref $@; 407 die if $@ && !ref $@;
321 408
322 last if $self->{h}{connection} =~ /close/ || $self->{version} < 1.1; 409 last if $self->{h}{connection} =~ /close/i;
410
411 $httpevent->broadcast;
323 412
324 $fh->timeout($::PER_TIMEOUT); 413 $fh->timeout($::PER_TIMEOUT);
325 } 414 }
415}
416
417sub block {
418 my $self = shift;
419
420 $blocked{$self->{remote_id}} = [$::NOW + $_[0], $_[1]];
421 $self->slog(2, "blocked ip $self->{remote_id}");
422 $self->err_blocked;
326} 423}
327 424
328# uri => path mapping 425# uri => path mapping
329sub map_uri { 426sub map_uri {
330 my $self = shift; 427 my $self = shift;
377 474
378sub respond { 475sub respond {
379 my $self = shift; 476 my $self = shift;
380 my $path = $self->{path}; 477 my $path = $self->{path};
381 478
382 stat $path 479 if ($self->{name} =~ s%^/internal/([^/]+)%%) {
383 or $self->err(404, "not found"); 480 if ($::internal{$1}) {
384 481 $::internal{$1}->($self);
385 $self->{stat} = [stat _];
386
387 # idiotic netscape sends idiotic headers AGAIN
388 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
389 ? str2time $1 : 0;
390
391 if (-d _ && -r _) {
392 # directory
393 if ($path !~ /\/$/) {
394 # create a redirect to get the trailing "/"
395 # we don't try to avoid the :80
396 $self->err(301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" });
397 } else { 482 } else {
398 $ims < $self->{stat}[9] 483 $self->err (404, "not found");
484 }
485 } else {
486
487 stat $path
399 or $self->err(304, "not modified"); 488 or $self->err (404, "not found");
400 489
401 if (-r "$path/index.html") { 490 $self->{stat} = [stat _];
402 $self->{path} .= "/index.html"; 491
403 $self->handle_file; 492 # idiotic netscape sends idiotic headers AGAIN
493 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
494 ? str2time $1 : 0;
495
496 if (-d _ && -r _) {
497 # directory
498 if ($path !~ /\/$/) {
499 # create a redirect to get the trailing "/"
500 # we don't try to avoid the :80
501 $self->err (301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" });
404 } else { 502 } else {
503 $ims < $self->{stat}[9]
504 or $self->err (304, "not modified");
505
506 if (-r "$path/index.html") {
507 # replace directory "size" by index.html filesize
508 $self->{stat} = [stat ($self->{path} .= "/index.html")];
509 $self->handle_file ($queue_index, $tbf_top);
510 } else {
405 $self->handle_dir; 511 $self->handle_dir;
406 } 512 }
407 } 513 }
408 } elsif (-f _ && -r _) { 514 } elsif (-f _ && -r _) {
409 -x _ and $self->err(403, "forbidden"); 515 -x _ and $self->err (403, "forbidden");
410 $self->handle_file; 516
517 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
518 my $timeout = $::NOW + 10;
519 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
520 if ($timeout < $::NOW) {
521 $self->block($::BLOCKTIME, "too many connections");
522 } else {
523 $httpevent->wait;
524 }
525 }
526 }
527
528 $self->handle_file ($queue_file, $tbf_top);
411 } else { 529 } else {
412 $self->err(404, "not found"); 530 $self->err (404, "not found");
531 }
413 } 532 }
414} 533}
415 534
416sub handle_dir { 535sub handle_dir {
417 my $self = shift; 536 my $self = shift;
418 my $idx = $self->diridx; 537 my $idx = $self->diridx;
419 538
420 $self->response(200, "ok", 539 $self->response (200, "ok",
421 { 540 {
422 "Content-Type" => "text/html", 541 "Content-Type" => "text/html; charset=utf-8",
423 "Content-Length" => length $idx, 542 "Content-Length" => length $idx,
543 "Last-Modified" => time2str ($self->{stat}[9]),
424 }, 544 },
425 $idx); 545 $idx);
426} 546}
427 547
428sub handle_file { 548sub handle_file {
429 my $self = shift; 549 my ($self, $queue, $tbf) = @_;
430 my $length = $self->{stat}[7]; 550 my $length = $self->{stat}[7];
431 my $queue = $::transfers[$length >= $::TRANSFER_SMALL];
432 my $hdr = { 551 my $hdr = {
433 "Last-Modified" => time2str ((stat _)[9]), 552 "Last-Modified" => time2str ((stat _)[9]),
553 "Accept-Ranges" => "bytes",
434 }; 554 };
435 555
436 my @code = (200, "ok"); 556 my @code = (200, "ok");
437 my ($l, $h); 557 my ($l, $h);
438 558
448 } 568 }
449 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; 569 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
450 } 570 }
451 $hdr->{"Content-Range"} = "bytes */$length"; 571 $hdr->{"Content-Range"} = "bytes */$length";
452 $hdr->{"Content-Length"} = $length; 572 $hdr->{"Content-Length"} = $length;
453 $self->err(416, "not satisfiable", $hdr, ""); 573 $self->err (416, "not satisfiable", $hdr, "");
454 574
455satisfiable: 575satisfiable:
456 # check for segmented downloads 576 # check for segmented downloads
457 if ($l && $::NO_SEGMENTED) { 577 if ($l && $::NO_SEGMENTED) {
458 my $delay = $::PER_TIMEOUT + 15; 578 my $timeout = $::NOW + 15;
459 while (%{$uri{$self->{remote_id}}{$self->{uri}}} > 1) { 579 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
460 if ($delay <= 0) { 580 if ($timeout <= $::NOW) {
581 $self->block ($::BLOCKTIME, "segmented downloads are forbidden");
461 $self->err_segmented_download; 582 #$self->err_segmented_download;
462 } else { 583 } else {
463 Coro::Event::do_timer(after => 4); $delay -= 4; 584 $httpevent->wait;
464 } 585 }
465 } 586 }
466 } 587 }
467 588
468 $hdr->{"Content-Range"} = "bytes $l-$h/$length"; 589 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
476 597
477 $self->{path} =~ /\.([^.]+)$/; 598 $self->{path} =~ /\.([^.]+)$/;
478 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream"; 599 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream";
479 $hdr->{"Content-Length"} = $length; 600 $hdr->{"Content-Length"} = $length;
480 601
481 $self->response(@code, $hdr, ""); 602 $self->response (@code, $hdr, "");
482 603
483 if ($self->{method} eq "GET") { 604 if ($self->{method} eq "GET") {
484 $self->{time} = $::NOW; 605 $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; 606 $self->{written} = 0;
498 607
499 $self->{fh}->writable or return;
500
501 my ($fh, $buf, $r);
502 my $current = $Coro::current;
503 open $fh, "<", $self->{path} 608 open my $fh, "<", $self->{path}
504 or die "$self->{path}: late open failure ($!)"; 609 or die "$self->{path}: late open failure ($!)";
505 610
506 $h -= $l - 1; 611 $h -= $l - 1;
507 612
508 if (0) { 613 my $transfer = $queue->start_transfer ($h);
509 if ($l) { 614 my $locked;
510 sysseek $fh, $l, 0; 615 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size
511 }
512 }
513 616
514 while ($h > 0) { 617 while ($h > 0) {
515 if (0) { 618 unless ($locked) {
516 sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h 619 if ($locked ||= $transfer->try ($::WAIT_INTERVAL)) {
620 $bufsize = $::BUFSIZE;
621 $self->{time} = $::NOW;
622 $self->{written} = 0;
623 }
624 }
625
626 if ($blocked{$self->{remote_id}}) {
627 $self->{h}{connection} = "close";
628 die bless {}, err::;
629 }
630
631 Coro::AIO::aio_read $fh, $l, ($h > $bufsize ? $bufsize : $h), my $buf, 0
517 or last; 632 or last;
518 } else { 633
519 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h), 634 $tbf->request (length $buf);
520 $buf, 0, sub {
521 $r = $_[0];
522 Coro::ready($current);
523 });
524 &Coro::schedule;
525 last unless $r;
526 }
527 my $w = syswrite $self->{fh}, $buf 635 my $w = syswrite $self->{fh}, $buf
528 or last; 636 or last;
529 $::written += $w; 637 $::written += $w;
530 $self->{written} += $w; 638 $self->{written} += $w;
531 $l += $r; 639 $l += $w;
532 } 640 }
533 641
534 close $fh; 642 close $fh;
535 } 643 }
536} 644}
537 645
5381; 6461
647

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines