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