1 package Catalyst::Engine::HTTP;
4 use base 'Catalyst::Engine::CGI';
5 use Data::Dump qw(dump);
6 use Errno 'EWOULDBLOCK';
12 use IO::Socket::INET ();
14 use POSIX ":sys_wait_h";
17 require Catalyst::Engine::HTTP::Restarter;
18 require Catalyst::Engine::HTTP::Restarter::Watcher;
20 use constant CHUNKSIZE => 64 * 1024;
21 use constant DEBUG => $ENV{CATALYST_HTTP_DEBUG} || 0;
25 Catalyst::Engine::HTTP - Catalyst HTTP Engine
29 A script using the Catalyst::Engine::HTTP module might look like:
33 BEGIN { $ENV{CATALYST_ENGINE} = 'HTTP' }
36 use lib '/path/to/MyApp/lib';
43 This is the Catalyst engine specialized for development and testing.
47 =head2 $self->finalize_headers($c)
51 sub finalize_headers {
52 my ( $self, $c ) = @_;
53 my $protocol = $c->request->protocol;
54 my $status = $c->response->status;
55 my $message = status_message($status);
58 push @headers, "$protocol $status $message";
60 $c->response->headers->header( Date => HTTP::Date::time2str(time) );
61 $c->response->headers->header( Status => $status );
63 # Should we keep the connection open?
64 my $connection = $c->request->header('Connection');
65 if ( $self->{options}->{keepalive}
67 && $connection =~ /^keep-alive$/i
69 $c->response->headers->header( Connection => 'keep-alive' );
70 $self->{_keepalive} = 1;
73 $c->response->headers->header( Connection => 'close' );
76 push @headers, $c->response->headers->as_string("\x0D\x0A");
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, '');
83 =head2 $self->finalize_read($c)
88 my ( $self, $c ) = @_;
90 # Never ever remove this, it would result in random length output
91 # streams if STDIN eq STDOUT (like in the HTTP engine)
94 return $self->NEXT::finalize_read($c);
97 =head2 $self->prepare_read($c)
102 my ( $self, $c ) = @_;
104 # Set the input handle to non-blocking
107 return $self->NEXT::prepare_read($c);
110 =head2 $self->read_chunk($c, $buffer, $length)
118 # If we have any remaining data in the input buffer, send it back first
119 if ( $_[0] = delete $self->{inputbuf} ) {
120 my $read = length( $_[0] );
121 DEBUG && warn "read_chunk: Read $read bytes from previous input buffer\n";
125 # support for non-blocking IO
127 vec( $rin, *STDIN->fileno, 1 ) = 1;
131 select( $rin, undef, undef, undef );
132 my $rc = *STDIN->sysread(@_);
134 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
138 next READ if $! == EWOULDBLOCK;
144 =head2 $self->write($c, $buffer)
146 Writes the buffer to the client.
151 my ( $self, $c, $buffer ) = @_;
153 # Avoid 'print() on closed filehandle Remote' warnings when using IE
154 return unless *STDOUT->opened();
156 # Prepend the headers if they have not yet been sent
157 if ( my $headers = delete $self->{_header_buf} ) {
158 $buffer = $headers . $buffer;
161 my $ret = $self->NEXT::write( $c, $buffer );
163 if ( !defined $ret ) {
164 $self->{_write_error} = $!;
165 DEBUG && warn "write: Failed to write response ($!)\n";
168 DEBUG && warn "write: Wrote response ($ret bytes)\n";
178 # A very very simple HTTP server that initializes a CGI environment
180 my ( $self, $class, $port, $host, $options ) = @_;
184 $self->{options} = $options;
186 if ($options->{background}) {
188 die "Can't fork: $!" unless defined($child);
189 return $child if $child;
193 local $SIG{CHLD} = \&_REAPER;
195 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
196 my $addr = $host ? inet_aton($host) : INADDR_ANY;
197 if ( $addr eq INADDR_ANY ) {
198 require Sys::Hostname;
199 $host = lc Sys::Hostname::hostname();
202 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
208 my $daemon = IO::Socket::INET->new(
210 LocalAddr => inet_ntoa($addr),
216 or die "Couldn't create daemon: $!";
218 my $url = "http://$host";
219 $url .= ":$port" unless $port == 80;
221 print "You can connect to your server at $url\n";
223 if ($options->{background}) {
224 open STDIN, "+</dev/null" or die $!;
225 open STDOUT, ">&STDIN" or die $!;
226 open STDERR, ">&STDIN" or die $!;
227 if ( $^O !~ /MSWin32/ ) {
230 or die "Can't start a new session: $!";
234 if (my $pidfile = $options->{pidfile}) {
235 if (! open PIDFILE, "> $pidfile") {
236 warn("Cannot open: $pidfile: $!");
238 print PIDFILE "$$\n";
244 # Ignore broken pipes as an HTTP server should
245 local $SIG{PIPE} = 'IGNORE';
248 local $SIG{HUP} = sub {
250 warn "Restarting server on SIGHUP...\n";
254 while ( !$restart ) {
255 while ( accept( Remote, $daemon ) ) {
256 DEBUG && warn "New connection\n";
262 # Read until we see all headers
263 $self->{inputbuf} = '';
265 if ( !$self->_read_headers ) {
266 # Error reading, give up
270 my ( $method, $uri, $protocol ) = $self->_parse_request_line;
272 DEBUG && warn "Parsed request: $method $uri $protocol\n";
276 unless ( uc($method) eq 'RESTART' ) {
279 if ( $options->{fork} ) {
281 DEBUG && warn "Forked child $pid\n";
286 $self->_handler( $class, $port, $method, $uri, $protocol );
288 if ( my $error = delete $self->{_write_error} ) {
291 if ( !defined $pid ) {
296 if ( defined $pid ) {
297 # Child process, close connection and exit
298 DEBUG && warn "Child process exiting\n";
304 my $sockdata = $self->_socket_data( \*Remote );
305 my $ipaddr = _inet_addr( $sockdata->{peeraddr} );
307 foreach my $ip ( keys %$allowed ) {
308 my $mask = $allowed->{$ip};
309 $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
325 DEBUG && warn "Shutting down\n";
328 $SIG{CHLD} = 'DEFAULT';
331 ### if the standalone server was invoked with perl -I .. we will loose
332 ### those include dirs upon re-exec. So add them to PERL5LIB, so they
333 ### are available again for the exec'ed process --kane
335 $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
337 exec $^X . ' "' . $0 . '" ' . join( ' ', @{ $options->{argv} } );
344 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
346 local *STDIN = \*Remote;
347 local *STDOUT = \*Remote;
349 # We better be careful and just use 1.0
352 my $sockdata = $self->_socket_data( \*Remote );
353 my %copy_of_env = %ENV;
355 my $sel = IO::Select->new;
356 $sel->add( \*STDIN );
360 my ( $path, $query_string ) = split /\?/, $uri, 2;
362 # Initialize CGI environment
364 PATH_INFO => $path || '',
365 QUERY_STRING => $query_string || '',
366 REMOTE_ADDR => $sockdata->{peeraddr},
367 REMOTE_HOST => $sockdata->{peername},
368 REQUEST_METHOD => $method || '',
369 SERVER_NAME => $sockdata->{localname},
370 SERVER_PORT => $port,
371 SERVER_PROTOCOL => "HTTP/$protocol",
376 if ( $protocol >= 1 ) {
377 $self->_parse_headers;
380 # Pass flow control to Catalyst
381 $class->handle_request;
383 DEBUG && warn "Request done\n";
385 # Allow keepalive requests, this is a hack but we'll support it until
386 # the next major release.
387 if ( delete $self->{_keepalive} ) {
389 DEBUG && warn "Reusing previous connection for keep-alive request\n";
391 if ( $sel->can_read(1) ) {
392 if ( !$self->_read_headers ) {
393 # Error reading, give up
397 ( $method, $uri, $protocol ) = $self->_parse_request_line;
399 DEBUG && warn "Parsed request: $method $uri $protocol\n";
407 DEBUG && warn "No keep-alive request within 1 second\n";
413 DEBUG && warn "Closing connection\n";
422 my $read = sysread Remote, my $buf, CHUNKSIZE;
425 DEBUG && warn "EOF or error: $!\n";
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;
437 sub _parse_request_line {
441 if ( $self->{inputbuf} !~ s/^(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
447 my $proto = $3 || 'HTTP/0.9';
449 return ( $method, $uri, $proto );
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;
461 my $headers = HTTP::Headers->new;
464 while ( $buf =~ s/^([^\012]*)\012// ) {
467 if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
468 $headers->push_header( $key, $val ) if $key;
469 ($key, $val) = ($1, $2);
471 elsif ( /^\s+(.*)/ ) {
478 $headers->push_header( $key, $val ) if $key;
480 DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
482 # Convert headers into ENV vars
483 $headers->scan( sub {
484 my ( $key, $val ) = @_;
487 $key = 'COOKIE' if $key eq 'COOKIES';
489 $key = 'HTTP_' . $key
490 unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
492 if ( exists $ENV{$key} ) {
493 $ENV{$key} .= ", $val";
502 my ( $self, $handle ) = @_;
504 my $remote_sockaddr = getpeername($handle);
505 my ( undef, $iaddr ) = $remote_sockaddr
506 ? sockaddr_in($remote_sockaddr)
509 my $local_sockaddr = getsockname($handle);
510 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
512 # This mess is necessary to keep IE from crashing the server
515 ? ( gethostbyaddr( $iaddr, AF_INET ) || 'localhost' )
518 ? ( inet_ntoa($iaddr) || '127.0.0.1' )
520 localname => gethostbyaddr( $localiaddr, AF_INET ) || 'localhost',
521 localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
527 sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
531 while ( ( $child = waitpid( -1,WNOHANG ) ) > 0 ) { }
532 $SIG{CHLD} = \&_REAPER;
537 L<Catalyst>, L<Catalyst::Engine>.
541 Sebastian Riedel, <sri@cpan.org>
543 Dan Kubb, <dan.kubb-cpan@onautopilot.com>
545 Sascha Kiefer, <esskar@cpan.org>
547 Andy Grundman, <andy@hybridized.org>
551 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
555 This program is free software, you can redistribute it and/or modify it under
556 the same terms as Perl itself.