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