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