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