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 sub CHUNKSIZE () { 64 * 1024 }
21 sub DEBUG () { $ENV{CATALYST_HTTP_DEBUG} || 0 }
25 Catalyst::Engine::HTTP - Catalyst HTTP Engine
29 A script using the Catalyst::Engine::HTTP module might look like:
33 BEGIN { $ENV{CATALYST_ENGINE} = 'HTTP' }
36 use lib '/path/to/MyApp/lib';
43 This is the Catalyst engine specialized for development and testing.
47 =head2 $self->finalize_headers($c)
51 sub finalize_headers {
52 my ( $self, $c ) = @_;
53 my $protocol = $c->request->protocol;
54 my $status = $c->response->status;
55 my $message = status_message($status);
58 push @headers, "$protocol $status $message";
60 $c->response->headers->header( Date => HTTP::Date::time2str(time) );
61 $c->response->headers->header( Status => $status );
63 # Should we keep the connection open?
64 my $connection = $c->request->header('Connection');
65 if ( $self->{options}->{keepalive}
67 && $connection =~ /^keep-alive$/i
69 $c->response->headers->header( Connection => 'keep-alive' );
70 $self->{_keepalive} = 1;
73 $c->response->headers->header( Connection => 'close' );
76 push @headers, $c->response->headers->as_string("\x0D\x0A");
78 # Buffer the headers so they are sent with the first write() call
79 # This reduces the number of TCP packets we are sending
80 $self->{_header_buf} = join("\x0D\x0A", @headers, '');
83 =head2 $self->finalize_read($c)
88 my ( $self, $c ) = @_;
90 # Never ever remove this, it would result in random length output
91 # streams if STDIN eq STDOUT (like in the HTTP engine)
94 return $self->NEXT::finalize_read($c);
97 =head2 $self->prepare_read($c)
102 my ( $self, $c ) = @_;
104 # Set the input handle to non-blocking
107 return $self->NEXT::prepare_read($c);
110 =head2 $self->read_chunk($c, $buffer, $length)
118 # If we have any remaining data in the input buffer, send it back first
119 if ( $_[0] = delete $self->{inputbuf} ) {
120 my $read = length( $_[0] );
121 DEBUG && warn "read_chunk: Read $read bytes from previous input buffer\n";
125 # support for non-blocking IO
127 vec( $rin, *STDIN->fileno, 1 ) = 1;
131 select( $rin, undef, undef, undef );
132 my $rc = *STDIN->sysread(@_);
134 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
138 next READ if $! == EWOULDBLOCK;
144 =head2 $self->write($c, $buffer)
146 Writes the buffer to the client. Can only be called once for a request.
151 my ( $self, $c, $buffer ) = @_;
153 # Avoid 'print() on closed filehandle Remote' warnings when using IE
154 return unless *STDOUT->opened();
158 # Prepend the headers if they have not yet been sent
159 if ( my $headers = delete $self->{_header_buf} ) {
160 DEBUG && warn "write: Wrote headers and first chunk (" . length($headers . $buffer) . " bytes)\n";
161 $ret = $self->NEXT::write( $c, $headers . $buffer );
164 DEBUG && warn "write: Wrote chunk (" . length($buffer) . " bytes)\n";
165 $ret = $self->NEXT::write( $c, $buffer );
169 $self->{_write_error} = $!;
179 # A very very simple HTTP server that initializes a CGI environment
181 my ( $self, $class, $port, $host, $options ) = @_;
185 $self->{options} = $options;
187 if ($options->{background}) {
189 die "Can't fork: $!" unless defined($child);
194 local $SIG{CHLD} = 'IGNORE';
196 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
197 my $addr = $host ? inet_aton($host) : INADDR_ANY;
198 if ( $addr eq INADDR_ANY ) {
199 require Sys::Hostname;
200 $host = lc Sys::Hostname::hostname();
203 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
209 my $daemon = IO::Socket::INET->new(
211 LocalAddr => inet_ntoa($addr),
217 or die "Couldn't create daemon: $!";
219 my $url = "http://$host";
220 $url .= ":$port" unless $port == 80;
222 print "You can connect to your server at $url\n";
224 if ($options->{background}) {
225 open STDIN, "+</dev/null" or die $!;
226 open STDOUT, ">&STDIN" or die $!;
227 open STDERR, ">&STDIN" or die $!;
228 if ( $^O !~ /MSWin32/ ) {
231 or die "Can't start a new session: $!";
235 if (my $pidfile = $options->{pidfile}) {
236 if (! open PIDFILE, "> $pidfile") {
237 warn("Cannot open: $pidfile: $!");
239 print PIDFILE "$$\n";
245 # Ignore broken pipes as an HTTP server should
246 local $SIG{PIPE} = 'IGNORE';
249 while ( !$restart ) {
250 while ( accept( Remote, $daemon ) ) {
251 DEBUG && warn "New connection\n";
257 # Read until we see all headers
258 $self->{inputbuf} = '';
260 if ( !$self->_read_headers ) {
261 # Error reading, give up
265 my ( $method, $uri, $protocol ) = $self->_parse_request_line;
267 DEBUG && warn "Parsed request: $method $uri $protocol\n";
271 unless ( uc($method) eq 'RESTART' ) {
274 if ( $options->{fork} ) { next if $pid = fork }
276 $self->_handler( $class, $port, $method, $uri, $protocol );
278 if ( my $error = delete $self->{_write_error} ) {
279 DEBUG && warn "Write error: $error\n";
284 $daemon->close if defined $pid;
287 my $sockdata = $self->_socket_data( \*Remote );
288 my $ipaddr = _inet_addr( $sockdata->{peeraddr} );
290 foreach my $ip ( keys %$allowed ) {
291 my $mask = $allowed->{$ip};
292 $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
301 exit if defined $pid;
310 DEBUG && warn "Shutting down\n";
313 $SIG{CHLD} = 'DEFAULT';
316 ### if the standalone server was invoked with perl -I .. we will loose
317 ### those include dirs upon re-exec. So add them to PERL5LIB, so they
318 ### are available again for the exec'ed process --kane
320 $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
322 exec $^X . ' "' . $0 . '" ' . join( ' ', @{ $options->{argv} } );
329 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
331 local *STDIN = \*Remote;
332 local *STDOUT = \*Remote;
334 # We better be careful and just use 1.0
337 my $sockdata = $self->_socket_data( \*Remote );
338 my %copy_of_env = %ENV;
340 my $sel = IO::Select->new;
341 $sel->add( \*STDIN );
345 my ( $path, $query_string ) = split /\?/, $uri, 2;
347 # Initialize CGI environment
349 PATH_INFO => $path || '',
350 QUERY_STRING => $query_string || '',
351 REMOTE_ADDR => $sockdata->{peeraddr},
352 REMOTE_HOST => $sockdata->{peername},
353 REQUEST_METHOD => $method || '',
354 SERVER_NAME => $sockdata->{localname},
355 SERVER_PORT => $port,
356 SERVER_PROTOCOL => "HTTP/$protocol",
361 if ( $protocol >= 1 ) {
362 $self->_parse_headers;
365 # Pass flow control to Catalyst
366 $class->handle_request;
368 DEBUG && warn "Request done\n";
370 # Allow keepalive requests, this is a hack but we'll support it until
371 # the next major release.
372 if ( delete $self->{_keepalive} ) {
374 DEBUG && warn "Reusing previous connection for keep-alive request\n";
376 if ( $sel->can_read(1) ) {
377 if ( !$self->_read_headers ) {
378 # Error reading, give up
382 ( $method, $uri, $protocol ) = $self->_parse_request_line;
384 DEBUG && warn "Parsed request: $method $uri $protocol\n";
392 DEBUG && warn "No keep-alive request within 1 second\n";
398 DEBUG && warn "Closing connection\n";
407 my $read = sysread Remote, my $buf, CHUNKSIZE;
410 DEBUG && warn "EOF or error: $!\n";
414 DEBUG && warn "Read $read bytes\n";
415 $self->{inputbuf} .= $buf;
416 last if $self->{inputbuf} =~ /(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)/s;
422 sub _parse_request_line {
426 if ( $self->{inputbuf} !~ s/^(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
432 my $proto = $3 || 'HTTP/0.9';
434 return ( $method, $uri, $proto );
440 # Copy the buffer for header parsing, and remove the header block
441 # from the content buffer.
442 my $buf = $self->{inputbuf};
443 $self->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s;
446 my $headers = HTTP::Headers->new;
449 while ( $buf =~ s/^([^\012]*)\012// ) {
452 if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
453 $headers->push_header( $key, $val ) if $key;
454 ($key, $val) = ($1, $2);
456 elsif ( /^\s+(.*)/ ) {
463 $headers->push_header( $key, $val ) if $key;
465 DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
467 # Convert headers into ENV vars
468 $headers->scan( sub {
469 my ( $key, $val ) = @_;
472 $key = 'COOKIE' if $key eq 'COOKIES';
474 $key = 'HTTP_' . $key
475 unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
477 if ( exists $ENV{$key} ) {
478 $ENV{$key} .= ", $val";
487 my ( $self, $handle ) = @_;
489 my $remote_sockaddr = getpeername($handle);
490 my ( undef, $iaddr ) = $remote_sockaddr
491 ? sockaddr_in($remote_sockaddr)
494 my $local_sockaddr = getsockname($handle);
495 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
497 # This mess is necessary to keep IE from crashing the server
500 ? ( gethostbyaddr( $iaddr, AF_INET ) || 'localhost' )
503 ? ( inet_ntoa($iaddr) || '127.0.0.1' )
505 localname => gethostbyaddr( $localiaddr, AF_INET ) || 'localhost',
506 localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
512 sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
516 L<Catalyst>, L<Catalyst::Engine>.
520 Sebastian Riedel, <sri@cpan.org>
522 Dan Kubb, <dan.kubb-cpan@onautopilot.com>
524 Sascha Kiefer, <esskar@cpan.org>
526 Andy Grundman, <andy@hybridized.org>
530 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
534 This program is free software, you can redistribute it and/or modify it under
535 the same terms as Perl itself.