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