1 package Catalyst::Engine::HTTP;
4 use base 'Catalyst::Engine::CGI';
5 use Data::Dump qw(dump);
6 use Errno 'EWOULDBLOCK';
11 use IO::Socket::INET ();
15 require Catalyst::Engine::HTTP::Restarter;
16 require Catalyst::Engine::HTTP::Restarter::Watcher;
18 sub CHUNKSIZE () { 64 * 1024 }
20 sub 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);
56 print "$protocol $status $message\015\012";
58 $c->response->headers->header( Date => HTTP::Date::time2str(time) );
59 $c->response->headers->header(
60 Connection => $self->_keep_alive ? 'keep-alive' : 'close' );
62 $c->response->headers->header( Status => $status );
64 # Avoid 'print() on closed filehandle Remote' warnings when using IE
65 print $c->response->headers->as_string("\015\012") if *STDOUT->opened();
66 print "\015\012" if *STDOUT->opened();
69 =head2 $self->finalize_read($c)
74 my ( $self, $c ) = @_;
76 # Never ever remove this, it would result in random length output
77 # streams if STDIN eq STDOUT (like in the HTTP engine)
80 return $self->NEXT::finalize_read($c);
83 =head2 $self->prepare_read($c)
88 my ( $self, $c ) = @_;
90 # Set the input handle to non-blocking
93 return $self->NEXT::prepare_read($c);
96 =head2 $self->read_chunk($c, $buffer, $length)
104 # If we have any remaining data in the input buffer, send it back first
105 if ( $_[0] = delete $self->{inputbuf} ) {
106 my $read = length( $_[0] );
107 DEBUG && warn "read_chunk: Read $read bytes from previous input buffer\n";
111 # support for non-blocking IO
113 vec( $rin, *STDIN->fileno, 1 ) = 1;
117 select( $rin, undef, undef, undef );
118 my $rc = *STDIN->sysread(@_);
120 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
124 next READ if $! == EWOULDBLOCK;
130 =head2 $self->write($c, $buffer)
132 Writes the buffer to the client. Can only be called once for a request.
137 my ( $self, $c, $buffer ) = @_;
139 # Avoid 'print() on closed filehandle Remote' warnings when using IE
140 return unless *STDOUT->opened();
144 # Prepend the headers if they have not yet been sent
145 if ( my $headers = delete $self->{_header_buf} ) {
146 DEBUG && warn "write: Wrote headers and first chunk (" . length($headers . $buffer) . " bytes)\n";
147 $ret = $self->NEXT::write( $c, $headers . $buffer );
150 DEBUG && warn "write: Wrote chunk (" . length($buffer) . " bytes)\n";
151 $ret = $self->NEXT::write( $c, $buffer );
155 $self->{_write_error} = $!;
165 # A very very simple HTTP server that initializes a CGI environment
167 my ( $self, $class, $port, $host, $options ) = @_;
171 $self->{options} = $options;
173 if ($options->{background}) {
175 die "Can't fork: $!" unless defined($child);
180 local $SIG{CHLD} = 'IGNORE';
182 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
183 my $addr = $host ? inet_aton($host) : INADDR_ANY;
184 if ( $addr eq INADDR_ANY ) {
185 require Sys::Hostname;
186 $host = lc Sys::Hostname::hostname();
189 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
195 my $daemon = IO::Socket::INET->new(
197 LocalAddr => inet_ntoa($addr),
203 or die "Couldn't create daemon: $!";
205 my $url = "http://$host";
206 $url .= ":$port" unless $port == 80;
208 print "You can connect to your server at $url\n";
210 if ($options->{background}) {
211 open STDIN, "+</dev/null" or die $!;
212 open STDOUT, ">&STDIN" or die $!;
213 open STDERR, ">&STDIN" or die $!;
214 if ( $^O !~ /MSWin32/ ) {
217 or die "Can't start a new session: $!";
221 if (my $pidfile = $options->{pidfile}) {
222 if (! open PIDFILE, "> $pidfile") {
223 warn("Cannot open: $pidfile: $!");
225 print PIDFILE "$$\n";
231 # Ignore broken pipes as an HTTP server should
232 local $SIG{PIPE} = 'IGNORE';
235 while ( !$restart ) {
236 while ( accept( Remote, $daemon ) ) {
237 DEBUG && warn "New connection\n";
243 # Read until we see all headers
244 $self->{inputbuf} = '';
246 if ( !$self->_read_headers ) {
247 # Error reading, give up
251 my ( $method, $uri, $protocol ) = $self->_parse_request_line;
253 DEBUG && warn "Parsed request: $method $uri $protocol\n";
257 unless ( uc($method) eq 'RESTART' ) {
260 if ( $options->{fork} ) { next if $pid = fork }
262 $self->_handler( $class, $port, $method, $uri, $protocol );
264 if ( my $error = delete $self->{_write_error} ) {
265 DEBUG && warn "Write error: $error\n";
270 $daemon->close if defined $pid;
273 my $sockdata = $self->_socket_data( \*Remote );
274 my $ipaddr = _inet_addr( $sockdata->{peeraddr} );
276 foreach my $ip ( keys %$allowed ) {
277 my $mask = $allowed->{$ip};
278 $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
287 exit if defined $pid;
296 DEBUG && warn "Shutting down\n";
299 $SIG{CHLD} = 'DEFAULT';
302 ### if the standalone server was invoked with perl -I .. we will loose
303 ### those include dirs upon re-exec. So add them to PERL5LIB, so they
304 ### are available again for the exec'ed process --kane
306 $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
308 exec $^X . ' "' . $0 . '" ' . join( ' ', @{ $options->{argv} } );
315 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
317 local *STDIN = \*Remote;
318 local *STDOUT = \*Remote;
320 # We better be careful and just use 1.0
323 my $sockdata = $self->_socket_data( \*Remote );
324 my %copy_of_env = %ENV;
326 my $sel = IO::Select->new;
327 $sel->add( \*STDIN );
331 my ( $path, $query_string ) = split /\?/, $uri, 2;
333 # Initialize CGI environment
335 PATH_INFO => $path || '',
336 QUERY_STRING => $query_string || '',
337 REMOTE_ADDR => $sockdata->{peeraddr},
338 REMOTE_HOST => $sockdata->{peername},
339 REQUEST_METHOD => $method || '',
340 SERVER_NAME => $sockdata->{localname},
341 SERVER_PORT => $port,
342 SERVER_PROTOCOL => "HTTP/$protocol",
347 if ( $protocol >= 1 ) {
348 $self->_parse_headers;
351 # Pass flow control to Catalyst
352 $class->handle_request;
354 DEBUG && warn "Request done\n";
356 # Allow keepalive requests, this is a hack but we'll support it until
357 # the next major release.
358 if ( delete $self->{_keepalive} ) {
360 DEBUG && warn "Reusing previous connection for keep-alive request\n";
362 if ( $sel->can_read(1) ) {
363 if ( !$self->_read_headers ) {
364 # Error reading, give up
368 ( $method, $uri, $protocol ) = $self->_parse_request_line;
370 DEBUG && warn "Parsed request: $method $uri $protocol\n";
378 DEBUG && warn "No keep-alive request within 1 second\n";
384 DEBUG && warn "Closing connection\n";
393 my $read = sysread Remote, my $buf, CHUNKSIZE;
396 DEBUG && warn "EOF or error: $!\n";
400 DEBUG && warn "Read $read bytes\n";
401 $self->{inputbuf} .= $buf;
402 last if $self->{inputbuf} =~ /(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)/s;
408 sub _parse_request_line {
412 if ( $self->{inputbuf} !~ s/^(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
418 my $proto = $3 || 'HTTP/0.9';
420 return ( $method, $uri, $proto );
426 # Copy the buffer for header parsing, and remove the header block
427 # from the content buffer.
428 my $buf = $self->{inputbuf};
429 $self->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s;
432 my $headers = HTTP::Headers->new;
435 while ( $buf =~ s/^([^\012]*)\012// ) {
438 if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
439 $headers->push_header( $key, $val ) if $key;
440 ($key, $val) = ($1, $2);
442 elsif ( /^\s+(.*)/ ) {
449 $headers->push_header( $key, $val ) if $key;
451 DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
453 # Convert headers into ENV vars
454 $headers->scan( sub {
455 my ( $key, $val ) = @_;
458 $key = 'COOKIE' if $key eq 'COOKIES';
460 $key = 'HTTP_' . $key
461 unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
463 if ( exists $ENV{$key} ) {
464 $ENV{$key} .= ", $val";
473 my ( $self, $handle ) = @_;
475 my $remote_sockaddr = getpeername($handle);
476 my ( undef, $iaddr ) = $remote_sockaddr
477 ? sockaddr_in($remote_sockaddr)
480 my $local_sockaddr = getsockname($handle);
481 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
483 # This mess is necessary to keep IE from crashing the server
486 ? ( gethostbyaddr( $iaddr, AF_INET ) || 'localhost' )
489 ? ( inet_ntoa($iaddr) || '127.0.0.1' )
491 localname => gethostbyaddr( $localiaddr, AF_INET ) || 'localhost',
492 localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
498 sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
502 L<Catalyst>, L<Catalyst::Engine>.
506 Sebastian Riedel, <sri@cpan.org>
508 Dan Kubb, <dan.kubb-cpan@onautopilot.com>
510 Sascha Kiefer, <esskar@cpan.org>
512 Andy Grundman, <andy@hybridized.org>
516 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
520 This program is free software, you can redistribute it and/or modify it under
521 the same terms as Perl itself.