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