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

Comparing cvsroot/Coro/myhttpd/httpd.pl (file contents):
Revision 1.2 by root, Thu Aug 9 19:11:13 2001 UTC vs.
Revision 1.17 by root, Wed Aug 15 03:06:21 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);
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;
75use Convert::Scalar 'weaken'; 74use Convert::Scalar 'weaken';
75use Linux::AIO;
76 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
83Event->add_hooks(prepare => sub {
84 &Coro::cede;
85});
86
77my %conn; # $conn{ip}{fh} => connobj 87our %conn; # $conn{ip}{fh} => connobj
88our %blocked;
89our %mimetype;
90
91sub read_mimetypes {
92 local *M;
93 if (open M, "<mime_types") {
94 while (<M>) {
95 if (/^([^#]\S+)\t+(\S+)$/) {
96 $mimetype{lc $1} = $2;
97 }
98 }
99 } else {
100 print "cannot open mime_types\n";
101 }
102}
103
104read_mimetypes;
78 105
79sub new { 106sub new {
80 my $class = shift; 107 my $class = shift;
108 my $peername = shift;
81 my $fh = shift; 109 my $fh = shift;
82 my $self = bless { fh => $fh }, $class; 110 my $self = bless { fh => $fh }, $class;
83 my (undef, $iaddr) = unpack_sockaddr_in $fh->getpeername 111 my (undef, $iaddr) = unpack_sockaddr_in $peername
84 or $self->err(500, "unable to get peername"); 112 or $self->err(500, "unable to decode peername");
113
85 $self->{remote_address} = inet_ntoa $iaddr; 114 $self->{remote_addr} = inet_ntoa $iaddr;
115 $self->{time} = $::NOW;
86 116
87 # enter ourselves into various lists 117 # enter ourselves into various lists
88 weaken ($conn{$self->{remote_address}}{$self*1} = $self); 118 weaken ($conn{$self->{remote_addr}}{$self*1} = $self);
89 print $self->{remote_address}.": ".($self*1)." > ".%{$conn{$self->{remote_address}}},"\n"; 119
120 $::conns++;
121
90 $self; 122 $self;
91} 123}
92 124
93sub DESTROY { 125sub DESTROY {
94 my $self = shift; 126 my $self = shift;
127
128 $::conns--;
129
95 delete $conn{$self->{remote_address}}{$self*1}; 130 delete $conn{$self->{remote_addr}}{$self*1};
131 delete $uri{$self->{remote_addr}}{$self->{uri}}{$self*1};
96} 132}
97 133
98sub slog { 134sub slog {
99 main::slog(@_); 135 my $self = shift;
136 main::slog($_[0], "$self->{remote_addr}> $_[1]");
100} 137}
101 138
102sub print_response { 139sub response {
103 my ($self, $code, $msg, $hdr, $content) = @_; 140 my ($self, $code, $msg, $hdr, $content) = @_;
104 my $res = "HTTP/1.0 $code $msg\015\012"; 141 my $res = "HTTP/1.1 $code $msg\015\012";
105 142
106 $hdr->{Date} = time2str time; # slow? nah. 143 #$res .= "Connection: close\015\012";
144 $res .= "Date: ".(time2str $::NOW)."\015\012"; # slow? nah. :(
107 145
108 while (my ($h, $v) = each %$hdr) { 146 while (my ($h, $v) = each %$hdr) {
109 $res .= "$h: $v\015\012" 147 $res .= "$h: $v\015\012"
110 } 148 }
111 $res .= "\015\012$content" if defined $content; 149 $res .= "\015\012";
112 150
151 $res .= $content if defined $content and $self->{method} ne "HEAD";
152
113 print STDERR "$self->{remote_address} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}." \"$self->{h}{referer}\"\n";#d# 153 print STDERR "$self->{remote_addr} \"$self->{uri}\" $code ".$hdr->{"Content-Length"}." \"$self->{h}{referer}\"\n";#d#
114 154
155 $self->{written} +=
115 print {$self->{fh}} $res; 156 print {$self->{fh}} $res;
116} 157}
117 158
118sub err { 159sub err {
119 my $self = shift; 160 my $self = shift;
120 my ($code, $msg, $hdr, $content) = @_; 161 my ($code, $msg, $hdr, $content) = @_;
122 unless (defined $content) { 163 unless (defined $content) {
123 $content = "$code $msg"; 164 $content = "$code $msg";
124 $hdr->{"Content-Type"} = "text/plain"; 165 $hdr->{"Content-Type"} = "text/plain";
125 $hdr->{"Content-Length"} = length $content; 166 $hdr->{"Content-Length"} = length $content;
126 } 167 }
168 $hdr->{"Connection"} = "close";
127 169
128 $self->slog($msg) if $code;
129
130 $self->print_response($code, $msg, $hdr, $content); 170 $self->response($code, $msg, $hdr, $content);
131 171
132 die bless {}, err::; 172 die bless {}, err::;
133} 173}
134 174
175sub err_blocked {
176 my $self = shift;
177 my $ip = $self->{remote_addr};
178 my $time = time2str $blocked{$ip} = $::NOW + $::BLOCKTIME;
179
180 Coro::Event::do_timer(after => 15);
181
182 $self->err(401, "too many connections",
183 {
184 "Content-Type" => "text/html",
185 "Retry-After" => $::BLOCKTIME
186 },
187 <<EOF);
188<html><p>
189You have been blocked because you opened too many connections. You
190may retry at</p>
191
192 <p><blockquote>$time.</blockquote></p>
193
194<p>Until then, each new access will renew the block. You might want to have a
195look at the <a href="http://www.goof.com/pcg/marc/animefaq.html">FAQ</a>.</p>
196</html>
197EOF
198}
199
135sub handle { 200sub handle {
136 my $self = shift; 201 my $self = shift;
137 my $fh = $self->{fh}; 202 my $fh = $self->{fh};
138 203
204 $fh->timeout($::REQ_TIMEOUT);
139 #while() { 205 while() {
206 $self->{reqs}++;
207
208 # read request and parse first line
209 my $req = $fh->readline("\015\012\015\012");
210
211 unless (defined $req) {
212 if (exists $self->{version}) {
213 last;
214 } else {
215 $self->err(408, "request timeout");
216 }
217 }
218
140 $self->{h} = {}; 219 $self->{h} = {};
141 220
142 # read request and parse first line
143 $fh->timeout($::REQ_TIMEOUT);
144 my $req = $fh->readline("\015\012\015\012");
145 $fh->timeout($::RES_TIMEOUT); 221 $fh->timeout($::RES_TIMEOUT);
222 my $ip = $self->{remote_addr};
146 223
147 defined $req or 224 if ($blocked{$ip}) {
148 $self->err(408, "request timeout"); 225 $self->err_blocked($blocked{$ip})
226 if $blocked{$ip} > $::NOW;
227
228 delete $blocked{$ip};
229 }
230
231 if (%{$conn{$ip}} > $::MAX_CONN_IP) {
232 $self->slog(2, "blocked ip $ip");
233 $self->err_blocked;
234 }
149 235
150 $req =~ /^(?:\015\012)? 236 $req =~ /^(?:\015\012)?
151 (GET|HEAD) \040+ 237 (GET|HEAD) \040+
152 ([^\040]+) \040+ 238 ([^\040]+) \040+
153 HTTP\/([0-9]+\.[0-9]+) 239 HTTP\/([0-9]+\.[0-9]+)
154 \015\012/gx 240 \015\012/gx
155 or $self->err(403, "method not allowed", { Allow => "GET,HEAD" }); 241 or $self->err(405, "method not allowed", { Allow => "GET,HEAD" });
156
157 $2 ne "1.0"
158 or $self->err(506, "http protocol version not supported");
159 242
160 $self->{method} = $1; 243 $self->{method} = $1;
161 $self->{uri} = $2; 244 $self->{uri} = $2;
245 $self->{version} = $3;
246
247 $3 eq "1.0" or $3 eq "1.1"
248 or $self->err(506, "http protocol version $3 not supported");
162 249
163 # parse headers 250 # parse headers
164 { 251 {
165 my (%hdr, $h, $v); 252 my (%hdr, $h, $v);
166 253
179 while ($h, $v) = each %hdr; 266 while ($h, $v) = each %hdr;
180 } 267 }
181 268
182 $self->{server_port} = $self->{h}{host} =~ s/:([0-9]+)$// ? $1 : 80; 269 $self->{server_port} = $self->{h}{host} =~ s/:([0-9]+)$// ? $1 : 80;
183 270
271 weaken ($uri{$self->{remote_addr}}{$self->{uri}}{$self*1} = $self);
272
184 $self->map_uri; 273 $self->map_uri;
185
186 Coro::Event::do_timer(after => 5);
187
188 $self->respond; 274 $self->respond;
275
276 last if $self->{h}{connection} =~ /close/ || $self->{version} lt "1.1";
277
278 $self->slog(9, "persistant connection [".$self->{h}{"user-agent"}."][$self->{reqs}]");
279 $fh->timeout($::PER_TIMEOUT);
189 #} 280 }
190} 281}
191 282
192# uri => path mapping 283# uri => path mapping
193sub map_uri { 284sub map_uri {
194 my $self = shift; 285 my $self = shift;
206 297
207 $self->{name} = $uri; 298 $self->{name} = $uri;
208 299
209 # now do the path mapping 300 # now do the path mapping
210 $self->{path} = "$::DOCROOT/$host$uri"; 301 $self->{path} = "$::DOCROOT/$host$uri";
302
303 $self->access_check;
211} 304}
212 305
213sub server_address { 306sub server_address {
214 my $self = shift; 307 my $self = shift;
215 my ($port, $iaddr) = unpack_sockaddr_in $self->{fh}->getsockname 308 my ($port, $iaddr) = unpack_sockaddr_in $self->{fh}->getsockname
249 if (chdir $::DOCROOT) { 342 if (chdir $::DOCROOT) {
250 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike 343 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike
251 $ENV{HTTP_HOST} = $self->server_host; 344 $ENV{HTTP_HOST} = $self->server_host;
252 $ENV{HTTP_PORT} = $self->{server_host}; 345 $ENV{HTTP_PORT} = $self->{server_host};
253 $ENV{SCRIPT_NAME} = $self->{name}; 346 $ENV{SCRIPT_NAME} = $self->{name};
254 exec $::INDEXPROG; 347 exec $path;
255 } 348 }
256 Coro::State::_exit(0); 349 Coro::State::_exit(0);
257 } else { 350 } else {
258 } 351 }
259} 352}
262 my $self = shift; 355 my $self = shift;
263 my $path = $self->{path}; 356 my $path = $self->{path};
264 357
265 stat $path 358 stat $path
266 or $self->err(404, "not found"); 359 or $self->err(404, "not found");
360
361 $self->{stat} = [stat _];
267 362
268 # idiotic netscape sends idiotic headers AGAIN 363 # idiotic netscape sends idiotic headers AGAIN
269 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/ 364 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
270 ? str2time $1 : 0; 365 ? str2time $1 : 0;
271 366
274 if ($path !~ /\/$/) { 369 if ($path !~ /\/$/) {
275 # create a redirect to get the trailing "/" 370 # create a redirect to get the trailing "/"
276 my $host = $self->server_hostport; 371 my $host = $self->server_hostport;
277 $self->err(301, "moved permanently", { Location => "http://$host$self->{uri}/" }); 372 $self->err(301, "moved permanently", { Location => "http://$host$self->{uri}/" });
278 } else { 373 } else {
279 $ims < (stat _)[9] 374 $ims < $self->{stat}[9]
280 or $self->err(304, "not modified"); 375 or $self->err(304, "not modified");
281 376
282 if ($self->{method} eq "GET") { 377 if ($self->{method} eq "GET") {
283 if (-r "$path/index.html") { 378 if (-r "$path/index.html") {
284 $self->{path} .= "/index.html"; 379 $self->{path} .= "/index.html";
296 } 391 }
297} 392}
298 393
299sub handle_dir { 394sub handle_dir {
300 my $self = shift; 395 my $self = shift;
301 $self->_cgi($::INDEXPROG); 396 my $idx = $self->diridx;
397
398 $self->response(200, "ok",
399 {
400 "Content-Type" => "text/html",
401 "Content-Length" => length $idx,
402 },
403 $idx);
302} 404}
303 405
304sub handle_file { 406sub handle_file {
305 my $self = shift; 407 my $self = shift;
306 my $length = -s _; 408 my $length = -s _;
325 } 427 }
326 $hdr->{"Content-Range"} = "bytes */$length"; 428 $hdr->{"Content-Range"} = "bytes */$length";
327 $self->err(416, "not satisfiable", $hdr); 429 $self->err(416, "not satisfiable", $hdr);
328 430
329satisfiable: 431satisfiable:
432 # check for segmented downloads
433 if ($l && $::NO_SEGMENTED) {
434 if (%{$uri{$self->{remote_addr}}{$self->{uri}}} > 1) {
435 Coro::Event::do_timer(after => 15);
436
437 $self->err(400, "segmented downloads are not allowed");
438 }
439 }
440
330 $hdr->{"Content-Range"} = "bytes $l-$h/$length"; 441 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
331 @code = (206, "partial content"); 442 @code = (206, "partial content");
332 $length = $h - $l + 1; 443 $length = $h - $l + 1;
333 444
334ignore: 445ignore:
335 } else { 446 } else {
336 ($l, $h) = (0, $length - 1); 447 ($l, $h) = (0, $length - 1);
337 } 448 }
338 449
339 if ($self->{path} =~ /\.html$/) { 450 $self->{path} =~ /\.([^.]+)$/;
340 $hdr->{"Content-Type"} = "text/html";
341 } else {
342 $hdr->{"Content-Type"} = "application/octet-stream"; 451 $hdr->{"Content-Type"} = $mimetype{lc $1} || "application/octet-stream";
343 }
344
345 $hdr->{"Content-Length"} = $length; 452 $hdr->{"Content-Length"} = $length;
346 453
347 $self->print_response(@code, $hdr, ""); 454 $self->response(@code, $hdr, "");
348 455
349 if ($self->{method} eq "GET") { 456 if ($self->{method} eq "GET") {
350 my ($fh, $buf); 457 my ($fh, $buf, $r);
458 my $current = $Coro::current;
351 open $fh, "<", $self->{path} 459 open $fh, "<", $self->{path}
352 or die "$self->{path}: late open failure ($!)"; 460 or die "$self->{path}: late open failure ($!)";
353 461
354 if ($l) {
355 sysseek $fh, $l, 0
356 or die "$self->{path}: cannot seek to $l ($!)";
357 }
358
359 $h -= $l - 1; 462 $h -= $l - 1;
360 463
361 while ($h > 0) { 464 while ($h > 0) {
362 $h -= sysread $fh, $buf, $h > 4096 ? 4096 : $h; 465 aio_read($fh, $l, ($h > $::BUFSIZE ? $::BUFSIZE : $h),
363 print {$self->{fh}} $buf 466 $buf, 0, sub {
467 $r = $_[0];
468 $current->ready;
469 });
470 &Coro::schedule;
471 last unless $r;
472 my $w = $self->{fh}->syswrite($buf)
364 or last; 473 or last;
474 $::written += $w;
475 $self->{written} += $w;
476 $l += $r;
365 } 477 }
366 } 478 }
367 479
368 close $fh; 480 close $fh;
369} 481}

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines