tabs => spaces
[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( Status => $status );
61     
62     # Should we keep the connection open?
63     my $connection = $c->request->header('Connection');
64     if (   $self->{options}->{keepalive} 
65         && $connection 
66         && $connection =~ /^keep-alive$/i
67     ) {
68         $c->response->headers->header( Connection => 'keep-alive' );
69         $self->{_keepalive} = 1;
70     }
71     else {
72         $c->response->headers->header( Connection => 'close' );
73     }
74     
75     push @headers, $c->response->headers->as_string("\x0D\x0A");
76     
77     # Buffer the headers so they are sent with the first write() call
78     # This reduces the number of TCP packets we are sending
79     $self->{_header_buf} = join("\x0D\x0A", @headers, '');
80 }
81
82 =head2 $self->finalize_read($c)
83
84 =cut
85
86 sub finalize_read {
87     my ( $self, $c ) = @_;
88
89     # Never ever remove this, it would result in random length output
90     # streams if STDIN eq STDOUT (like in the HTTP engine)
91     *STDIN->blocking(1);
92
93     return $self->NEXT::finalize_read($c);
94 }
95
96 =head2 $self->prepare_read($c)
97
98 =cut
99
100 sub prepare_read {
101     my ( $self, $c ) = @_;
102
103     # Set the input handle to non-blocking
104     *STDIN->blocking(0);
105
106     return $self->NEXT::prepare_read($c);
107 }
108
109 =head2 $self->read_chunk($c, $buffer, $length)
110
111 =cut
112
113 sub read_chunk {
114     my $self = shift;
115     my $c    = shift;
116     
117     # If we have any remaining data in the input buffer, send it back first
118     if ( $_[0] = delete $self->{inputbuf} ) {
119         my $read = length( $_[0] );
120         DEBUG && warn "read_chunk: Read $read bytes from previous input buffer\n";
121         return $read;
122     }
123
124     # support for non-blocking IO
125     my $rin = '';
126     vec( $rin, *STDIN->fileno, 1 ) = 1;
127
128   READ:
129     {
130         select( $rin, undef, undef, undef );
131         my $rc = *STDIN->sysread(@_);
132         if ( defined $rc ) {
133             DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
134             return $rc;
135         }
136         else {
137             next READ if $! == EWOULDBLOCK;
138             return;
139         }
140     }
141 }
142
143 =head2 $self->write($c, $buffer)
144
145 Writes the buffer to the client. Can only be called once for a request.
146
147 =cut
148
149 sub write {
150     my ( $self, $c, $buffer ) = @_;
151     
152     # Avoid 'print() on closed filehandle Remote' warnings when using IE
153     return unless *STDOUT->opened();
154
155     my $ret;
156
157     # Prepend the headers if they have not yet been sent
158     if ( my $headers = delete $self->{_header_buf} ) {
159         DEBUG && warn "write: Wrote headers and first chunk (" . length($headers . $buffer) . " bytes)\n";
160         $ret = $self->NEXT::write( $c, $headers . $buffer );
161     }
162     else {
163         DEBUG && warn "write: Wrote chunk (" . length($buffer) . " bytes)\n";
164         $ret = $self->NEXT::write( $c, $buffer );
165     }
166     
167     if ( !$ret ) {
168         $self->{_write_error} = $!;
169     }
170     
171     return $ret;
172 }
173
174 =head2 run
175
176 =cut
177
178 # A very very simple HTTP server that initializes a CGI environment
179 sub run {
180     my ( $self, $class, $port, $host, $options ) = @_;
181
182     $options ||= {};
183     
184     $self->{options} = $options;
185
186     if ($options->{background}) {
187         my $child = fork;
188         die "Can't fork: $!" unless defined($child);
189         exit if $child;
190     }
191
192     my $restart = 0;
193     local $SIG{CHLD} = 'IGNORE';
194
195     my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
196     my $addr = $host ? inet_aton($host) : INADDR_ANY;
197     if ( $addr eq INADDR_ANY ) {
198         require Sys::Hostname;
199         $host = lc Sys::Hostname::hostname();
200     }
201     else {
202         $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
203     }
204
205     # Handle requests
206
207     # Setup socket
208     my $daemon = IO::Socket::INET->new(
209         Listen    => SOMAXCONN,
210         LocalAddr => inet_ntoa($addr),
211         LocalPort => $port,
212         Proto     => 'tcp',
213         ReuseAddr => 1,
214         Type      => SOCK_STREAM,
215       )
216       or die "Couldn't create daemon: $!";
217
218     my $url = "http://$host";
219     $url .= ":$port" unless $port == 80;
220
221     print "You can connect to your server at $url\n";
222
223     if ($options->{background}) {
224         open STDIN,  "+</dev/null" or die $!;
225         open STDOUT, ">&STDIN"     or die $!;
226         open STDERR, ">&STDIN"     or die $!;
227         if ( $^O !~ /MSWin32/ ) {
228              require POSIX;
229              POSIX::setsid()
230                  or die "Can't start a new session: $!";
231         }
232     }
233
234     if (my $pidfile = $options->{pidfile}) {
235         if (! open PIDFILE, "> $pidfile") {
236             warn("Cannot open: $pidfile: $!");
237         }
238         print PIDFILE "$$\n";
239         close PIDFILE;
240     }
241
242     my $pid = undef;
243     
244     # Ignore broken pipes as an HTTP server should
245     local $SIG{PIPE} = 'IGNORE';
246     
247     # Restart on HUP
248     local $SIG{HUP} = sub { 
249         $restart = 1;
250         warn "Restarting server on SIGHUP...\n";
251     };
252     
253     LISTEN:
254     while ( !$restart ) {
255         while ( accept( Remote, $daemon ) ) {        
256             DEBUG && warn "New connection\n";
257
258             select Remote;
259
260             Remote->blocking(1);
261         
262             # Read until we see all headers
263             $self->{inputbuf} = '';
264             
265             if ( !$self->_read_headers ) {
266                 # Error reading, give up
267                 next LISTEN;
268             }
269
270             my ( $method, $uri, $protocol ) = $self->_parse_request_line;
271         
272             DEBUG && warn "Parsed request: $method $uri $protocol\n";
273         
274             next unless $method;
275
276             unless ( uc($method) eq 'RESTART' ) {
277
278                 # Fork
279                 if ( $options->{fork} ) { 
280                     if ( $pid = fork ) {
281                         DEBUG && warn "Forked child $pid\n";
282                         next;
283                     }
284                 }
285
286                 $self->_handler( $class, $port, $method, $uri, $protocol );
287             
288                 if ( my $error = delete $self->{_write_error} ) {
289                     DEBUG && warn "Write error: $error\n";
290                     close Remote;
291                     
292                     if ( !defined $pid ) {
293                         next LISTEN;
294                     }
295                 }
296
297                 if ( defined $pid ) {
298                     # Child process, close connection and exit
299                     DEBUG && warn "Child process exiting\n";
300                     $daemon->close;
301                     exit;
302                 }
303             }
304             else {
305                 my $sockdata = $self->_socket_data( \*Remote );
306                 my $ipaddr   = _inet_addr( $sockdata->{peeraddr} );
307                 my $ready    = 0;
308                 foreach my $ip ( keys %$allowed ) {
309                     my $mask = $allowed->{$ip};
310                     $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
311                     last if $ready;
312                 }
313                 if ($ready) {
314                     $restart = 1;
315                     last;
316                 }
317             }
318         }
319         continue {
320             close Remote;
321         }
322     }
323     
324     $daemon->close;
325     
326     DEBUG && warn "Shutting down\n";
327
328     if ($restart) {
329         $SIG{CHLD} = 'DEFAULT';
330         wait;
331
332         ### if the standalone server was invoked with perl -I .. we will loose
333         ### those include dirs upon re-exec. So add them to PERL5LIB, so they
334         ### are available again for the exec'ed process --kane
335         use Config;
336         $ENV{PERL5LIB} .= join $Config{path_sep}, @INC; 
337         
338         exec $^X . ' "' . $0 . '" ' . join( ' ', @{ $options->{argv} } );
339     }
340
341     exit;
342 }
343
344 sub _handler {
345     my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
346
347     local *STDIN  = \*Remote;
348     local *STDOUT = \*Remote;
349
350     # We better be careful and just use 1.0
351     $protocol = '1.0';
352
353     my $sockdata    = $self->_socket_data( \*Remote );
354     my %copy_of_env = %ENV;
355
356     my $sel = IO::Select->new;
357     $sel->add( \*STDIN );
358     
359     REQUEST:
360     while (1) {
361         my ( $path, $query_string ) = split /\?/, $uri, 2;
362         
363         # Initialize CGI environment
364         local %ENV = (
365             PATH_INFO       => $path         || '',
366             QUERY_STRING    => $query_string || '',
367             REMOTE_ADDR     => $sockdata->{peeraddr},
368             REMOTE_HOST     => $sockdata->{peername},
369             REQUEST_METHOD  => $method || '',
370             SERVER_NAME     => $sockdata->{localname},
371             SERVER_PORT     => $port,
372             SERVER_PROTOCOL => "HTTP/$protocol",
373             %copy_of_env,
374         );
375
376         # Parse headers
377         if ( $protocol >= 1 ) {
378             $self->_parse_headers;
379         }
380
381         # Pass flow control to Catalyst
382         $class->handle_request;
383     
384         DEBUG && warn "Request done\n";
385     
386         # Allow keepalive requests, this is a hack but we'll support it until
387         # the next major release.
388         if ( delete $self->{_keepalive} ) {
389             
390             DEBUG && warn "Reusing previous connection for keep-alive request\n";
391             
392             if ( $sel->can_read(1) ) {            
393                 if ( !$self->_read_headers ) {
394                     # Error reading, give up
395                     last REQUEST;
396                 }
397
398                 ( $method, $uri, $protocol ) = $self->_parse_request_line;
399                 
400                 DEBUG && warn "Parsed request: $method $uri $protocol\n";
401                 
402                 # Force HTTP/1.0
403                 $protocol = '1.0';
404                 
405                 next REQUEST;
406             }
407             
408             DEBUG && warn "No keep-alive request within 1 second\n";
409         }
410         
411         last REQUEST;
412     }
413     
414     DEBUG && warn "Closing connection\n";
415
416     close Remote;
417 }
418
419 sub _read_headers {
420     my $self = shift;
421     
422     while (1) {
423         my $read = sysread Remote, my $buf, CHUNKSIZE;
424     
425         if ( !$read ) {
426             DEBUG && warn "EOF or error: $!\n";
427             return;
428         }
429     
430         DEBUG && warn "Read $read bytes\n";
431         $self->{inputbuf} .= $buf;
432         last if $self->{inputbuf} =~ /(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)/s;
433     }
434     
435     return 1;
436 }
437
438 sub _parse_request_line {
439     my $self = shift;
440
441     # Parse request line    
442     if ( $self->{inputbuf} !~ s/^(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
443         return ();
444     }
445     
446     my $method = $1;
447     my $uri    = $2;
448     my $proto  = $3 || 'HTTP/0.9';
449     
450     return ( $method, $uri, $proto );
451 }
452
453 sub _parse_headers {
454     my $self = shift;
455     
456     # Copy the buffer for header parsing, and remove the header block
457     # from the content buffer.
458     my $buf = $self->{inputbuf};
459     $self->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s;
460     
461     # Parse headers
462     my $headers = HTTP::Headers->new;
463     my ($key, $val);
464     HEADER:
465     while ( $buf =~ s/^([^\012]*)\012// ) {
466         $_ = $1;
467         s/\015$//;
468         if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
469             $headers->push_header( $key, $val ) if $key;
470             ($key, $val) = ($1, $2);
471         }
472         elsif ( /^\s+(.*)/ ) {
473             $val .= " $1";
474         }
475         else {
476             last HEADER;
477         }
478     }
479     $headers->push_header( $key, $val ) if $key;
480     
481     DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
482
483     # Convert headers into ENV vars
484     $headers->scan( sub {
485         my ( $key, $val ) = @_;
486         
487         $key = uc $key;
488         $key = 'COOKIE' if $key eq 'COOKIES';
489         $key =~ tr/-/_/;
490         $key = 'HTTP_' . $key
491             unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
492             
493         if ( exists $ENV{$key} ) {
494             $ENV{$key} .= ", $val";
495         }
496         else {
497             $ENV{$key} = $val;
498         }
499     } );
500 }
501
502 sub _socket_data {
503     my ( $self, $handle ) = @_;
504
505     my $remote_sockaddr       = getpeername($handle);
506     my ( undef, $iaddr )      = $remote_sockaddr 
507         ? sockaddr_in($remote_sockaddr) 
508         : (undef, undef);
509         
510     my $local_sockaddr        = getsockname($handle);
511     my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
512
513     # This mess is necessary to keep IE from crashing the server
514     my $data = {
515         peername  => $iaddr 
516             ? ( gethostbyaddr( $iaddr, AF_INET ) || 'localhost' )
517             : 'localhost',
518         peeraddr  => $iaddr 
519             ? ( inet_ntoa($iaddr) || '127.0.0.1' )
520             : '127.0.0.1',
521         localname => gethostbyaddr( $localiaddr, AF_INET ) || 'localhost',
522         localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
523     };
524
525     return $data;
526 }
527
528 sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
529
530 =head1 SEE ALSO
531
532 L<Catalyst>, L<Catalyst::Engine>.
533
534 =head1 AUTHORS
535
536 Sebastian Riedel, <sri@cpan.org>
537
538 Dan Kubb, <dan.kubb-cpan@onautopilot.com>
539
540 Sascha Kiefer, <esskar@cpan.org>
541
542 Andy Grundman, <andy@hybridized.org>
543
544 =head1 THANKS
545
546 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
547
548 =head1 COPYRIGHT
549
550 This program is free software, you can redistribute it and/or modify it under
551 the same terms as Perl itself.
552
553 =cut
554
555 1;