ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/eg/myhttpd
Revision: 1.9
Committed: Wed Apr 11 02:49:39 2007 UTC (17 years, 3 months ago) by root
Branch: MAIN
Changes since 1.8: +11 -15 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 #!/usr/bin/perl
2
3 # this is a relatively small web-server, using coroutines for connections.
4 # play around with it but do not use it in production without checking it
5 # works for you. ask myhttpd@plan9.de in case of problems, or if you are
6 # interested in a newer version (more useless features).
7
8 use Coro;
9 use Coro::Semaphore;
10 use Coro::Event;
11 use Coro::Socket;
12
13 no utf8;
14 use bytes;
15
16 # at least on my machine, this thingy serves files
17 # quite a bit faster than apache, ;)
18 # and quite a bit slower than thttpd :(
19
20 $MAX_CONNECTS = 500; # maximum simult. connects
21 $REQ_TIMEOUT = 60; # request timeout
22 $RES_TIMEOUT = 180; # response timeout
23 $MAX_POOL = 20; # max. number of idle workers
24 $DOCROOT = "/usr/www/htdocs"; # document root
25 $INDEXPROG = "/usr/www/bin/dols"; # indexing program (nph-cgi script)
26 $SERVER_HOST = "0.0.0.0"; # host to bind on
27 $SERVER_PORT = 80; # port to listen on
28
29 my $port = new Coro::Socket
30 LocalAddr => $SERVER_HOST,
31 LocalPort => $SERVER_PORT,
32 ReuseAddr => 1,
33 Listen => 1,
34 or die "unable to start server";
35
36 $SIG{PIPE} = 'IGNORE';
37
38 sub slog {
39 my $level = shift;
40 my $format = shift;
41 #printf "---: $format\n", @_;
42 }
43
44 my $connections = new Coro::Semaphore $MAX_CONNECTS;
45
46 my @fh;
47 my @pool;
48
49 sub handler {
50 while () {
51 my $fh = pop @fh;
52 if ($fh) {
53 eval {
54 conn->new($fh)->handle;
55 };
56 close $fh;
57 slog 1, "$@" if $@ && !ref $@;
58 $connections->up;
59 } else {
60 last if @pool >= $MAX_POOL;
61 push @pool, $Coro::current;
62 schedule;
63 }
64 }
65 }
66
67 async { loop };
68
69 slog 1, "accepting connections";
70 while () {
71 $connections->down;
72 push @fh, $port->accept;
73 #slog 3, "accepted @$connections ".scalar(@pool);
74 if (@pool) {
75 (pop @pool)->ready;
76 } else {
77 async \&handler;
78 }
79
80 }
81
82 package conn;
83
84 use Socket;
85 use HTTP::Date;
86
87 sub new {
88 my $class = shift;
89 my $fh = shift;
90 my (undef, $iaddr) = unpack_sockaddr_in $fh->peername
91 or $self->err(500, "unable to get peername");
92 $self->{remote_address} = inet_ntoa $iaddr;
93 bless { fh => $fh }, $class;
94 }
95
96 sub slog {
97 main::slog(@_);
98 }
99
100 sub print_response {
101 my ($self, $code, $msg, $hdr, $content) = @_;
102 my $res = "HTTP/1.0 $code $msg\015\012";
103
104 $hdr->{Date} = time2str time; # slow? nah.
105
106 while (my ($h, $v) = each %$hdr) {
107 $res .= "$h: $v\015\012"
108 }
109 $res .= "\015\012$content" if defined $content;
110
111 print {$self->{fh}} $res;
112 }
113
114 sub err {
115 my $self = shift;
116 my ($code, $msg, $hdr, $content) = @_;
117
118 unless (defined $content) {
119 $content = "$code $msg";
120 $hdr->{"Content-Type"} = "text/plain";
121 $hdr->{"Content-Length"} = length $content;
122 }
123
124 $self->slog($msg) if $code;
125
126 $self->print_response($code, $msg, $hdr, $content);
127
128 die bless {}, err::;
129 }
130
131 sub handle {
132 my $self = shift;
133 my $fh = $self->{fh};
134
135 #while() {
136 $self->{h} = {};
137
138 # read request and parse first line
139 $fh->timeout($::REQ_TIMEOUT);
140 my $req = $fh->readline("\015\012\015\012");
141 $fh->timeout($::RES_TIMEOUT);
142
143 defined $req or
144 $self->err(408, "request timeout");
145
146 $req =~ /^(?:\015\012)?
147 (GET|HEAD) \040+
148 ([^\040]+) \040+
149 HTTP\/([0-9]+\.[0-9]+)
150 \015\012/gx
151 or $self->err(403, "method not allowed", { Allow => "GET,HEAD" });
152
153 $2 < 2
154 or $self->err(506, "http protocol version not supported");
155
156 $self->{method} = $1;
157 $self->{uri} = $2;
158
159 # parse headers
160 {
161 my (%hdr, $h, $v);
162
163 $hdr{lc $1} .= ",$2"
164 while $req =~ /\G
165 ([^:\000-\040]+):
166 [\011\040]*
167 ((?: [^\015\012]+ | \015\012[\011\040] )*)
168 \015\012
169 /gxc;
170
171 $req =~ /\G\015\012$/
172 or $self->err(400, "bad request");
173
174 $self->{h}{$h} = substr $v, 1
175 while ($h, $v) = each %hdr;
176 }
177
178 $self->{server_port} = $self->{h}{host} =~ s/:([0-9]+)$// ? $1 : 80;
179
180 $self->map_uri;
181 $self->respond;
182 #}
183 }
184
185 # uri => path mapping
186 sub map_uri {
187 my $self = shift;
188 my $host = $self->{h}{host} || "default";
189 my $uri = $self->{uri};
190
191 # some massaging, also makes it more secure
192 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge;
193 $uri =~ s%//+%/%g;
194 $uri =~ s%/\.(?=/|$)%%g;
195 1 while $uri =~ s%/[^/]+/\.\.(?=/|$)%%;
196
197 $uri =~ m%^/?\.\.(?=/|$)%
198 and $self->err(400, "bad request");
199
200 $self->{name} = $uri;
201
202 # now do the path mapping
203 $self->{path} = "$::DOCROOT/$host$uri";
204 }
205
206 sub server_address {
207 my $self = shift;
208 my ($port, $iaddr) = unpack_sockaddr_in $self->{fh}->sockname
209 or $self->err(500, "unable to get socket name");
210 ((inet_ntoa $iaddr), $port);
211 }
212
213 sub server_host {
214 my $self = shift;
215 if (exists $self->{h}{host}) {
216 return $self->{h}{host};
217 } else {
218 return (($self->server_address)[0]);
219 }
220 }
221
222 sub server_hostport {
223 my $self = shift;
224 my ($host, $port);
225 if (exists $self->{h}{host}) {
226 ($host, $port) = ($self->{h}{host}, $self->{server_port});
227 } else {
228 ($host, $port) = $self->server_address;
229 }
230 $port = $port == 80 ? "" : ":$port";
231 $host.$port;
232 }
233
234 # no, this doesn't do cgi, but it's close enough
235 # for the no-longer-used directory indexing script.
236 sub _cgi {
237 my $self = shift;
238 my $path = shift;
239 my $fh;
240
241 # no two-way xxx supported
242 if (0 == fork) {
243 open STDOUT, ">&".fileno($self->{fh});
244 if (chdir $::DOCROOT) {
245 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike
246 $ENV{HTTP_HOST} = $self->server_host;
247 $ENV{HTTP_PORT} = $self->{server_host};
248 $ENV{SCRIPT_NAME} = $self->{name};
249 exec $::INDEXPROG;
250 }
251 Coro::State::_exit(0);
252 } else {
253 }
254 }
255
256 sub respond {
257 my $self = shift;
258 my $path = $self->{path};
259
260 stat $path
261 or $self->err(404, "not found");
262
263 # idiotic netscape sends idiotic headers AGAIN
264 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
265 ? str2time $1 : 0;
266
267 if (-d _ && -r _) {
268 # directory
269 if ($path !~ /\/$/) {
270 # create a redirect to get the trailing "/"
271 my $host = $self->server_hostport;
272 $self->err(301, "moved permanently", { Location => "http://$host$self->{uri}/" });
273 } else {
274 $ims < (stat _)[9]
275 or $self->err(304, "not modified");
276
277 if ($self->{method} eq "GET") {
278 if (-r "$path/index.html") {
279 $self->{path} .= "/index.html";
280 $self->handle_file;
281 } else {
282 $self->handle_dir;
283 }
284 }
285 }
286 } elsif (-f _ && -r _) {
287 -x _ and $self->err(403, "forbidden");
288 $self->handle_file;
289 } else {
290 $self->err(404, "not found");
291 }
292 }
293
294 sub handle_dir {
295 my $self = shift;
296 $self->_cgi($::INDEXPROG);
297 }
298
299 sub handle_file {
300 my $self = shift;
301 my $length = -s _;
302 my $hdr = {
303 "Last-Modified" => time2str ((stat _)[9]),
304 };
305
306 my @code = (200, "ok");
307 my ($l, $h);
308
309 if ($self->{h}{range} =~ /^bytes=(.*)$/) {
310 for (split /,/, $1) {
311 if (/^-(\d+)$/) {
312 ($l, $h) = ($length - $1, $length - 1);
313 } elsif (/^(\d+)-(\d*)$/) {
314 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1);
315 } else {
316 ($l, $h) = (0, $length - 1);
317 goto ignore;
318 }
319 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
320 }
321 $hdr->{"Content-Range"} = "bytes */$length";
322 $self->err(416, "not satisfiable", $hdr);
323
324 satisfiable:
325 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
326 @code = (206, "partial content");
327 $length = $h - $l + 1;
328
329 ignore:
330 } else {
331 ($l, $h) = (0, $length - 1);
332 }
333
334 if ($self->{path} =~ /\.html$/) {
335 $hdr->{"Content-Type"} = "text/html";
336 } else {
337 $hdr->{"Content-Type"} = "application/octet-stream";
338 }
339
340 $hdr->{"Content-Length"} = $length;
341
342 $self->print_response(@code, $hdr, "");
343
344 if ($self->{method} eq "GET") {
345 my ($fh, $buf);
346 open $fh, "<", $self->{path}
347 or die "$self->{path}: late open failure ($!)";
348
349 if ($l) {
350 sysseek $fh, $l, 0
351 or die "$self->{path}: cannot seek to $l ($!)";
352 }
353
354 $h -= $l - 1;
355
356 while ($h > 0) {
357 $h -= sysread $fh, $buf, $h > 4096 ? 4096 : $h;
358 print {$self->{fh}} $buf
359 or last;
360 }
361 }
362
363 close $fh;
364 }
365