1 package Catalyst::Engine::HTTP;
6 extends 'Catalyst::Engine::CGI';
9 use Data::Dump qw(dump);
10 use Errno 'EWOULDBLOCK';
15 use IO::Socket::INET ();
19 require Catalyst::Engine::HTTP::Restarter;
20 require Catalyst::Engine::HTTP::Restarter::Watcher;
22 use constant CHUNKSIZE => 64 * 1024;
23 use constant DEBUG => $ENV{CATALYST_HTTP_DEBUG} || 0;
27 Catalyst::Engine::HTTP - Catalyst HTTP Engine
31 A script using the Catalyst::Engine::HTTP module might look like:
35 BEGIN { $ENV{CATALYST_ENGINE} = 'HTTP' }
38 use lib '/path/to/MyApp/lib';
45 This is the Catalyst engine specialized for development and testing.
49 =head2 $self->finalize_headers($c)
53 sub finalize_headers {
54 my ( $self, $c ) = @_;
55 my $protocol = $c->request->protocol;
56 my $status = $c->response->status;
57 my $message = status_message($status);
58 my $res_headers = $c->response->headers;
61 push @headers, "$protocol $status $message";
63 $res_headers->header( Date => HTTP::Date::time2str(time) );
64 $res_headers->header( Status => $status );
66 # Should we keep the connection open?
67 my $connection = $c->request->header('Connection');
68 if ( $self->{options}->{keepalive}
70 && $connection =~ /^keep-alive$/i
72 $res_headers->header( Connection => 'keep-alive' );
73 $self->{_keepalive} = 1;
76 $res_headers->header( Connection => 'close' );
79 push @headers, $res_headers->as_string("\x0D\x0A");
81 # Buffer the headers so they are sent with the first write() call
82 # This reduces the number of TCP packets we are sending
83 $self->{_header_buf} = join("\x0D\x0A", @headers, '');
86 =head2 $self->finalize_read($c)
91 # Never ever remove this, it would result in random length output
92 # streams if STDIN eq STDOUT (like in the HTTP engine)
94 shift->next::method(@_);
97 =head2 $self->prepare_read($c)
102 # Set the input handle to non-blocking
104 shift->next::method(@_);
107 =head2 $self->read_chunk($c, $buffer, $length)
115 # If we have any remaining data in the input buffer, send it back first
116 if ( $_[0] = delete $self->{inputbuf} ) {
117 my $read = length( $_[0] );
118 DEBUG && warn "read_chunk: Read $read bytes from previous input buffer\n";
122 # support for non-blocking IO
124 vec( $rin, *STDIN->fileno, 1 ) = 1;
128 select( $rin, undef, undef, undef );
129 my $rc = *STDIN->sysread(@_);
131 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
135 next READ if $! == EWOULDBLOCK;
141 =head2 $self->write($c, $buffer)
143 Writes the buffer to the client.
148 my ( $self, $c, $buffer ) = @_;
150 # Avoid 'print() on closed filehandle Remote' warnings when using IE
151 return unless *STDOUT->opened();
153 # Prepend the headers if they have not yet been sent
154 if ( my $headers = delete $self->{_header_buf} ) {
155 $buffer = $headers . $buffer;
158 my $ret = $self->next::method($c, $buffer);
160 if ( !defined $ret ) {
161 $self->{_write_error} = $!;
162 DEBUG && warn "write: Failed to write response ($!)\n";
165 DEBUG && warn "write: Wrote response ($ret bytes)\n";
175 # A very very simple HTTP server that initializes a CGI environment
177 my ( $self, $class, $port, $host, $options ) = @_;
181 $self->{options} = $options;
183 if ($options->{background}) {
185 die "Can't fork: $!" unless defined($child);
186 return $child if $child;
190 local $SIG{CHLD} = 'IGNORE';
192 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
193 my $addr = $host ? inet_aton($host) : INADDR_ANY;
194 if ( $addr eq INADDR_ANY ) {
195 require Sys::Hostname;
196 $host = lc Sys::Hostname::hostname();
199 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
205 my $daemon = IO::Socket::INET->new(
207 LocalAddr => inet_ntoa($addr),
213 or die "Couldn't create daemon: $!";
215 my $url = "http://$host";
216 $url .= ":$port" unless $port == 80;
218 print "You can connect to your server at $url\n";
220 if ($options->{background}) {
221 open STDIN, "+</dev/null" or die $!;
222 open STDOUT, ">&STDIN" or die $!;
223 open STDERR, ">&STDIN" or die $!;
224 if ( $^O !~ /MSWin32/ ) {
227 or die "Can't start a new session: $!";
231 if (my $pidfile = $options->{pidfile}) {
232 if (! open PIDFILE, "> $pidfile") {
233 warn("Cannot open: $pidfile: $!");
235 print PIDFILE "$$\n";
241 # Ignore broken pipes as an HTTP server should
242 local $SIG{PIPE} = 'IGNORE';
245 local $SIG{HUP} = sub {
247 warn "Restarting server on SIGHUP...\n";
251 while ( !$restart ) {
252 while ( accept( Remote, $daemon ) ) {
253 DEBUG && warn "New connection\n";
259 # Read until we see all headers
260 $self->{inputbuf} = '';
262 if ( !$self->_read_headers ) {
263 # Error reading, give up
268 my ( $method, $uri, $protocol ) = $self->_parse_request_line;
270 DEBUG && warn "Parsed request: $method $uri $protocol\n";
273 unless ( uc($method) eq 'RESTART' ) {
276 if ( $options->{fork} ) {
278 DEBUG && warn "Forked child $pid\n";
283 $self->_handler( $class, $port, $method, $uri, $protocol );
285 if ( my $error = delete $self->{_write_error} ) {
288 if ( !defined $pid ) {
293 if ( defined $pid ) {
294 # Child process, close connection and exit
295 DEBUG && warn "Child process exiting\n";
301 my $sockdata = $self->_socket_data( \*Remote );
302 my $ipaddr = _inet_addr( $sockdata->{peeraddr} );
304 foreach my $ip ( keys %$allowed ) {
305 my $mask = $allowed->{$ip};
306 $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
322 DEBUG && warn "Shutting down\n";
325 $SIG{CHLD} = 'DEFAULT';
328 ### if the standalone server was invoked with perl -I .. we will loose
329 ### those include dirs upon re-exec. So add them to PERL5LIB, so they
330 ### are available again for the exec'ed process --kane
332 $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
334 exec $^X, $0, @{ $options->{argv} };
341 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
343 local *STDIN = \*Remote;
344 local *STDOUT = \*Remote;
346 # We better be careful and just use 1.0
349 my $sockdata = $self->_socket_data( \*Remote );
350 my %copy_of_env = %ENV;
352 my $sel = IO::Select->new;
353 $sel->add( \*STDIN );
357 my ( $path, $query_string ) = split /\?/, $uri, 2;
359 # Initialize CGI environment
361 PATH_INFO => $path || '',
362 QUERY_STRING => $query_string || '',
363 REMOTE_ADDR => $sockdata->{peeraddr},
364 REMOTE_HOST => $sockdata->{peername},
365 REQUEST_METHOD => $method || '',
366 SERVER_NAME => $sockdata->{localname},
367 SERVER_PORT => $port,
368 SERVER_PROTOCOL => "HTTP/$protocol",
373 if ( $protocol >= 1 ) {
374 $self->_parse_headers;
377 # Pass flow control to Catalyst
378 $class->handle_request;
380 DEBUG && warn "Request done\n";
382 # Allow keepalive requests, this is a hack but we'll support it until
383 # the next major release.
384 if ( delete $self->{_keepalive} ) {
386 DEBUG && warn "Reusing previous connection for keep-alive request\n";
388 if ( $sel->can_read(1) ) {
389 if ( !$self->_read_headers ) {
390 # Error reading, give up
394 ( $method, $uri, $protocol ) = $self->_parse_request_line;
396 DEBUG && warn "Parsed request: $method $uri $protocol\n";
404 DEBUG && warn "No keep-alive request within 1 second\n";
410 DEBUG && warn "Closing connection\n";
419 my $read = sysread Remote, my $buf, CHUNKSIZE;
421 if ( !defined $read ) {
422 next if $! == EWOULDBLOCK;
423 DEBUG && warn "Error reading headers: $!\n";
425 } elsif ( $read == 0 ) {
426 DEBUG && warn "EOF\n";
430 DEBUG && warn "Read $read bytes\n";
431 $self->{inputbuf} .= $buf;
432 last if $self->{inputbuf} =~ /(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)/s;
438 sub _parse_request_line {
442 if ( $self->{inputbuf} !~ s/^(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
448 my $proto = $3 || 'HTTP/0.9';
450 return ( $method, $uri, $proto );
456 # Copy the buffer for header parsing, and remove the header block
457 # from the content buffer.
458 my $buf = $self->{inputbuf};
459 $self->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s;
462 my $headers = HTTP::Headers->new;
465 while ( $buf =~ s/^([^\012]*)\012// ) {
468 if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
469 $headers->push_header( $key, $val ) if $key;
470 ($key, $val) = ($1, $2);
472 elsif ( /^\s+(.*)/ ) {
479 $headers->push_header( $key, $val ) if $key;
481 DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
483 # Convert headers into ENV vars
484 $headers->scan( sub {
485 my ( $key, $val ) = @_;
488 $key = 'COOKIE' if $key eq 'COOKIES';
490 $key = 'HTTP_' . $key
491 unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
493 if ( exists $ENV{$key} ) {
494 $ENV{$key} .= ", $val";
503 my ( $self, $handle ) = @_;
505 my $remote_sockaddr = getpeername($handle);
506 my ( undef, $iaddr ) = $remote_sockaddr
507 ? sockaddr_in($remote_sockaddr)
510 my $local_sockaddr = getsockname($handle);
511 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
513 # This mess is necessary to keep IE from crashing the server
516 ? ( gethostbyaddr( $iaddr, AF_INET ) || 'localhost' )
519 ? ( inet_ntoa($iaddr) || '127.0.0.1' )
521 localname => gethostbyaddr( $localiaddr, AF_INET ) || 'localhost',
522 localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
528 sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
532 L<Catalyst>, L<Catalyst::Engine>.
536 Sebastian Riedel, <sri@cpan.org>
538 Dan Kubb, <dan.kubb-cpan@onautopilot.com>
540 Sascha Kiefer, <esskar@cpan.org>
542 Andy Grundman, <andy@hybridized.org>
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.