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 ();
16 require Catalyst::Engine::HTTP::Restarter;
17 require Catalyst::Engine::HTTP::Restarter::Watcher;
19 use constant CHUNKSIZE => 64 * 1024;
20 use constant DEBUG => $ENV{CATALYST_HTTP_DEBUG} || 0;
24 Catalyst::Engine::HTTP - Catalyst HTTP Engine
28 A script using the Catalyst::Engine::HTTP module might look like:
32 BEGIN { $ENV{CATALYST_ENGINE} = 'HTTP' }
35 use lib '/path/to/MyApp/lib';
42 This is the Catalyst engine specialized for development and testing.
46 =head2 $self->finalize_headers($c)
50 sub finalize_headers {
51 my ( $self, $c ) = @_;
52 my $protocol = $c->request->protocol;
53 my $status = $c->response->status;
54 my $message = status_message($status);
55 my $res_headers = $c->response->headers;
58 push @headers, "$protocol $status $message";
60 $res_headers->header( Date => HTTP::Date::time2str(time) );
61 $res_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 $res_headers->header( Connection => 'keep-alive' );
70 $self->{_keepalive} = 1;
73 $res_headers->header( Connection => 'close' );
76 push @headers, $res_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)
87 before finalize_read => sub {
88 # Never ever remove this, it would result in random length output
89 # streams if STDIN eq STDOUT (like in the HTTP engine)
93 =head2 $self->prepare_read($c)
97 before prepare_read => sub {
98 # Set the input handle to non-blocking
102 =head2 $self->read_chunk($c, $buffer, $length)
110 # If we have any remaining data in the input buffer, send it back first
111 if ( $_[0] = delete $self->{inputbuf} ) {
112 my $read = length( $_[0] );
113 DEBUG && warn "read_chunk: Read $read bytes from previous input buffer\n";
117 # support for non-blocking IO
119 vec( $rin, *STDIN->fileno, 1 ) = 1;
123 select( $rin, undef, undef, undef );
124 my $rc = *STDIN->sysread(@_);
126 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
130 next READ if $! == EWOULDBLOCK;
136 =head2 $self->write($c, $buffer)
138 Writes the buffer to the client.
142 around write => sub {
144 my ( $self, $c, $buffer ) = @_;
146 # Avoid 'print() on closed filehandle Remote' warnings when using IE
147 return unless *STDOUT->opened();
149 # Prepend the headers if they have not yet been sent
150 if ( my $headers = delete $self->{_header_buf} ) {
151 $buffer = $headers . $buffer;
154 my $ret = $self->$orig($c, $buffer);
156 if ( !defined $ret ) {
157 $self->{_write_error} = $!;
158 DEBUG && warn "write: Failed to write response ($!)\n";
161 DEBUG && warn "write: Wrote response ($ret bytes)\n";
171 # A very very simple HTTP server that initializes a CGI environment
173 my ( $self, $class, $port, $host, $options ) = @_;
177 $self->{options} = $options;
179 if ($options->{background}) {
181 die "Can't fork: $!" unless defined($child);
182 return $child if $child;
186 local $SIG{CHLD} = 'IGNORE';
188 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
189 my $addr = $host ? inet_aton($host) : INADDR_ANY;
190 if ( $addr eq INADDR_ANY ) {
191 require Sys::Hostname;
192 $host = lc Sys::Hostname::hostname();
195 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
201 my $daemon = IO::Socket::INET->new(
203 LocalAddr => inet_ntoa($addr),
209 or die "Couldn't create daemon: $!";
211 my $url = "http://$host";
212 $url .= ":$port" unless $port == 80;
214 print "You can connect to your server at $url\n";
216 if ($options->{background}) {
217 open STDIN, "+</dev/null" or die $!;
218 open STDOUT, ">&STDIN" or die $!;
219 open STDERR, ">&STDIN" or die $!;
220 if ( $^O !~ /MSWin32/ ) {
223 or die "Can't start a new session: $!";
227 if (my $pidfile = $options->{pidfile}) {
228 if (! open PIDFILE, "> $pidfile") {
229 warn("Cannot open: $pidfile: $!");
231 print PIDFILE "$$\n";
237 # Ignore broken pipes as an HTTP server should
238 local $SIG{PIPE} = 'IGNORE';
241 local $SIG{HUP} = sub {
243 warn "Restarting server on SIGHUP...\n";
247 while ( !$restart ) {
248 while ( accept( Remote, $daemon ) ) {
249 DEBUG && warn "New connection\n";
255 # Read until we see all headers
256 $self->{inputbuf} = '';
258 if ( !$self->_read_headers ) {
259 # Error reading, give up
264 my ( $method, $uri, $protocol ) = $self->_parse_request_line;
266 DEBUG && warn "Parsed request: $method $uri $protocol\n";
269 unless ( uc($method) eq 'RESTART' ) {
272 if ( $options->{fork} ) {
274 DEBUG && warn "Forked child $pid\n";
279 $self->_handler( $class, $port, $method, $uri, $protocol );
281 if ( my $error = delete $self->{_write_error} ) {
284 if ( !defined $pid ) {
289 if ( defined $pid ) {
290 # Child process, close connection and exit
291 DEBUG && warn "Child process exiting\n";
297 my $sockdata = $self->_socket_data( \*Remote );
298 my $ipaddr = _inet_addr( $sockdata->{peeraddr} );
300 foreach my $ip ( keys %$allowed ) {
301 my $mask = $allowed->{$ip};
302 $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
318 DEBUG && warn "Shutting down\n";
321 $SIG{CHLD} = 'DEFAULT';
324 ### if the standalone server was invoked with perl -I .. we will loose
325 ### those include dirs upon re-exec. So add them to PERL5LIB, so they
326 ### are available again for the exec'ed process --kane
328 $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
330 exec $^X, $0, @{ $options->{argv} };
337 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
339 local *STDIN = \*Remote;
340 local *STDOUT = \*Remote;
342 # We better be careful and just use 1.0
345 my $sockdata = $self->_socket_data( \*Remote );
346 my %copy_of_env = %ENV;
348 my $sel = IO::Select->new;
349 $sel->add( \*STDIN );
353 my ( $path, $query_string ) = split /\?/, $uri, 2;
355 # Initialize CGI environment
357 PATH_INFO => $path || '',
358 QUERY_STRING => $query_string || '',
359 REMOTE_ADDR => $sockdata->{peeraddr},
360 REMOTE_HOST => $sockdata->{peername},
361 REQUEST_METHOD => $method || '',
362 SERVER_NAME => $sockdata->{localname},
363 SERVER_PORT => $port,
364 SERVER_PROTOCOL => "HTTP/$protocol",
369 if ( $protocol >= 1 ) {
370 $self->_parse_headers;
373 # Pass flow control to Catalyst
374 $class->handle_request;
376 DEBUG && warn "Request done\n";
378 # Allow keepalive requests, this is a hack but we'll support it until
379 # the next major release.
380 if ( delete $self->{_keepalive} ) {
382 DEBUG && warn "Reusing previous connection for keep-alive request\n";
384 if ( $sel->can_read(1) ) {
385 if ( !$self->_read_headers ) {
386 # Error reading, give up
390 ( $method, $uri, $protocol ) = $self->_parse_request_line;
392 DEBUG && warn "Parsed request: $method $uri $protocol\n";
400 DEBUG && warn "No keep-alive request within 1 second\n";
406 DEBUG && warn "Closing connection\n";
415 my $read = sysread Remote, my $buf, CHUNKSIZE;
417 if ( !defined $read ) {
418 next if $! == EWOULDBLOCK;
419 DEBUG && warn "Error reading headers: $!\n";
421 } elsif ( $read == 0 ) {
422 DEBUG && warn "EOF\n";
426 DEBUG && warn "Read $read bytes\n";
427 $self->{inputbuf} .= $buf;
428 last if $self->{inputbuf} =~ /(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)/s;
434 sub _parse_request_line {
438 if ( $self->{inputbuf} !~ s/^(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
444 my $proto = $3 || 'HTTP/0.9';
446 return ( $method, $uri, $proto );
452 # Copy the buffer for header parsing, and remove the header block
453 # from the content buffer.
454 my $buf = $self->{inputbuf};
455 $self->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s;
458 my $headers = HTTP::Headers->new;
461 while ( $buf =~ s/^([^\012]*)\012// ) {
464 if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
465 $headers->push_header( $key, $val ) if $key;
466 ($key, $val) = ($1, $2);
468 elsif ( /^\s+(.*)/ ) {
475 $headers->push_header( $key, $val ) if $key;
477 DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
479 # Convert headers into ENV vars
480 $headers->scan( sub {
481 my ( $key, $val ) = @_;
484 $key = 'COOKIE' if $key eq 'COOKIES';
486 $key = 'HTTP_' . $key
487 unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
489 if ( exists $ENV{$key} ) {
490 $ENV{$key} .= ", $val";
499 my ( $self, $handle ) = @_;
501 my $remote_sockaddr = getpeername($handle);
502 my ( undef, $iaddr ) = $remote_sockaddr
503 ? sockaddr_in($remote_sockaddr)
506 my $local_sockaddr = getsockname($handle);
507 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
509 # This mess is necessary to keep IE from crashing the server
512 ? ( gethostbyaddr( $iaddr, AF_INET ) || 'localhost' )
515 ? ( inet_ntoa($iaddr) || '127.0.0.1' )
517 localname => gethostbyaddr( $localiaddr, AF_INET ) || 'localhost',
518 localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
524 sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
530 L<Catalyst>, L<Catalyst::Engine>
534 Catalyst Contributors, see Catalyst.pm
538 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
542 This program is free software, you can redistribute it and/or modify it under
543 the same terms as Perl itself.