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