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