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');
71 if ( $self->options->{keepalive}
73 && $connection =~ /^keep-alive$/i
75 $res_headers->header( Connection => 'keep-alive' );
79 $res_headers->header( Connection => 'close' );
82 push @headers, $res_headers->as_string("\x0D\x0A");
84 # Buffer the headers so they are sent with the first write() call
85 # This reduces the number of TCP packets we are sending
86 $self->_header_buf( join("\x0D\x0A", @headers, '') );
89 =head2 $self->finalize_read($c)
93 before finalize_read => sub {
94 # Never ever remove this, it would result in random length output
95 # streams if STDIN eq STDOUT (like in the HTTP engine)
99 =head2 $self->prepare_read($c)
103 before prepare_read => sub {
104 # Set the input handle to non-blocking
108 =head2 $self->read_chunk($c, $buffer, $length)
116 # If we have any remaining data in the input buffer, send it back first
117 if ( $_[0] = delete $self->{inputbuf} ) {
118 my $read = length( $_[0] );
119 DEBUG && warn "read_chunk: Read $read bytes from previous input buffer\n";
123 # support for non-blocking IO
125 vec( $rin, *STDIN->fileno, 1 ) = 1;
129 select( $rin, undef, undef, undef );
130 my $rc = *STDIN->sysread(@_);
132 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
136 next READ if $! == EWOULDBLOCK;
142 =head2 $self->write($c, $buffer)
144 Writes the buffer to the client.
148 around write => sub {
150 my ( $self, $c, $buffer ) = @_;
152 # Avoid 'print() on closed filehandle Remote' warnings when using IE
153 return unless *STDOUT->opened();
155 # Prepend the headers if they have not yet been sent
156 if ( $self->_has_header_buf ) {
157 $self->_warn_on_write_error(
158 $self->$orig($c, $self->_clear_header_buf)
162 $self->_warn_on_write_error($self->$orig($c, $buffer));
165 sub _warn_on_write_error {
166 my ($self, $ret) = @_;
167 if ( !defined $ret ) {
168 $self->_write_error($!);
169 DEBUG && warn "write: Failed to write response ($!)\n";
172 DEBUG && warn "write: Wrote response ($ret bytes)\n";
181 # A very very simple HTTP server that initializes a CGI environment
183 my ( $self, $class, $port, $host, $options ) = @_;
187 $self->options($options);
189 if ($options->{background}) {
191 die "Can't fork: $!" unless defined($child);
192 return $child if $child;
196 local $SIG{CHLD} = 'IGNORE';
198 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
199 my $addr = $host ? inet_aton($host) : INADDR_ANY;
200 if ( $addr eq INADDR_ANY ) {
201 require Sys::Hostname;
202 $host = lc Sys::Hostname::hostname();
205 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
211 my $daemon = IO::Socket::INET->new(
213 LocalAddr => inet_ntoa($addr),
219 or die "Couldn't create daemon: $@";
221 $port = $daemon->sockport();
223 my $url = "http://$host";
224 $url .= ":$port" unless $port == 80;
226 print "You can connect to your server at $url\n";
228 if ($options->{background}) {
229 open STDIN, "+</dev/null" or die $!;
230 open STDOUT, ">&STDIN" or die $!;
231 open STDERR, ">&STDIN" or die $!;
232 if ( $^O !~ /MSWin32/ ) {
235 or die "Can't start a new session: $!";
239 if (my $pidfile = $options->{pidfile}) {
240 if (! open PIDFILE, "> $pidfile") {
241 warn("Cannot open: $pidfile: $!");
243 print PIDFILE "$$\n";
249 # Ignore broken pipes as an HTTP server should
250 local $SIG{PIPE} = 'IGNORE';
253 local $SIG{HUP} = sub {
255 warn "Restarting server on SIGHUP...\n";
259 while ( !$restart ) {
260 while ( accept( Remote, $daemon ) ) {
261 DEBUG && warn "New connection\n";
267 # Read until we see all headers
268 $self->{inputbuf} = '';
270 if ( !$self->_read_headers ) {
271 # Error reading, give up
276 my ( $method, $uri, $protocol ) = $self->_parse_request_line;
278 DEBUG && warn "Parsed request: $method $uri $protocol\n";
281 unless ( uc($method) eq 'RESTART' ) {
284 if ( $options->{fork} ) {
286 DEBUG && warn "Forked child $pid\n";
291 $self->_handler( $class, $port, $method, $uri, $protocol );
293 if ( $self->_has_write_error ) {
296 if ( !defined $pid ) {
301 if ( defined $pid ) {
302 # Child process, close connection and exit
303 DEBUG && warn "Child process exiting\n";
309 my $sockdata = $self->_socket_data( \*Remote );
310 my $ipaddr = _inet_addr( $sockdata->{peeraddr} );
312 foreach my $ip ( keys %$allowed ) {
313 my $mask = $allowed->{$ip};
314 $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
330 DEBUG && warn "Shutting down\n";
333 $SIG{CHLD} = 'DEFAULT';
336 ### if the standalone server was invoked with perl -I .. we will loose
337 ### those include dirs upon re-exec. So add them to PERL5LIB, so they
338 ### are available again for the exec'ed process --kane
340 $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
342 exec $^X, $0, @{ $options->{argv} };
349 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
351 local *STDIN = \*Remote;
352 local *STDOUT = \*Remote;
354 # We better be careful and just use 1.0
357 my $sockdata = $self->_socket_data( \*Remote );
358 my %copy_of_env = %ENV;
360 my $sel = IO::Select->new;
361 $sel->add( \*STDIN );
365 my ( $path, $query_string ) = split /\?/, $uri, 2;
367 # URI is not the same as path. Remove scheme, domain name and port from it
368 $path =~ s{^https?://[^/?#]+}{};
370 # Initialize CGI environment
372 PATH_INFO => $path || '',
373 QUERY_STRING => $query_string || '',
374 REMOTE_ADDR => $sockdata->{peeraddr},
375 REQUEST_METHOD => $method || '',
376 SERVER_NAME => $sockdata->{localname},
377 SERVER_PORT => $port,
378 SERVER_PROTOCOL => "HTTP/$protocol",
383 if ( $protocol >= 1 ) {
384 $self->_parse_headers;
387 # Pass flow control to Catalyst
389 # FIXME: don't ignore SIGCHLD while handling requests so system()
390 # et al. work within actions. it might be a little risky to do that
391 # this far out, but then again it's only the dev server anyway.
392 local $SIG{CHLD} = 'DEFAULT';
394 $class->handle_request( env => \%ENV );
397 DEBUG && warn "Request done\n";
399 # Allow keepalive requests, this is a hack but we'll support it until
400 # the next major release.
401 if ( $self->_is_keepalive ) {
402 $self->_clear_keepalive;
404 DEBUG && warn "Reusing previous connection for keep-alive request\n";
406 if ( $sel->can_read(1) ) {
407 if ( !$self->_read_headers ) {
408 # Error reading, give up
412 ( $method, $uri, $protocol ) = $self->_parse_request_line;
414 DEBUG && warn "Parsed request: $method $uri $protocol\n";
422 DEBUG && warn "No keep-alive request within 1 second\n";
428 DEBUG && warn "Closing connection\n";
437 my $read = sysread Remote, my $buf, CHUNKSIZE;
439 if ( !defined $read ) {
440 next if $! == EWOULDBLOCK;
441 DEBUG && warn "Error reading headers: $!\n";
443 } elsif ( $read == 0 ) {
444 DEBUG && warn "EOF\n";
448 DEBUG && warn "Read $read bytes\n";
449 $self->{inputbuf} .= $buf;
450 last if $self->{inputbuf} =~ /(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)/s;
456 sub _parse_request_line {
460 # Leading CRLF sometimes sent by buggy IE versions
461 if ( $self->{inputbuf} !~ s/^(?:\x0D\x0A)?(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
467 my $proto = $3 || 'HTTP/0.9';
469 return ( $method, $uri, $proto );
475 # Copy the buffer for header parsing, and remove the header block
476 # from the content buffer.
477 my $buf = $self->{inputbuf};
478 $self->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s;
481 my $headers = HTTP::Headers->new;
484 while ( $buf =~ s/^([^\012]*)\012// ) {
487 if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
488 $headers->push_header( $key, $val ) if $key;
489 ($key, $val) = ($1, $2);
491 elsif ( /^\s+(.*)/ ) {
498 $headers->push_header( $key, $val ) if $key;
500 DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
502 # Convert headers into ENV vars
503 $headers->scan( sub {
504 my ( $key, $val ) = @_;
507 $key = 'COOKIE' if $key eq 'COOKIES';
509 $key = 'HTTP_' . $key
510 unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
512 if ( exists $ENV{$key} ) {
513 $ENV{$key} .= ", $val";
522 my ( $self, $handle ) = @_;
524 my $remote_sockaddr = getpeername($handle);
525 my ( undef, $iaddr ) = $remote_sockaddr
526 ? sockaddr_in($remote_sockaddr)
529 my $local_sockaddr = getsockname($handle);
530 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
532 # This mess is necessary to keep IE from crashing the server
535 ? ( inet_ntoa($iaddr) || '127.0.0.1' )
537 localname => gethostbyaddr( $localiaddr, AF_INET ) || 'localhost',
538 localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
544 sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
548 Options hash passed to the http engine to control things like if keepalive
553 L<Catalyst>, L<Catalyst::Engine>
557 Catalyst Contributors, see Catalyst.pm
561 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
565 This library is free software. You can redistribute it and/or modify it under
566 the same terms as Perl itself.