1 package Catalyst::Engine::HTTP;
4 extends 'Catalyst::Engine::CGI';
6 use Data::Dump qw(dump);
7 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;
22 has options => ( is => 'rw' );
23 has _keepalive => ( is => 'rw', predicate => '_is_keepalive', clearer => '_clear_keepalive' );
24 has _write_error => ( is => 'rw', predicate => '_has_write_error' );
26 use namespace::clean -except => [qw/meta/];
30 Catalyst::Engine::HTTP - Catalyst HTTP Engine
34 A script using the Catalyst::Engine::HTTP module might look like:
38 BEGIN { $ENV{CATALYST_ENGINE} = 'HTTP' }
41 use lib '/path/to/MyApp/lib';
48 This is the Catalyst engine specialized for development and testing.
52 =head2 $self->finalize_headers($c)
56 sub finalize_headers {
57 my ( $self, $c ) = @_;
58 my $protocol = $c->request->protocol;
59 my $status = $c->response->status;
60 my $message = status_message($status);
61 my $res_headers = $c->response->headers;
64 push @headers, "$protocol $status $message";
66 $res_headers->header( Date => HTTP::Date::time2str(time) );
67 $res_headers->header( Status => $status );
69 # Should we keep the connection open?
70 my $connection = $c->request->header('Connection');
71 if ( $self->options->{keepalive}
73 && $connection =~ /^keep-alive$/i
75 $res_headers->header( Connection => 'keep-alive' );
79 $res_headers->header( Connection => 'close' );
82 push @headers, $res_headers->as_string("\x0D\x0A");
84 # Buffer the headers so they are sent with the first write() call
85 # This reduces the number of TCP packets we are sending
86 $self->_header_buf( join("\x0D\x0A", @headers, '') );
89 =head2 $self->finalize_read($c)
93 before finalize_read => sub {
94 # Never ever remove this, it would result in random length output
95 # streams if STDIN eq STDOUT (like in the HTTP engine)
99 =head2 $self->prepare_read($c)
103 before prepare_read => sub {
104 # Set the input handle to non-blocking
108 =head2 $self->read_chunk($c, $buffer, $length)
116 # If we have any remaining data in the input buffer, send it back first
117 if ( $_[0] = delete $self->{inputbuf} ) {
118 my $read = length( $_[0] );
119 DEBUG && warn "read_chunk: Read $read bytes from previous input buffer\n";
123 # support for non-blocking IO
125 vec( $rin, *STDIN->fileno, 1 ) = 1;
129 select( $rin, undef, undef, undef );
130 my $rc = *STDIN->sysread(@_);
132 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
136 next READ if $! == EWOULDBLOCK;
142 =head2 $self->write($c, $buffer)
144 Writes the buffer to the client.
148 around write => sub {
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 ( $self->_has_header_buf ) {
157 $buffer = $self->_clear_header_buf . $buffer;
160 my $ret = $self->$orig($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;
272 DEBUG && warn "Parsed request: $method $uri $protocol\n";
275 unless ( uc($method) eq 'RESTART' ) {
278 if ( $options->{fork} ) {
280 DEBUG && warn "Forked child $pid\n";
285 $self->_handler( $class, $port, $method, $uri, $protocol );
287 if ( $self->_has_write_error ) {
290 if ( !defined $pid ) {
295 if ( defined $pid ) {
296 # Child process, close connection and exit
297 DEBUG && warn "Child process exiting\n";
303 my $sockdata = $self->_socket_data( \*Remote );
304 my $ipaddr = _inet_addr( $sockdata->{peeraddr} );
306 foreach my $ip ( keys %$allowed ) {
307 my $mask = $allowed->{$ip};
308 $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
324 DEBUG && warn "Shutting down\n";
327 $SIG{CHLD} = 'DEFAULT';
330 ### if the standalone server was invoked with perl -I .. we will loose
331 ### those include dirs upon re-exec. So add them to PERL5LIB, so they
332 ### are available again for the exec'ed process --kane
334 $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
336 exec $^X, $0, @{ $options->{argv} };
343 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
345 local *STDIN = \*Remote;
346 local *STDOUT = \*Remote;
348 # We better be careful and just use 1.0
351 my $sockdata = $self->_socket_data( \*Remote );
352 my %copy_of_env = %ENV;
354 my $sel = IO::Select->new;
355 $sel->add( \*STDIN );
359 my ( $path, $query_string ) = split /\?/, $uri, 2;
361 # Initialize CGI environment
363 PATH_INFO => $path || '',
364 QUERY_STRING => $query_string || '',
365 REMOTE_ADDR => $sockdata->{peeraddr},
366 REQUEST_METHOD => $method || '',
367 SERVER_NAME => $sockdata->{localname},
368 SERVER_PORT => $port,
369 SERVER_PROTOCOL => "HTTP/$protocol",
374 if ( $protocol >= 1 ) {
375 $self->_parse_headers;
378 # Pass flow control to Catalyst
379 $class->handle_request;
381 DEBUG && warn "Request done\n";
383 # Allow keepalive requests, this is a hack but we'll support it until
384 # the next major release.
385 if ( $self->_is_keepalive ) {
386 $self->_clear_keepalive;
388 DEBUG && warn "Reusing previous connection for keep-alive request\n";
390 if ( $sel->can_read(1) ) {
391 if ( !$self->_read_headers ) {
392 # Error reading, give up
396 ( $method, $uri, $protocol ) = $self->_parse_request_line;
398 DEBUG && warn "Parsed request: $method $uri $protocol\n";
406 DEBUG && warn "No keep-alive request within 1 second\n";
412 DEBUG && warn "Closing connection\n";
421 my $read = sysread Remote, my $buf, CHUNKSIZE;
423 if ( !defined $read ) {
424 next if $! == EWOULDBLOCK;
425 DEBUG && warn "Error reading headers: $!\n";
427 } elsif ( $read == 0 ) {
428 DEBUG && warn "EOF\n";
432 DEBUG && warn "Read $read bytes\n";
433 $self->{inputbuf} .= $buf;
434 last if $self->{inputbuf} =~ /(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)/s;
440 sub _parse_request_line {
444 if ( $self->{inputbuf} !~ s/^(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
450 my $proto = $3 || 'HTTP/0.9';
452 return ( $method, $uri, $proto );
458 # Copy the buffer for header parsing, and remove the header block
459 # from the content buffer.
460 my $buf = $self->{inputbuf};
461 $self->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s;
464 my $headers = HTTP::Headers->new;
467 while ( $buf =~ s/^([^\012]*)\012// ) {
470 if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
471 $headers->push_header( $key, $val ) if $key;
472 ($key, $val) = ($1, $2);
474 elsif ( /^\s+(.*)/ ) {
481 $headers->push_header( $key, $val ) if $key;
483 DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
485 # Convert headers into ENV vars
486 $headers->scan( sub {
487 my ( $key, $val ) = @_;
490 $key = 'COOKIE' if $key eq 'COOKIES';
492 $key = 'HTTP_' . $key
493 unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
495 if ( exists $ENV{$key} ) {
496 $ENV{$key} .= ", $val";
505 my ( $self, $handle ) = @_;
507 my $remote_sockaddr = getpeername($handle);
508 my ( undef, $iaddr ) = $remote_sockaddr
509 ? sockaddr_in($remote_sockaddr)
512 my $local_sockaddr = getsockname($handle);
513 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
515 # This mess is necessary to keep IE from crashing the server
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] ) }
533 Options hash passed to the http engine to control things like if keepalive
538 L<Catalyst>, L<Catalyst::Engine>
542 Catalyst Contributors, see Catalyst.pm
546 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
550 This program is free software, you can redistribute it and/or modify it under
551 the same terms as Perl itself.