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 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);
57 push @headers, "$protocol $status $message";
59 $c->response->headers->header( Date => HTTP::Date::time2str(time) );
60 $c->response->headers->header( Connection => 'close' );
61 $c->response->headers->header( Status => $status );
63 push @headers, $c->response->headers->as_string("\x0D\x0A");
65 # Buffer the headers so they are sent with the first write() call
66 # This reduces the number of TCP packets we are sending
67 $self->{_header_buf} = join("\x0D\x0A", @headers, '');
70 =head2 $self->finalize_read($c)
75 my ( $self, $c ) = @_;
77 # Never ever remove this, it would result in random length output
78 # streams if STDIN eq STDOUT (like in the HTTP engine)
81 return $self->NEXT::finalize_read($c);
84 =head2 $self->prepare_read($c)
89 my ( $self, $c ) = @_;
91 # Set the input handle to non-blocking
94 return $self->NEXT::prepare_read($c);
97 =head2 $self->read_chunk($c, $buffer, $length)
105 # If we have any remaining data in the input buffer, send it back first
106 if ( $_[0] = delete $self->{inputbuf} ) {
107 my $read = length( $_[0] );
108 DEBUG && warn "read_chunk: Read $read bytes from previous input buffer\n";
112 # support for non-blocking IO
114 vec( $rin, *STDIN->fileno, 1 ) = 1;
118 select( $rin, undef, undef, undef );
119 my $rc = *STDIN->sysread(@_);
121 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
125 next READ if $! == EWOULDBLOCK;
131 =head2 $self->write($c, $buffer)
133 Writes the buffer to the client. Can only be called once for a request.
138 my ( $self, $c, $buffer ) = @_;
140 # Avoid 'print() on closed filehandle Remote' warnings when using IE
141 return unless *STDOUT->opened();
145 # Prepend the headers if they have not yet been sent
146 if ( my $headers = delete $self->{_header_buf} ) {
147 DEBUG && warn "write: Wrote headers and first chunk (" . length($headers . $buffer) . " bytes)\n";
148 $ret = $self->NEXT::write( $c, $headers . $buffer );
151 DEBUG && warn "write: Wrote chunk (" . length($buffer) . " bytes)\n";
152 $ret = $self->NEXT::write( $c, $buffer );
156 $self->{_write_error} = $!;
166 # A very very simple HTTP server that initializes a CGI environment
168 my ( $self, $class, $port, $host, $options ) = @_;
172 $self->{options} = $options;
174 if ($options->{background}) {
176 die "Can't fork: $!" unless defined($child);
181 local $SIG{CHLD} = 'IGNORE';
183 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
184 my $addr = $host ? inet_aton($host) : INADDR_ANY;
185 if ( $addr eq INADDR_ANY ) {
186 require Sys::Hostname;
187 $host = lc Sys::Hostname::hostname();
190 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
196 my $daemon = IO::Socket::INET->new(
198 LocalAddr => inet_ntoa($addr),
204 or die "Couldn't create daemon: $!";
206 my $url = "http://$host";
207 $url .= ":$port" unless $port == 80;
209 print "You can connect to your server at $url\n";
211 if ($options->{background}) {
212 open STDIN, "+</dev/null" or die $!;
213 open STDOUT, ">&STDIN" or die $!;
214 open STDERR, ">&STDIN" or die $!;
215 if ( $^O !~ /MSWin32/ ) {
218 or die "Can't start a new session: $!";
222 if (my $pidfile = $options->{pidfile}) {
223 if (! open PIDFILE, "> $pidfile") {
224 warn("Cannot open: $pidfile: $!");
226 print PIDFILE "$$\n";
232 # Ignore broken pipes as an HTTP server should
233 local $SIG{PIPE} = 'IGNORE';
236 local $SIG{HUP} = sub {
238 warn "Restarting server on SIGHUP...\n";
242 while ( !$restart ) {
243 while ( accept( Remote, $daemon ) ) {
244 DEBUG && warn "New connection\n";
250 # Read until we see a newline
251 $self->{inputbuf} = '';
254 my $read = sysread Remote, my $buf, CHUNKSIZE;
257 DEBUG && warn "EOF or error: $!\n";
261 DEBUG && warn "Read $read bytes\n";
262 $self->{inputbuf} .= $buf;
263 last if $self->{inputbuf} =~ /(\x0D\x0A?|\x0A\x0D?)/s;
266 my ( $method, $uri, $protocol ) = $self->_parse_request_line;
268 DEBUG && warn "Parsed request: $method $uri $protocol\n";
272 unless ( uc($method) eq 'RESTART' ) {
275 if ( $options->{fork} ) { next if $pid = fork }
277 $self->_handler( $class, $port, $method, $uri, $protocol );
279 if ( my $error = delete $self->{_write_error} ) {
280 DEBUG && warn "Write error: $error\n";
285 $daemon->close if defined $pid;
288 my $sockdata = $self->_socket_data( \*Remote );
289 my $ipaddr = _inet_addr( $sockdata->{peeraddr} );
291 foreach my $ip ( keys %$allowed ) {
292 my $mask = $allowed->{$ip};
293 $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
302 exit if defined $pid;
311 DEBUG && warn "Shutting down\n";
314 $SIG{CHLD} = 'DEFAULT';
317 ### if the standalone server was invoked with perl -I .. we will loose
318 ### those include dirs upon re-exec. So add them to PERL5LIB, so they
319 ### are available again for the exec'ed process --kane
321 $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
323 exec $^X . ' "' . $0 . '" ' . join( ' ', @{ $options->{argv} } );
330 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
332 local *STDIN = \*Remote;
333 local *STDOUT = \*Remote;
335 # We better be careful and just use 1.0
338 my $sockdata = $self->_socket_data( \*Remote );
339 my %copy_of_env = %ENV;
341 my $sel = IO::Select->new;
342 $sel->add( \*STDIN );
345 # Initialize CGI environment
347 PATH_INFO => $path || '',
348 QUERY_STRING => $query_string || '',
349 REMOTE_ADDR => $sockdata->{peeraddr},
350 REMOTE_HOST => $sockdata->{peername},
351 REQUEST_METHOD => $method || '',
352 SERVER_NAME => $sockdata->{localname},
353 SERVER_PORT => $port,
354 SERVER_PROTOCOL => "HTTP/$protocol",
358 # Initialize CGI environment
360 PATH_INFO => $path || '',
361 QUERY_STRING => $query_string || '',
362 REMOTE_ADDR => $sockdata->{peeraddr},
363 REMOTE_HOST => $sockdata->{peername},
364 REQUEST_METHOD => $method || '',
365 SERVER_NAME => $sockdata->{localname},
366 SERVER_PORT => $port,
367 SERVER_PROTOCOL => "HTTP/$protocol",
372 if ( $protocol >= 1 ) {
373 $self->_parse_headers;
376 # Pass flow control to Catalyst
377 $class->handle_request;
379 DEBUG && warn "Request done\n";
381 # XXX: We used to have a hack for keep-alive here but keep-alive
382 # has no place in a single-tasking server like this. Use HTTP::POE
383 # if you want keep-alive.
388 sub _parse_request_line {
392 if ( $self->{inputbuf} !~ s/^(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
398 my $proto = $3 || 'HTTP/0.9';
400 return ( $method, $uri, $proto );
406 # Copy the buffer for header parsing, and remove the header block
407 # from the content buffer.
408 my $buf = $self->{inputbuf};
409 $self->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s;
412 my $headers = HTTP::Headers->new;
415 while ( $buf =~ s/^([^\012]*)\012// ) {
418 if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
419 $headers->push_header( $key, $val ) if $key;
420 ($key, $val) = ($1, $2);
422 elsif ( /^\s+(.*)/ ) {
429 $headers->push_header( $key, $val ) if $key;
431 DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
433 # Convert headers into ENV vars
434 $headers->scan( sub {
435 my ( $key, $val ) = @_;
438 $key = 'COOKIE' if $key eq 'COOKIES';
440 $key = 'HTTP_' . $key
441 unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
443 if ( exists $ENV{$key} ) {
444 $ENV{$key} .= ", $val";
453 my ( $self, $handle ) = @_;
455 my $remote_sockaddr = getpeername($handle);
456 my ( undef, $iaddr ) = $remote_sockaddr
457 ? sockaddr_in($remote_sockaddr)
460 my $local_sockaddr = getsockname($handle);
461 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
463 # This mess is necessary to keep IE from crashing the server
466 ? ( gethostbyaddr( $iaddr, AF_INET ) || 'localhost' )
469 ? ( inet_ntoa($iaddr) || '127.0.0.1' )
471 localname => gethostbyaddr( $localiaddr, AF_INET ) || 'localhost',
472 localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
478 sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
482 L<Catalyst>, L<Catalyst::Engine>.
486 Sebastian Riedel, <sri@cpan.org>
488 Dan Kubb, <dan.kubb-cpan@onautopilot.com>
490 Sascha Kiefer, <esskar@cpan.org>
492 Andy Grundman, <andy@hybridized.org>
496 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
500 This program is free software, you can redistribute it and/or modify it under
501 the same terms as Perl itself.