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 ();
15 use constant CHUNKSIZE => 64 * 1024;
16 use constant DEBUG => $ENV{CATALYST_HTTP_DEBUG} || 0;
18 use namespace::clean -except => 'meta';
20 has options => ( is => 'rw' );
21 has _keepalive => ( is => 'rw', predicate => '_is_keepalive', clearer => '_clear_keepalive' );
22 has _write_error => ( is => 'rw', predicate => '_has_write_error' );
24 # Refactoring note - could/should Eliminate all instances of $self->{inputbuf},
25 # which I haven't touched as it is used as an lvalue in a lot of places, and I guess
26 # doing it differently could be expensive.. Feel free to refactor and NYTProf :)
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');
72 && $self->options->{keepalive}
74 && $connection =~ /^keep-alive$/i
76 $res_headers->header( Connection => 'keep-alive' );
80 $res_headers->header( Connection => 'close' );
83 push @headers, $res_headers->as_string("\x0D\x0A");
85 # Buffer the headers so they are sent with the first write() call
86 # This reduces the number of TCP packets we are sending
87 $self->_header_buf( join("\x0D\x0A", @headers, '') );
90 =head2 $self->finalize_read($c)
94 before finalize_read => sub {
95 # Never ever remove this, it would result in random length output
96 # streams if STDIN eq STDOUT (like in the HTTP engine)
100 =head2 $self->prepare_read($c)
104 before prepare_read => sub {
105 # Set the input handle to non-blocking
109 =head2 $self->read_chunk($c, $buffer, $length)
117 # If we have any remaining data in the input buffer, send it back first
118 if ( $_[0] = delete $self->{inputbuf} ) {
119 my $read = length( $_[0] );
120 DEBUG && warn "read_chunk: Read $read bytes from previous input buffer\n";
124 # support for non-blocking IO
126 vec( $rin, *STDIN->fileno, 1 ) = 1;
130 select( $rin, undef, undef, undef );
131 my $rc = *STDIN->sysread(@_);
133 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
137 next READ if $! == EWOULDBLOCK;
143 =head2 $self->write($c, $buffer)
145 Writes the buffer to the client.
149 around write => sub {
151 my ( $self, $c, $buffer ) = @_;
153 # Avoid 'print() on closed filehandle Remote' warnings when using IE
154 return unless *STDOUT->opened();
156 # Prepend the headers if they have not yet been sent
157 if ( $self->_has_header_buf ) {
158 $self->_warn_on_write_error(
159 $self->$orig($c, $self->_clear_header_buf)
163 $self->_warn_on_write_error($self->$orig($c, $buffer));
166 sub _warn_on_write_error {
167 my ($self, $ret) = @_;
168 if ( !defined $ret ) {
169 $self->_write_error($!);
170 DEBUG && warn "write: Failed to write response ($!)\n";
173 DEBUG && warn "write: Wrote response ($ret bytes)\n";
182 # A very very simple HTTP server that initializes a CGI environment
184 my ( $self, $class, $port, $host, $options ) = @_;
188 $self->options($options);
190 if ($options->{background}) {
192 die "Can't fork: $!" unless defined($child);
193 return $child if $child;
197 local $SIG{CHLD} = 'IGNORE';
199 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
200 my $addr = $host ? inet_aton($host) : INADDR_ANY;
201 if ( $addr eq INADDR_ANY ) {
202 require Sys::Hostname;
203 $host = lc Sys::Hostname::hostname();
206 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
212 my $daemon = IO::Socket::INET->new(
214 LocalAddr => inet_ntoa($addr),
220 or die "Couldn't create daemon: $@";
222 $port = $daemon->sockport();
224 my $url = "http://$host";
225 $url .= ":$port" unless $port == 80;
227 print "You can connect to your server at $url\n";
229 if ($options->{background}) {
230 open STDIN, "+</dev/null" or die $!;
231 open STDOUT, ">&STDIN" or die $!;
232 open STDERR, ">&STDIN" or die $!;
233 if ( $^O !~ /MSWin32/ ) {
236 or die "Can't start a new session: $!";
240 if (my $pidfile = $options->{pidfile}) {
241 if (! open PIDFILE, "> $pidfile") {
242 warn("Cannot open: $pidfile: $!");
244 print PIDFILE "$$\n";
250 # Ignore broken pipes as an HTTP server should
251 local $SIG{PIPE} = 'IGNORE';
254 local $SIG{HUP} = sub {
256 warn "Restarting server on SIGHUP...\n";
260 while ( !$restart ) {
261 while ( accept( Remote, $daemon ) ) {
262 DEBUG && warn "New connection\n";
268 # Read until we see all headers
269 $self->{inputbuf} = '';
271 if ( !$self->_read_headers ) {
272 # Error reading, give up
277 my ( $method, $uri, $protocol ) = $self->_parse_request_line;
279 DEBUG && warn "Parsed request: $method $uri $protocol\n";
282 unless ( uc($method) eq 'RESTART' ) {
285 if ( $options->{fork} ) {
287 DEBUG && warn "Forked child $pid\n";
292 $self->_handler( $class, $port, $method, $uri, $protocol );
294 if ( $self->_has_write_error ) {
297 if ( !defined $pid ) {
302 if ( defined $pid ) {
303 # Child process, close connection and exit
304 DEBUG && warn "Child process exiting\n";
310 my $sockdata = $self->_socket_data( \*Remote );
311 my $ipaddr = _inet_addr( $sockdata->{peeraddr} );
313 foreach my $ip ( keys %$allowed ) {
314 my $mask = $allowed->{$ip};
315 $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
331 DEBUG && warn "Shutting down\n";
334 $SIG{CHLD} = 'DEFAULT';
337 ### if the standalone server was invoked with perl -I .. we will loose
338 ### those include dirs upon re-exec. So add them to PERL5LIB, so they
339 ### are available again for the exec'ed process --kane
341 $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
343 exec $^X, $0, @{ $options->{argv} || [] };
350 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
352 local *STDIN = \*Remote;
353 local *STDOUT = \*Remote;
355 # We better be careful and just use 1.0
358 my $sockdata = $self->_socket_data( \*Remote );
359 my %copy_of_env = %ENV;
361 my $sel = IO::Select->new;
362 $sel->add( \*STDIN );
366 my ( $path, $query_string ) = split /\?/, $uri, 2;
368 # URI is not the same as path. Remove scheme, domain name and port from it
369 $path =~ s{^https?://[^/?#]+}{};
371 # Initialize CGI environment
373 PATH_INFO => $path || '',
374 QUERY_STRING => $query_string || '',
375 REMOTE_ADDR => $sockdata->{peeraddr},
376 REQUEST_METHOD => $method || '',
377 SERVER_NAME => $sockdata->{localname},
378 SERVER_PORT => $port,
379 SERVER_PROTOCOL => "HTTP/$protocol",
384 if ( $protocol >= 1 ) {
385 $self->_parse_headers;
388 # Pass flow control to Catalyst
390 # FIXME: don't ignore SIGCHLD while handling requests so system()
391 # et al. work within actions. it might be a little risky to do that
392 # this far out, but then again it's only the dev server anyway.
393 local $SIG{CHLD} = 'DEFAULT';
395 $class->handle_request( env => \%ENV );
398 DEBUG && warn "Request done\n";
400 # Allow keepalive requests, this is a hack but we'll support it until
401 # the next major release.
402 if ( $self->_is_keepalive ) {
403 $self->_clear_keepalive;
405 DEBUG && warn "Reusing previous connection for keep-alive request\n";
407 if ( $sel->can_read(1) ) {
408 if ( !$self->_read_headers ) {
409 # Error reading, give up
413 ( $method, $uri, $protocol ) = $self->_parse_request_line;
415 DEBUG && warn "Parsed request: $method $uri $protocol\n";
423 DEBUG && warn "No keep-alive request within 1 second\n";
429 DEBUG && warn "Closing connection\n";
438 my $read = sysread Remote, my $buf, CHUNKSIZE;
440 if ( !defined $read ) {
441 next if $! == EWOULDBLOCK;
442 DEBUG && warn "Error reading headers: $!\n";
444 } elsif ( $read == 0 ) {
445 DEBUG && warn "EOF\n";
449 DEBUG && warn "Read $read bytes\n";
450 $self->{inputbuf} .= $buf;
451 last if $self->{inputbuf} =~ /(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)/s;
457 sub _parse_request_line {
461 # Leading CRLF sometimes sent by buggy IE versions
462 if ( $self->{inputbuf} !~ s/^(?:\x0D\x0A)?(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
468 my $proto = $3 || 'HTTP/0.9';
470 return ( $method, $uri, $proto );
476 # Copy the buffer for header parsing, and remove the header block
477 # from the content buffer.
478 my $buf = $self->{inputbuf};
479 $self->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s;
482 my $headers = HTTP::Headers->new;
485 while ( $buf =~ s/^([^\012]*)\012// ) {
488 if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
489 $headers->push_header( $key, $val ) if $key;
490 ($key, $val) = ($1, $2);
492 elsif ( /^\s+(.*)/ ) {
499 $headers->push_header( $key, $val ) if $key;
501 DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
503 # Convert headers into ENV vars
504 $headers->scan( sub {
505 my ( $key, $val ) = @_;
508 $key = 'COOKIE' if $key eq 'COOKIES';
510 $key = 'HTTP_' . $key
511 unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
513 if ( exists $ENV{$key} ) {
514 $ENV{$key} .= ", $val";
523 my ( $self, $handle ) = @_;
525 my $remote_sockaddr = getpeername($handle);
526 my ( undef, $iaddr ) = $remote_sockaddr
527 ? sockaddr_in($remote_sockaddr)
530 my $local_sockaddr = getsockname($handle);
531 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
533 # This mess is necessary to keep IE from crashing the server
536 ? ( inet_ntoa($iaddr) || '127.0.0.1' )
538 localname => _gethostbyaddr( $localiaddr ),
539 localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
545 { # If you have a crappy DNS server then these can be slow, so cache 'em
549 $hostname_cache{$ip} ||= gethostbyaddr( $ip, AF_INET ) || 'localhost';
553 sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
557 Options hash passed to the http engine to control things like if keepalive
562 L<Catalyst>, L<Catalyst::Engine>
566 Catalyst Contributors, see Catalyst.pm
570 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
574 This library is free software. You can redistribute it and/or modify it under
575 the same terms as Perl itself.