1 |
use Coro; |
2 |
use Coro::Semaphore; |
3 |
use Coro::Event; |
4 |
use Coro::Socket; |
5 |
|
6 |
use HTTP::Date; |
7 |
|
8 |
no utf8; |
9 |
use bytes; |
10 |
|
11 |
# at least on my machine, this thingy serves files |
12 |
# quite a bit faster than apache, ;) |
13 |
# and quite a bit slower than thttpd :( |
14 |
|
15 |
$SIG{PIPE} = 'IGNORE'; |
16 |
|
17 |
our $accesslog; |
18 |
|
19 |
if ($ACCESS_LOG) { |
20 |
use IO::Handle; |
21 |
open $accesslog, ">>$ACCESS_LOG" |
22 |
or die "$ACCESS_LOG: $!"; |
23 |
$accesslog->autoflush(1); |
24 |
} |
25 |
|
26 |
sub slog { |
27 |
my $level = shift; |
28 |
my $format = shift; |
29 |
printf "---: $format\n", @_; |
30 |
} |
31 |
|
32 |
our $connections = new Coro::Semaphore $MAX_CONNECTS || 250; |
33 |
|
34 |
our $wait_factor = 0.95; |
35 |
|
36 |
our @transfers = ( |
37 |
[(new Coro::Semaphore $MAX_TRANSFERS_SMALL || 50), 1], |
38 |
[(new Coro::Semaphore $MAX_TRANSFERS_LARGE || 50), 1], |
39 |
); |
40 |
|
41 |
my @newcons; |
42 |
my @pool; |
43 |
|
44 |
# one "execution thread" |
45 |
sub handler { |
46 |
while () { |
47 |
if (@newcons) { |
48 |
eval { |
49 |
conn->new(@{pop @newcons})->handle; |
50 |
}; |
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 |
} |
59 |
} |
60 |
|
61 |
sub listen_on { |
62 |
my $listen = $_[0]; |
63 |
|
64 |
push @listen_sockets, $listen; |
65 |
|
66 |
# the "main thread" |
67 |
async { |
68 |
slog 1, "accepting connections"; |
69 |
while () { |
70 |
$connections->down; |
71 |
push @newcons, [$listen->accept]; |
72 |
#slog 3, "accepted @$connections ".scalar(@pool); |
73 |
if (@pool) { |
74 |
(pop @pool)->ready; |
75 |
} else { |
76 |
async \&handler; |
77 |
} |
78 |
|
79 |
} |
80 |
}; |
81 |
} |
82 |
|
83 |
my $http_port = new Coro::Socket |
84 |
LocalAddr => $SERVER_HOST, |
85 |
LocalPort => $SERVER_PORT, |
86 |
ReuseAddr => 1, |
87 |
Listen => 50, |
88 |
or die "unable to start server"; |
89 |
|
90 |
listen_on $http_port; |
91 |
|
92 |
if ($SERVER_PORT2) { |
93 |
my $http_port = new Coro::Socket |
94 |
LocalAddr => $SERVER_HOST, |
95 |
LocalPort => $SERVER_PORT2, |
96 |
ReuseAddr => 1, |
97 |
Listen => 50, |
98 |
or die "unable to start server"; |
99 |
|
100 |
listen_on $http_port; |
101 |
} |
102 |
|
103 |
our $NOW; |
104 |
our $HTTP_NOW; |
105 |
|
106 |
Event->timer(interval => 1, hard => 1, cb => sub { |
107 |
$NOW = time; |
108 |
$HTTP_NOW = time2str $NOW; |
109 |
})->now; |
110 |
|
111 |
package conn; |
112 |
|
113 |
use Socket; |
114 |
use HTTP::Date; |
115 |
use Convert::Scalar 'weaken'; |
116 |
use Linux::AIO; |
117 |
|
118 |
Linux::AIO::min_parallel $::AIO_PARALLEL; |
119 |
|
120 |
Event->io(fd => Linux::AIO::poll_fileno, |
121 |
poll => 'r', async => 1, |
122 |
cb => \&Linux::AIO::poll_cb); |
123 |
|
124 |
our %conn; # $conn{ip}{self} => connobj |
125 |
our %uri; # $uri{ip}{uri}{self} |
126 |
our %blocked; |
127 |
our %mimetype; |
128 |
|
129 |
sub read_mimetypes { |
130 |
local *M; |
131 |
if (open M, "<mime_types") { |
132 |
while (<M>) { |
133 |
if (/^([^#]\S+)\t+(\S+)$/) { |
134 |
$mimetype{lc $1} = $2; |
135 |
} |
136 |
} |
137 |
} else { |
138 |
print "cannot open mime_types\n"; |
139 |
} |
140 |
} |
141 |
|
142 |
read_mimetypes; |
143 |
|
144 |
sub new { |
145 |
my $class = shift; |
146 |
my $fh = shift; |
147 |
my $peername = shift; |
148 |
my $self = bless { fh => $fh }, $class; |
149 |
my (undef, $iaddr) = unpack_sockaddr_in $peername |
150 |
or $self->err(500, "unable to decode peername"); |
151 |
|
152 |
$self->{remote_addr} = inet_ntoa $iaddr; |
153 |
$self->{time} = $::NOW; |
154 |
|
155 |
$::conns++; |
156 |
|
157 |
$self; |
158 |
} |
159 |
|
160 |
sub DESTROY { |
161 |
my $self = shift; |
162 |
$::conns--; |
163 |
$self->eoconn; |
164 |
} |
165 |
|
166 |
# end of connection |
167 |
sub eoconn { |
168 |
my $self = shift; |
169 |
|
170 |
# clean up hints |
171 |
delete $conn{$self->{remote_id}}{$self*1}; |
172 |
delete $uri{$self->{remote_id}}{$self->{uri}}{$self*1}; |
173 |
} |
174 |
|
175 |
sub slog { |
176 |
my $self = shift; |
177 |
main::slog($_[0], ($self->{remote_id} || $self->{remote_addr}) ."> $_[1]"); |
178 |
} |
179 |
|
180 |
sub response { |
181 |
my ($self, $code, $msg, $hdr, $content) = @_; |
182 |
my $res = "HTTP/1.1 $code $msg\015\012"; |
183 |
|
184 |
$self->{h}{connection} = "close" if $hdr->{Connection} =~ /close/; |
185 |
|
186 |
$res .= "Date: $HTTP_NOW\015\012"; |
187 |
|
188 |
while (my ($h, $v) = each %$hdr) { |
189 |
$res .= "$h: $v\015\012" |
190 |
} |
191 |
$res .= "\015\012"; |
192 |
|
193 |
$res .= $content if defined $content and $self->{method} ne "HEAD"; |
194 |
|
195 |
my $log = "$self->{remote_addr} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}." \"$self->{h}{referer}\"\n"; |
196 |
|
197 |
print $accesslog $log if $accesslog; |
198 |
print STDERR $log; |
199 |
|
200 |
$self->{written} += |
201 |
print {$self->{fh}} $res; |
202 |
} |
203 |
|
204 |
sub err { |
205 |
my $self = shift; |
206 |
my ($code, $msg, $hdr, $content) = @_; |
207 |
|
208 |
unless (defined $content) { |
209 |
$content = "$code $msg\n"; |
210 |
$hdr->{"Content-Type"} = "text/plain"; |
211 |
$hdr->{"Content-Length"} = length $content; |
212 |
} |
213 |
$hdr->{"Connection"} = "close"; |
214 |
|
215 |
$self->response($code, $msg, $hdr, $content); |
216 |
|
217 |
die bless {}, err::; |
218 |
} |
219 |
|
220 |
sub handle { |
221 |
my $self = shift; |
222 |
my $fh = $self->{fh}; |
223 |
|
224 |
my $host; |
225 |
|
226 |
$fh->timeout($::REQ_TIMEOUT); |
227 |
while() { |
228 |
$self->{reqs}++; |
229 |
|
230 |
# read request and parse first line |
231 |
my $req = $fh->readline("\015\012\015\012"); |
232 |
|
233 |
unless (defined $req) { |
234 |
if (exists $self->{version}) { |
235 |
last; |
236 |
} else { |
237 |
$self->err(408, "request timeout"); |
238 |
} |
239 |
} |
240 |
|
241 |
$self->{h} = {}; |
242 |
|
243 |
$fh->timeout($::RES_TIMEOUT); |
244 |
|
245 |
$req =~ /^(?:\015\012)? |
246 |
(GET|HEAD) \040+ |
247 |
([^\040]+) \040+ |
248 |
HTTP\/([0-9]+\.[0-9]+) |
249 |
\015\012/gx |
250 |
or $self->err(405, "method not allowed", { Allow => "GET,HEAD" }); |
251 |
|
252 |
$self->{method} = $1; |
253 |
$self->{uri} = $2; |
254 |
$self->{version} = $3; |
255 |
|
256 |
$3 =~ /^1\./ |
257 |
or $self->err(506, "http protocol version $3 not supported"); |
258 |
|
259 |
# parse headers |
260 |
{ |
261 |
my (%hdr, $h, $v); |
262 |
|
263 |
$hdr{lc $1} .= ",$2" |
264 |
while $req =~ /\G |
265 |
([^:\000-\040]+): |
266 |
[\008\040]* |
267 |
((?: [^\015\012]+ | \015\012[\008\040] )*) |
268 |
\015\012 |
269 |
/gxc; |
270 |
|
271 |
$req =~ /\G\015\012$/ |
272 |
or $self->err(400, "bad request"); |
273 |
|
274 |
$self->{h}{$h} = substr $v, 1 |
275 |
while ($h, $v) = each %hdr; |
276 |
} |
277 |
|
278 |
# remote id should be unique per user |
279 |
my $id = $self->{remote_addr}; |
280 |
|
281 |
if (exists $self->{h}{"client-ip"}) { |
282 |
$id .= "[".$self->{h}{"client-ip"}."]"; |
283 |
} elsif (exists $self->{h}{"x-forwarded-for"}) { |
284 |
$id .= "[".$self->{h}{"x-forwarded-for"}."]"; |
285 |
} |
286 |
|
287 |
$self->{remote_id} = $id; |
288 |
|
289 |
if ($blocked{$id}) { |
290 |
$self->err_blocked($blocked{$id}) |
291 |
if $blocked{$id} > $::NOW; |
292 |
|
293 |
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 |
} |
307 |
|
308 |
# find out server name and port |
309 |
if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) { |
310 |
$host = $1; |
311 |
} else { |
312 |
$host = $self->{h}{host}; |
313 |
} |
314 |
|
315 |
if (defined $host) { |
316 |
$self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80; |
317 |
} else { |
318 |
($self->{server_port}, $host) |
319 |
= unpack_sockaddr_in $self->{fh}->getsockname |
320 |
or $self->err(500, "unable to get socket name"); |
321 |
$host = inet_ntoa $host; |
322 |
} |
323 |
|
324 |
$self->{server_name} = $host; |
325 |
|
326 |
# enter ourselves into various lists |
327 |
weaken ($conn{$id}{$self*1} = $self); |
328 |
weaken ($uri{$id}{$self->{uri}}{$self*1} = $self); |
329 |
|
330 |
eval { |
331 |
$self->map_uri; |
332 |
$self->respond; |
333 |
}; |
334 |
|
335 |
$self->eoconn; |
336 |
|
337 |
die if $@ && !ref $@; |
338 |
|
339 |
last if $self->{h}{connection} =~ /close/ || $self->{version} < 1.1; |
340 |
|
341 |
$fh->timeout($::PER_TIMEOUT); |
342 |
} |
343 |
} |
344 |
|
345 |
# uri => path mapping |
346 |
sub map_uri { |
347 |
my $self = shift; |
348 |
my $host = $self->{server_name}; |
349 |
my $uri = $self->{uri}; |
350 |
|
351 |
# some massaging, also makes it more secure |
352 |
$uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge; |
353 |
$uri =~ s%//+%/%g; |
354 |
$uri =~ s%/\.(?=/|$)%%g; |
355 |
1 while $uri =~ s%/[^/]+/\.\.(?=/|$)%%; |
356 |
|
357 |
$uri =~ m%^/?\.\.(?=/|$)% |
358 |
and $self->err(400, "bad request"); |
359 |
|
360 |
$self->{name} = $uri; |
361 |
|
362 |
# now do the path mapping |
363 |
$self->{path} = "$::DOCROOT/$host$uri"; |
364 |
|
365 |
$self->access_check; |
366 |
} |
367 |
|
368 |
sub _cgi { |
369 |
my $self = shift; |
370 |
my $path = shift; |
371 |
my $fh; |
372 |
|
373 |
# no two-way xxx supported |
374 |
if (0 == fork) { |
375 |
open STDOUT, ">&".fileno($self->{fh}); |
376 |
if (chdir $::DOCROOT) { |
377 |
$ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike |
378 |
$ENV{HTTP_HOST} = $self->{server_name}; |
379 |
$ENV{HTTP_PORT} = $self->{server_port}; |
380 |
$ENV{SCRIPT_NAME} = $self->{name}; |
381 |
exec $path; |
382 |
} |
383 |
Coro::State::_exit(0); |
384 |
} else { |
385 |
die; |
386 |
} |
387 |
} |
388 |
|
389 |
sub server_hostport { |
390 |
$_[0]{server_port} == 80 |
391 |
? $_[0]{server_name} |
392 |
: "$_[0]{server_name}:$_[0]{server_port}"; |
393 |
} |
394 |
|
395 |
sub respond { |
396 |
my $self = shift; |
397 |
my $path = $self->{path}; |
398 |
|
399 |
stat $path |
400 |
or $self->err(404, "not found"); |
401 |
|
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 { |
415 |
$ims < $self->{stat}[9] |
416 |
or $self->err(304, "not modified"); |
417 |
|
418 |
if (-r "$path/index.html") { |
419 |
$self->{path} .= "/index.html"; |
420 |
$self->handle_file; |
421 |
} else { |
422 |
$self->handle_dir; |
423 |
} |
424 |
} |
425 |
} elsif (-f _ && -r _) { |
426 |
-x _ and $self->err(403, "forbidden"); |
427 |
$self->handle_file; |
428 |
} else { |
429 |
$self->err(404, "not found"); |
430 |
} |
431 |
} |
432 |
|
433 |
sub handle_dir { |
434 |
my $self = shift; |
435 |
my $idx = $self->diridx; |
436 |
|
437 |
$self->response(200, "ok", |
438 |
{ |
439 |
"Content-Type" => "text/html", |
440 |
"Content-Length" => length $idx, |
441 |
}, |
442 |
$idx); |
443 |
} |
444 |
|
445 |
sub handle_file { |
446 |
my $self = shift; |
447 |
my $length = $self->{stat}[7]; |
448 |
my $queue = $::transfers[$length >= $::TRANSFER_SMALL]; |
449 |
my $hdr = { |
450 |
"Last-Modified" => time2str ((stat _)[9]), |
451 |
}; |
452 |
|
453 |
my @code = (200, "ok"); |
454 |
my ($l, $h); |
455 |
|
456 |
if ($self->{h}{range} =~ /^bytes=(.*)$/) { |
457 |
for (split /,/, $1) { |
458 |
if (/^-(\d+)$/) { |
459 |
($l, $h) = ($length - $1, $length - 1); |
460 |
} elsif (/^(\d+)-(\d*)$/) { |
461 |
($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1); |
462 |
} else { |
463 |
($l, $h) = (0, $length - 1); |
464 |
goto ignore; |
465 |
} |
466 |
goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; |
467 |
} |
468 |
$hdr->{"Content-Range"} = "bytes */$length"; |
469 |
$hdr->{"Content-Length"} = $length; |
470 |
$self->err(416, "not satisfiable", $hdr, ""); |
471 |
|
472 |
satisfiable: |
473 |
# check for segmented downloads |
474 |
if ($l && $::NO_SEGMENTED) { |
475 |
my $delay = $::PER_TIMEOUT + 15; |
476 |
while (%{$uri{$self->{remote_id}}{$self->{uri}}} > 1) { |
477 |
if ($delay <= 0) { |
478 |
$self->err_segmented_download; |
479 |
} else { |
480 |
Coro::Event::do_timer(after => 4); $delay -= 4; |
481 |
} |
482 |
} |
483 |
} |
484 |
|
485 |
$hdr->{"Content-Range"} = "bytes $l-$h/$length"; |
486 |
@code = (206, "partial content"); |
487 |
$length = $h - $l + 1; |
488 |
|
489 |
ignore: |
490 |
} else { |
491 |
($l, $h) = (0, $length - 1); |
492 |
} |
493 |
|
494 |
$self->{path} =~ /\.([^.]+)$/; |
495 |
$hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream"; |
496 |
$hdr->{"Content-Length"} = $length; |
497 |
|
498 |
$self->response(@code, $hdr, ""); |
499 |
|
500 |
if ($self->{method} eq "GET") { |
501 |
$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; |
515 |
|
516 |
$self->{fh}->writable or return; |
517 |
|
518 |
my ($fh, $buf, $r); |
519 |
my $current = $Coro::current; |
520 |
open $fh, "<", $self->{path} |
521 |
or die "$self->{path}: late open failure ($!)"; |
522 |
|
523 |
$h -= $l - 1; |
524 |
|
525 |
if (0) { |
526 |
if ($l) { |
527 |
sysseek $fh, $l, 0; |
528 |
} |
529 |
} |
530 |
|
531 |
while ($h > 0) { |
532 |
if (0) { |
533 |
sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h |
534 |
or last; |
535 |
} else { |
536 |
aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h), |
537 |
$buf, 0, sub { |
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; |
546 |
$::written += $w; |
547 |
$self->{written} += $w; |
548 |
$l += $r; |
549 |
} |
550 |
|
551 |
close $fh; |
552 |
} |
553 |
} |
554 |
|
555 |
1; |