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