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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines