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