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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines