ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/myhttpd/httpd.pl
Revision: 1.32
Committed: Wed Aug 29 01:32:50 2001 UTC (22 years, 10 months ago) by root
Content type: text/plain
Branch: MAIN
Changes since 1.31: +26 -5 lines
Log Message:
*** empty log message ***

File Contents

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