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 ();
16 require Catalyst::Engine::HTTP::Restarter;
17 require Catalyst::Engine::HTTP::Restarter::Watcher;
19 use constant CHUNKSIZE => 64 * 1024;
20 use constant DEBUG => $ENV{CATALYST_HTTP_DEBUG} || 0;
24 Catalyst::Engine::HTTP - Catalyst HTTP Engine
28 A script using the Catalyst::Engine::HTTP module might look like:
32 BEGIN { $ENV{CATALYST_ENGINE} = 'HTTP' }
35 use lib '/path/to/MyApp/lib';
42 This is the Catalyst engine specialized for development and testing.
46 =head2 $self->finalize_headers($c)
50 sub finalize_headers {
51 my ( $self, $c ) = @_;
52 my $protocol = $c->request->protocol;
53 my $status = $c->response->status;
54 my $message = status_message($status);
57 push @headers, "$protocol $status $message";
59 $c->response->headers->header( Date => HTTP::Date::time2str(time) );
60 $c->response->headers->header( Status => $status );
62 # Should we keep the connection open?
63 my $connection = $c->request->header('Connection');
64 if ( $self->{options}->{keepalive}
66 && $connection =~ /^keep-alive$/i
68 $c->response->headers->header( Connection => 'keep-alive' );
69 $self->{_keepalive} = 1;
72 $c->response->headers->header( Connection => 'close' );
75 push @headers, $c->response->headers->as_string("\x0D\x0A");
77 # Buffer the headers so they are sent with the first write() call
78 # This reduces the number of TCP packets we are sending
79 $self->{_header_buf} = join("\x0D\x0A", @headers, '');
82 =head2 $self->finalize_read($c)
87 my ( $self, $c ) = @_;
89 # Never ever remove this, it would result in random length output
90 # streams if STDIN eq STDOUT (like in the HTTP engine)
93 return $self->NEXT::finalize_read($c);
96 =head2 $self->prepare_read($c)
101 my ( $self, $c ) = @_;
103 # Set the input handle to non-blocking
106 return $self->NEXT::prepare_read($c);
109 =head2 $self->read_chunk($c, $buffer, $length)
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";
124 # support for non-blocking IO
126 vec( $rin, *STDIN->fileno, 1 ) = 1;
130 select( $rin, undef, undef, undef );
131 my $rc = *STDIN->sysread(@_);
133 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
137 next READ if $! == EWOULDBLOCK;
143 =head2 $self->write($c, $buffer)
145 Writes the buffer to the client.
150 my ( $self, $c, $buffer ) = @_;
152 # Avoid 'print() on closed filehandle Remote' warnings when using IE
153 return unless *STDOUT->opened();
155 # Prepend the headers if they have not yet been sent
156 if ( my $headers = delete $self->{_header_buf} ) {
157 $buffer = $headers . $buffer;
160 my $ret = $self->NEXT::write( $c, $buffer );
162 if ( !defined $ret ) {
163 $self->{_write_error} = $!;
164 DEBUG && warn "write: Failed to write response ($!)\n";
167 DEBUG && warn "write: Wrote response ($ret bytes)\n";
177 # A very very simple HTTP server that initializes a CGI environment
179 my ( $self, $class, $port, $host, $options ) = @_;
183 $self->{options} = $options;
185 if ($options->{background}) {
187 die "Can't fork: $!" unless defined($child);
188 return $child if $child;
192 local $SIG{CHLD} = 'IGNORE';
194 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
195 my $addr = $host ? inet_aton($host) : INADDR_ANY;
196 if ( $addr eq INADDR_ANY ) {
197 require Sys::Hostname;
198 $host = lc Sys::Hostname::hostname();
201 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
207 my $daemon = IO::Socket::INET->new(
209 LocalAddr => inet_ntoa($addr),
215 or die "Couldn't create daemon: $!";
217 my $url = "http://$host";
218 $url .= ":$port" unless $port == 80;
220 print "You can connect to your server at $url\n";
222 if ($options->{background}) {
223 open STDIN, "+</dev/null" or die $!;
224 open STDOUT, ">&STDIN" or die $!;
225 open STDERR, ">&STDIN" or die $!;
226 if ( $^O !~ /MSWin32/ ) {
229 or die "Can't start a new session: $!";
233 if (my $pidfile = $options->{pidfile}) {
234 if (! open PIDFILE, "> $pidfile") {
235 warn("Cannot open: $pidfile: $!");
237 print PIDFILE "$$\n";
243 # Ignore broken pipes as an HTTP server should
244 local $SIG{PIPE} = 'IGNORE';
247 local $SIG{HUP} = sub {
249 warn "Restarting server on SIGHUP...\n";
253 while ( !$restart ) {
254 while ( accept( Remote, $daemon ) ) {
255 DEBUG && warn "New connection\n";
261 # Read until we see all headers
262 $self->{inputbuf} = '';
264 if ( !$self->_read_headers ) {
265 # Error reading, give up
270 my ( $method, $uri, $protocol ) = $self->_parse_request_line;
274 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, @{ $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;
424 if ( !defined $read ) {
425 next if $! == EWOULDBLOCK;
426 DEBUG && warn "Error reading headers: $!\n";
429 elsif ( $read == 0 ) {
430 DEBUG && warn "EOF\n";
434 DEBUG && warn "Read $read bytes\n";
435 $self->{inputbuf} .= $buf;
436 last if $self->{inputbuf} =~ /(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)/s;
442 sub _parse_request_line {
446 if ( $self->{inputbuf} !~ s/^(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
452 my $proto = $3 || 'HTTP/0.9';
454 return ( $method, $uri, $proto );
460 # Copy the buffer for header parsing, and remove the header block
461 # from the content buffer.
462 my $buf = $self->{inputbuf};
463 $self->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s;
466 my $headers = HTTP::Headers->new;
469 while ( $buf =~ s/^([^\012]*)\012// ) {
472 if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
473 $headers->push_header( $key, $val ) if $key;
474 ($key, $val) = ($1, $2);
476 elsif ( /^\s+(.*)/ ) {
483 $headers->push_header( $key, $val ) if $key;
485 DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
487 # Convert headers into ENV vars
488 $headers->scan( sub {
489 my ( $key, $val ) = @_;
492 $key = 'COOKIE' if $key eq 'COOKIES';
494 $key = 'HTTP_' . $key
495 unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
497 if ( exists $ENV{$key} ) {
498 $ENV{$key} .= ", $val";
507 my ( $self, $handle ) = @_;
509 my $remote_sockaddr = getpeername($handle);
510 my ( undef, $iaddr ) = $remote_sockaddr
511 ? sockaddr_in($remote_sockaddr)
514 my $local_sockaddr = getsockname($handle);
515 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
517 # This mess is necessary to keep IE from crashing the server
520 ? ( gethostbyaddr( $iaddr, AF_INET ) || 'localhost' )
523 ? ( inet_ntoa($iaddr) || '127.0.0.1' )
525 localname => gethostbyaddr( $localiaddr, AF_INET ) || 'localhost',
526 localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
532 sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
536 L<Catalyst>, L<Catalyst::Engine>.
540 Sebastian Riedel, <sri@cpan.org>
542 Dan Kubb, <dan.kubb-cpan@onautopilot.com>
544 Sascha Kiefer, <esskar@cpan.org>
546 Andy Grundman, <andy@hybridized.org>
550 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
554 This program is free software, you can redistribute it and/or modify it under
555 the same terms as Perl itself.