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