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