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