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

# User Rev Content
1 root 1.1 use Coro;
2     use Coro::Semaphore;
3     use Coro::Event;
4     use Coro::Socket;
5 root 1.44 use Coro::Signal;
6 root 1.79 use Coro::AIO ();
7 root 1.1
8 root 1.32 use HTTP::Date;
9 root 1.47 use POSIX ();
10 root 1.32
11 root 1.63 use Compress::Zlib ();
12    
13 root 1.1 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 root 1.27
22     our $accesslog;
23 root 1.56 our $errorlog;
24    
25     our $NOW;
26     our $HTTP_NOW;
27    
28 root 1.80 our $ERROR_LOG;
29     our $ACCESS_LOG;
30    
31 root 1.56 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 root 1.27
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 root 1.1 sub slog {
51     my $level = shift;
52     my $format = shift;
53 root 1.56 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 root 1.1 }
57    
58 root 1.32 our $connections = new Coro::Semaphore $MAX_CONNECTS || 250;
59 root 1.44 our $httpevent = new Coro::Signal;
60 root 1.34
61 root 1.63 our $queue_file = new transferqueue $MAX_TRANSFERS;
62     our $queue_index = new transferqueue 10;
63 root 1.62
64 root 1.72 our $tbf_top = new tbf rate => $TBF_RATE || 100000;
65 root 1.67
66 root 1.68 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 root 1.6 my @newcons;
80 root 1.1 my @pool;
81    
82 root 1.2 # one "execution thread"
83 root 1.1 sub handler {
84     while () {
85 root 1.38 if (@newcons) {
86 root 1.1 eval {
87 root 1.81 conn->new (@{pop @newcons})->handle;
88 root 1.1 };
89     slog 1, "$@" if $@ && !ref $@;
90 root 1.56
91     $httpevent->broadcast; # only for testing, but doesn't matter much
92    
93 root 1.1 $connections->up;
94     } else {
95     last if @pool >= $MAX_POOL;
96     push @pool, $Coro::current;
97     schedule;
98     }
99     }
100     }
101    
102 root 1.40 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 root 1.4 my $http_port = new Coro::Socket
124     LocalAddr => $SERVER_HOST,
125     LocalPort => $SERVER_PORT,
126     ReuseAddr => 1,
127 root 1.81 Listen => 50,
128 root 1.4 or die "unable to start server";
129    
130 root 1.40 listen_on $http_port;
131    
132 root 1.41 if ($SERVER_PORT2) {
133     my $http_port = new Coro::Socket
134     LocalAddr => $SERVER_HOST,
135     LocalPort => $SERVER_PORT2,
136     ReuseAddr => 1,
137 root 1.81 Listen => 50,
138 root 1.41 or die "unable to start server";
139 root 1.40
140 root 1.41 listen_on $http_port;
141     }
142 root 1.4
143 root 1.1 package conn;
144    
145 root 1.80 use strict;
146     use bytes;
147    
148 root 1.1 use Socket;
149     use HTTP::Date;
150 root 1.2 use Convert::Scalar 'weaken';
151 root 1.77 use IO::AIO;
152 root 1.16
153 root 1.77 IO::AIO::min_parallel $::AIO_PARALLEL;
154 root 1.16
155 root 1.79 Event->io (fd => IO::AIO::poll_fileno,
156     poll => 'r', async => 1,
157     cb => \&IO::AIO::poll_cb);
158 root 1.16
159 root 1.26 our %conn; # $conn{ip}{self} => connobj
160     our %uri; # $uri{ip}{uri}{self}
161 root 1.3 our %blocked;
162 root 1.9 our %mimetype;
163    
164     sub read_mimetypes {
165 root 1.81 if (open my $fh, "<mime_types") {
166     while (<$fh>) {
167 root 1.9 if (/^([^#]\S+)\t+(\S+)$/) {
168     $mimetype{lc $1} = $2;
169     }
170     }
171     } else {
172 root 1.10 print "cannot open mime_types\n";
173 root 1.9 }
174     }
175 root 1.1
176 root 1.10 read_mimetypes;
177    
178 root 1.1 sub new {
179     my $class = shift;
180 root 1.42 my $fh = shift;
181 root 1.6 my $peername = shift;
182 root 1.2 my $self = bless { fh => $fh }, $class;
183 root 1.6 my (undef, $iaddr) = unpack_sockaddr_in $peername
184 root 1.81 or $self->err (500, "unable to decode peername");
185 root 1.7
186 root 1.50 $self->{remote_addr} =
187     $self->{remote_id} = inet_ntoa $iaddr;
188 root 1.60
189 root 1.11 $self->{time} = $::NOW;
190 root 1.2
191 root 1.49 weaken ($Coro::current->{conn} = $self);
192    
193 root 1.82 ++$::conns;
194 root 1.53 $::maxconns = $::conns if $::conns > $::maxconns;
195 root 1.13
196 root 1.81 $self
197 root 1.2 }
198    
199     sub DESTROY {
200 root 1.82 my $self = shift;
201    
202 root 1.81 close $self->{fh}; # workaround
203     --$::conns;
204 root 1.1 }
205    
206 root 1.73 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 root 1.74 delete $blocked{$_} unless $blocked{$_}[0] > $::NOW;
225 root 1.73 }
226     }
227    
228 root 1.81 Event->timer (interval => 60, cb => \&prune_caches);
229 root 1.73
230 root 1.1 sub slog {
231 root 1.4 my $self = shift;
232 root 1.50 main::slog($_[0], "$self->{remote_id}> $_[1]");
233 root 1.1 }
234    
235 root 1.4 sub response {
236 root 1.1 my ($self, $code, $msg, $hdr, $content) = @_;
237 root 1.17 my $res = "HTTP/1.1 $code $msg\015\012";
238 root 1.63 my $GZ = "";
239 root 1.1
240 root 1.46 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 root 1.28
254 root 1.63 if ($self->{method} ne "HEAD"
255     && $self->{h}{"accept-encoding"} =~ /\bgzip\b/
256 root 1.64 && 400 < length $content
257 root 1.63 && $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 root 1.32 $res .= "Date: $HTTP_NOW\015\012";
268 root 1.71 $res .= "Server: $::NAME\015\012";
269 root 1.1
270     while (my ($h, $v) = each %$hdr) {
271     $res .= "$h: $v\015\012"
272     }
273 root 1.10 $res .= "\015\012";
274 root 1.4
275 root 1.13 $res .= $content if defined $content and $self->{method} ne "HEAD";
276 root 1.1
277 root 1.65 my $log = (POSIX::strftime "%Y-%m-%d %H:%M:%S", gmtime $::NOW).
278 root 1.63 " $self->{remote_id} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}.$GZ.
279 root 1.50 " \"$self->{h}{referer}\"\n";
280 root 1.27
281 root 1.65 print $::accesslog $log if $::accesslog;
282 root 1.27 print STDERR $log;
283 root 1.2
284 root 1.67 $tbf_top->request(length $res, 1e6);
285     $self->{written} += print {$self->{fh}} $res;
286 root 1.1 }
287    
288     sub err {
289     my $self = shift;
290     my ($code, $msg, $hdr, $content) = @_;
291    
292     unless (defined $content) {
293 root 1.35 $content = "$code $msg\n";
294 root 1.1 $hdr->{"Content-Type"} = "text/plain";
295     $hdr->{"Content-Length"} = length $content;
296     }
297 root 1.17 $hdr->{"Connection"} = "close";
298 root 1.1
299 root 1.81 $self->response ($code, $msg, $hdr, $content);
300 root 1.1
301 root 1.81 die bless {}, err::
302 root 1.1 }
303    
304     sub handle {
305     my $self = shift;
306     my $fh = $self->{fh};
307    
308 root 1.29 my $host;
309    
310 root 1.17 $fh->timeout($::REQ_TIMEOUT);
311 root 1.81 while () {
312 root 1.17 $self->{reqs}++;
313 root 1.1
314     # read request and parse first line
315     my $req = $fh->readline("\015\012\015\012");
316    
317 root 1.17 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 root 1.1
327 root 1.17 $fh->timeout($::RES_TIMEOUT);
328 root 1.3
329 root 1.1 $req =~ /^(?:\015\012)?
330     (GET|HEAD) \040+
331     ([^\040]+) \040+
332     HTTP\/([0-9]+\.[0-9]+)
333     \015\012/gx
334 root 1.14 or $self->err(405, "method not allowed", { Allow => "GET,HEAD" });
335 root 1.1
336     $self->{method} = $1;
337     $self->{uri} = $2;
338 root 1.17 $self->{version} = $3;
339    
340 root 1.20 $3 =~ /^1\./
341 root 1.17 or $self->err(506, "http protocol version $3 not supported");
342 root 1.1
343     # parse headers
344     {
345     my (%hdr, $h, $v);
346    
347     $hdr{lc $1} .= ",$2"
348     while $req =~ /\G
349     ([^:\000-\040]+):
350 root 1.66 [\011\040]*
351     ((?: [^\015\012]+ | \015\012[\011\040] )*)
352 root 1.1 \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 root 1.36 # 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 root 1.56 weaken (local $conn{$id}{$self*1} = $self);
374    
375 root 1.36 if ($blocked{$id}) {
376 root 1.56 $self->err_blocked
377     if $blocked{$id}[0] > $::NOW;
378 root 1.36
379     delete $blocked{$id};
380     }
381    
382 root 1.29 # 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 root 1.43 = unpack_sockaddr_in $self->{fh}->sockname
394 root 1.29 or $self->err(500, "unable to get socket name");
395     $host = inet_ntoa $host;
396     }
397    
398     $self->{server_name} = $host;
399    
400 root 1.56 weaken (local $uri{$id}{$self->{uri}}{$self*1} = $self);
401 root 1.1
402 root 1.24 eval {
403     $self->map_uri;
404     $self->respond;
405     };
406    
407     die if $@ && !ref $@;
408 root 1.17
409 root 1.56 last if $self->{h}{connection} =~ /close/i;
410 root 1.17
411 root 1.44 $httpevent->broadcast;
412    
413 root 1.17 $fh->timeout($::PER_TIMEOUT);
414     }
415 root 1.1 }
416    
417 root 1.56 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 root 1.1 # uri => path mapping
426     sub map_uri {
427     my $self = shift;
428 root 1.29 my $host = $self->{server_name};
429 root 1.1 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 root 1.7
445     $self->access_check;
446 root 1.1 }
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 root 1.29 $ENV{HTTP_HOST} = $self->{server_name};
459     $ENV{HTTP_PORT} = $self->{server_port};
460 root 1.1 $ENV{SCRIPT_NAME} = $self->{name};
461 root 1.10 exec $path;
462 root 1.1 }
463     Coro::State::_exit(0);
464     } else {
465 root 1.29 die;
466 root 1.1 }
467     }
468    
469 root 1.29 sub server_hostport {
470     $_[0]{server_port} == 80
471     ? $_[0]{server_name}
472     : "$_[0]{server_name}:$_[0]{server_port}";
473     }
474    
475 root 1.1 sub respond {
476     my $self = shift;
477     my $path = $self->{path};
478    
479 root 1.49 if ($self->{name} =~ s%^/internal/([^/]+)%%) {
480     if ($::internal{$1}) {
481     $::internal{$1}->($self);
482     } else {
483 root 1.81 $self->err (404, "not found");
484 root 1.49 }
485     } else {
486 root 1.1
487 root 1.49 stat $path
488 root 1.81 or $self->err (404, "not found");
489 root 1.10
490 root 1.49 $self->{stat} = [stat _];
491 root 1.1
492 root 1.49 # 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 root 1.81 $self->err (301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" });
502 root 1.25 } else {
503 root 1.49 $ims < $self->{stat}[9]
504 root 1.81 or $self->err (304, "not modified");
505 root 1.49
506     if (-r "$path/index.html") {
507     # replace directory "size" by index.html filesize
508 root 1.55 $self->{stat} = [stat ($self->{path} .= "/index.html")];
509 root 1.81 $self->handle_file ($queue_index, $tbf_top);
510 root 1.49 } else {
511     $self->handle_dir;
512     }
513 root 1.1 }
514 root 1.49 } elsif (-f _ && -r _) {
515 root 1.81 -x _ and $self->err (403, "forbidden");
516 root 1.56
517 root 1.58 if (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
518 root 1.56 my $timeout = $::NOW + 10;
519 root 1.58 while (keys %{$conn{$self->{remote_id}}} > $::MAX_TRANSFERS_IP) {
520 root 1.56 if ($timeout < $::NOW) {
521     $self->block($::BLOCKTIME, "too many connections");
522     } else {
523     $httpevent->wait;
524     }
525     }
526     }
527    
528 root 1.81 $self->handle_file ($queue_file, $tbf_top);
529 root 1.49 } else {
530 root 1.81 $self->err (404, "not found");
531 root 1.1 }
532     }
533     }
534    
535     sub handle_dir {
536     my $self = shift;
537 root 1.10 my $idx = $self->diridx;
538    
539 root 1.81 $self->response (200, "ok",
540 root 1.10 {
541 root 1.76 "Content-Type" => "text/html; charset=utf-8",
542 root 1.10 "Content-Length" => length $idx,
543 root 1.55 "Last-Modified" => time2str ($self->{stat}[9]),
544 root 1.10 },
545     $idx);
546 root 1.1 }
547    
548     sub handle_file {
549 root 1.67 my ($self, $queue, $tbf) = @_;
550 root 1.34 my $length = $self->{stat}[7];
551 root 1.1 my $hdr = {
552 root 1.75 "Last-Modified" => time2str ((stat _)[9]),
553     "Accept-Ranges" => "bytes",
554 root 1.1 };
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 root 1.26 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
570 root 1.1 }
571     $hdr->{"Content-Range"} = "bytes */$length";
572 root 1.24 $hdr->{"Content-Length"} = $length;
573 root 1.81 $self->err (416, "not satisfiable", $hdr, "");
574 root 1.1
575     satisfiable:
576 root 1.4 # check for segmented downloads
577 root 1.10 if ($l && $::NO_SEGMENTED) {
578 root 1.56 my $timeout = $::NOW + 15;
579 root 1.58 while (keys %{$uri{$self->{remote_id}}{$self->{uri}}} > 1) {
580 root 1.56 if ($timeout <= $::NOW) {
581 root 1.81 $self->block ($::BLOCKTIME, "segmented downloads are forbidden");
582 root 1.56 #$self->err_segmented_download;
583 root 1.29 } else {
584 root 1.46 $httpevent->wait;
585 root 1.29 }
586 root 1.4 }
587     }
588    
589 root 1.1 $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 root 1.9 $self->{path} =~ /\.([^.]+)$/;
599     $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream";
600 root 1.1 $hdr->{"Content-Length"} = $length;
601    
602 root 1.81 $self->response (@code, $hdr, "");
603 root 1.1
604     if ($self->{method} eq "GET") {
605 root 1.32 $self->{time} = $::NOW;
606 root 1.71 $self->{written} = 0;
607 root 1.32
608 root 1.81 open my $fh, "<", $self->{path}
609 root 1.1 or die "$self->{path}: late open failure ($!)";
610    
611     $h -= $l - 1;
612    
613 root 1.81 my $transfer = $queue->start_transfer ($h);
614 root 1.51 my $locked;
615 root 1.48 my $bufsize = $::WAIT_BUFSIZE; # initial buffer size
616 root 1.19
617 root 1.1 while ($h > 0) {
618 root 1.51 unless ($locked) {
619 root 1.81 if ($locked ||= $transfer->try ($::WAIT_INTERVAL)) {
620 root 1.48 $bufsize = $::BUFSIZE;
621     $self->{time} = $::NOW;
622 root 1.71 $self->{written} = 0;
623 root 1.48 }
624 root 1.56 }
625    
626     if ($blocked{$self->{remote_id}}) {
627     $self->{h}{connection} = "close";
628 root 1.59 die bless {}, err::;
629 root 1.48 }
630    
631 root 1.80 Coro::AIO::aio_read $fh, $l, ($h > $bufsize ? $bufsize : $h), my $buf, 0
632 root 1.79 or last;
633 root 1.67
634 root 1.79 $tbf->request (length $buf);
635 root 1.37 my $w = syswrite $self->{fh}, $buf
636 root 1.1 or last;
637 root 1.11 $::written += $w;
638     $self->{written} += $w;
639 root 1.80 $l += $w;
640 root 1.1 }
641 root 1.32
642     close $fh;
643 root 1.1 }
644 root 1.7 }
645    
646 root 1.78 1
647 root 1.79