ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/myhttpd/httpd.pl
(Generate patch)

Comparing Coro/myhttpd/httpd.pl (file contents):
Revision 1.28 by root, Mon Aug 20 16:58:19 2001 UTC vs.
Revision 1.80 by root, Fri Dec 1 04:18:32 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
11# and quite a bit slower than thttpd :( 18# and quite a bit slower than thttpd :(
12 19
13$SIG{PIPE} = 'IGNORE'; 20$SIG{PIPE} = 'IGNORE';
14 21
15our $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}
16 42
17if ($ACCESS_LOG) { 43if ($ACCESS_LOG) {
18 use IO::Handle; 44 use IO::Handle;
19 open $accesslog, ">>$ACCESS_LOG" 45 open $accesslog, ">>$ACCESS_LOG"
20 or die "$ACCESS_LOG: $!"; 46 or die "$ACCESS_LOG: $!";
22} 48}
23 49
24sub slog { 50sub slog {
25 my $level = shift; 51 my $level = shift;
26 my $format = shift; 52 my $format = shift;
53 my $NOW = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $::NOW);
27 printf "---: $format\n", @_; 54 printf "$NOW: $format\n", @_;
55 printf $errorlog "$NOW: $format\n", @_ if $errorlog;
28} 56}
29 57
30my $connections = new Coro::Semaphore $MAX_CONNECTS; 58our $connections = new Coro::Semaphore $MAX_CONNECTS || 250;
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}
31 78
32my @newcons; 79my @newcons;
33my @pool; 80my @pool;
34 81
35# one "execution thread" 82# one "execution thread"
36sub handler { 83sub handler {
37 while () { 84 while () {
38 my $new = pop @newcons;
39 if ($new) { 85 if (@newcons) {
40 eval { 86 eval {
41 conn->new(@$new)->handle; 87 conn->new(@{pop @newcons})->handle;
42 }; 88 };
43 slog 1, "$@" if $@ && !ref $@; 89 slog 1, "$@" if $@ && !ref $@;
90
91 $httpevent->broadcast; # only for testing, but doesn't matter much
92
44 $connections->up; 93 $connections->up;
45 } else { 94 } else {
46 last if @pool >= $MAX_POOL; 95 last if @pool >= $MAX_POOL;
47 push @pool, $Coro::current; 96 push @pool, $Coro::current;
48 schedule; 97 schedule;
49 } 98 }
50 } 99 }
100}
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 };
51} 121}
52 122
53my $http_port = new Coro::Socket 123my $http_port = new Coro::Socket
54 LocalAddr => $SERVER_HOST, 124 LocalAddr => $SERVER_HOST,
55 LocalPort => $SERVER_PORT, 125 LocalPort => $SERVER_PORT,
56 ReuseAddr => 1, 126 ReuseAddr => 1,
57 Listen => 50, 127 Listen => 50,
58 or die "unable to start server"; 128 or die "unable to start server";
59 129
60push @listen_sockets, $http_port; 130listen_on $http_port;
61 131
62# the "main thread" 132if ($SERVER_PORT2) {
63async { 133 my $http_port = new Coro::Socket
64 slog 1, "accepting connections"; 134 LocalAddr => $SERVER_HOST,
65 while () { 135 LocalPort => $SERVER_PORT2,
66 $connections->down; 136 ReuseAddr => 1,
67 push @newcons, [$http_port->accept]; 137 Listen => 50,
68 #slog 3, "accepted @$connections ".scalar(@pool); 138 or die "unable to start server";
69 $::NOW = time;
70 if (@pool) {
71 (pop @pool)->ready;
72 } else {
73 async \&handler;
74 }
75 139
76 } 140 listen_on $http_port;
77}; 141}
78 142
79package conn; 143package conn;
144
145use strict;
146use bytes;
80 147
81use Socket; 148use Socket;
82use HTTP::Date; 149use HTTP::Date;
83use Convert::Scalar 'weaken'; 150use Convert::Scalar 'weaken';
84use Linux::AIO; 151use IO::AIO;
85 152
86Linux::AIO::min_parallel $::AIO_PARALLEL; 153IO::AIO::min_parallel $::AIO_PARALLEL;
87 154
88Event->io(fd => Linux::AIO::poll_fileno, 155Event->io (fd => IO::AIO::poll_fileno,
89 poll => 'r', async => 1, 156 poll => 'r', async => 1,
90 cb => \&Linux::AIO::poll_cb); 157 cb => \&IO::AIO::poll_cb);
91 158
92our %conn; # $conn{ip}{self} => connobj 159our %conn; # $conn{ip}{self} => connobj
93our %uri; # $uri{ip}{uri}{self} 160our %uri; # $uri{ip}{uri}{self}
94our %blocked; 161our %blocked;
95our %mimetype; 162our %mimetype;
109 176
110read_mimetypes; 177read_mimetypes;
111 178
112sub new { 179sub new {
113 my $class = shift; 180 my $class = shift;
181 my $fh = shift;
114 my $peername = shift; 182 my $peername = shift;
115 my $fh = shift;
116 my $self = bless { fh => $fh }, $class; 183 my $self = bless { fh => $fh }, $class;
117 my (undef, $iaddr) = unpack_sockaddr_in $peername 184 my (undef, $iaddr) = unpack_sockaddr_in $peername
118 or $self->err(500, "unable to decode peername"); 185 or $self->err(500, "unable to decode peername");
119 186
187 $self->{remote_addr} =
120 $self->{remote_addr} = inet_ntoa $iaddr; 188 $self->{remote_id} = inet_ntoa $iaddr;
189
121 $self->{time} = $::NOW; 190 $self->{time} = $::NOW;
122 191
123 # enter ourselves into various lists 192 weaken ($Coro::current->{conn} = $self);
124 weaken ($conn{$self->{remote_addr}}{$self*1} = $self);
125 193
126 $::conns++; 194 $::conns++;
195 $::maxconns = $::conns if $::conns > $::maxconns;
127 196
128 $self; 197 $self;
129} 198}
130 199
131sub DESTROY { 200sub DESTROY {
132 my $self = shift; 201 #my $self = shift;
133
134 $::conns--; 202 $::conns--;
135
136 $self->eoconn;
137 delete $conn{$self->{remote_addr}}{$self*1};
138} 203}
139 204
140# end of connection 205sub prune_cache {
141sub eoconn { 206 my $hash = $_[0];
142 my $self = shift; 207
143 delete $uri{$self->{remote_addr}}{$self->{uri}}{$self*1}; 208 for (keys %$hash) {
209 if (ref $hash->{$_} eq HASH::) {
210 prune_cache($hash->{$_});
211 unless (scalar keys %{$hash->{$_}}) {
212 delete $hash->{$_};
213 }
214 }
215 }
144} 216}
217
218sub prune_caches {
219 prune_cache \%conn;
220 prune_cache \%uri;
221
222 for (keys %blocked) {
223 delete $blocked{$_} unless $blocked{$_}[0] > $::NOW;
224 }
225}
226
227Event->timer(interval => 60, cb => \&prune_caches);
145 228
146sub slog { 229sub slog {
147 my $self = shift; 230 my $self = shift;
148 main::slog($_[0], "$self->{remote_addr}> $_[1]"); 231 main::slog($_[0], "$self->{remote_id}> $_[1]");
149} 232}
150 233
151sub response { 234sub response {
152 my ($self, $code, $msg, $hdr, $content) = @_; 235 my ($self, $code, $msg, $hdr, $content) = @_;
153 my $res = "HTTP/1.1 $code $msg\015\012"; 236 my $res = "HTTP/1.1 $code $msg\015\012";
237 my $GZ = "";
154 238
155 $self->{h}{connection} ||= $hdr->{Connection}; 239 if (exists $hdr->{Connection}) {
240 if ($hdr->{Connection} =~ /close/) {
241 $self->{h}{connection} = "close"
242 }
243 } else {
244 if ($self->{version} < 1.1) {
245 if ($self->{h}{connection} =~ /keep-alive/i) {
246 $hdr->{Connection} = "Keep-Alive";
247 } else {
248 $self->{h}{connection} = "close"
249 }
250 }
251 }
156 252
157 $res .= "Date: ".(time2str $::NOW)."\015\012"; # slow? nah. :( 253 if ($self->{method} ne "HEAD"
254 && $self->{h}{"accept-encoding"} =~ /\bgzip\b/
255 && 400 < length $content
256 && $hdr->{"Content-Length"} == length $content
257 && !exists $hdr->{"Content-Encoding"}
258 ) {
259 my $orig = length $content;
260 $hdr->{"Content-Encoding"} = "gzip";
261 $content = Compress::Zlib::memGzip(\$content);
262 $hdr->{"Content-Length"} = length $content;
263 $GZ = sprintf "GZ%02d", 100 - 100*((length $content) / $orig);
264 }
265
266 $res .= "Date: $HTTP_NOW\015\012";
267 $res .= "Server: $::NAME\015\012";
158 268
159 while (my ($h, $v) = each %$hdr) { 269 while (my ($h, $v) = each %$hdr) {
160 $res .= "$h: $v\015\012" 270 $res .= "$h: $v\015\012"
161 } 271 }
162 $res .= "\015\012"; 272 $res .= "\015\012";
163 273
164 $res .= $content if defined $content and $self->{method} ne "HEAD"; 274 $res .= $content if defined $content and $self->{method} ne "HEAD";
165 275
166 my $log = "$self->{remote_addr} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}." \"$self->{h}{referer}\"\n"; 276 my $log = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $::NOW).
277 " $self->{remote_id} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}.$GZ.
278 " \"$self->{h}{referer}\"\n";
167 279
168 print $accesslog $log if $accesslog; 280 print $::accesslog $log if $::accesslog;
169 print STDERR $log; 281 print STDERR $log;
170 282
171 $self->{written} += 283 $tbf_top->request(length $res, 1e6);
172 print {$self->{fh}} $res; 284 $self->{written} += print {$self->{fh}} $res;
173} 285}
174 286
175sub err { 287sub err {
176 my $self = shift; 288 my $self = shift;
177 my ($code, $msg, $hdr, $content) = @_; 289 my ($code, $msg, $hdr, $content) = @_;
178 290
179 unless (defined $content) { 291 unless (defined $content) {
180 $content = "$code $msg"; 292 $content = "$code $msg\n";
181 $hdr->{"Content-Type"} = "text/plain"; 293 $hdr->{"Content-Type"} = "text/plain";
182 $hdr->{"Content-Length"} = length $content; 294 $hdr->{"Content-Length"} = length $content;
183 } 295 }
184 $hdr->{"Connection"} = "close"; 296 $hdr->{"Connection"} = "close";
185 297
186 $self->response($code, $msg, $hdr, $content); 298 $self->response($code, $msg, $hdr, $content);
187 299
188 die bless {}, err::; 300 die bless {}, err::;
189} 301}
190 302
191sub err_blocked {
192 my $self = shift;
193 my $ip = $self->{remote_addr};
194 my $time = time2str $blocked{$ip} = $::NOW + $::BLOCKTIME;
195
196 Coro::Event::do_timer(after => 20*rand);
197
198 $self->err(401, "too many connections",
199 {
200 "Content-Type" => "text/html",
201 "Retry-After" => $::BLOCKTIME,
202 "Warning" => "Please do NOT retry, you have been blocked",
203 "WWW-Authenticate" => "Basic realm=\"Please do NOT retry, you have been blocked\"",
204 "Connection" => "close",
205 },
206 <<EOF);
207<html>
208<head>
209<title>Too many connections</title>
210</head>
211<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#000080" alink="#ff0000">
212
213<p>You have been blocked because you opened too many connections. You
214may retry at</p>
215
216 <p><blockquote>$time.</blockquote></p>
217
218<p>Until then, each new access will renew the block. You might want to have a
219look at the <a href="http://www.goof.com/pcg/marc/animefaq.html#connectionlimit">FAQ</a>.</p>
220
221</body></html>
222EOF
223}
224
225sub handle { 303sub handle {
226 my $self = shift; 304 my $self = shift;
227 my $fh = $self->{fh}; 305 my $fh = $self->{fh};
306
307 my $host;
228 308
229 $fh->timeout($::REQ_TIMEOUT); 309 $fh->timeout($::REQ_TIMEOUT);
230 while() { 310 while() {
231 $self->{reqs}++; 311 $self->{reqs}++;
232 312
242 } 322 }
243 323
244 $self->{h} = {}; 324 $self->{h} = {};
245 325
246 $fh->timeout($::RES_TIMEOUT); 326 $fh->timeout($::RES_TIMEOUT);
247 my $ip = $self->{remote_addr};
248
249 if ($blocked{$ip}) {
250 $self->err_blocked($blocked{$ip})
251 if $blocked{$ip} > $::NOW;
252
253 delete $blocked{$ip};
254 }
255
256 if (%{$conn{$ip}} > $::MAX_CONN_IP) {
257 $self->slog(2, "blocked ip $ip");
258 $self->err_blocked;
259 }
260 327
261 $req =~ /^(?:\015\012)? 328 $req =~ /^(?:\015\012)?
262 (GET|HEAD) \040+ 329 (GET|HEAD) \040+
263 ([^\040]+) \040+ 330 ([^\040]+) \040+
264 HTTP\/([0-9]+\.[0-9]+) 331 HTTP\/([0-9]+\.[0-9]+)
277 my (%hdr, $h, $v); 344 my (%hdr, $h, $v);
278 345
279 $hdr{lc $1} .= ",$2" 346 $hdr{lc $1} .= ",$2"
280 while $req =~ /\G 347 while $req =~ /\G
281 ([^:\000-\040]+): 348 ([^:\000-\040]+):
282 [\008\040]* 349 [\011\040]*
283 ((?: [^\015\012]+ | \015\012[\008\040] )*) 350 ((?: [^\015\012]+ | \015\012[\011\040] )*)
284 \015\012 351 \015\012
285 /gxc; 352 /gxc;
286 353
287 $req =~ /\G\015\012$/ 354 $req =~ /\G\015\012$/
288 or $self->err(400, "bad request"); 355 or $self->err(400, "bad request");
289 356
290 $self->{h}{$h} = substr $v, 1 357 $self->{h}{$h} = substr $v, 1
291 while ($h, $v) = each %hdr; 358 while ($h, $v) = each %hdr;
292 } 359 }
293 360
361 # remote id should be unique per user
362 my $id = $self->{remote_addr};
363
364 if (exists $self->{h}{"client-ip"}) {
365 $id .= "[".$self->{h}{"client-ip"}."]";
366 } elsif (exists $self->{h}{"x-forwarded-for"}) {
367 $id .= "[".$self->{h}{"x-forwarded-for"}."]";
368 }
369
370 $self->{remote_id} = $id;
371
372 weaken (local $conn{$id}{$self*1} = $self);
373
374 if ($blocked{$id}) {
375 $self->err_blocked
376 if $blocked{$id}[0] > $::NOW;
377
378 delete $blocked{$id};
379 }
380
381 # find out server name and port
382 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) {
383 $host = $1;
384 } else {
385 $host = $self->{h}{host};
386 }
387
388 if (defined $host) {
294 $self->{server_port} = $self->{h}{host} =~ s/:([0-9]+)$// ? $1 : 80; 389 $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80;
390 } else {
391 ($self->{server_port}, $host)
392 = unpack_sockaddr_in $self->{fh}->sockname
393 or $self->err(500, "unable to get socket name");
394 $host = inet_ntoa $host;
395 }
295 396
397 $self->{server_name} = $host;
398
296 weaken ($uri{$self->{remote_addr}}{$self->{uri}}{$self*1} = $self); 399 weaken (local $uri{$id}{$self->{uri}}{$self*1} = $self);
297 400
298 eval { 401 eval {
299 $self->map_uri; 402 $self->map_uri;
300 $self->respond; 403 $self->respond;
301 }; 404 };
302 405
303 $self->eoconn;
304
305 die if $@ && !ref $@; 406 die if $@ && !ref $@;
306 407
307 last if $self->{h}{connection} =~ /close/ || $self->{version} lt "1.1"; 408 last if $self->{h}{connection} =~ /close/i;
308 409
309 $self->slog(9, "persistent connection [".$self->{h}{"user-agent"}."][$self->{reqs}]"); 410 $httpevent->broadcast;
411
310 $fh->timeout($::PER_TIMEOUT); 412 $fh->timeout($::PER_TIMEOUT);
311 } 413 }
414}
415
416sub block {
417 my $self = shift;
418
419 $blocked{$self->{remote_id}} = [$::NOW + $_[0], $_[1]];
420 $self->slog(2, "blocked ip $self->{remote_id}");
421 $self->err_blocked;
312} 422}
313 423
314# uri => path mapping 424# uri => path mapping
315sub map_uri { 425sub map_uri {
316 my $self = shift; 426 my $self = shift;
317 my $host = $self->{h}{host} || "default"; 427 my $host = $self->{server_name};
318 my $uri = $self->{uri}; 428 my $uri = $self->{uri};
319 429
320 # some massaging, also makes it more secure 430 # some massaging, also makes it more secure
321 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge; 431 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge;
322 $uri =~ s%//+%/%g; 432 $uri =~ s%//+%/%g;
332 $self->{path} = "$::DOCROOT/$host$uri"; 442 $self->{path} = "$::DOCROOT/$host$uri";
333 443
334 $self->access_check; 444 $self->access_check;
335} 445}
336 446
337sub server_address {
338 my $self = shift;
339 my ($port, $iaddr) = unpack_sockaddr_in $self->{fh}->getsockname
340 or $self->err(500, "unable to get socket name");
341 ((inet_ntoa $iaddr), $port);
342}
343
344sub server_host {
345 my $self = shift;
346 if (exists $self->{h}{host}) {
347 return $self->{h}{host};
348 } else {
349 return (($self->server_address)[0]);
350 }
351}
352
353sub server_hostport {
354 my $self = shift;
355 my ($host, $port);
356 if (exists $self->{h}{host}) {
357 ($host, $port) = ($self->{h}{host}, $self->{server_port});
358 } else {
359 ($host, $port) = $self->server_address;
360 }
361 $port = $port == 80 ? "" : ":$port";
362 $host.$port;
363}
364
365sub _cgi { 447sub _cgi {
366 my $self = shift; 448 my $self = shift;
367 my $path = shift; 449 my $path = shift;
368 my $fh; 450 my $fh;
369 451
370 # no two-way xxx supported 452 # no two-way xxx supported
371 if (0 == fork) { 453 if (0 == fork) {
372 open STDOUT, ">&".fileno($self->{fh}); 454 open STDOUT, ">&".fileno($self->{fh});
373 if (chdir $::DOCROOT) { 455 if (chdir $::DOCROOT) {
374 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike 456 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike
375 $ENV{HTTP_HOST} = $self->server_host; 457 $ENV{HTTP_HOST} = $self->{server_name};
376 $ENV{HTTP_PORT} = $self->{server_host}; 458 $ENV{HTTP_PORT} = $self->{server_port};
377 $ENV{SCRIPT_NAME} = $self->{name}; 459 $ENV{SCRIPT_NAME} = $self->{name};
378 exec $path; 460 exec $path;
379 } 461 }
380 Coro::State::_exit(0); 462 Coro::State::_exit(0);
381 } else { 463 } else {
464 die;
382 } 465 }
466}
467
468sub server_hostport {
469 $_[0]{server_port} == 80
470 ? $_[0]{server_name}
471 : "$_[0]{server_name}:$_[0]{server_port}";
383} 472}
384 473
385sub respond { 474sub respond {
386 my $self = shift; 475 my $self = shift;
387 my $path = $self->{path}; 476 my $path = $self->{path};
388 477
389 stat $path 478 if ($self->{name} =~ s%^/internal/([^/]+)%%) {
390 or $self->err(404, "not found"); 479 if ($::internal{$1}) {
391 480 $::internal{$1}->($self);
392 $self->{stat} = [stat _];
393
394 # idiotic netscape sends idiotic headers AGAIN
395 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
396 ? str2time $1 : 0;
397
398 if (-d _ && -r _) {
399 # directory
400 if ($path !~ /\/$/) {
401 # create a redirect to get the trailing "/"
402 my $host = $self->server_hostport;
403 $self->err(301, "moved permanently", { Location => "http://$host$self->{uri}/" });
404 } else { 481 } else {
405 $ims < $self->{stat}[9] 482 $self->err(404, "not found");
483 }
484 } else {
485
486 stat $path
406 or $self->err(304, "not modified"); 487 or $self->err(404, "not found");
407 488
408 if (-r "$path/index.html") { 489 $self->{stat} = [stat _];
409 $self->{path} .= "/index.html"; 490
410 $self->handle_file; 491 # idiotic netscape sends idiotic headers AGAIN
492 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
493 ? str2time $1 : 0;
494
495 if (-d _ && -r _) {
496 # directory
497 if ($path !~ /\/$/) {
498 # create a redirect to get the trailing "/"
499 # we don't try to avoid the :80
500 $self->err(301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" });
411 } else { 501 } else {
502 $ims < $self->{stat}[9]
503 or $self->err(304, "not modified");
504
505 if (-r "$path/index.html") {
506 # replace directory "size" by index.html filesize
507 $self->{stat} = [stat ($self->{path} .= "/index.html")];
508 $self->handle_file($queue_index, $tbf_top);
509 } else {
412 $self->handle_dir; 510 $self->handle_dir;
413 } 511 }
414 } 512 }
415 } elsif (-f _ && -r _) { 513 } elsif (-f _ && -r _) {
416 -x _ and $self->err(403, "forbidden"); 514 -x _ and $self->err(403, "forbidden");
417 $self->handle_file; 515
516 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
517 my $timeout = $::NOW + 10;
518 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
519 if ($timeout < $::NOW) {
520 $self->block($::BLOCKTIME, "too many connections");
521 } else {
522 $httpevent->wait;
523 }
524 }
525 }
526
527 $self->handle_file($queue_file, $tbf_top);
418 } else { 528 } else {
419 $self->err(404, "not found"); 529 $self->err(404, "not found");
530 }
420 } 531 }
421} 532}
422 533
423sub handle_dir { 534sub handle_dir {
424 my $self = shift; 535 my $self = shift;
425 my $idx = $self->diridx; 536 my $idx = $self->diridx;
426 537
427 $self->response(200, "ok", 538 $self->response(200, "ok",
428 { 539 {
429 "Content-Type" => "text/html", 540 "Content-Type" => "text/html; charset=utf-8",
430 "Content-Length" => length $idx, 541 "Content-Length" => length $idx,
542 "Last-Modified" => time2str ($self->{stat}[9]),
431 }, 543 },
432 $idx); 544 $idx);
433} 545}
434 546
435sub handle_file { 547sub handle_file {
436 my $self = shift; 548 my ($self, $queue, $tbf) = @_;
437 my $length = -s _; 549 my $length = $self->{stat}[7];
438 my $hdr = { 550 my $hdr = {
439 "Last-Modified" => time2str ((stat _)[9]), 551 "Last-Modified" => time2str ((stat _)[9]),
552 "Accept-Ranges" => "bytes",
440 }; 553 };
441 554
442 my @code = (200, "ok"); 555 my @code = (200, "ok");
443 my ($l, $h); 556 my ($l, $h);
444 557
454 } 567 }
455 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; 568 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
456 } 569 }
457 $hdr->{"Content-Range"} = "bytes */$length"; 570 $hdr->{"Content-Range"} = "bytes */$length";
458 $hdr->{"Content-Length"} = $length; 571 $hdr->{"Content-Length"} = $length;
459 $self->slog(9, "not satisfiable($self->{h}{range}|".$self->{h}{"user-agent"}.")");
460 $self->err(416, "not satisfiable", $hdr, ""); 572 $self->err(416, "not satisfiable", $hdr, "");
461 573
462satisfiable: 574satisfiable:
463 # check for segmented downloads 575 # check for segmented downloads
464 if ($l && $::NO_SEGMENTED) { 576 if ($l && $::NO_SEGMENTED) {
577 my $timeout = $::NOW + 15;
465 if (%{$uri{$self->{remote_addr}}{$self->{uri}}} > 1) { 578 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
466 $self->err(400, "segmented downloads are not allowed", 579 if ($timeout <= $::NOW) {
467 { "Content-Type" => "text/html", Connection => "close" }, <<EOF); 580 $self->block($::BLOCKTIME, "segmented downloads are forbidden");
468<html> 581 #$self->err_segmented_download;
469<head> 582 } else {
470<title>Segmented downloads are not allowed</title> 583 $httpevent->wait;
471</head> 584 }
472<body bgcolor="#ffffff" text="#000000" link="#0000ff" vlink="#000080" alink="#ff0000">
473
474<p>Segmented downloads are not allowed on this server. Please refer to the
475<a href="http://www.goof.com/pcg/marc/animefaq.html#segmented_downloads">FAQ</a>.</p>
476
477</body></html>
478EOF
479EOF
480 } 585 }
481 } 586 }
482 587
483 $hdr->{"Content-Range"} = "bytes $l-$h/$length"; 588 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
484 @code = (206, "partial content"); 589 @code = (206, "partial content");
494 $hdr->{"Content-Length"} = $length; 599 $hdr->{"Content-Length"} = $length;
495 600
496 $self->response(@code, $hdr, ""); 601 $self->response(@code, $hdr, "");
497 602
498 if ($self->{method} eq "GET") { 603 if ($self->{method} eq "GET") {
499 my ($fh, $buf, $r); 604 $self->{time} = $::NOW;
500 my $current = $Coro::current; 605 $self->{written} = 0;
606
607 my $fh;
608
501 open $fh, "<", $self->{path} 609 open $fh, "<", $self->{path}
502 or die "$self->{path}: late open failure ($!)"; 610 or die "$self->{path}: late open failure ($!)";
503 611
504 $h -= $l - 1; 612 $h -= $l - 1;
505 613
506 if (0) { 614 if (0) { # !AIO
507 if ($l) { 615 if ($l) {
508 sysseek $fh, $l, 0; 616 sysseek $fh, $l, 0;
509 } 617 }
510 } 618 }
619
620 my $transfer = $queue->start_transfer($h);
621 my $locked;
622 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size
511 623
512 while ($h > 0) { 624 while ($h > 0) {
513 if (0) { 625 unless ($locked) {
514 sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h 626 if ($locked ||= $transfer->try($::WAIT_INTERVAL)) {
627 $bufsize = $::BUFSIZE;
628 $self->{time} = $::NOW;
629 $self->{written} = 0;
630 }
631 }
632
633 if ($blocked{$self->{remote_id}}) {
634 $self->{h}{connection} = "close";
635 die bless {}, err::;
636 }
637
638 Coro::AIO::aio_read $fh, $l, ($h > $bufsize ? $bufsize : $h), my $buf, 0
515 or last; 639 or last;
516 } else { 640
517 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h), 641 $tbf->request (length $buf);
518 $buf, 0, sub { 642 my $w = syswrite $self->{fh}, $buf
519 $r = $_[0];
520 $current->ready;
521 });
522 &Coro::schedule;
523 last unless $r;
524 }
525 my $w = $self->{fh}->syswrite($buf)
526 or last; 643 or last;
527 $::written += $w; 644 $::written += $w;
528 $self->{written} += $w; 645 $self->{written} += $w;
529 $l += $r; 646 $l += $w;
530 } 647 }
531 }
532 648
533 close $fh; 649 close $fh;
650 }
534} 651}
535 652
5361; 6531
654

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines