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