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.84 by root, Sat Dec 8 21:01:16 2007 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines