(no commit message)
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Engine / HTTP.pm
1 package Catalyst::Engine::HTTP;
2
3 use strict;
4 use base 'Catalyst::Engine::CGI';
5 use Data::Dump qw(dump);
6 use Errno 'EWOULDBLOCK';
7 use HTTP::Date ();
8 use HTTP::Headers;
9 use HTTP::Status;
10 use NEXT;
11 use Socket;
12 use IO::Socket::INET ();
13 use IO::Select       ();
14
15 # For PAR
16 require Catalyst::Engine::HTTP::Restarter;
17 require Catalyst::Engine::HTTP::Restarter::Watcher;
18
19 use constant CHUNKSIZE => 64 * 1024;
20 use constant DEBUG     => $ENV{CATALYST_HTTP_DEBUG} || 0;
21
22 =head1 NAME
23
24 Catalyst::Engine::HTTP - Catalyst HTTP Engine
25
26 =head1 SYNOPSIS
27
28 A script using the Catalyst::Engine::HTTP module might look like:
29
30     #!/usr/bin/perl -w
31
32     BEGIN {  $ENV{CATALYST_ENGINE} = 'HTTP' }
33
34     use strict;
35     use lib '/path/to/MyApp/lib';
36     use MyApp;
37
38     MyApp->run;
39
40 =head1 DESCRIPTION
41
42 This is the Catalyst engine specialized for development and testing.
43
44 =head1 METHODS
45
46 =head2 $self->finalize_headers($c)
47
48 =cut
49
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     
56     my @headers;
57     push @headers, "$protocol $status $message";
58     
59     $c->response->headers->header( Date => HTTP::Date::time2str(time) );
60     $c->response->headers->header( Connection => 'close' );
61     $c->response->headers->header( Status => $status );
62     
63     push @headers, $c->response->headers->as_string("\x0D\x0A");
64     
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, '');
68 }
69
70 =head2 $self->finalize_read($c)
71
72 =cut
73
74 sub finalize_read {
75     my ( $self, $c ) = @_;
76
77     # Never ever remove this, it would result in random length output
78     # streams if STDIN eq STDOUT (like in the HTTP engine)
79     *STDIN->blocking(1);
80
81     return $self->NEXT::finalize_read($c);
82 }
83
84 =head2 $self->prepare_read($c)
85
86 =cut
87
88 sub prepare_read {
89     my ( $self, $c ) = @_;
90
91     # Set the input handle to non-blocking
92     *STDIN->blocking(0);
93
94     return $self->NEXT::prepare_read($c);
95 }
96
97 =head2 $self->read_chunk($c, $buffer, $length)
98
99 =cut
100
101 sub read_chunk {
102     my $self = shift;
103     my $c    = shift;
104     
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";
109         return $read;
110     }
111
112     # support for non-blocking IO
113     my $rin = '';
114     vec( $rin, *STDIN->fileno, 1 ) = 1;
115
116   READ:
117     {
118         select( $rin, undef, undef, undef );
119         my $rc = *STDIN->sysread(@_);
120         if ( defined $rc ) {
121             DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
122             return $rc;
123         }
124         else {
125             next READ if $! == EWOULDBLOCK;
126             return;
127         }
128     }
129 }
130
131 =head2 $self->write($c, $buffer)
132
133 Writes the buffer to the client. Can only be called once for a request.
134
135 =cut
136
137 sub write {
138     my ( $self, $c, $buffer ) = @_;
139     
140         # Avoid 'print() on closed filehandle Remote' warnings when using IE
141         return unless *STDOUT->opened();
142         
143         my $ret;
144         
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 );
149     }
150     else {
151         DEBUG && warn "write: Wrote chunk (" . length($buffer) . " bytes)\n";
152         $ret = $self->NEXT::write( $c, $buffer );
153     }
154     
155     if ( !$ret ) {
156         $self->{_write_error} = $!;
157     }
158     
159     return $ret;
160 }
161
162 =head2 run
163
164 =cut
165
166 # A very very simple HTTP server that initializes a CGI environment
167 sub run {
168     my ( $self, $class, $port, $host, $options ) = @_;
169
170     $options ||= {};
171     
172     $self->{options} = $options;
173
174     if ($options->{background}) {
175         my $child = fork;
176         die "Can't fork: $!" unless defined($child);
177         exit if $child;
178     }
179
180     my $restart = 0;
181     local $SIG{CHLD} = 'IGNORE';
182
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();
188     }
189     else {
190         $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
191     }
192
193     # Handle requests
194
195     # Setup socket
196     my $daemon = IO::Socket::INET->new(
197         Listen    => SOMAXCONN,
198         LocalAddr => inet_ntoa($addr),
199         LocalPort => $port,
200         Proto     => 'tcp',
201         ReuseAddr => 1,
202         Type      => SOCK_STREAM,
203       )
204       or die "Couldn't create daemon: $!";
205
206     my $url = "http://$host";
207     $url .= ":$port" unless $port == 80;
208
209     print "You can connect to your server at $url\n";
210
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/ ) {
216              require POSIX;
217              POSIX::setsid()
218                  or die "Can't start a new session: $!";
219         }
220     }
221
222     if (my $pidfile = $options->{pidfile}) {
223         if (! open PIDFILE, "> $pidfile") {
224             warn("Cannot open: $pidfile: $!");
225         }
226         print PIDFILE "$$\n";
227         close PIDFILE;
228     }
229
230     my $pid = undef;
231     
232     # Ignore broken pipes as an HTTP server should
233     local $SIG{PIPE} = 'IGNORE';
234     
235     # Restart on HUP
236     local $SIG{HUP} = sub { 
237         $restart = 1;
238         warn "Restarting server on SIGHUP...\n";
239     };
240     
241     LISTEN:
242     while ( !$restart ) {
243         while ( accept( Remote, $daemon ) ) {        
244             DEBUG && warn "New connection\n";
245
246             select Remote;
247
248             Remote->blocking(1);
249         
250             # Read until we see a newline
251             $self->{inputbuf} = '';
252         
253             while (1) {
254                 my $read = sysread Remote, my $buf, CHUNKSIZE;
255             
256                 if ( !$read ) {
257                     DEBUG && warn "EOF or error: $!\n";
258                     next LISTEN;
259                 }
260             
261                 DEBUG && warn "Read $read bytes\n";
262                 $self->{inputbuf} .= $buf;
263                 last if $self->{inputbuf} =~ /(\x0D\x0A?|\x0A\x0D?)/s;
264             }
265
266             my ( $method, $uri, $protocol ) = $self->_parse_request_line;
267         
268             DEBUG && warn "Parsed request: $method $uri $protocol\n";
269         
270             next unless $method;
271
272             unless ( uc($method) eq 'RESTART' ) {
273
274                 # Fork
275                 if ( $options->{fork} ) { next if $pid = fork }
276
277                 $self->_handler( $class, $port, $method, $uri, $protocol );
278             
279                 if ( my $error = delete $self->{_write_error} ) {
280                     DEBUG && warn "Write error: $error\n";
281                     close Remote;
282                     next LISTEN;
283                 }
284
285                 $daemon->close if defined $pid;
286             }
287             else {
288                 my $sockdata = $self->_socket_data( \*Remote );
289                 my $ipaddr   = _inet_addr( $sockdata->{peeraddr} );
290                 my $ready    = 0;
291                 foreach my $ip ( keys %$allowed ) {
292                     my $mask = $allowed->{$ip};
293                     $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
294                     last if $ready;
295                 }
296                 if ($ready) {
297                     $restart = 1;
298                     last;
299                 }
300             }
301
302             exit if defined $pid;
303         }
304         continue {
305             close Remote;
306         }
307     }
308     
309     $daemon->close;
310     
311     DEBUG && warn "Shutting down\n";
312
313     if ($restart) {
314         $SIG{CHLD} = 'DEFAULT';
315         wait;
316
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
320         use Config;
321         $ENV{PERL5LIB} .= join $Config{path_sep}, @INC; 
322         
323         exec $^X . ' "' . $0 . '" ' . join( ' ', @{ $options->{argv} } );
324     }
325
326     exit;
327 }
328
329 sub _handler {
330     my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
331
332     local *STDIN  = \*Remote;
333     local *STDOUT = \*Remote;
334
335     # We better be careful and just use 1.0
336     $protocol = '1.0';
337
338     my $sockdata    = $self->_socket_data( \*Remote );
339     my %copy_of_env = %ENV;
340
341     my $sel = IO::Select->new;
342     $sel->add( \*STDIN );
343     
344     REQUEST:
345         # Initialize CGI environment
346         local %ENV = (
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",
355             %copy_of_env,
356         );
357
358     # Initialize CGI environment
359     local %ENV = (
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",
368         %copy_of_env,
369     );
370
371     # Parse headers
372     if ( $protocol >= 1 ) {
373         $self->_parse_headers;
374     }
375
376     # Pass flow control to Catalyst
377     $class->handle_request;
378     
379     DEBUG && warn "Request done\n";
380     
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.
384
385     close Remote;
386 }
387
388 sub _parse_request_line {
389     my $self = shift;
390
391     # Parse request line    
392     if ( $self->{inputbuf} !~ s/^(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
393         return ();
394     }
395     
396     my $method = $1;
397     my $uri    = $2;
398     my $proto  = $3 || 'HTTP/0.9';
399     
400     return ( $method, $uri, $proto );
401 }
402
403 sub _parse_headers {
404     my $self = shift;
405     
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;
410     
411     # Parse headers
412     my $headers = HTTP::Headers->new;
413     my ($key, $val);
414     HEADER:
415     while ( $buf =~ s/^([^\012]*)\012// ) {
416         $_ = $1;
417         s/\015$//;
418         if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
419             $headers->push_header( $key, $val ) if $key;
420             ($key, $val) = ($1, $2);
421         }
422         elsif ( /^\s+(.*)/ ) {
423             $val .= " $1";
424         }
425         else {
426             last HEADER;
427         }
428     }
429     $headers->push_header( $key, $val ) if $key;
430     
431     DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
432
433     # Convert headers into ENV vars
434     $headers->scan( sub {
435         my ( $key, $val ) = @_;
436         
437         $key = uc $key;
438         $key = 'COOKIE' if $key eq 'COOKIES';
439         $key =~ tr/-/_/;
440         $key = 'HTTP_' . $key
441             unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
442             
443         if ( exists $ENV{$key} ) {
444             $ENV{$key} .= ", $val";
445         }
446         else {
447             $ENV{$key} = $val;
448         }
449     } );
450 }
451
452 sub _socket_data {
453     my ( $self, $handle ) = @_;
454
455     my $remote_sockaddr       = getpeername($handle);
456     my ( undef, $iaddr )      = $remote_sockaddr 
457         ? sockaddr_in($remote_sockaddr) 
458         : (undef, undef);
459         
460     my $local_sockaddr        = getsockname($handle);
461     my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
462
463     # This mess is necessary to keep IE from crashing the server
464     my $data = {
465         peername  => $iaddr 
466             ? ( gethostbyaddr( $iaddr, AF_INET ) || 'localhost' )
467             : 'localhost',
468         peeraddr  => $iaddr 
469             ? ( inet_ntoa($iaddr) || '127.0.0.1' )
470             : '127.0.0.1',
471         localname => gethostbyaddr( $localiaddr, AF_INET ) || 'localhost',
472         localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
473     };
474
475     return $data;
476 }
477
478 sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
479
480 =head1 SEE ALSO
481
482 L<Catalyst>, L<Catalyst::Engine>.
483
484 =head1 AUTHORS
485
486 Sebastian Riedel, <sri@cpan.org>
487
488 Dan Kubb, <dan.kubb-cpan@onautopilot.com>
489
490 Sascha Kiefer, <esskar@cpan.org>
491
492 Andy Grundman, <andy@hybridized.org>
493
494 =head1 THANKS
495
496 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
497
498 =head1 COPYRIGHT
499
500 This program is free software, you can redistribute it and/or modify it under
501 the same terms as Perl itself.
502
503 =cut
504
505 1;