ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/Coro/eg/myhttpd
Revision: 1.8
Committed: Wed Apr 11 02:48:20 2007 UTC (17 years, 1 month ago) by root
Branch: MAIN
Changes since 1.7: +2 -0 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 {
68 slog 1, "accepting connections";
69 while () {
70 $connections->down;
71 push @fh, $port->accept;
72 #slog 3, "accepted @$connections ".scalar(@pool);
73 if (@pool) {
74 (pop @pool)->ready;
75 } else {
76 async \&handler;
77 }
78
79 }
80 };
81
82 cede;
83 loop;
84 print "ende\n";#d#
85
86 package conn;
87
88 use Socket;
89 use HTTP::Date;
90
91 sub new {
92 my $class = shift;
93 my $fh = shift;
94 my (undef, $iaddr) = unpack_sockaddr_in $fh->peername
95 or $self->err(500, "unable to get peername");
96 $self->{remote_address} = inet_ntoa $iaddr;
97 bless { fh => $fh }, $class;
98 }
99
100 sub slog {
101 main::slog(@_);
102 }
103
104 sub print_response {
105 my ($self, $code, $msg, $hdr, $content) = @_;
106 my $res = "HTTP/1.0 $code $msg\015\012";
107
108 $hdr->{Date} = time2str time; # slow? nah.
109
110 while (my ($h, $v) = each %$hdr) {
111 $res .= "$h: $v\015\012"
112 }
113 $res .= "\015\012$content" if defined $content;
114
115 print {$self->{fh}} $res;
116 }
117
118 sub err {
119 my $self = shift;
120 my ($code, $msg, $hdr, $content) = @_;
121
122 unless (defined $content) {
123 $content = "$code $msg";
124 $hdr->{"Content-Type"} = "text/plain";
125 $hdr->{"Content-Length"} = length $content;
126 }
127
128 $self->slog($msg) if $code;
129
130 $self->print_response($code, $msg, $hdr, $content);
131
132 die bless {}, err::;
133 }
134
135 sub handle {
136 my $self = shift;
137 my $fh = $self->{fh};
138
139 #while() {
140 $self->{h} = {};
141
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);
146
147 defined $req or
148 $self->err(408, "request timeout");
149
150 $req =~ /^(?:\015\012)?
151 (GET|HEAD) \040+
152 ([^\040]+) \040+
153 HTTP\/([0-9]+\.[0-9]+)
154 \015\012/gx
155 or $self->err(403, "method not allowed", { Allow => "GET,HEAD" });
156
157 $2 < 2
158 or $self->err(506, "http protocol version not supported");
159
160 $self->{method} = $1;
161 $self->{uri} = $2;
162
163 # parse headers
164 {
165 my (%hdr, $h, $v);
166
167 $hdr{lc $1} .= ",$2"
168 while $req =~ /\G
169 ([^:\000-\040]+):
170 [\011\040]*
171 ((?: [^\015\012]+ | \015\012[\011\040] )*)
172 \015\012
173 /gxc;
174
175 $req =~ /\G\015\012$/
176 or $self->err(400, "bad request");
177
178 $self->{h}{$h} = substr $v, 1
179 while ($h, $v) = each %hdr;
180 }
181
182 $self->{server_port} = $self->{h}{host} =~ s/:([0-9]+)$// ? $1 : 80;
183
184 $self->map_uri;
185 $self->respond;
186 #}
187 }
188
189 # uri => path mapping
190 sub map_uri {
191 my $self = shift;
192 my $host = $self->{h}{host} || "default";
193 my $uri = $self->{uri};
194
195 # some massaging, also makes it more secure
196 $uri =~ s/%([0-9a-fA-F][0-9a-fA-F])/chr hex $1/ge;
197 $uri =~ s%//+%/%g;
198 $uri =~ s%/\.(?=/|$)%%g;
199 1 while $uri =~ s%/[^/]+/\.\.(?=/|$)%%;
200
201 $uri =~ m%^/?\.\.(?=/|$)%
202 and $self->err(400, "bad request");
203
204 $self->{name} = $uri;
205
206 # now do the path mapping
207 $self->{path} = "$::DOCROOT/$host$uri";
208 }
209
210 sub server_address {
211 my $self = shift;
212 my ($port, $iaddr) = unpack_sockaddr_in $self->{fh}->sockname
213 or $self->err(500, "unable to get socket name");
214 ((inet_ntoa $iaddr), $port);
215 }
216
217 sub server_host {
218 my $self = shift;
219 if (exists $self->{h}{host}) {
220 return $self->{h}{host};
221 } else {
222 return (($self->server_address)[0]);
223 }
224 }
225
226 sub server_hostport {
227 my $self = shift;
228 my ($host, $port);
229 if (exists $self->{h}{host}) {
230 ($host, $port) = ($self->{h}{host}, $self->{server_port});
231 } else {
232 ($host, $port) = $self->server_address;
233 }
234 $port = $port == 80 ? "" : ":$port";
235 $host.$port;
236 }
237
238 # no, this doesn't do cgi, but it's close enough
239 # for the no-longer-used directory indexing script.
240 sub _cgi {
241 my $self = shift;
242 my $path = shift;
243 my $fh;
244
245 # no two-way xxx supported
246 if (0 == fork) {
247 open STDOUT, ">&".fileno($self->{fh});
248 if (chdir $::DOCROOT) {
249 $ENV{SERVER_SOFTWARE} = "thttpd-myhttpd"; # we are thttpd-alike
250 $ENV{HTTP_HOST} = $self->server_host;
251 $ENV{HTTP_PORT} = $self->{server_host};
252 $ENV{SCRIPT_NAME} = $self->{name};
253 exec $::INDEXPROG;
254 }
255 Coro::State::_exit(0);
256 } else {
257 }
258 }
259
260 sub respond {
261 my $self = shift;
262 my $path = $self->{path};
263
264 stat $path
265 or $self->err(404, "not found");
266
267 # idiotic netscape sends idiotic headers AGAIN
268 my $ims = $self->{h}{"if-modified-since"} =~ /^([^;]+)/
269 ? str2time $1 : 0;
270
271 if (-d _ && -r _) {
272 # directory
273 if ($path !~ /\/$/) {
274 # create a redirect to get the trailing "/"
275 my $host = $self->server_hostport;
276 $self->err(301, "moved permanently", { Location => "http://$host$self->{uri}/" });
277 } else {
278 $ims < (stat _)[9]
279 or $self->err(304, "not modified");
280
281 if ($self->{method} eq "GET") {
282 if (-r "$path/index.html") {
283 $self->{path} .= "/index.html";
284 $self->handle_file;
285 } else {
286 $self->handle_dir;
287 }
288 }
289 }
290 } elsif (-f _ && -r _) {
291 -x _ and $self->err(403, "forbidden");
292 $self->handle_file;
293 } else {
294 $self->err(404, "not found");
295 }
296 }
297
298 sub handle_dir {
299 my $self = shift;
300 $self->_cgi($::INDEXPROG);
301 }
302
303 sub handle_file {
304 my $self = shift;
305 my $length = -s _;
306 my $hdr = {
307 "Last-Modified" => time2str ((stat _)[9]),
308 };
309
310 my @code = (200, "ok");
311 my ($l, $h);
312
313 if ($self->{h}{range} =~ /^bytes=(.*)$/) {
314 for (split /,/, $1) {
315 if (/^-(\d+)$/) {
316 ($l, $h) = ($length - $1, $length - 1);
317 } elsif (/^(\d+)-(\d*)$/) {
318 ($l, $h) = ($1, ($2 ne "" || $2 >= $length) ? $2 : $length - 1);
319 } else {
320 ($l, $h) = (0, $length - 1);
321 goto ignore;
322 }
323 goto satisfiable if $l >= 0 && $l < $length && $h >= 0 && $h >= $l;
324 }
325 $hdr->{"Content-Range"} = "bytes */$length";
326 $self->err(416, "not satisfiable", $hdr);
327
328 satisfiable:
329 $hdr->{"Content-Range"} = "bytes $l-$h/$length";
330 @code = (206, "partial content");
331 $length = $h - $l + 1;
332
333 ignore:
334 } else {
335 ($l, $h) = (0, $length - 1);
336 }
337
338 if ($self->{path} =~ /\.html$/) {
339 $hdr->{"Content-Type"} = "text/html";
340 } else {
341 $hdr->{"Content-Type"} = "application/octet-stream";
342 }
343
344 $hdr->{"Content-Length"} = $length;
345
346 $self->print_response(@code, $hdr, "");
347
348 if ($self->{method} eq "GET") {
349 my ($fh, $buf);
350 open $fh, "<", $self->{path}
351 or die "$self->{path}: late open failure ($!)";
352
353 if ($l) {
354 sysseek $fh, $l, 0
355 or die "$self->{path}: cannot seek to $l ($!)";
356 }
357
358 $h -= $l - 1;
359
360 while ($h > 0) {
361 $h -= sysread $fh, $buf, $h > 4096 ? 4096 : $h;
362 print {$self->{fh}} $buf
363 or last;
364 }
365 }
366
367 close $fh;
368 }
369