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