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