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