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