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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines