ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/myhttpd/httpd.pl
Revision: 1.82
Committed: Sat Dec 2 03:31:42 2006 UTC (17 years, 7 months ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.81: +3 -2 lines
Log Message:
*** empty log message ***

File Contents

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