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.3 by root, Fri Aug 10 02:28:28 2001 UTC vs.
Revision 1.21 by root, Fri Aug 17 03:33:00 2001 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines