update Changes to note inclusion of stats
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Engine / HTTP.pm
CommitLineData
ca61af20 1package Catalyst::Engine::HTTP;
45374ac6 2
3use strict;
fbcc39ad 4use base 'Catalyst::Engine::CGI';
4bb8bd62 5use Data::Dump qw(dump);
fbcc39ad 6use Errno 'EWOULDBLOCK';
055ff026 7use HTTP::Date ();
06744540 8use HTTP::Headers;
fbcc39ad 9use HTTP::Status;
10use NEXT;
11use Socket;
6c7a1d2f 12use IO::Socket::INET ();
b5ecfcf0 13use IO::Select ();
41593b49 14use POSIX ":sys_wait_h";
45374ac6 15
71fd2e0f 16# For PAR
17require Catalyst::Engine::HTTP::Restarter;
18require Catalyst::Engine::HTTP::Restarter::Watcher;
19
333123ef 20use constant CHUNKSIZE => 64 * 1024;
21use constant DEBUG => $ENV{CATALYST_HTTP_DEBUG} || 0;
4bb8bd62 22
45374ac6 23=head1 NAME
24
ca61af20 25Catalyst::Engine::HTTP - Catalyst HTTP Engine
45374ac6 26
27=head1 SYNOPSIS
28
ca61af20 29A script using the Catalyst::Engine::HTTP module might look like:
45374ac6 30
31 #!/usr/bin/perl -w
32
ca61af20 33 BEGIN { $ENV{CATALYST_ENGINE} = 'HTTP' }
45374ac6 34
35 use strict;
36 use lib '/path/to/MyApp/lib';
37 use MyApp;
38
39 MyApp->run;
40
41=head1 DESCRIPTION
42
43This is the Catalyst engine specialized for development and testing.
44
fbcc39ad 45=head1 METHODS
46
b5ecfcf0 47=head2 $self->finalize_headers($c)
fbcc39ad 48
49=cut
50
51sub finalize_headers {
52 my ( $self, $c ) = @_;
53 my $protocol = $c->request->protocol;
54 my $status = $c->response->status;
55 my $message = status_message($status);
055ff026 56
06744540 57 my @headers;
58 push @headers, "$protocol $status $message";
055ff026 59
60 $c->response->headers->header( Date => HTTP::Date::time2str(time) );
055ff026 61 $c->response->headers->header( Status => $status );
06744540 62
7f3c5736 63 # Should we keep the connection open?
64 my $connection = $c->request->header('Connection');
65 if ( $self->{options}->{keepalive}
66 && $connection
67 && $connection =~ /^keep-alive$/i
68 ) {
69 $c->response->headers->header( Connection => 'keep-alive' );
70 $self->{_keepalive} = 1;
71 }
72 else {
73 $c->response->headers->header( Connection => 'close' );
74 }
75
06744540 76 push @headers, $c->response->headers->as_string("\x0D\x0A");
77
78 # Buffer the headers so they are sent with the first write() call
79 # This reduces the number of TCP packets we are sending
80 $self->{_header_buf} = join("\x0D\x0A", @headers, '');
fbcc39ad 81}
82
b5ecfcf0 83=head2 $self->finalize_read($c)
fbcc39ad 84
85=cut
86
87sub finalize_read {
88 my ( $self, $c ) = @_;
89
90 # Never ever remove this, it would result in random length output
91 # streams if STDIN eq STDOUT (like in the HTTP engine)
4f5ebacd 92 *STDIN->blocking(1);
fbcc39ad 93
94 return $self->NEXT::finalize_read($c);
95}
96
b5ecfcf0 97=head2 $self->prepare_read($c)
fbcc39ad 98
99=cut
100
101sub prepare_read {
102 my ( $self, $c ) = @_;
103
104 # Set the input handle to non-blocking
4f5ebacd 105 *STDIN->blocking(0);
fbcc39ad 106
107 return $self->NEXT::prepare_read($c);
108}
109
b5ecfcf0 110=head2 $self->read_chunk($c, $buffer, $length)
fbcc39ad 111
112=cut
113
114sub read_chunk {
115 my $self = shift;
116 my $c = shift;
4bb8bd62 117
118 # If we have any remaining data in the input buffer, send it back first
119 if ( $_[0] = delete $self->{inputbuf} ) {
120 my $read = length( $_[0] );
121 DEBUG && warn "read_chunk: Read $read bytes from previous input buffer\n";
122 return $read;
123 }
fbcc39ad 124
125 # support for non-blocking IO
4f5ebacd 126 my $rin = '';
127 vec( $rin, *STDIN->fileno, 1 ) = 1;
fbcc39ad 128
129 READ:
130 {
131 select( $rin, undef, undef, undef );
4f5ebacd 132 my $rc = *STDIN->sysread(@_);
fbcc39ad 133 if ( defined $rc ) {
4bb8bd62 134 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
fbcc39ad 135 return $rc;
136 }
137 else {
138 next READ if $! == EWOULDBLOCK;
139 return;
140 }
141 }
142}
143
00c99324 144=head2 $self->write($c, $buffer)
145
e512dd24 146Writes the buffer to the client.
00c99324 147
148=cut
149
150sub write {
4bb8bd62 151 my ( $self, $c, $buffer ) = @_;
152
85d9fce6 153 # Avoid 'print() on closed filehandle Remote' warnings when using IE
154 return unless *STDOUT->opened();
155
85d9fce6 156 # Prepend the headers if they have not yet been sent
157 if ( my $headers = delete $self->{_header_buf} ) {
e512dd24 158 $buffer = $headers . $buffer;
4bb8bd62 159 }
160
e512dd24 161 my $ret = $self->NEXT::write( $c, $buffer );
162
e512dd24 163 if ( !defined $ret ) {
4bb8bd62 164 $self->{_write_error} = $!;
e2b0ddd3 165 DEBUG && warn "write: Failed to write response ($!)\n";
4bb8bd62 166 }
9f3ebd8a 167 else {
168 DEBUG && warn "write: Wrote response ($ret bytes)\n";
169 }
4bb8bd62 170
171 return $ret;
00c99324 172}
173
b5ecfcf0 174=head2 run
fbcc39ad 175
176=cut
177
178# A very very simple HTTP server that initializes a CGI environment
179sub run {
37553dc8 180 my ( $self, $class, $port, $host, $options ) = @_;
fbcc39ad 181
4eeca0f2 182 $options ||= {};
3bcb3aae 183
184 $self->{options} = $options;
1cf1c56a 185
e1576f62 186 if ($options->{background}) {
187 my $child = fork;
188 die "Can't fork: $!" unless defined($child);
44c6d25a 189 return $child if $child;
e1576f62 190 }
191
57a87bb3 192 my $restart = 0;
41593b49 193 local $SIG{CHLD} = \&_REAPER;
fbcc39ad 194
1cf1c56a 195 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
6c7a1d2f 196 my $addr = $host ? inet_aton($host) : INADDR_ANY;
197 if ( $addr eq INADDR_ANY ) {
fbcc39ad 198 require Sys::Hostname;
6c7a1d2f 199 $host = lc Sys::Hostname::hostname();
fbcc39ad 200 }
201 else {
6c7a1d2f 202 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
fbcc39ad 203 }
6c7a1d2f 204
205 # Handle requests
206
207 # Setup socket
208 my $daemon = IO::Socket::INET->new(
209 Listen => SOMAXCONN,
210 LocalAddr => inet_ntoa($addr),
211 LocalPort => $port,
212 Proto => 'tcp',
213 ReuseAddr => 1,
214 Type => SOCK_STREAM,
215 )
216 or die "Couldn't create daemon: $!";
217
218 my $url = "http://$host";
219 $url .= ":$port" unless $port == 80;
220
fbcc39ad 221 print "You can connect to your server at $url\n";
fbcc39ad 222
e1576f62 223 if ($options->{background}) {
224 open STDIN, "+</dev/null" or die $!;
225 open STDOUT, ">&STDIN" or die $!;
226 open STDERR, ">&STDIN" or die $!;
227 if ( $^O !~ /MSWin32/ ) {
228 require POSIX;
229 POSIX::setsid()
230 or die "Can't start a new session: $!";
231 }
232 }
233
234 if (my $pidfile = $options->{pidfile}) {
235 if (! open PIDFILE, "> $pidfile") {
236 warn("Cannot open: $pidfile: $!");
237 }
238 print PIDFILE "$$\n";
239 close PIDFILE;
240 }
241
4bb8bd62 242 my $pid = undef;
243
244 # Ignore broken pipes as an HTTP server should
245 local $SIG{PIPE} = 'IGNORE';
246
b095458a 247 # Restart on HUP
248 local $SIG{HUP} = sub {
249 $restart = 1;
250 warn "Restarting server on SIGHUP...\n";
251 };
252
4bb8bd62 253 LISTEN:
254 while ( !$restart ) {
255 while ( accept( Remote, $daemon ) ) {
256 DEBUG && warn "New connection\n";
fbcc39ad 257
4bb8bd62 258 select Remote;
fbcc39ad 259
4bb8bd62 260 Remote->blocking(1);
261
7f3c5736 262 # Read until we see all headers
4bb8bd62 263 $self->{inputbuf} = '';
4bb8bd62 264
7f3c5736 265 if ( !$self->_read_headers ) {
266 # Error reading, give up
267 next LISTEN;
4bb8bd62 268 }
fbcc39ad 269
4bb8bd62 270 my ( $method, $uri, $protocol ) = $self->_parse_request_line;
271
272 DEBUG && warn "Parsed request: $method $uri $protocol\n";
273
274 next unless $method;
57a87bb3 275
4bb8bd62 276 unless ( uc($method) eq 'RESTART' ) {
57a87bb3 277
4bb8bd62 278 # Fork
1b45d7e5 279 if ( $options->{fork} ) {
280 if ( $pid = fork ) {
281 DEBUG && warn "Forked child $pid\n";
282 next;
283 }
284 }
6c7a1d2f 285
4bb8bd62 286 $self->_handler( $class, $port, $method, $uri, $protocol );
287
288 if ( my $error = delete $self->{_write_error} ) {
4bb8bd62 289 close Remote;
1b45d7e5 290
291 if ( !defined $pid ) {
292 next LISTEN;
293 }
4bb8bd62 294 }
fbcc39ad 295
1b45d7e5 296 if ( defined $pid ) {
297 # Child process, close connection and exit
298 DEBUG && warn "Child process exiting\n";
299 $daemon->close;
300 exit;
301 }
1cf1c56a 302 }
4bb8bd62 303 else {
304 my $sockdata = $self->_socket_data( \*Remote );
305 my $ipaddr = _inet_addr( $sockdata->{peeraddr} );
306 my $ready = 0;
307 foreach my $ip ( keys %$allowed ) {
308 my $mask = $allowed->{$ip};
309 $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
310 last if $ready;
311 }
312 if ($ready) {
313 $restart = 1;
314 last;
315 }
1cf1c56a 316 }
4bb8bd62 317 }
318 continue {
319 close Remote;
320 }
fbcc39ad 321 }
4bb8bd62 322
6c7a1d2f 323 $daemon->close;
4bb8bd62 324
325 DEBUG && warn "Shutting down\n";
37553dc8 326
57a87bb3 327 if ($restart) {
60c38e3e 328 $SIG{CHLD} = 'DEFAULT';
6844bc1c 329 wait;
e37e3977 330
331 ### if the standalone server was invoked with perl -I .. we will loose
332 ### those include dirs upon re-exec. So add them to PERL5LIB, so they
333 ### are available again for the exec'ed process --kane
334 use Config;
335 $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
336
1cf1c56a 337 exec $^X . ' "' . $0 . '" ' . join( ' ', @{ $options->{argv} } );
60c38e3e 338 }
57a87bb3 339
340 exit;
fbcc39ad 341}
342
6c7a1d2f 343sub _handler {
344 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
345
6c7a1d2f 346 local *STDIN = \*Remote;
347 local *STDOUT = \*Remote;
348
349 # We better be careful and just use 1.0
350 $protocol = '1.0';
351
352 my $sockdata = $self->_socket_data( \*Remote );
353 my %copy_of_env = %ENV;
354
355 my $sel = IO::Select->new;
356 $sel->add( \*STDIN );
3bcb3aae 357
358 REQUEST:
683762ca 359 while (1) {
360 my ( $path, $query_string ) = split /\?/, $uri, 2;
361
7f3c5736 362 # Initialize CGI environment
363 local %ENV = (
364 PATH_INFO => $path || '',
365 QUERY_STRING => $query_string || '',
366 REMOTE_ADDR => $sockdata->{peeraddr},
367 REMOTE_HOST => $sockdata->{peername},
368 REQUEST_METHOD => $method || '',
369 SERVER_NAME => $sockdata->{localname},
370 SERVER_PORT => $port,
371 SERVER_PROTOCOL => "HTTP/$protocol",
372 %copy_of_env,
373 );
cf26c39c 374
7f3c5736 375 # Parse headers
376 if ( $protocol >= 1 ) {
377 $self->_parse_headers;
378 }
6c7a1d2f 379
7f3c5736 380 # Pass flow control to Catalyst
381 $class->handle_request;
382
383 DEBUG && warn "Request done\n";
cf26c39c 384
7f3c5736 385 # Allow keepalive requests, this is a hack but we'll support it until
386 # the next major release.
387 if ( delete $self->{_keepalive} ) {
388
389 DEBUG && warn "Reusing previous connection for keep-alive request\n";
390
391 if ( $sel->can_read(1) ) {
392 if ( !$self->_read_headers ) {
393 # Error reading, give up
394 last REQUEST;
395 }
396
397 ( $method, $uri, $protocol ) = $self->_parse_request_line;
398
399 DEBUG && warn "Parsed request: $method $uri $protocol\n";
400
401 # Force HTTP/1.0
402 $protocol = '1.0';
403
404 next REQUEST;
405 }
406
407 DEBUG && warn "No keep-alive request within 1 second\n";
408 }
409
410 last REQUEST;
411 }
3bcb3aae 412
7f3c5736 413 DEBUG && warn "Closing connection\n";
06744540 414
415 close Remote;
3bcb3aae 416}
417
7f3c5736 418sub _read_headers {
419 my $self = shift;
420
421 while (1) {
422 my $read = sysread Remote, my $buf, CHUNKSIZE;
423
424 if ( !$read ) {
425 DEBUG && warn "EOF or error: $!\n";
426 return;
427 }
428
429 DEBUG && warn "Read $read bytes\n";
430 $self->{inputbuf} .= $buf;
431 last if $self->{inputbuf} =~ /(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)/s;
432 }
433
434 return 1;
435}
436
4bb8bd62 437sub _parse_request_line {
438 my $self = shift;
6c7a1d2f 439
4bb8bd62 440 # Parse request line
441 if ( $self->{inputbuf} !~ s/^(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
442 return ();
443 }
444
445 my $method = $1;
446 my $uri = $2;
447 my $proto = $3 || 'HTTP/0.9';
448
449 return ( $method, $uri, $proto );
6c7a1d2f 450}
451
4bb8bd62 452sub _parse_headers {
453 my $self = shift;
454
455 # Copy the buffer for header parsing, and remove the header block
456 # from the content buffer.
457 my $buf = $self->{inputbuf};
458 $self->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s;
459
460 # Parse headers
461 my $headers = HTTP::Headers->new;
462 my ($key, $val);
463 HEADER:
464 while ( $buf =~ s/^([^\012]*)\012// ) {
465 $_ = $1;
466 s/\015$//;
467 if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
468 $headers->push_header( $key, $val ) if $key;
469 ($key, $val) = ($1, $2);
470 }
471 elsif ( /^\s+(.*)/ ) {
472 $val .= " $1";
473 }
474 else {
475 last HEADER;
476 }
477 }
478 $headers->push_header( $key, $val ) if $key;
479
480 DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
6c7a1d2f 481
4bb8bd62 482 # Convert headers into ENV vars
483 $headers->scan( sub {
484 my ( $key, $val ) = @_;
485
486 $key = uc $key;
487 $key = 'COOKIE' if $key eq 'COOKIES';
488 $key =~ tr/-/_/;
489 $key = 'HTTP_' . $key
490 unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
491
492 if ( exists $ENV{$key} ) {
493 $ENV{$key} .= ", $val";
494 }
495 else {
496 $ENV{$key} = $val;
497 }
498 } );
6c7a1d2f 499}
500
501sub _socket_data {
502 my ( $self, $handle ) = @_;
503
8b9d0298 504 my $remote_sockaddr = getpeername($handle);
3150d774 505 my ( undef, $iaddr ) = $remote_sockaddr
506 ? sockaddr_in($remote_sockaddr)
507 : (undef, undef);
508
8b9d0298 509 my $local_sockaddr = getsockname($handle);
6c7a1d2f 510 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
511
8b9d0298 512 # This mess is necessary to keep IE from crashing the server
6c7a1d2f 513 my $data = {
8b9d0298 514 peername => $iaddr
515 ? ( gethostbyaddr( $iaddr, AF_INET ) || 'localhost' )
516 : 'localhost',
517 peeraddr => $iaddr
518 ? ( inet_ntoa($iaddr) || '127.0.0.1' )
519 : '127.0.0.1',
520 localname => gethostbyaddr( $localiaddr, AF_INET ) || 'localhost',
521 localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
6c7a1d2f 522 };
523
524 return $data;
525}
526
1cf1c56a 527sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
528
41593b49 529sub _REAPER {
530 my $child;
531 while ( ( $child = waitpid( -1,WNOHANG ) ) > 0 ) { }
532 $SIG{CHLD} = \&_REAPER;
533}
534
45374ac6 535=head1 SEE ALSO
536
fbcc39ad 537L<Catalyst>, L<Catalyst::Engine>.
538
539=head1 AUTHORS
540
541Sebastian Riedel, <sri@cpan.org>
542
543Dan Kubb, <dan.kubb-cpan@onautopilot.com>
45374ac6 544
6c7a1d2f 545Sascha Kiefer, <esskar@cpan.org>
546
4bb8bd62 547Andy Grundman, <andy@hybridized.org>
548
fbcc39ad 549=head1 THANKS
45374ac6 550
fbcc39ad 551Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
45374ac6 552
553=head1 COPYRIGHT
554
555This program is free software, you can redistribute it and/or modify it under
556the same terms as Perl itself.
557
558=cut
559
45374ac6 5601;