ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/myhttpd/httpd.pl
Revision: 1.30
Committed: Sun Aug 26 14:55:46 2001 UTC (22 years, 10 months ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.29: +2 -48 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.12 $self->slog(2, "blocked ip $ip");
228 root 1.3 $self->err_blocked;
229     }
230    
231 root 1.1 $req =~ /^(?:\015\012)?
232     (GET|HEAD) \040+
233     ([^\040]+) \040+
234     HTTP\/([0-9]+\.[0-9]+)
235     \015\012/gx
236 root 1.14 or $self->err(405, "method not allowed", { Allow => "GET,HEAD" });
237 root 1.1
238     $self->{method} = $1;
239     $self->{uri} = $2;
240 root 1.17 $self->{version} = $3;
241    
242 root 1.20 $3 =~ /^1\./
243 root 1.17 or $self->err(506, "http protocol version $3 not supported");
244 root 1.1
245     # parse headers
246     {
247     my (%hdr, $h, $v);
248    
249     $hdr{lc $1} .= ",$2"
250     while $req =~ /\G
251     ([^:\000-\040]+):
252     [\008\040]*
253     ((?: [^\015\012]+ | \015\012[\008\040] )*)
254     \015\012
255     /gxc;
256    
257     $req =~ /\G\015\012$/
258     or $self->err(400, "bad request");
259    
260     $self->{h}{$h} = substr $v, 1
261     while ($h, $v) = each %hdr;
262     }
263    
264 root 1.29 # find out server name and port
265     if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) {
266     $host = $1;
267     } else {
268     $host = $self->{h}{host};
269     }
270    
271     if (defined $host) {
272     $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80;
273     } else {
274     ($self->{server_port}, $host)
275     = unpack_sockaddr_in $self->{fh}->getsockname
276     or $self->err(500, "unable to get socket name");
277     $host = inet_ntoa $host;
278     }
279    
280     $self->{server_name} = $host;
281    
282     # remote id should be unique per user
283     $self->{remote_id} = $self->{remote_addr};
284    
285     if (exists $self->{h}{"client-ip"}) {
286     $self->{remote_id} .= "[".$self->{h}{"client-ip"}."]";
287     } elsif (exists $self->{h}{"x-forwarded-for"}) {
288     $self->{remote_id} .= "[".$self->{h}{"x-forwarded-for"}."]";
289     }
290 root 1.3
291 root 1.13 weaken ($uri{$self->{remote_addr}}{$self->{uri}}{$self*1} = $self);
292 root 1.1
293 root 1.24 eval {
294     $self->map_uri;
295     $self->respond;
296     };
297    
298 root 1.26 $self->eoconn;
299    
300 root 1.24 die if $@ && !ref $@;
301 root 1.17
302 root 1.29 last if $self->{h}{connection} =~ /close/ || $self->{version} < 1.1;
303 root 1.17
304     $fh->timeout($::PER_TIMEOUT);
305     }
306 root 1.1 }
307    
308     # uri => path mapping
309     sub map_uri {
310     my $self = shift;
311 root 1.29 my $host = $self->{server_name};
312 root 1.1 my $uri = $self->{uri};
313    
314     # some massaging, also makes it more secure
315     $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge;
316     $uri =~ s%//+%/%g;
317     $uri =~ s%/\.(?=/|$)%%g;
318     1 while $uri =~ s%/[^/]+/\.\.(?=/|$)%%;
319    
320     $uri =~ m%^/?\.\.(?=/|$)%
321     and $self->err(400, "bad request");
322    
323     $self->{name} = $uri;
324    
325     # now do the path mapping
326     $self->{path} = "$::DOCROOT/$host$uri";
327 root 1.7
328     $self->access_check;
329 root 1.1 }
330    
331     sub _cgi {
332     my $self = shift;
333     my $path = shift;
334     my $fh;
335    
336     # no two-way xxx supported
337     if (0 == fork) {
338     open STDOUT, ">&".fileno($self->{fh});
339     if (chdir $::DOCROOT) {
340     $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike
341 root 1.29 $ENV{HTTP_HOST} = $self->{server_name};
342     $ENV{HTTP_PORT} = $self->{server_port};
343 root 1.1 $ENV{SCRIPT_NAME} = $self->{name};
344 root 1.10 exec $path;
345 root 1.1 }
346     Coro::State::_exit(0);
347     } else {
348 root 1.29 die;
349 root 1.1 }
350     }
351    
352 root 1.29 sub server_hostport {
353     $_[0]{server_port} == 80
354     ? $_[0]{server_name}
355     : "$_[0]{server_name}:$_[0]{server_port}";
356     }
357    
358 root 1.1 sub respond {
359     my $self = shift;
360     my $path = $self->{path};
361    
362     stat $path
363     or $self->err(404, "not found");
364    
365 root 1.10 $self->{stat} = [stat _];
366    
367 root 1.1 # idiotic netscape sends idiotic headers AGAIN
368     my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
369     ? str2time $1 : 0;
370    
371     if (-d _ && -r _) {
372     # directory
373     if ($path !~ /\/$/) {
374     # create a redirect to get the trailing "/"
375 root 1.29 # we don't try to avoid the :80
376     $self->err(301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" });
377 root 1.1 } else {
378 root 1.10 $ims < $self->{stat}[9]
379 root 1.1 or $self->err(304, "not modified");
380    
381 root 1.25 if (-r "$path/index.html") {
382     $self->{path} .= "/index.html";
383     $self->handle_file;
384     } else {
385     $self->handle_dir;
386 root 1.1 }
387     }
388     } elsif (-f _ && -r _) {
389     -x _ and $self->err(403, "forbidden");
390     $self->handle_file;
391     } else {
392     $self->err(404, "not found");
393     }
394     }
395    
396     sub handle_dir {
397     my $self = shift;
398 root 1.10 my $idx = $self->diridx;
399    
400     $self->response(200, "ok",
401     {
402     "Content-Type" => "text/html",
403     "Content-Length" => length $idx,
404     },
405     $idx);
406 root 1.1 }
407    
408     sub handle_file {
409     my $self = shift;
410     my $length = -s _;
411     my $hdr = {
412     "Last-Modified" => time2str ((stat _)[9]),
413     };
414    
415     my @code = (200, "ok");
416     my ($l, $h);
417    
418     if ($self->{h}{range} =~ /^bytes=(.*)$/) {
419     for (split /,/, $1) {
420     if (/^-(\d+)$/) {
421     ($l, $h) = ($length - $1, $length - 1);
422     } elsif (/^(\d+)-(\d*)$/) {
423     ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1);
424     } else {
425     ($l, $h) = (0, $length - 1);
426     goto ignore;
427     }
428 root 1.26 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
429 root 1.1 }
430     $hdr->{"Content-Range"} = "bytes */$length";
431 root 1.24 $hdr->{"Content-Length"} = $length;
432 root 1.20 $self->slog(9, "not satisfiable($self->{h}{range}|".$self->{h}{"user-agent"}.")");
433 root 1.24 $self->err(416, "not satisfiable", $hdr, "");
434 root 1.1
435     satisfiable:
436 root 1.4 # check for segmented downloads
437 root 1.10 if ($l && $::NO_SEGMENTED) {
438 root 1.30 my $delay = 180;
439 root 1.29 while (%{$uri{$self->{remote_addr}}{$self->{uri}}} > 1) {
440     if ($delay <= 0) {
441 root 1.30 $self->err_segmented_download;
442 root 1.29 } else {
443     Coro::Event::do_timer(after => 3); $delay -= 3;
444     }
445 root 1.4 }
446     }
447    
448 root 1.1 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
449     @code = (206, "partial content");
450     $length = $h - $l + 1;
451    
452     ignore:
453     } else {
454     ($l, $h) = (0, $length - 1);
455     }
456    
457 root 1.9 $self->{path} =~ /\.([^.]+)$/;
458     $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream";
459 root 1.1 $hdr->{"Content-Length"} = $length;
460    
461 root 1.4 $self->response(@code, $hdr, "");
462 root 1.1
463     if ($self->{method} eq "GET") {
464 root 1.16 my ($fh, $buf, $r);
465     my $current = $Coro::current;
466 root 1.1 open $fh, "<", $self->{path}
467     or die "$self->{path}: late open failure ($!)";
468    
469     $h -= $l - 1;
470    
471 root 1.19 if (0) {
472     if ($l) {
473     sysseek $fh, $l, 0;
474     }
475     }
476    
477 root 1.1 while ($h > 0) {
478 root 1.19 if (0) {
479     sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h
480     or last;
481     } else {
482 root 1.29 undef $buf;
483     $aio_requests->down;
484 root 1.19 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h),
485     $buf, 0, sub {
486     $r = $_[0];
487     $current->ready;
488     });
489     &Coro::schedule;
490 root 1.29 $aio_requests->up;
491 root 1.19 last unless $r;
492     }
493 root 1.11 my $w = $self->{fh}->syswrite($buf)
494 root 1.1 or last;
495 root 1.11 $::written += $w;
496     $self->{written} += $w;
497 root 1.16 $l += $r;
498 root 1.1 }
499     }
500    
501     close $fh;
502 root 1.7 }
503    
504 root 1.2 1;