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 |
$self->slog(2, "blocked ip $ip"); |
228 |
$self->err_blocked; |
229 |
} |
230 |
|
231 |
$req =~ /^(?:\015\012)? |
232 |
(GET|HEAD) \040+ |
233 |
([^\040]+) \040+ |
234 |
HTTP\/([0-9]+\.[0-9]+) |
235 |
\015\012/gx |
236 |
or $self->err(405, "method not allowed", { Allow => "GET,HEAD" }); |
237 |
|
238 |
$self->{method} = $1; |
239 |
$self->{uri} = $2; |
240 |
$self->{version} = $3; |
241 |
|
242 |
$3 =~ /^1\./ |
243 |
or $self->err(506, "http protocol version $3 not supported"); |
244 |
|
245 |
# parse headers |
246 |
{ |
247 |
my (%hdr, $h, $v); |
248 |
|
249 |
$hdr{lc $1} .= ",$2" |
250 |
while $req =~ /\G |
251 |
([^:\000-\040]+): |
252 |
[\008\040]* |
253 |
((?: [^\015\012]+ | \015\012[\008\040] )*) |
254 |
\015\012 |
255 |
/gxc; |
256 |
|
257 |
$req =~ /\G\015\012$/ |
258 |
or $self->err(400, "bad request"); |
259 |
|
260 |
$self->{h}{$h} = substr $v, 1 |
261 |
while ($h, $v) = each %hdr; |
262 |
} |
263 |
|
264 |
# find out server name and port |
265 |
if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) { |
266 |
$host = $1; |
267 |
} else { |
268 |
$host = $self->{h}{host}; |
269 |
} |
270 |
|
271 |
if (defined $host) { |
272 |
$self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80; |
273 |
} else { |
274 |
($self->{server_port}, $host) |
275 |
= unpack_sockaddr_in $self->{fh}->getsockname |
276 |
or $self->err(500, "unable to get socket name"); |
277 |
$host = inet_ntoa $host; |
278 |
} |
279 |
|
280 |
$self->{server_name} = $host; |
281 |
|
282 |
# remote id should be unique per user |
283 |
$self->{remote_id} = $self->{remote_addr}; |
284 |
|
285 |
if (exists $self->{h}{"client-ip"}) { |
286 |
$self->{remote_id} .= "[".$self->{h}{"client-ip"}."]"; |
287 |
} elsif (exists $self->{h}{"x-forwarded-for"}) { |
288 |
$self->{remote_id} .= "[".$self->{h}{"x-forwarded-for"}."]"; |
289 |
} |
290 |
|
291 |
weaken ($uri{$self->{remote_addr}}{$self->{uri}}{$self*1} = $self); |
292 |
|
293 |
eval { |
294 |
$self->map_uri; |
295 |
$self->respond; |
296 |
}; |
297 |
|
298 |
$self->eoconn; |
299 |
|
300 |
die if $@ && !ref $@; |
301 |
|
302 |
last if $self->{h}{connection} =~ /close/ || $self->{version} < 1.1; |
303 |
|
304 |
$fh->timeout($::PER_TIMEOUT); |
305 |
} |
306 |
} |
307 |
|
308 |
# uri => path mapping |
309 |
sub map_uri { |
310 |
my $self = shift; |
311 |
my $host = $self->{server_name}; |
312 |
my $uri = $self->{uri}; |
313 |
|
314 |
# some massaging, also makes it more secure |
315 |
$uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge; |
316 |
$uri =~ s%//+%/%g; |
317 |
$uri =~ s%/\.(?=/|$)%%g; |
318 |
1 while $uri =~ s%/[^/]+/\.\.(?=/|$)%%; |
319 |
|
320 |
$uri =~ m%^/?\.\.(?=/|$)% |
321 |
and $self->err(400, "bad request"); |
322 |
|
323 |
$self->{name} = $uri; |
324 |
|
325 |
# now do the path mapping |
326 |
$self->{path} = "$::DOCROOT/$host$uri"; |
327 |
|
328 |
$self->access_check; |
329 |
} |
330 |
|
331 |
sub _cgi { |
332 |
my $self = shift; |
333 |
my $path = shift; |
334 |
my $fh; |
335 |
|
336 |
# no two-way xxx supported |
337 |
if (0 == fork) { |
338 |
open STDOUT, ">&".fileno($self->{fh}); |
339 |
if (chdir $::DOCROOT) { |
340 |
$ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike |
341 |
$ENV{HTTP_HOST} = $self->{server_name}; |
342 |
$ENV{HTTP_PORT} = $self->{server_port}; |
343 |
$ENV{SCRIPT_NAME} = $self->{name}; |
344 |
exec $path; |
345 |
} |
346 |
Coro::State::_exit(0); |
347 |
} else { |
348 |
die; |
349 |
} |
350 |
} |
351 |
|
352 |
sub server_hostport { |
353 |
$_[0]{server_port} == 80 |
354 |
? $_[0]{server_name} |
355 |
: "$_[0]{server_name}:$_[0]{server_port}"; |
356 |
} |
357 |
|
358 |
sub respond { |
359 |
my $self = shift; |
360 |
my $path = $self->{path}; |
361 |
|
362 |
stat $path |
363 |
or $self->err(404, "not found"); |
364 |
|
365 |
$self->{stat} = [stat _]; |
366 |
|
367 |
# idiotic netscape sends idiotic headers AGAIN |
368 |
my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/ |
369 |
? str2time $1 : 0; |
370 |
|
371 |
if (-d _ && -r _) { |
372 |
# directory |
373 |
if ($path !~ /\/$/) { |
374 |
# create a redirect to get the trailing "/" |
375 |
# we don't try to avoid the :80 |
376 |
$self->err(301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" }); |
377 |
} else { |
378 |
$ims < $self->{stat}[9] |
379 |
or $self->err(304, "not modified"); |
380 |
|
381 |
if (-r "$path/index.html") { |
382 |
$self->{path} .= "/index.html"; |
383 |
$self->handle_file; |
384 |
} else { |
385 |
$self->handle_dir; |
386 |
} |
387 |
} |
388 |
} elsif (-f _ && -r _) { |
389 |
-x _ and $self->err(403, "forbidden"); |
390 |
$self->handle_file; |
391 |
} else { |
392 |
$self->err(404, "not found"); |
393 |
} |
394 |
} |
395 |
|
396 |
sub handle_dir { |
397 |
my $self = shift; |
398 |
my $idx = $self->diridx; |
399 |
|
400 |
$self->response(200, "ok", |
401 |
{ |
402 |
"Content-Type" => "text/html", |
403 |
"Content-Length" => length $idx, |
404 |
}, |
405 |
$idx); |
406 |
} |
407 |
|
408 |
sub handle_file { |
409 |
my $self = shift; |
410 |
my $length = -s _; |
411 |
my $hdr = { |
412 |
"Last-Modified" => time2str ((stat _)[9]), |
413 |
}; |
414 |
|
415 |
my @code = (200, "ok"); |
416 |
my ($l, $h); |
417 |
|
418 |
if ($self->{h}{range} =~ /^bytes=(.*)$/) { |
419 |
for (split /,/, $1) { |
420 |
if (/^-(\d+)$/) { |
421 |
($l, $h) = ($length - $1, $length - 1); |
422 |
} elsif (/^(\d+)-(\d*)$/) { |
423 |
($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1); |
424 |
} else { |
425 |
($l, $h) = (0, $length - 1); |
426 |
goto ignore; |
427 |
} |
428 |
goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l; |
429 |
} |
430 |
$hdr->{"Content-Range"} = "bytes */$length"; |
431 |
$hdr->{"Content-Length"} = $length; |
432 |
$self->slog(9, "not satisfiable($self->{h}{range}|".$self->{h}{"user-agent"}.")"); |
433 |
$self->err(416, "not satisfiable", $hdr, ""); |
434 |
|
435 |
satisfiable: |
436 |
# check for segmented downloads |
437 |
if ($l && $::NO_SEGMENTED) { |
438 |
my $delay = 180; |
439 |
while (%{$uri{$self->{remote_addr}}{$self->{uri}}} > 1) { |
440 |
if ($delay <= 0) { |
441 |
$self->err_segmented_download; |
442 |
} else { |
443 |
Coro::Event::do_timer(after => 3); $delay -= 3; |
444 |
} |
445 |
} |
446 |
} |
447 |
|
448 |
$hdr->{"Content-Range"} = "bytes $l-$h/$length"; |
449 |
@code = (206, "partial content"); |
450 |
$length = $h - $l + 1; |
451 |
|
452 |
ignore: |
453 |
} else { |
454 |
($l, $h) = (0, $length - 1); |
455 |
} |
456 |
|
457 |
$self->{path} =~ /\.([^.]+)$/; |
458 |
$hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream"; |
459 |
$hdr->{"Content-Length"} = $length; |
460 |
|
461 |
$self->response(@code, $hdr, ""); |
462 |
|
463 |
if ($self->{method} eq "GET") { |
464 |
my ($fh, $buf, $r); |
465 |
my $current = $Coro::current; |
466 |
open $fh, "<", $self->{path} |
467 |
or die "$self->{path}: late open failure ($!)"; |
468 |
|
469 |
$h -= $l - 1; |
470 |
|
471 |
if (0) { |
472 |
if ($l) { |
473 |
sysseek $fh, $l, 0; |
474 |
} |
475 |
} |
476 |
|
477 |
while ($h > 0) { |
478 |
if (0) { |
479 |
sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h |
480 |
or last; |
481 |
} else { |
482 |
undef $buf; |
483 |
$aio_requests->down; |
484 |
aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h), |
485 |
$buf, 0, sub { |
486 |
$r = $_[0]; |
487 |
$current->ready; |
488 |
}); |
489 |
&Coro::schedule; |
490 |
$aio_requests->up; |
491 |
last unless $r; |
492 |
} |
493 |
my $w = $self->{fh}->syswrite($buf) |
494 |
or last; |
495 |
$::written += $w; |
496 |
$self->{written} += $w; |
497 |
$l += $r; |
498 |
} |
499 |
} |
500 |
|
501 |
close $fh; |
502 |
} |
503 |
|
504 |
1; |