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.12 by root, Sat Aug 11 23:10:56 2001 UTC vs.
Revision 1.31 by root, Mon Aug 27 05:05:26 2001 UTC

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 12
13$SIG{PIPE} = 'IGNORE'; 13$SIG{PIPE} = 'IGNORE';
14 14
15our $accesslog;
16
17if ($ACCESS_LOG) {
18 use IO::Handle;
19 open $accesslog, ">>$ACCESS_LOG"
20 or die "$ACCESS_LOG: $!";
21 $accesslog->autoflush(1);
22}
23
15sub slog { 24sub slog {
16 my $level = shift; 25 my $level = shift;
17 my $format = shift; 26 my $format = shift;
18 printf "---: $format\n", @_; 27 printf "---: $format\n", @_;
19} 28}
43 52
44my $http_port = new Coro::Socket 53my $http_port = new Coro::Socket
45 LocalAddr => $SERVER_HOST, 54 LocalAddr => $SERVER_HOST,
46 LocalPort => $SERVER_PORT, 55 LocalPort => $SERVER_PORT,
47 ReuseAddr => 1, 56 ReuseAddr => 1,
48 Listen => 1, 57 Listen => 50,
49 or die "unable to start server"; 58 or die "unable to start server";
50 59
51push @listen_sockets, $http_port; 60push @listen_sockets, $http_port;
52 61
53# the "main thread" 62# the "main thread"
70package conn; 79package conn;
71 80
72use Socket; 81use Socket;
73use HTTP::Date; 82use HTTP::Date;
74use Convert::Scalar 'weaken'; 83use Convert::Scalar 'weaken';
84use Linux::AIO;
75 85
86Linux::AIO::min_parallel $::AIO_PARALLEL;
87
88my $aio_requests = new Coro::Semaphore $::AIO_PARALLEL * 4;
89
90Event->io(fd => Linux::AIO::poll_fileno,
91 poll => 'r', async => 1,
92 cb => \&Linux::AIO::poll_cb);
93
76our %conn; # $conn{ip}{fh} => connobj 94our %conn; # $conn{ip}{self} => connobj
95our %uri; # $uri{ip}{uri}{self}
77our %blocked; 96our %blocked;
78our %mimetype; 97our %mimetype;
79 98
80sub read_mimetypes { 99sub read_mimetypes {
81 local *M; 100 local *M;
104 $self->{time} = $::NOW; 123 $self->{time} = $::NOW;
105 124
106 # enter ourselves into various lists 125 # enter ourselves into various lists
107 weaken ($conn{$self->{remote_addr}}{$self*1} = $self); 126 weaken ($conn{$self->{remote_addr}}{$self*1} = $self);
108 127
128 $::conns++;
129
109 $self; 130 $self;
110} 131}
111 132
112sub DESTROY { 133sub DESTROY {
113 my $self = shift; 134 my $self = shift;
135
136 $::conns--;
137
138 $self->eoconn;
114 delete $conn{$self->{remote_addr}}{$self*1}; 139 delete $conn{$self->{remote_addr}}{$self*1};
140}
141
142# end of connection
143sub eoconn {
144 my $self = shift;
115 delete $uri{$self->{uri}}{$self*1}; 145 delete $uri{$self->{remote_addr}}{$self->{uri}}{$self*1};
116} 146}
117 147
118sub slog { 148sub slog {
119 my $self = shift; 149 my $self = shift;
120 main::slog($_[0], "$self->{remote_addr}> $_[1]"); 150 main::slog($_[0], ($self->{remote_id} || $self->{remote_addr}) ."> $_[1]");
121} 151}
122 152
123sub response { 153sub response {
124 my ($self, $code, $msg, $hdr, $content) = @_; 154 my ($self, $code, $msg, $hdr, $content) = @_;
125 my $res = "HTTP/1.0 $code $msg\015\012"; 155 my $res = "HTTP/1.1 $code $msg\015\012";
126 156
127 $res .= "Connection: close\015\012"; 157 $self->{h}{connection} ||= $hdr->{Connection};
158
128 $res .= "Date: ".(time2str $::NOW)."\015\012"; # slow? nah. :( 159 $res .= "Date: ".(time2str $::NOW)."\015\012"; # slow? nah. :(
129 160
130 while (my ($h, $v) = each %$hdr) { 161 while (my ($h, $v) = each %$hdr) {
131 $res .= "$h: $v\015\012" 162 $res .= "$h: $v\015\012"
132 } 163 }
133 $res .= "\015\012"; 164 $res .= "\015\012";
134 165
135 $res .= $content if defined $content and $self->{method} eq "GET"; 166 $res .= $content if defined $content and $self->{method} ne "HEAD";
136 167
137 print STDERR "$self->{remote_addr} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}." \"$self->{h}{referer}\"\n";#d# 168 my $log = "$self->{remote_addr} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}." \"$self->{h}{referer}\"\n";
169
170 print $accesslog $log if $accesslog;
171 print STDERR $log;
138 172
139 $self->{written} += 173 $self->{written} +=
140 print {$self->{fh}} $res; 174 print {$self->{fh}} $res;
141} 175}
142 176
147 unless (defined $content) { 181 unless (defined $content) {
148 $content = "$code $msg"; 182 $content = "$code $msg";
149 $hdr->{"Content-Type"} = "text/plain"; 183 $hdr->{"Content-Type"} = "text/plain";
150 $hdr->{"Content-Length"} = length $content; 184 $hdr->{"Content-Length"} = length $content;
151 } 185 }
186 $hdr->{"Connection"} = "close";
152 187
153 $self->response($code, $msg, $hdr, $content); 188 $self->response($code, $msg, $hdr, $content);
154 189
155 die bless {}, err::; 190 die bless {}, err::;
156} 191}
157 192
158sub err_blocked {
159 my $self = shift;
160 my $ip = $self->{remote_addr};
161 my $time = time2str $blocked{$ip} = $::NOW + $::BLOCKTIME;
162
163 Coro::Event::do_timer(after => 5);
164
165 $self->err(403, "too many connections",
166 {
167 "Content-Type" => "text/html",
168 "Retry-After" => $::BLOCKTIME
169 },
170 <<EOF);
171<html><p>
172You have been blocked because you opened too many connections. You
173may retry at</p>
174
175 <p><blockquote>$time.</blockquote></p>
176
177<p>Until then, each new access will renew the block. You might want to have a
178look at the <a href="http://www.goof.com/pcg/marc/animefaq.html">FAQ</a>.</p>
179</html>
180EOF
181}
182
183sub handle { 193sub handle {
184 my $self = shift; 194 my $self = shift;
185 my $fh = $self->{fh}; 195 my $fh = $self->{fh};
186 196
197 my $host;
198
199 $fh->timeout($::REQ_TIMEOUT);
187 #while() { 200 while() {
201 $self->{reqs}++;
202
203 # read request and parse first line
204 my $req = $fh->readline("\015\012\015\012");
205
206 unless (defined $req) {
207 if (exists $self->{version}) {
208 last;
209 } else {
210 $self->err(408, "request timeout");
211 }
212 }
213
188 $self->{h} = {}; 214 $self->{h} = {};
189 215
190 # read request and parse first line
191 $fh->timeout($::REQ_TIMEOUT);
192 my $req = $fh->readline("\015\012\015\012");
193 $fh->timeout($::RES_TIMEOUT); 216 $fh->timeout($::RES_TIMEOUT);
194
195 defined $req or
196 $self->err(408, "request timeout");
197
198 my $ip = $self->{remote_addr}; 217 my $ip = $self->{remote_addr};
199 218
200 if ($blocked{$ip}) { 219 if ($blocked{$ip}) {
201 $self->err_blocked($blocked{$ip}) 220 $self->err_blocked($blocked{$ip})
202 if $blocked{$ip} > $::NOW; 221 if $blocked{$ip} > $::NOW;
203 222
204 delete $blocked{$ip}; 223 delete $blocked{$ip};
205 } 224 }
206 225
207 if (%{$conn{$ip}} > $::MAX_CONN_IP) { 226 if (%{$conn{$ip}} > $::MAX_CONN_IP) {
227 my $delay = 120;
228 while (%{$conn{$ip}} > $::MAX_CONN_IP) {
229 if ($delay <= 0) {
208 $self->slog(2, "blocked ip $ip"); 230 $self->slog(2, "blocked ip $ip");
209 $self->err_blocked; 231 $self->err_blocked;
232 } else {
233 Coro::Event::do_timer(after => 3);
234 $delay -= 3;
235 }
236 }
210 } 237 }
211 238
212 $req =~ /^(?:\015\012)? 239 $req =~ /^(?:\015\012)?
213 (GET|HEAD) \040+ 240 (GET|HEAD) \040+
214 ([^\040]+) \040+ 241 ([^\040]+) \040+
215 HTTP\/([0-9]+\.[0-9]+) 242 HTTP\/([0-9]+\.[0-9]+)
216 \015\012/gx 243 \015\012/gx
217 or $self->err(403, "method not allowed", { Allow => "GET,HEAD" }); 244 or $self->err(405, "method not allowed", { Allow => "GET,HEAD" });
218
219 $2 ne "1.0"
220 or $self->err(506, "http protocol version not supported");
221 245
222 $self->{method} = $1; 246 $self->{method} = $1;
223 $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");
224 252
225 # parse headers 253 # parse headers
226 { 254 {
227 my (%hdr, $h, $v); 255 my (%hdr, $h, $v);
228 256
239 267
240 $self->{h}{$h} = substr $v, 1 268 $self->{h}{$h} = substr $v, 1
241 while ($h, $v) = each %hdr; 269 while ($h, $v) = each %hdr;
242 } 270 }
243 271
272 # find out server name and port
273 if ($self->{uri} =~ s/^http:\/\/([^\/?#]*)//i) {
274 $host = $1;
275 } else {
276 $host = $self->{h}{host};
277 }
278
279 if (defined $host) {
244 $self->{server_port} = $self->{h}{host} =~ s/:([0-9]+)$// ? $1 : 80; 280 $self->{server_port} = $host =~ s/:([0-9]+)$// ? $1 : 80;
281 } else {
282 ($self->{server_port}, $host)
283 = unpack_sockaddr_in $self->{fh}->getsockname
284 or $self->err(500, "unable to get socket name");
285 $host = inet_ntoa $host;
286 }
245 287
288 $self->{server_name} = $host;
289
290 # remote id should be unique per user
291 $self->{remote_id} = $self->{remote_addr};
292
293 if (exists $self->{h}{"client-ip"}) {
294 $self->{remote_id} .= "[".$self->{h}{"client-ip"}."]";
295 } elsif (exists $self->{h}{"x-forwarded-for"}) {
296 $self->{remote_id} .= "[".$self->{h}{"x-forwarded-for"}."]";
297 }
298
246 weaken ($uri{$self->{uri}}{$self*1} = $self); 299 weaken ($uri{$self->{remote_addr}}{$self->{uri}}{$self*1} = $self);
247 300
301 eval {
248 $self->map_uri; 302 $self->map_uri;
249 $self->respond; 303 $self->respond;
304 };
305
306 $self->eoconn;
307
308 die if $@ && !ref $@;
309
310 last if $self->{h}{connection} =~ /close/ || $self->{version} < 1.1;
311
312 $fh->timeout($::PER_TIMEOUT);
250 #} 313 }
251} 314}
252 315
253# uri => path mapping 316# uri => path mapping
254sub map_uri { 317sub map_uri {
255 my $self = shift; 318 my $self = shift;
256 my $host = $self->{h}{host} || "default"; 319 my $host = $self->{server_name};
257 my $uri = $self->{uri}; 320 my $uri = $self->{uri};
258 321
259 # some massaging, also makes it more secure 322 # some massaging, also makes it more secure
260 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge; 323 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge;
261 $uri =~ s%//+%/%g; 324 $uri =~ s%//+%/%g;
271 $self->{path} = "$::DOCROOT/$host$uri"; 334 $self->{path} = "$::DOCROOT/$host$uri";
272 335
273 $self->access_check; 336 $self->access_check;
274} 337}
275 338
276sub server_address {
277 my $self = shift;
278 my ($port, $iaddr) = unpack_sockaddr_in $self->{fh}->getsockname
279 or $self->err(500, "unable to get socket name");
280 ((inet_ntoa $iaddr), $port);
281}
282
283sub server_host {
284 my $self = shift;
285 if (exists $self->{h}{host}) {
286 return $self->{h}{host};
287 } else {
288 return (($self->server_address)[0]);
289 }
290}
291
292sub server_hostport {
293 my $self = shift;
294 my ($host, $port);
295 if (exists $self->{h}{host}) {
296 ($host, $port) = ($self->{h}{host}, $self->{server_port});
297 } else {
298 ($host, $port) = $self->server_address;
299 }
300 $port = $port == 80 ? "" : ":$port";
301 $host.$port;
302}
303
304sub _cgi { 339sub _cgi {
305 my $self = shift; 340 my $self = shift;
306 my $path = shift; 341 my $path = shift;
307 my $fh; 342 my $fh;
308 343
309 # no two-way xxx supported 344 # no two-way xxx supported
310 if (0 == fork) { 345 if (0 == fork) {
311 open STDOUT, ">&".fileno($self->{fh}); 346 open STDOUT, ">&".fileno($self->{fh});
312 if (chdir $::DOCROOT) { 347 if (chdir $::DOCROOT) {
313 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike 348 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike
314 $ENV{HTTP_HOST} = $self->server_host; 349 $ENV{HTTP_HOST} = $self->{server_name};
315 $ENV{HTTP_PORT} = $self->{server_host}; 350 $ENV{HTTP_PORT} = $self->{server_port};
316 $ENV{SCRIPT_NAME} = $self->{name}; 351 $ENV{SCRIPT_NAME} = $self->{name};
317 exec $path; 352 exec $path;
318 } 353 }
319 Coro::State::_exit(0); 354 Coro::State::_exit(0);
320 } else { 355 } else {
356 die;
321 } 357 }
358}
359
360sub server_hostport {
361 $_[0]{server_port} == 80
362 ? $_[0]{server_name}
363 : "$_[0]{server_name}:$_[0]{server_port}";
322} 364}
323 365
324sub respond { 366sub respond {
325 my $self = shift; 367 my $self = shift;
326 my $path = $self->{path}; 368 my $path = $self->{path};
336 378
337 if (-d _ && -r _) { 379 if (-d _ && -r _) {
338 # directory 380 # directory
339 if ($path !~ /\/$/) { 381 if ($path !~ /\/$/) {
340 # create a redirect to get the trailing "/" 382 # create a redirect to get the trailing "/"
341 my $host = $self->server_hostport; 383 # we don't try to avoid the :80
342 $self->err(301, "moved permanently", { Location => "http://$host$self->{uri}/" }); 384 $self->err(301, "moved permanently", { Location => "http://".$self->server_hostport."$self->{uri}/" });
343 } else { 385 } else {
344 $ims < $self->{stat}[9] 386 $ims < $self->{stat}[9]
345 or $self->err(304, "not modified"); 387 or $self->err(304, "not modified");
346 388
347 if ($self->{method} eq "GET") {
348 if (-r "$path/index.html") { 389 if (-r "$path/index.html") {
349 $self->{path} .= "/index.html"; 390 $self->{path} .= "/index.html";
350 $self->handle_file; 391 $self->handle_file;
351 } else { 392 } else {
352 $self->handle_dir; 393 $self->handle_dir;
353 }
354 } 394 }
355 } 395 }
356 } elsif (-f _ && -r _) { 396 } elsif (-f _ && -r _) {
357 -x _ and $self->err(403, "forbidden"); 397 -x _ and $self->err(403, "forbidden");
358 $self->handle_file; 398 $self->handle_file;
391 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1); 431 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1);
392 } else { 432 } else {
393 ($l, $h) = (0, $length - 1); 433 ($l, $h) = (0, $length - 1);
394 goto ignore; 434 goto ignore;
395 } 435 }
396 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h > $l; 436 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
397 } 437 }
398 $hdr->{"Content-Range"} = "bytes */$length"; 438 $hdr->{"Content-Range"} = "bytes */$length";
439 $hdr->{"Content-Length"} = $length;
440 $self->slog(9, "not satisfiable($self->{h}{range}|".$self->{h}{"user-agent"}.")");
399 $self->err(416, "not satisfiable", $hdr); 441 $self->err(416, "not satisfiable", $hdr, "");
400 442
401satisfiable: 443satisfiable:
402 # check for segmented downloads 444 # check for segmented downloads
403 if ($l && $::NO_SEGMENTED) { 445 if ($l && $::NO_SEGMENTED) {
404 if (%{$uri{$self->{uri}}} > 1) { 446 my $delay = 180;
405 $self->err(400, "segmented downloads are not allowed"); 447 while (%{$uri{$self->{remote_addr}}{$self->{uri}}} > 1) {
448 if ($delay <= 0) {
449 $self->err_segmented_download;
450 } else {
451 Coro::Event::do_timer(after => 3); $delay -= 3;
452 }
406 } 453 }
407 } 454 }
408 455
409 $hdr->{"Content-Range"} = "bytes $l-$h/$length"; 456 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
410 @code = (206, "partial content"); 457 @code = (206, "partial content");
420 $hdr->{"Content-Length"} = $length; 467 $hdr->{"Content-Length"} = $length;
421 468
422 $self->response(@code, $hdr, ""); 469 $self->response(@code, $hdr, "");
423 470
424 if ($self->{method} eq "GET") { 471 if ($self->{method} eq "GET") {
425 my ($fh, $buf); 472 my ($fh, $buf, $r);
473 my $current = $Coro::current;
426 open $fh, "<", $self->{path} 474 open $fh, "<", $self->{path}
427 or die "$self->{path}: late open failure ($!)"; 475 or die "$self->{path}: late open failure ($!)";
428 476
429 if ($l) {
430 sysseek $fh, $l, 0
431 or die "$self->{path}: cannot seek to $l ($!)";
432 }
433
434 $h -= $l - 1; 477 $h -= $l - 1;
435 478
479 if (0) {
480 if ($l) {
481 sysseek $fh, $l, 0;
482 }
483 }
484
436 while ($h > 0) { 485 while ($h > 0) {
486 if (0) {
437 $h -= sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h; 487 sysread $fh, $buf, $h > $::BUFSIZE ? $::BUFSIZE : $h
488 or last;
489 } else {
490 undef $buf;
491 $aio_requests->down;
492 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h),
493 $buf, 0, sub {
494 $r = $_[0];
495 $current->ready;
496 });
497 &Coro::schedule;
498 $aio_requests->up;
499 last unless $r;
500 }
438 my $w = $self->{fh}->syswrite($buf) 501 my $w = $self->{fh}->syswrite($buf)
439 or last; 502 or last;
440 $::written += $w; 503 $::written += $w;
441 $self->{written} += $w; 504 $self->{written} += $w;
505 $l += $r;
442 } 506 }
443 } 507 }
444 508
445 close $fh; 509 close $fh;
446} 510}

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines