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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines