1 package Catalyst::Engine::HTTP;
5 extends 'Catalyst::Engine::CGI';
8 use Data::Dump qw(dump);
9 use Errno 'EWOULDBLOCK';
14 use IO::Socket::INET ();
18 require Catalyst::Engine::HTTP::Restarter;
19 require Catalyst::Engine::HTTP::Restarter::Watcher;
21 use constant CHUNKSIZE => 64 * 1024;
22 use constant DEBUG => $ENV{CATALYST_HTTP_DEBUG} || 0;
26 Catalyst::Engine::HTTP - Catalyst HTTP Engine
30 A script using the Catalyst::Engine::HTTP module might look like:
34 BEGIN { $ENV{CATALYST_ENGINE} = 'HTTP' }
37 use lib '/path/to/MyApp/lib';
44 This is the Catalyst engine specialized for development and testing.
48 =head2 $self->finalize_headers($c)
52 sub finalize_headers {
53 my ( $self, $c ) = @_;
54 my $protocol = $c->request->protocol;
55 my $status = $c->response->status;
56 my $message = status_message($status);
57 my $res_headers = $c->response->headers;
60 push @headers, "$protocol $status $message";
62 $res_headers->header( Date => HTTP::Date::time2str(time) );
63 $res_headers->header( Status => $status );
65 # Should we keep the connection open?
66 my $connection = $c->request->header('Connection');
67 if ( $self->{options}->{keepalive}
69 && $connection =~ /^keep-alive$/i
71 $res_headers->header( Connection => 'keep-alive' );
72 $self->{_keepalive} = 1;
75 $res_headers->header( Connection => 'close' );
78 push @headers, $res_headers->as_string("\x0D\x0A");
80 # Buffer the headers so they are sent with the first write() call
81 # This reduces the number of TCP packets we are sending
82 $self->{_header_buf} = join("\x0D\x0A", @headers, '');
85 =head2 $self->finalize_read($c)
90 # Never ever remove this, it would result in random length output
91 # streams if STDIN eq STDOUT (like in the HTTP engine)
93 shift->next::method(@_);
96 =head2 $self->prepare_read($c)
101 # Set the input handle to non-blocking
103 shift->next::method(@_);
106 =head2 $self->read_chunk($c, $buffer, $length)
114 # If we have any remaining data in the input buffer, send it back first
115 if ( $_[0] = delete $self->{inputbuf} ) {
116 my $read = length( $_[0] );
117 DEBUG && warn "read_chunk: Read $read bytes from previous input buffer\n";
121 # support for non-blocking IO
123 vec( $rin, *STDIN->fileno, 1 ) = 1;
127 select( $rin, undef, undef, undef );
128 my $rc = *STDIN->sysread(@_);
130 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
134 next READ if $! == EWOULDBLOCK;
140 =head2 $self->write($c, $buffer)
142 Writes the buffer to the client.
147 my ( $self, $c, $buffer ) = @_;
149 # Avoid 'print() on closed filehandle Remote' warnings when using IE
150 return unless *STDOUT->opened();
152 # Prepend the headers if they have not yet been sent
153 if ( my $headers = delete $self->{_header_buf} ) {
154 $buffer = $headers . $buffer;
157 my $ret = $self->next::method($c, $buffer);
159 if ( !defined $ret ) {
160 $self->{_write_error} = $!;
161 DEBUG && warn "write: Failed to write response ($!)\n";
164 DEBUG && warn "write: Wrote response ($ret bytes)\n";
174 # A very very simple HTTP server that initializes a CGI environment
176 my ( $self, $class, $port, $host, $options ) = @_;
180 $self->{options} = $options;
182 if ($options->{background}) {
184 die "Can't fork: $!" unless defined($child);
185 return $child if $child;
189 local $SIG{CHLD} = 'IGNORE';
191 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
192 my $addr = $host ? inet_aton($host) : INADDR_ANY;
193 if ( $addr eq INADDR_ANY ) {
194 require Sys::Hostname;
195 $host = lc Sys::Hostname::hostname();
198 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
204 my $daemon = IO::Socket::INET->new(
206 LocalAddr => inet_ntoa($addr),
212 or die "Couldn't create daemon: $!";
214 my $url = "http://$host";
215 $url .= ":$port" unless $port == 80;
217 print "You can connect to your server at $url\n";
219 if ($options->{background}) {
220 open STDIN, "+</dev/null" or die $!;
221 open STDOUT, ">&STDIN" or die $!;
222 open STDERR, ">&STDIN" or die $!;
223 if ( $^O !~ /MSWin32/ ) {
226 or die "Can't start a new session: $!";
230 if (my $pidfile = $options->{pidfile}) {
231 if (! open PIDFILE, "> $pidfile") {
232 warn("Cannot open: $pidfile: $!");
234 print PIDFILE "$$\n";
240 # Ignore broken pipes as an HTTP server should
241 local $SIG{PIPE} = 'IGNORE';
244 local $SIG{HUP} = sub {
246 warn "Restarting server on SIGHUP...\n";
250 while ( !$restart ) {
251 while ( accept( Remote, $daemon ) ) {
252 DEBUG && warn "New connection\n";
258 # Read until we see all headers
259 $self->{inputbuf} = '';
261 if ( !$self->_read_headers ) {
262 # Error reading, give up
267 my ( $method, $uri, $protocol ) = $self->_parse_request_line;
269 DEBUG && warn "Parsed request: $method $uri $protocol\n";
272 unless ( uc($method) eq 'RESTART' ) {
275 if ( $options->{fork} ) {
277 DEBUG && warn "Forked child $pid\n";
282 $self->_handler( $class, $port, $method, $uri, $protocol );
284 if ( my $error = delete $self->{_write_error} ) {
287 if ( !defined $pid ) {
292 if ( defined $pid ) {
293 # Child process, close connection and exit
294 DEBUG && warn "Child process exiting\n";
300 my $sockdata = $self->_socket_data( \*Remote );
301 my $ipaddr = _inet_addr( $sockdata->{peeraddr} );
303 foreach my $ip ( keys %$allowed ) {
304 my $mask = $allowed->{$ip};
305 $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
321 DEBUG && warn "Shutting down\n";
324 $SIG{CHLD} = 'DEFAULT';
327 ### if the standalone server was invoked with perl -I .. we will loose
328 ### those include dirs upon re-exec. So add them to PERL5LIB, so they
329 ### are available again for the exec'ed process --kane
331 $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
333 exec $^X, $0, @{ $options->{argv} };
340 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
342 local *STDIN = \*Remote;
343 local *STDOUT = \*Remote;
345 # We better be careful and just use 1.0
348 my $sockdata = $self->_socket_data( \*Remote );
349 my %copy_of_env = %ENV;
351 my $sel = IO::Select->new;
352 $sel->add( \*STDIN );
356 my ( $path, $query_string ) = split /\?/, $uri, 2;
358 # Initialize CGI environment
360 PATH_INFO => $path || '',
361 QUERY_STRING => $query_string || '',
362 REMOTE_ADDR => $sockdata->{peeraddr},
363 REMOTE_HOST => $sockdata->{peername},
364 REQUEST_METHOD => $method || '',
365 SERVER_NAME => $sockdata->{localname},
366 SERVER_PORT => $port,
367 SERVER_PROTOCOL => "HTTP/$protocol",
372 if ( $protocol >= 1 ) {
373 $self->_parse_headers;
376 # Pass flow control to Catalyst
377 $class->handle_request;
379 DEBUG && warn "Request done\n";
381 # Allow keepalive requests, this is a hack but we'll support it until
382 # the next major release.
383 if ( delete $self->{_keepalive} ) {
385 DEBUG && warn "Reusing previous connection for keep-alive request\n";
387 if ( $sel->can_read(1) ) {
388 if ( !$self->_read_headers ) {
389 # Error reading, give up
393 ( $method, $uri, $protocol ) = $self->_parse_request_line;
395 DEBUG && warn "Parsed request: $method $uri $protocol\n";
403 DEBUG && warn "No keep-alive request within 1 second\n";
409 DEBUG && warn "Closing connection\n";
418 my $read = sysread Remote, my $buf, CHUNKSIZE;
420 if ( !defined $read ) {
421 next if $! == EWOULDBLOCK;
422 DEBUG && warn "Error reading headers: $!\n";
424 } elsif ( $read == 0 ) {
425 DEBUG && warn "EOF\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 L<Catalyst>, L<Catalyst::Engine>.
535 Sebastian Riedel, <sri@cpan.org>
537 Dan Kubb, <dan.kubb-cpan@onautopilot.com>
539 Sascha Kiefer, <esskar@cpan.org>
541 Andy Grundman, <andy@hybridized.org>
545 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
549 This program is free software, you can redistribute it and/or modify it under
550 the same terms as Perl itself.