ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/myhttpd/httpd.pl
(Generate patch)

Comparing Coro/myhttpd/httpd.pl (file contents):
Revision 1.1 by root, Thu Aug 9 02:57:54 2001 UTC vs.
Revision 1.24 by root, Sat Aug 18 13:32:17 2001 UTC

1#!/usr/bin/perl
2
3use Coro; 1use Coro;
4use Coro::Semaphore; 2use Coro::Semaphore;
5use Coro::Event; 3use Coro::Event;
6use Coro::Socket; 4use Coro::Socket;
7 5
9use bytes; 7use bytes;
10 8
11# at least on my machine, this thingy serves files 9# at least on my machine, this thingy serves files
12# quite a bit faster than apache, ;) 10# quite a bit faster than apache, ;)
13# and quite a bit slower than thttpd :( 11# and quite a bit slower than thttpd :(
14
15my $port = new Coro::Socket
16 LocalAddr => $SERVER_HOST,
17 LocalPort => $SERVER_PORT,
18 ReuseAddr => 1,
19 Listen => 1,
20 or die "unable to start server";
21 12
22$SIG{PIPE} = 'IGNORE'; 13$SIG{PIPE} = 'IGNORE';
23 14
24sub slog { 15sub slog {
25 my $level = shift; 16 my $level = shift;
27 printf "---: $format\n", @_; 18 printf "---: $format\n", @_;
28} 19}
29 20
30my $connections = new Coro::Semaphore $MAX_CONNECTS; 21my $connections = new Coro::Semaphore $MAX_CONNECTS;
31 22
32my @fh; 23my @newcons;
33my @pool; 24my @pool;
34 25
26# one "execution thread"
35sub handler { 27sub handler {
36 while () { 28 while () {
37 my $fh = pop @fh; 29 my $new = pop @newcons;
38 if ($fh) { 30 if ($new) {
39 eval { 31 eval {
40 conn->new($fh)->handle; 32 conn->new(@$new)->handle;
41 }; 33 };
42 close $fh;
43 slog 1, "$@" if $@ && !ref $@; 34 slog 1, "$@" if $@ && !ref $@;
44 $connections->up; 35 $connections->up;
45 } else { 36 } else {
46 last if @pool >= $MAX_POOL; 37 last if @pool >= $MAX_POOL;
47 push @pool, $Coro::current; 38 push @pool, $Coro::current;
48 schedule; 39 schedule;
49 } 40 }
50 } 41 }
51} 42}
52 43
44my $http_port = new Coro::Socket
45 LocalAddr => $SERVER_HOST,
46 LocalPort => $SERVER_PORT,
47 ReuseAddr => 1,
48 Listen => 50,
49 or die "unable to start server";
50
51push @listen_sockets, $http_port;
52
53# the "main thread"
53async { 54async {
54 slog 1, "accepting connections"; 55 slog 1, "accepting connections";
55 while () { 56 while () {
56 $connections->down; 57 $connections->down;
57 push @fh, $port->accept; 58 push @newcons, [$http_port->accept];
58 #slog 3, "accepted @$connections ".scalar(@pool); 59 #slog 3, "accepted @$connections ".scalar(@pool);
60 $::NOW = time;
59 if (@pool) { 61 if (@pool) {
60 (pop @pool)->ready; 62 (pop @pool)->ready;
61 } else { 63 } else {
62 async \&handler; 64 async \&handler;
63 } 65 }
64 66
65 } 67 }
66}; 68};
67 69
68loop;
69print "ende\n";#d#
70
71package conn; 70package conn;
72 71
73use Socket; 72use Socket;
74use HTTP::Date; 73use HTTP::Date;
74use Convert::Scalar 'weaken';
75use Linux::AIO;
76
77Linux::AIO::min_parallel $::AIO_PARALLEL;
78
79Event->io(fd => Linux::AIO::poll_fileno,
80 poll => 'r', async => 1,
81 cb => \&Linux::AIO::poll_cb);
82
83our %conn; # $conn{ip}{fh} => connobj
84our %blocked;
85our %mimetype;
86
87sub read_mimetypes {
88 local *M;
89 if (open M, "<mime_types") {
90 while (<M>) {
91 if (/^([^#]\S+)\t+(\S+)$/) {
92 $mimetype{lc $1} = $2;
93 }
94 }
95 } else {
96 print "cannot open mime_types\n";
97 }
98}
99
100read_mimetypes;
75 101
76sub new { 102sub new {
77 my $class = shift; 103 my $class = shift;
104 my $peername = shift;
78 my $fh = shift; 105 my $fh = shift;
106 my $self = bless { fh => $fh }, $class;
79 my (undef, $iaddr) = unpack_sockaddr_in $fh->getpeername 107 my (undef, $iaddr) = unpack_sockaddr_in $peername
80 or $self->err(500, "unable to get peername"); 108 or $self->err(500, "unable to decode peername");
109
81 $self->{remote_address} = inet_ntoa $iaddr; 110 $self->{remote_addr} = inet_ntoa $iaddr;
82 bless { fh => $fh }, $class; 111 $self->{time} = $::NOW;
112
113 # enter ourselves into various lists
114 weaken ($conn{$self->{remote_addr}}{$self*1} = $self);
115
116 $::conns++;
117
118 $self;
119}
120
121sub DESTROY {
122 my $self = shift;
123
124 $::conns--;
125
126 $self->eoconn;
127 delete $conn{$self->{remote_addr}}{$self*1};
128}
129
130# end of connection
131sub eoconn {
132 delete $uri{$self->{remote_addr}}{$self->{uri}}{$self*1};
83} 133}
84 134
85sub slog { 135sub slog {
86 main::slog(@_); 136 my $self = shift;
137 main::slog($_[0], "$self->{remote_addr}> $_[1]");
87} 138}
88 139
89sub print_response { 140sub response {
90 my ($self, $code, $msg, $hdr, $content) = @_; 141 my ($self, $code, $msg, $hdr, $content) = @_;
91 my $res = "HTTP/1.0 $code $msg\015\012"; 142 my $res = "HTTP/1.1 $code $msg\015\012";
92 143
93 $hdr->{Date} = time2str time; # slow? nah. 144 #$res .= "Connection: close\015\012";
145 $res .= "Date: ".(time2str $::NOW)."\015\012"; # slow? nah. :(
94 146
95 while (my ($h, $v) = each %$hdr) { 147 while (my ($h, $v) = each %$hdr) {
96 $res .= "$h: $v\015\012" 148 $res .= "$h: $v\015\012"
97 } 149 }
98 $res .= "\015\012$content" if defined $content; 150 $res .= "\015\012";
99 151
152 $res .= $content if defined $content and $self->{method} ne "HEAD";
153
154 print STDERR "$self->{remote_addr} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}." \"$self->{h}{referer}\"\n";#d#
155
156 $self->{written} +=
100 print {$self->{fh}} $res; 157 print {$self->{fh}} $res;
101} 158}
102 159
103sub err { 160sub err {
104 my $self = shift; 161 my $self = shift;
105 my ($code, $msg, $hdr, $content) = @_; 162 my ($code, $msg, $hdr, $content) = @_;
107 unless (defined $content) { 164 unless (defined $content) {
108 $content = "$code $msg"; 165 $content = "$code $msg";
109 $hdr->{"Content-Type"} = "text/plain"; 166 $hdr->{"Content-Type"} = "text/plain";
110 $hdr->{"Content-Length"} = length $content; 167 $hdr->{"Content-Length"} = length $content;
111 } 168 }
169 $hdr->{"Connection"} = "close";
112 170
113 $self->slog($msg) if $code;
114
115 $self->print_response($code, $msg, $hdr, $content); 171 $self->response($code, $msg, $hdr, $content);
116 172
117 die bless {}, err::; 173 die bless {}, err::;
118} 174}
119 175
176sub err_blocked {
177 my $self = shift;
178 my $ip = $self->{remote_addr};
179 my $time = time2str $blocked{$ip} = $::NOW + $::BLOCKTIME;
180
181 Coro::Event::do_timer(after => 20*rand);
182
183 $self->err(401, "too many connections",
184 {
185 "Content-Type" => "text/html",
186 "Retry-After" => $::BLOCKTIME,
187 "Warning" => "Please do NOT retry, you have been blocked",
188 "WWW-Authenticate" => "Basic realm=\"Please do NOT retry, you have been blocked\"",
189 },
190 <<EOF);
191<html><p>
192You have been blocked because you opened too many connections. You
193may retry at</p>
194
195 <p><blockquote>$time.</blockquote></p>
196
197<p>Until then, each new access will renew the block. You might want to have a
198look at the <a href="http://www.goof.com/pcg/marc/animefaq.html">FAQ</a>.</p>
199</html>
200EOF
201}
202
120sub handle { 203sub handle {
121 my $self = shift; 204 my $self = shift;
122 my $fh = $self->{fh}; 205 my $fh = $self->{fh};
123 206
207 $fh->timeout($::REQ_TIMEOUT);
124 #while() { 208 while() {
209 $self->{reqs}++;
210
211 # read request and parse first line
212 my $req = $fh->readline("\015\012\015\012");
213
214 unless (defined $req) {
215 if (exists $self->{version}) {
216 last;
217 } else {
218 $self->err(408, "request timeout");
219 }
220 }
221
125 $self->{h} = {}; 222 $self->{h} = {};
126 223
127 # read request and parse first line
128 $fh->timeout($::REQ_TIMEOUT);
129 my $req = $fh->readline("\015\012\015\012");
130 $fh->timeout($::RES_TIMEOUT); 224 $fh->timeout($::RES_TIMEOUT);
225 my $ip = $self->{remote_addr};
131 226
132 defined $req or 227 if ($blocked{$ip}) {
133 $self->err(408, "request timeout"); 228 $self->err_blocked($blocked{$ip})
229 if $blocked{$ip} > $::NOW;
230
231 delete $blocked{$ip};
232 }
233
234 if (%{$conn{$ip}} > $::MAX_CONN_IP) {
235 $self->slog(2, "blocked ip $ip");
236 $self->err_blocked;
237 }
134 238
135 $req =~ /^(?:\015\012)? 239 $req =~ /^(?:\015\012)?
136 (GET|HEAD) \040+ 240 (GET|HEAD) \040+
137 ([^\040]+) \040+ 241 ([^\040]+) \040+
138 HTTP\/([0-9]+\.[0-9]+) 242 HTTP\/([0-9]+\.[0-9]+)
139 \015\012/gx 243 \015\012/gx
140 or $self->err(403, "method not allowed", { Allow => "GET,HEAD" }); 244 or $self->err(405, "method not allowed", { Allow => "GET,HEAD" });
141
142 $2 ne "1.0"
143 or $self->err(506, "http protocol version not supported");
144 245
145 $self->{method} = $1; 246 $self->{method} = $1;
146 $self->{uri} = $2; 247 $self->{uri} = $2;
248 $self->{version} = $3;
249
250 $3 =~ /^1\./
251 or $self->err(506, "http protocol version $3 not supported");
147 252
148 # parse headers 253 # parse headers
149 { 254 {
150 my (%hdr, $h, $v); 255 my (%hdr, $h, $v);
151 256
164 while ($h, $v) = each %hdr; 269 while ($h, $v) = each %hdr;
165 } 270 }
166 271
167 $self->{server_port} = $self->{h}{host} =~ s/:([0-9]+)$// ? $1 : 80; 272 $self->{server_port} = $self->{h}{host} =~ s/:([0-9]+)$// ? $1 : 80;
168 273
274 weaken ($uri{$self->{remote_addr}}{$self->{uri}}{$self*1} = $self);
275
276 eval {
169 $self->map_uri; 277 $self->map_uri;
170 $self->respond; 278 $self->respond;
279 };
280
281 die if $@ && !ref $@;
282
283 $self->eoconn;
284
285 last if $self->{h}{connection} =~ /close/ || $self->{version} lt "1.1";
286
287 $self->slog(9, "persistent connection [".$self->{h}{"user-agent"}."][$self->{reqs}]");
288 $fh->timeout($::PER_TIMEOUT);
171 #} 289 }
172} 290}
173 291
174# uri => path mapping 292# uri => path mapping
175sub map_uri { 293sub map_uri {
176 my $self = shift; 294 my $self = shift;
188 306
189 $self->{name} = $uri; 307 $self->{name} = $uri;
190 308
191 # now do the path mapping 309 # now do the path mapping
192 $self->{path} = "$::DOCROOT/$host$uri"; 310 $self->{path} = "$::DOCROOT/$host$uri";
311
312 $self->access_check;
193} 313}
194 314
195sub server_address { 315sub server_address {
196 my $self = shift; 316 my $self = shift;
197 my ($port, $iaddr) = unpack_sockaddr_in $self->{fh}->getsockname 317 my ($port, $iaddr) = unpack_sockaddr_in $self->{fh}->getsockname
231 if (chdir $::DOCROOT) { 351 if (chdir $::DOCROOT) {
232 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike 352 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike
233 $ENV{HTTP_HOST} = $self->server_host; 353 $ENV{HTTP_HOST} = $self->server_host;
234 $ENV{HTTP_PORT} = $self->{server_host}; 354 $ENV{HTTP_PORT} = $self->{server_host};
235 $ENV{SCRIPT_NAME} = $self->{name}; 355 $ENV{SCRIPT_NAME} = $self->{name};
236 exec $::INDEXPROG; 356 exec $path;
237 } 357 }
238 Coro::State::_exit(0); 358 Coro::State::_exit(0);
239 } else { 359 } else {
240 } 360 }
241} 361}
244 my $self = shift; 364 my $self = shift;
245 my $path = $self->{path}; 365 my $path = $self->{path};
246 366
247 stat $path 367 stat $path
248 or $self->err(404, "not found"); 368 or $self->err(404, "not found");
369
370 $self->{stat} = [stat _];
249 371
250 # idiotic netscape sends idiotic headers AGAIN 372 # idiotic netscape sends idiotic headers AGAIN
251 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/ 373 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
252 ? str2time $1 : 0; 374 ? str2time $1 : 0;
253 375
256 if ($path !~ /\/$/) { 378 if ($path !~ /\/$/) {
257 # create a redirect to get the trailing "/" 379 # create a redirect to get the trailing "/"
258 my $host = $self->server_hostport; 380 my $host = $self->server_hostport;
259 $self->err(301, "moved permanently", { Location => "http://$host$self->{uri}/" }); 381 $self->err(301, "moved permanently", { Location => "http://$host$self->{uri}/" });
260 } else { 382 } else {
261 $ims < (stat _)[9] 383 $ims < $self->{stat}[9]
262 or $self->err(304, "not modified"); 384 or $self->err(304, "not modified");
263 385
264 if ($self->{method} eq "GET") { 386 if ($self->{method} eq "GET") {
265 if (-r "$path/index.html") { 387 if (-r "$path/index.html") {
266 $self->{path} .= "/index.html"; 388 $self->{path} .= "/index.html";
278 } 400 }
279} 401}
280 402
281sub handle_dir { 403sub handle_dir {
282 my $self = shift; 404 my $self = shift;
283 $self->_cgi($::INDEXPROG); 405 my $idx = $self->diridx;
406
407 $self->response(200, "ok",
408 {
409 "Content-Type" => "text/html",
410 "Content-Length" => length $idx,
411 },
412 $idx);
284} 413}
285 414
286sub handle_file { 415sub handle_file {
287 my $self = shift; 416 my $self = shift;
288 my $length = -s _; 417 my $length = -s _;
304 goto ignore; 433 goto ignore;
305 } 434 }
306 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h > $l; 435 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h > $l;
307 } 436 }
308 $hdr->{"Content-Range"} = "bytes */$length"; 437 $hdr->{"Content-Range"} = "bytes */$length";
438 $hdr->{"Content-Length"} = $length;
439 $self->slog(9, "not satisfiable($self->{h}{range}|".$self->{h}{"user-agent"}.")");
309 $self->err(416, "not satisfiable", $hdr); 440 $self->err(416, "not satisfiable", $hdr, "");
310 441
311satisfiable: 442satisfiable:
443 # check for segmented downloads
444 if ($l && $::NO_SEGMENTED) {
445 if (%{$uri{$self->{remote_addr}}{$self->{uri}}} > 1) {
446 Coro::Event::do_timer(after => 15);
447
448 $self->err(400, "segmented downloads are not allowed");
449 }
450 }
451
312 $hdr->{"Content-Range"} = "bytes $l-$h/$length"; 452 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
313 @code = (206, "partial content"); 453 @code = (206, "partial content");
314 $length = $h - $l + 1; 454 $length = $h - $l + 1;
315 455
316ignore: 456ignore:
317 } else { 457 } else {
318 ($l, $h) = (0, $length - 1); 458 ($l, $h) = (0, $length - 1);
319 } 459 }
320 460
321 if ($self->{path} =~ /\.html$/) { 461 $self->{path} =~ /\.([^.]+)$/;
322 $hdr->{"Content-Type"} = "text/html";
323 } else {
324 $hdr->{"Content-Type"} = "application/octet-stream"; 462 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream";
325 }
326
327 $hdr->{"Content-Length"} = $length; 463 $hdr->{"Content-Length"} = $length;
328 464
329 $self->print_response(@code, $hdr, ""); 465 $self->response(@code, $hdr, "");
330 466
331 if ($self->{method} eq "GET") { 467 if ($self->{method} eq "GET") {
332 my ($fh, $buf); 468 my ($fh, $buf, $r);
469 my $current = $Coro::current;
333 open $fh, "<", $self->{path} 470 open $fh, "<", $self->{path}
334 or die "$self->{path}: late open failure ($!)"; 471 or die "$self->{path}: late open failure ($!)";
335 472
336 if ($l) {
337 sysseek $fh, $l, 0
338 or die "$self->{path}: cannot seek to $l ($!)";
339 }
340
341 $h -= $l - 1; 473 $h -= $l - 1;
342 474
475 if (0) {
476 if ($l) {
477 sysseek $fh, $l, 0;
478 }
479 }
480
343 while ($h > 0) { 481 while ($h > 0) {
344 $h -= sysread $fh, $buf, $h > 4096 ? 4096 : $h; 482 if (0) {
345 print {$self->{fh}} $buf 483 sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h
484 or last;
485 } else {
486 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h),
487 $buf, 0, sub {
488 $r = $_[0];
489 $current->ready;
490 });
491 &Coro::schedule;
492 last unless $r;
493 }
494 my $w = $self->{fh}->syswrite($buf)
346 or last; 495 or last;
496 $::written += $w;
497 $self->{written} += $w;
498 $l += $r;
347 } 499 }
348 } 500 }
349 501
350 close $fh; 502 close $fh;
351} 503}
504
5051;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines