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