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.2 by root, Thu Aug 9 19:11:13 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 ();
7
8use HTTP::Date;
9use POSIX ();
10
11use Compress::Zlib ();
5 12
6no utf8; 13no utf8;
7use bytes; 14use bytes;
8 15
9# at least on my machine, this thingy serves files 16# at least on my machine, this thingy serves files
10# quite a bit faster than apache, ;) 17# quite a bit faster than apache, ;)
11# and quite a bit slower than thttpd :( 18# and quite a bit slower than thttpd :(
12 19
13my $port = new Coro::Socket
14 LocalAddr => $SERVER_HOST,
15 LocalPort => $SERVER_PORT,
16 ReuseAddr => 1,
17 Listen => 1,
18 or die "unable to start server";
19
20$SIG{PIPE} = 'IGNORE'; 20$SIG{PIPE} = 'IGNORE';
21 21
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}
42
43if ($ACCESS_LOG) {
44 use IO::Handle;
45 open $accesslog, ">>$ACCESS_LOG"
46 or die "$ACCESS_LOG: $!";
47 $accesslog->autoflush(1);
48}
49
22sub slog { 50sub slog {
23 my $level = shift; 51 my $level = shift;
24 my $format = shift; 52 my $format = shift;
53 my $NOW = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $::NOW);
25 printf "---: $format\n", @_; 54 printf "$NOW: $format\n", @_;
55 printf $errorlog "$NOW: $format\n", @_ if $errorlog;
26} 56}
27 57
28my $connections = new Coro::Semaphore $MAX_CONNECTS; 58our $connections = new Coro::Semaphore $MAX_CONNECTS || 250;
59our $httpevent = new Coro::Signal;
29 60
30my @fh; 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}
78
79my @newcons;
31my @pool; 80my @pool;
32 81
33# one "execution thread" 82# one "execution thread"
34sub handler { 83sub handler {
35 while () { 84 while () {
36 my $fh = pop @fh; 85 if (@newcons) {
37 if ($fh) {
38 eval { 86 eval {
39 conn->new($fh)->handle; 87 conn->new (@{pop @newcons})->handle;
40 }; 88 };
41 close $fh;
42 slog 1, "$@" if $@ && !ref $@; 89 slog 1, "$@" if $@ && !ref $@;
90
91 $httpevent->broadcast; # only for testing, but doesn't matter much
92
43 $connections->up; 93 $connections->up;
44 } else { 94 } else {
45 last if @pool >= $MAX_POOL; 95 last if @pool >= $MAX_POOL;
46 push @pool, $Coro::current; 96 push @pool, $Coro::current;
47 schedule; 97 schedule;
48 } 98 }
49 } 99 }
50} 100}
51 101
102sub listen_on {
103 my $listen = $_[0];
104
105 push @listen_sockets, $listen;
106
52# the "main thread" 107 # the "main thread"
53async { 108 async {
54 slog 1, "accepting connections"; 109 slog 1, "accepting connections";
55 while () { 110 while () {
56 $connections->down; 111 $connections->down;
57 push @fh, $port->accept; 112 push @newcons, [$listen->accept];
58 #slog 3, "accepted @$connections ".scalar(@pool); 113 #slog 3, "accepted @$connections ".scalar(@pool);
59 if (@pool) { 114 if (@pool) {
60 (pop @pool)->ready; 115 (pop @pool)->ready;
61 } else { 116 } else {
62 async \&handler; 117 async \&handler;
63 } 118 }
64 119 }
65 } 120 };
66}; 121}
67 122
68loop; 123my $http_port = new Coro::Socket
69print "ende\n";#d# 124 LocalAddr => $SERVER_HOST,
125 LocalPort => $SERVER_PORT,
126 ReuseAddr => 1,
127 Listen => 50,
128 or die "unable to start server";
129
130listen_on $http_port;
131
132if ($SERVER_PORT2) {
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";
139
140 listen_on $http_port;
141}
70 142
71package conn; 143package conn;
144
145use strict;
146use bytes;
72 147
73use Socket; 148use Socket;
74use HTTP::Date; 149use HTTP::Date;
75use Convert::Scalar 'weaken'; 150use Convert::Scalar 'weaken';
151use IO::AIO;
76 152
153IO::AIO::min_parallel $::AIO_PARALLEL;
154
155Event->io (fd => IO::AIO::poll_fileno,
156 poll => 'r', async => 1,
157 cb => \&IO::AIO::poll_cb);
158
77my %conn; # $conn{ip}{fh} => connobj 159our %conn; # $conn{ip}{self} => connobj
160our %uri; # $uri{ip}{uri}{self}
161our %blocked;
162our %mimetype;
163
164sub read_mimetypes {
165 if (open my $fh, "<mime_types") {
166 while (<$fh>) {
167 if (/^([^#]\S+)\t+(\S+)$/) {
168 $mimetype{lc $1} = $2;
169 }
170 }
171 } else {
172 print "cannot open mime_types\n";
173 }
174}
175
176read_mimetypes;
78 177
79sub new { 178sub new {
80 my $class = shift; 179 my $class = shift;
81 my $fh = shift; 180 my $fh = shift;
181 my $peername = shift;
82 my $self = bless { fh => $fh }, $class; 182 my $self = bless { fh => $fh }, $class;
83 my (undef, $iaddr) = unpack_sockaddr_in $fh->getpeername 183 my (undef, $iaddr) = unpack_sockaddr_in $peername
84 or $self->err(500, "unable to get peername"); 184 or $self->err (500, "unable to decode peername");
185
186 $self->{remote_addr} =
85 $self->{remote_address} = inet_ntoa $iaddr; 187 $self->{remote_id} = inet_ntoa $iaddr;
86 188
87 # enter ourselves into various lists 189 $self->{time} = $::NOW;
88 weaken ($conn{$self->{remote_address}}{$self*1} = $self); 190
89 print $self->{remote_address}.": ".($self*1)." > ".%{$conn{$self->{remote_address}}},"\n"; 191 weaken ($Coro::current->{conn} = $self);
192
193 ++$::conns;
194 $::maxconns = $::conns if $::conns > $::maxconns;
195
90 $self; 196 $self
91} 197}
92 198
93sub DESTROY { 199sub DESTROY {
94 my $self = shift; 200 my $self = shift;
95 delete $conn{$self->{remote_address}}{$self*1}; 201
202 close $self->{fh}; # workaround
203 --$::conns;
96} 204}
205
206sub prune_cache {
207 my $hash = $_[0];
208
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 }
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);
97 229
98sub slog { 230sub slog {
99 main::slog(@_); 231 my $self = shift;
232 main::slog($_[0], "$self->{remote_id}> $_[1]");
100} 233}
101 234
102sub print_response { 235sub response {
103 my ($self, $code, $msg, $hdr, $content) = @_; 236 my ($self, $code, $msg, $hdr, $content) = @_;
104 my $res = "HTTP/1.0 $code $msg\015\012"; 237 my $res = "HTTP/1.1 $code $msg\015\012";
238 my $GZ = "";
105 239
106 $hdr->{Date} = time2str time; # slow? nah. 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 }
266
267 $res .= "Date: $HTTP_NOW\015\012";
268 $res .= "Server: $::NAME\015\012";
107 269
108 while (my ($h, $v) = each %$hdr) { 270 while (my ($h, $v) = each %$hdr) {
109 $res .= "$h: $v\015\012" 271 $res .= "$h: $v\015\012"
110 } 272 }
111 $res .= "\015\012$content" if defined $content; 273 $res .= "\015\012";
112 274
113 print STDERR "$self->{remote_address} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}." \"$self->{h}{referer}\"\n";#d# 275 $res .= $content if defined $content and $self->{method} ne "HEAD";
114 276
115 print {$self->{fh}} $res; 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";
280
281 print $::accesslog $log if $::accesslog;
282 print STDERR $log;
283
284 $tbf_top->request(length $res, 1e6);
285 $self->{written} += print {$self->{fh}} $res;
116} 286}
117 287
118sub err { 288sub err {
119 my $self = shift; 289 my $self = shift;
120 my ($code, $msg, $hdr, $content) = @_; 290 my ($code, $msg, $hdr, $content) = @_;
121 291
122 unless (defined $content) { 292 unless (defined $content) {
123 $content = "$code $msg"; 293 $content = "$code $msg\n";
124 $hdr->{"Content-Type"} = "text/plain"; 294 $hdr->{"Content-Type"} = "text/plain";
125 $hdr->{"Content-Length"} = length $content; 295 $hdr->{"Content-Length"} = length $content;
126 } 296 }
297 $hdr->{"Connection"} = "close";
127 298
128 $self->slog($msg) if $code;
129
130 $self->print_response($code, $msg, $hdr, $content); 299 $self->response ($code, $msg, $hdr, $content);
131 300
132 die bless {}, err::; 301 die bless {}, err::
133} 302}
134 303
135sub handle { 304sub handle {
136 my $self = shift; 305 my $self = shift;
137 my $fh = $self->{fh}; 306 my $fh = $self->{fh};
138 307
308 my $host;
309
310 $fh->timeout($::REQ_TIMEOUT);
139 #while() { 311 while () {
312 $self->{reqs}++;
313
314 # read request and parse first line
315 my $req = $fh->readline("\015\012\015\012");
316
317 unless (defined $req) {
318 if (exists $self->{version}) {
319 last;
320 } else {
321 $self->err(408, "request timeout");
322 }
323 }
324
140 $self->{h} = {}; 325 $self->{h} = {};
141 326
142 # read request and parse first line
143 $fh->timeout($::REQ_TIMEOUT);
144 my $req = $fh->readline("\015\012\015\012");
145 $fh->timeout($::RES_TIMEOUT); 327 $fh->timeout($::RES_TIMEOUT);
146
147 defined $req or
148 $self->err(408, "request timeout");
149 328
150 $req =~ /^(?:\015\012)? 329 $req =~ /^(?:\015\012)?
151 (GET|HEAD) \040+ 330 (GET|HEAD) \040+
152 ([^\040]+) \040+ 331 ([^\040]+) \040+
153 HTTP\/([0-9]+\.[0-9]+) 332 HTTP\/([0-9]+\.[0-9]+)
154 \015\012/gx 333 \015\012/gx
155 or $self->err(403, "method not allowed", { Allow => "GET,HEAD" }); 334 or $self->err(405, "method not allowed", { Allow => "GET,HEAD" });
156
157 $2 ne "1.0"
158 or $self->err(506, "http protocol version not supported");
159 335
160 $self->{method} = $1; 336 $self->{method} = $1;
161 $self->{uri} = $2; 337 $self->{uri} = $2;
338 $self->{version} = $3;
339
340 $3 =~ /^1\./
341 or $self->err(506, "http protocol version $3 not supported");
162 342
163 # parse headers 343 # parse headers
164 { 344 {
165 my (%hdr, $h, $v); 345 my (%hdr, $h, $v);
166 346
167 $hdr{lc $1} .= ",$2" 347 $hdr{lc $1} .= ",$2"
168 while $req =~ /\G 348 while $req =~ /\G
169 ([^:\000-\040]+): 349 ([^:\000-\040]+):
170 [\008\040]* 350 [\011\040]*
171 ((?: [^\015\012]+ | \015\012[\008\040] )*) 351 ((?: [^\015\012]+ | \015\012[\011\040] )*)
172 \015\012 352 \015\012
173 /gxc; 353 /gxc;
174 354
175 $req =~ /\G\015\012$/ 355 $req =~ /\G\015\012$/
176 or $self->err(400, "bad request"); 356 or $self->err(400, "bad request");
177 357
178 $self->{h}{$h} = substr $v, 1 358 $self->{h}{$h} = substr $v, 1
179 while ($h, $v) = each %hdr; 359 while ($h, $v) = each %hdr;
180 } 360 }
181 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};
380 }
381
382 # find out server name and port
383 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) {
384 $host = $1;
385 } else {
386 $host = $self->{h}{host};
387 }
388
389 if (defined $host) {
182 $self->{server_port} = $self->{h}{host} =~ s/:([0-9]+)$// ? $1 : 80; 390 $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80;
391 } else {
392 ($self->{server_port}, $host)
393 = unpack_sockaddr_in $self->{fh}->sockname
394 or $self->err(500, "unable to get socket name");
395 $host = inet_ntoa $host;
396 }
183 397
398 $self->{server_name} = $host;
399
400 weaken (local $uri{$id}{$self->{uri}}{$self*1} = $self);
401
402 eval {
184 $self->map_uri; 403 $self->map_uri;
185
186 Coro::Event::do_timer(after => 5);
187
188 $self->respond; 404 $self->respond;
405 };
406
407 die if $@ && !ref $@;
408
409 last if $self->{h}{connection} =~ /close/i;
410
411 $httpevent->broadcast;
412
413 $fh->timeout($::PER_TIMEOUT);
189 #} 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;
190} 423}
191 424
192# uri => path mapping 425# uri => path mapping
193sub map_uri { 426sub map_uri {
194 my $self = shift; 427 my $self = shift;
195 my $host = $self->{h}{host} || "default"; 428 my $host = $self->{server_name};
196 my $uri = $self->{uri}; 429 my $uri = $self->{uri};
197 430
198 # some massaging, also makes it more secure 431 # some massaging, also makes it more secure
199 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge; 432 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge;
200 $uri =~ s%//+%/%g; 433 $uri =~ s%//+%/%g;
206 439
207 $self->{name} = $uri; 440 $self->{name} = $uri;
208 441
209 # now do the path mapping 442 # now do the path mapping
210 $self->{path} = "$::DOCROOT/$host$uri"; 443 $self->{path} = "$::DOCROOT/$host$uri";
211}
212 444
213sub server_address { 445 $self->access_check;
214 my $self = shift;
215 my ($port, $iaddr) = unpack_sockaddr_in $self->{fh}->getsockname
216 or $self->err(500, "unable to get socket name");
217 ((inet_ntoa $iaddr), $port);
218}
219
220sub server_host {
221 my $self = shift;
222 if (exists $self->{h}{host}) {
223 return $self->{h}{host};
224 } else {
225 return (($self->server_address)[0]);
226 }
227}
228
229sub server_hostport {
230 my $self = shift;
231 my ($host, $port);
232 if (exists $self->{h}{host}) {
233 ($host, $port) = ($self->{h}{host}, $self->{server_port});
234 } else {
235 ($host, $port) = $self->server_address;
236 }
237 $port = $port == 80 ? "" : ":$port";
238 $host.$port;
239} 446}
240 447
241sub _cgi { 448sub _cgi {
242 my $self = shift; 449 my $self = shift;
243 my $path = shift; 450 my $path = shift;
246 # no two-way xxx supported 453 # no two-way xxx supported
247 if (0 == fork) { 454 if (0 == fork) {
248 open STDOUT, ">&".fileno($self->{fh}); 455 open STDOUT, ">&".fileno($self->{fh});
249 if (chdir $::DOCROOT) { 456 if (chdir $::DOCROOT) {
250 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike 457 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike
251 $ENV{HTTP_HOST} = $self->server_host; 458 $ENV{HTTP_HOST} = $self->{server_name};
252 $ENV{HTTP_PORT} = $self->{server_host}; 459 $ENV{HTTP_PORT} = $self->{server_port};
253 $ENV{SCRIPT_NAME} = $self->{name}; 460 $ENV{SCRIPT_NAME} = $self->{name};
254 exec $::INDEXPROG; 461 exec $path;
255 } 462 }
256 Coro::State::_exit(0); 463 Coro::State::_exit(0);
257 } else { 464 } else {
465 die;
258 } 466 }
467}
468
469sub server_hostport {
470 $_[0]{server_port} == 80
471 ? $_[0]{server_name}
472 : "$_[0]{server_name}:$_[0]{server_port}";
259} 473}
260 474
261sub respond { 475sub respond {
262 my $self = shift; 476 my $self = shift;
263 my $path = $self->{path}; 477 my $path = $self->{path};
264 478
265 stat $path 479 if ($self->{name} =~ s%^/internal/([^/]+)%%) {
266 or $self->err(404, "not found"); 480 if ($::internal{$1}) {
267 481 $::internal{$1}->($self);
268 # idiotic netscape sends idiotic headers AGAIN
269 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
270 ? str2time $1 : 0;
271
272 if (-d _ && -r _) {
273 # directory
274 if ($path !~ /\/$/) {
275 # create a redirect to get the trailing "/"
276 my $host = $self->server_hostport;
277 $self->err(301, "moved permanently", { Location => "http://$host$self->{uri}/" });
278 } else { 482 } else {
279 $ims < (stat _)[9] 483 $self->err (404, "not found");
484 }
485 } else {
486
487 stat $path
488 or $self->err (404, "not found");
489
490 $self->{stat} = [stat _];
491
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}/" });
502 } else {
503 $ims < $self->{stat}[9]
280 or $self->err(304, "not modified"); 504 or $self->err (304, "not modified");
281 505
282 if ($self->{method} eq "GET") {
283 if (-r "$path/index.html") { 506 if (-r "$path/index.html") {
507 # replace directory "size" by index.html filesize
284 $self->{path} .= "/index.html"; 508 $self->{stat} = [stat ($self->{path} .= "/index.html")];
285 $self->handle_file; 509 $self->handle_file ($queue_index, $tbf_top);
286 } else { 510 } else {
287 $self->handle_dir; 511 $self->handle_dir;
288 } 512 }
289 } 513 }
290 }
291 } elsif (-f _ && -r _) { 514 } elsif (-f _ && -r _) {
292 -x _ and $self->err(403, "forbidden"); 515 -x _ and $self->err (403, "forbidden");
293 $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);
294 } else { 529 } else {
295 $self->err(404, "not found"); 530 $self->err (404, "not found");
531 }
296 } 532 }
297} 533}
298 534
299sub handle_dir { 535sub handle_dir {
300 my $self = shift; 536 my $self = shift;
301 $self->_cgi($::INDEXPROG); 537 my $idx = $self->diridx;
538
539 $self->response (200, "ok",
540 {
541 "Content-Type" => "text/html; charset=utf-8",
542 "Content-Length" => length $idx,
543 "Last-Modified" => time2str ($self->{stat}[9]),
544 },
545 $idx);
302} 546}
303 547
304sub handle_file { 548sub handle_file {
305 my $self = shift; 549 my ($self, $queue, $tbf) = @_;
306 my $length = -s _; 550 my $length = $self->{stat}[7];
307 my $hdr = { 551 my $hdr = {
308 "Last-Modified" => time2str ((stat _)[9]), 552 "Last-Modified" => time2str ((stat _)[9]),
553 "Accept-Ranges" => "bytes",
309 }; 554 };
310 555
311 my @code = (200, "ok"); 556 my @code = (200, "ok");
312 my ($l, $h); 557 my ($l, $h);
313 558
319 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1); 564 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1);
320 } else { 565 } else {
321 ($l, $h) = (0, $length - 1); 566 ($l, $h) = (0, $length - 1);
322 goto ignore; 567 goto ignore;
323 } 568 }
324 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h > $l; 569 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
325 } 570 }
326 $hdr->{"Content-Range"} = "bytes */$length"; 571 $hdr->{"Content-Range"} = "bytes */$length";
572 $hdr->{"Content-Length"} = $length;
327 $self->err(416, "not satisfiable", $hdr); 573 $self->err (416, "not satisfiable", $hdr, "");
328 574
329satisfiable: 575satisfiable:
576 # check for segmented downloads
577 if ($l && $::NO_SEGMENTED) {
578 my $timeout = $::NOW + 15;
579 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
580 if ($timeout <= $::NOW) {
581 $self->block ($::BLOCKTIME, "segmented downloads are forbidden");
582 #$self->err_segmented_download;
583 } else {
584 $httpevent->wait;
585 }
586 }
587 }
588
330 $hdr->{"Content-Range"} = "bytes $l-$h/$length"; 589 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
331 @code = (206, "partial content"); 590 @code = (206, "partial content");
332 $length = $h - $l + 1; 591 $length = $h - $l + 1;
333 592
334ignore: 593ignore:
335 } else { 594 } else {
336 ($l, $h) = (0, $length - 1); 595 ($l, $h) = (0, $length - 1);
337 } 596 }
338 597
339 if ($self->{path} =~ /\.html$/) { 598 $self->{path} =~ /\.([^.]+)$/;
340 $hdr->{"Content-Type"} = "text/html";
341 } else {
342 $hdr->{"Content-Type"} = "application/octet-stream"; 599 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream";
343 }
344
345 $hdr->{"Content-Length"} = $length; 600 $hdr->{"Content-Length"} = $length;
346 601
347 $self->print_response(@code, $hdr, ""); 602 $self->response (@code, $hdr, "");
348 603
349 if ($self->{method} eq "GET") { 604 if ($self->{method} eq "GET") {
350 my ($fh, $buf); 605 $self->{time} = $::NOW;
606 $self->{written} = 0;
607
351 open $fh, "<", $self->{path} 608 open my $fh, "<", $self->{path}
352 or die "$self->{path}: late open failure ($!)"; 609 or die "$self->{path}: late open failure ($!)";
353 610
354 if ($l) {
355 sysseek $fh, $l, 0
356 or die "$self->{path}: cannot seek to $l ($!)";
357 }
358
359 $h -= $l - 1; 611 $h -= $l - 1;
360 612
613 my $transfer = $queue->start_transfer ($h);
614 my $locked;
615 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size
616
361 while ($h > 0) { 617 while ($h > 0) {
362 $h -= sysread $fh, $buf, $h > 4096 ? 4096 : $h; 618 unless ($locked) {
363 print {$self->{fh}} $buf 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
364 or last; 632 or last;
365 }
366 }
367 633
634 $tbf->request (length $buf);
635 my $w = syswrite $self->{fh}, $buf
636 or last;
637 $::written += $w;
638 $self->{written} += $w;
639 $l += $w;
640 }
641
368 close $fh; 642 close $fh;
643 }
369} 644}
370 645
3711; 6461
647

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines