1 package Catalyst::Engine::HTTP;
4 extends 'Catalyst::Engine::CGI';
5 use Data::Dump qw(dump);
6 use Errno 'EWOULDBLOCK';
11 use IO::Socket::INET ();
15 require Catalyst::Engine::HTTP::Restarter;
16 require Catalyst::Engine::HTTP::Restarter::Watcher;
18 use constant CHUNKSIZE => 64 * 1024;
19 use constant DEBUG => $ENV{CATALYST_HTTP_DEBUG} || 0;
23 Catalyst::Engine::HTTP - Catalyst HTTP Engine
27 A script using the Catalyst::Engine::HTTP module might look like:
31 BEGIN { $ENV{CATALYST_ENGINE} = 'HTTP' }
34 use lib '/path/to/MyApp/lib';
41 This is the Catalyst engine specialized for development and testing.
45 =head2 $self->finalize_headers($c)
49 sub finalize_headers {
50 my ( $self, $c ) = @_;
51 my $protocol = $c->request->protocol;
52 my $status = $c->response->status;
53 my $message = status_message($status);
54 my $res_headers = $c->response->headers;
57 push @headers, "$protocol $status $message";
59 $res_headers->header( Date => HTTP::Date::time2str(time) );
60 $res_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 $res_headers->header( Connection => 'keep-alive' );
69 $self->{_keepalive} = 1;
72 $res_headers->header( Connection => 'close' );
75 push @headers, $res_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)
86 before finalize_read => sub {
87 # Never ever remove this, it would result in random length output
88 # streams if STDIN eq STDOUT (like in the HTTP engine)
92 =head2 $self->prepare_read($c)
96 befpre prepare_read => sub {
97 # Set the input handle to non-blocking
101 =head2 $self->read_chunk($c, $buffer, $length)
109 # If we have any remaining data in the input buffer, send it back first
110 if ( $_[0] = delete $self->{inputbuf} ) {
111 my $read = length( $_[0] );
112 DEBUG && warn "read_chunk: Read $read bytes from previous input buffer\n";
116 # support for non-blocking IO
118 vec( $rin, *STDIN->fileno, 1 ) = 1;
122 select( $rin, undef, undef, undef );
123 my $rc = *STDIN->sysread(@_);
125 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
129 next READ if $! == EWOULDBLOCK;
135 =head2 $self->write($c, $buffer)
137 Writes the buffer to the client.
141 around write => sub {
143 my ( $self, $c, $buffer ) = @_;
145 # Avoid 'print() on closed filehandle Remote' warnings when using IE
146 return unless *STDOUT->opened();
148 # Prepend the headers if they have not yet been sent
149 if ( my $headers = delete $self->{_header_buf} ) {
150 $buffer = $headers . $buffer;
153 my $ret = $self->$orig( $c, $buffer );
155 if ( !defined $ret ) {
156 $self->{_write_error} = $!;
157 DEBUG && warn "write: Failed to write response ($!)\n";
160 DEBUG && warn "write: Wrote response ($ret bytes)\n";
170 # A very very simple HTTP server that initializes a CGI environment
172 my ( $self, $class, $port, $host, $options ) = @_;
176 $self->{options} = $options;
178 if ($options->{background}) {
180 die "Can't fork: $!" unless defined($child);
181 return $child if $child;
185 local $SIG{CHLD} = 'IGNORE';
187 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
188 my $addr = $host ? inet_aton($host) : INADDR_ANY;
189 if ( $addr eq INADDR_ANY ) {
190 require Sys::Hostname;
191 $host = lc Sys::Hostname::hostname();
194 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
200 my $daemon = IO::Socket::INET->new(
202 LocalAddr => inet_ntoa($addr),
208 or die "Couldn't create daemon: $!";
210 my $url = "http://$host";
211 $url .= ":$port" unless $port == 80;
213 print "You can connect to your server at $url\n";
215 if ($options->{background}) {
216 open STDIN, "+</dev/null" or die $!;
217 open STDOUT, ">&STDIN" or die $!;
218 open STDERR, ">&STDIN" or die $!;
219 if ( $^O !~ /MSWin32/ ) {
222 or die "Can't start a new session: $!";
226 if (my $pidfile = $options->{pidfile}) {
227 if (! open PIDFILE, "> $pidfile") {
228 warn("Cannot open: $pidfile: $!");
230 print PIDFILE "$$\n";
236 # Ignore broken pipes as an HTTP server should
237 local $SIG{PIPE} = 'IGNORE';
240 local $SIG{HUP} = sub {
242 warn "Restarting server on SIGHUP...\n";
246 while ( !$restart ) {
247 while ( accept( Remote, $daemon ) ) {
248 DEBUG && warn "New connection\n";
254 # Read until we see all headers
255 $self->{inputbuf} = '';
257 if ( !$self->_read_headers ) {
258 # Error reading, give up
263 my ( $method, $uri, $protocol ) = $self->_parse_request_line;
265 DEBUG && warn "Parsed request: $method $uri $protocol\n";
268 unless ( uc($method) eq 'RESTART' ) {
271 if ( $options->{fork} ) {
273 DEBUG && warn "Forked child $pid\n";
278 $self->_handler( $class, $port, $method, $uri, $protocol );
280 if ( my $error = delete $self->{_write_error} ) {
283 if ( !defined $pid ) {
288 if ( defined $pid ) {
289 # Child process, close connection and exit
290 DEBUG && warn "Child process exiting\n";
296 my $sockdata = $self->_socket_data( \*Remote );
297 my $ipaddr = _inet_addr( $sockdata->{peeraddr} );
299 foreach my $ip ( keys %$allowed ) {
300 my $mask = $allowed->{$ip};
301 $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
317 DEBUG && warn "Shutting down\n";
320 $SIG{CHLD} = 'DEFAULT';
323 ### if the standalone server was invoked with perl -I .. we will loose
324 ### those include dirs upon re-exec. So add them to PERL5LIB, so they
325 ### are available again for the exec'ed process --kane
327 $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
329 exec $^X, $0, @{ $options->{argv} };
336 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
338 local *STDIN = \*Remote;
339 local *STDOUT = \*Remote;
341 # We better be careful and just use 1.0
344 my $sockdata = $self->_socket_data( \*Remote );
345 my %copy_of_env = %ENV;
347 my $sel = IO::Select->new;
348 $sel->add( \*STDIN );
352 my ( $path, $query_string ) = split /\?/, $uri, 2;
354 # Initialize CGI environment
356 PATH_INFO => $path || '',
357 QUERY_STRING => $query_string || '',
358 REMOTE_ADDR => $sockdata->{peeraddr},
359 REMOTE_HOST => $sockdata->{peername},
360 REQUEST_METHOD => $method || '',
361 SERVER_NAME => $sockdata->{localname},
362 SERVER_PORT => $port,
363 SERVER_PROTOCOL => "HTTP/$protocol",
368 if ( $protocol >= 1 ) {
369 $self->_parse_headers;
372 # Pass flow control to Catalyst
373 $class->handle_request;
375 DEBUG && warn "Request done\n";
377 # Allow keepalive requests, this is a hack but we'll support it until
378 # the next major release.
379 if ( delete $self->{_keepalive} ) {
381 DEBUG && warn "Reusing previous connection for keep-alive request\n";
383 if ( $sel->can_read(1) ) {
384 if ( !$self->_read_headers ) {
385 # Error reading, give up
389 ( $method, $uri, $protocol ) = $self->_parse_request_line;
391 DEBUG && warn "Parsed request: $method $uri $protocol\n";
399 DEBUG && warn "No keep-alive request within 1 second\n";
405 DEBUG && warn "Closing connection\n";
414 my $read = sysread Remote, my $buf, CHUNKSIZE;
416 if ( !defined $read ) {
417 next if $! == EWOULDBLOCK;
418 DEBUG && warn "Error reading headers: $!\n";
420 } elsif ( $read == 0 ) {
421 DEBUG && warn "EOF\n";
425 DEBUG && warn "Read $read bytes\n";
426 $self->{inputbuf} .= $buf;
427 last if $self->{inputbuf} =~ /(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)/s;
433 sub _parse_request_line {
437 if ( $self->{inputbuf} !~ s/^(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
443 my $proto = $3 || 'HTTP/0.9';
445 return ( $method, $uri, $proto );
451 # Copy the buffer for header parsing, and remove the header block
452 # from the content buffer.
453 my $buf = $self->{inputbuf};
454 $self->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s;
457 my $headers = HTTP::Headers->new;
460 while ( $buf =~ s/^([^\012]*)\012// ) {
463 if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
464 $headers->push_header( $key, $val ) if $key;
465 ($key, $val) = ($1, $2);
467 elsif ( /^\s+(.*)/ ) {
474 $headers->push_header( $key, $val ) if $key;
476 DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
478 # Convert headers into ENV vars
479 $headers->scan( sub {
480 my ( $key, $val ) = @_;
483 $key = 'COOKIE' if $key eq 'COOKIES';
485 $key = 'HTTP_' . $key
486 unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
488 if ( exists $ENV{$key} ) {
489 $ENV{$key} .= ", $val";
498 my ( $self, $handle ) = @_;
500 my $remote_sockaddr = getpeername($handle);
501 my ( undef, $iaddr ) = $remote_sockaddr
502 ? sockaddr_in($remote_sockaddr)
505 my $local_sockaddr = getsockname($handle);
506 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
508 # This mess is necessary to keep IE from crashing the server
511 ? ( gethostbyaddr( $iaddr, AF_INET ) || 'localhost' )
514 ? ( inet_ntoa($iaddr) || '127.0.0.1' )
516 localname => gethostbyaddr( $localiaddr, AF_INET ) || 'localhost',
517 localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
523 sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
527 L<Catalyst>, L<Catalyst::Engine>.
531 Sebastian Riedel, <sri@cpan.org>
533 Dan Kubb, <dan.kubb-cpan@onautopilot.com>
535 Sascha Kiefer, <esskar@cpan.org>
537 Andy Grundman, <andy@hybridized.org>
541 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
545 This program is free software, you can redistribute it and/or modify it under
546 the same terms as Perl itself.