Fixed run-on sentence in COPYRIGHT and s/program/library/
[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 use namespace::clean -except => 'meta';
23
24 has options => ( is => 'rw' );
25 has _keepalive => ( is => 'rw', predicate => '_is_keepalive', clearer => '_clear_keepalive' );
26 has _write_error => ( is => 'rw', predicate => '_has_write_error' );
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     $port = $daemon->sockport();
222
223     my $url = "http://$host";
224     $url .= ":$port" unless $port == 80;
225
226     print "You can connect to your server at $url\n";
227
228     if ($options->{background}) {
229         open STDIN,  "+</dev/null" or die $!;
230         open STDOUT, ">&STDIN"     or die $!;
231         open STDERR, ">&STDIN"     or die $!;
232         if ( $^O !~ /MSWin32/ ) {
233              require POSIX;
234              POSIX::setsid()
235                  or die "Can't start a new session: $!";
236         }
237     }
238
239     if (my $pidfile = $options->{pidfile}) {
240         if (! open PIDFILE, "> $pidfile") {
241             warn("Cannot open: $pidfile: $!");
242         }
243         print PIDFILE "$$\n";
244         close PIDFILE;
245     }
246
247     my $pid = undef;
248
249     # Ignore broken pipes as an HTTP server should
250     local $SIG{PIPE} = 'IGNORE';
251
252     # Restart on HUP
253     local $SIG{HUP} = sub {
254         $restart = 1;
255         warn "Restarting server on SIGHUP...\n";
256     };
257
258     LISTEN:
259     while ( !$restart ) {
260         while ( accept( Remote, $daemon ) ) {
261             DEBUG && warn "New connection\n";
262
263             select Remote;
264
265             Remote->blocking(1);
266
267             # Read until we see all headers
268             $self->{inputbuf} = '';
269
270             if ( !$self->_read_headers ) {
271                 # Error reading, give up
272                 close Remote;
273                 next LISTEN;
274             }
275
276             my ( $method, $uri, $protocol ) = $self->_parse_request_line;
277
278             DEBUG && warn "Parsed request: $method $uri $protocol\n";
279             next unless $method;
280
281             unless ( uc($method) eq 'RESTART' ) {
282
283                 # Fork
284                 if ( $options->{fork} ) {
285                     if ( $pid = fork ) {
286                         DEBUG && warn "Forked child $pid\n";
287                         next;
288                     }
289                 }
290
291                 $self->_handler( $class, $port, $method, $uri, $protocol );
292
293                 if ( $self->_has_write_error ) {
294                     close Remote;
295
296                     if ( !defined $pid ) {
297                         next LISTEN;
298                     }
299                 }
300
301                 if ( defined $pid ) {
302                     # Child process, close connection and exit
303                     DEBUG && warn "Child process exiting\n";
304                     $daemon->close;
305                     exit;
306                 }
307             }
308             else {
309                 my $sockdata = $self->_socket_data( \*Remote );
310                 my $ipaddr   = _inet_addr( $sockdata->{peeraddr} );
311                 my $ready    = 0;
312                 foreach my $ip ( keys %$allowed ) {
313                     my $mask = $allowed->{$ip};
314                     $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
315                     last if $ready;
316                 }
317                 if ($ready) {
318                     $restart = 1;
319                     last;
320                 }
321             }
322         }
323         continue {
324             close Remote;
325         }
326     }
327
328     $daemon->close;
329
330     DEBUG && warn "Shutting down\n";
331
332     if ($restart) {
333         $SIG{CHLD} = 'DEFAULT';
334         wait;
335
336         ### if the standalone server was invoked with perl -I .. we will loose
337         ### those include dirs upon re-exec. So add them to PERL5LIB, so they
338         ### are available again for the exec'ed process --kane
339         use Config;
340         $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
341
342         exec $^X, $0, @{ $options->{argv} };
343     }
344
345     exit;
346 }
347
348 sub _handler {
349     my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
350
351     local *STDIN  = \*Remote;
352     local *STDOUT = \*Remote;
353
354     # We better be careful and just use 1.0
355     $protocol = '1.0';
356
357     my $sockdata    = $self->_socket_data( \*Remote );
358     my %copy_of_env = %ENV;
359
360     my $sel = IO::Select->new;
361     $sel->add( \*STDIN );
362     
363     REQUEST:
364     while (1) {
365         my ( $path, $query_string ) = split /\?/, $uri, 2;
366         
367         # Initialize CGI environment
368         local %ENV = (
369             PATH_INFO       => $path         || '',
370             QUERY_STRING    => $query_string || '',
371             REMOTE_ADDR     => $sockdata->{peeraddr},
372             REQUEST_METHOD  => $method || '',
373             SERVER_NAME     => $sockdata->{localname},
374             SERVER_PORT     => $port,
375             SERVER_PROTOCOL => "HTTP/$protocol",
376             %copy_of_env,
377         );
378
379         # Parse headers
380         if ( $protocol >= 1 ) {
381             $self->_parse_headers;
382         }
383
384         # Pass flow control to Catalyst
385         {
386             # FIXME: don't ignore SIGCHLD while handling requests so system()
387             # et al. work within actions. it might be a little risky to do that
388             # this far out, but then again it's only the dev server anyway.
389             local $SIG{CHLD} = 'DEFAULT';
390
391             $class->handle_request( env => \%ENV );
392         }
393     
394         DEBUG && warn "Request done\n";
395     
396         # Allow keepalive requests, this is a hack but we'll support it until
397         # the next major release.
398         if ( $self->_is_keepalive ) {
399             $self->_clear_keepalive;
400             
401             DEBUG && warn "Reusing previous connection for keep-alive request\n";
402             
403             if ( $sel->can_read(1) ) {            
404                 if ( !$self->_read_headers ) {
405                     # Error reading, give up
406                     last REQUEST;
407                 }
408
409                 ( $method, $uri, $protocol ) = $self->_parse_request_line;
410                 
411                 DEBUG && warn "Parsed request: $method $uri $protocol\n";
412                 
413                 # Force HTTP/1.0
414                 $protocol = '1.0';
415                 
416                 next REQUEST;
417             }
418             
419             DEBUG && warn "No keep-alive request within 1 second\n";
420         }
421         
422         last REQUEST;
423     }
424     
425     DEBUG && warn "Closing connection\n";
426
427     close Remote;
428 }
429
430 sub _read_headers {
431     my $self = shift;
432
433     while (1) {
434         my $read = sysread Remote, my $buf, CHUNKSIZE;
435
436         if ( !defined $read ) {
437             next if $! == EWOULDBLOCK;
438             DEBUG && warn "Error reading headers: $!\n";
439             return;
440         } elsif ( $read == 0 ) {
441             DEBUG && warn "EOF\n";
442             return;
443         }
444
445         DEBUG && warn "Read $read bytes\n";
446         $self->{inputbuf} .= $buf;
447         last if $self->{inputbuf} =~ /(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)/s;
448     }
449
450     return 1;
451 }
452
453 sub _parse_request_line {
454     my $self = shift;
455
456     # Parse request line
457     # Leading CRLF sometimes sent by buggy IE versions
458     if ( $self->{inputbuf} !~ s/^(?:\x0D\x0A)?(\w+)[ \t]+(\S+)(?:[ \t]+(HTTP\/\d+\.\d+))?[^\012]*\012// ) {
459         return ();
460     }
461
462     my $method = $1;
463     my $uri    = $2;
464     my $proto  = $3 || 'HTTP/0.9';
465
466     return ( $method, $uri, $proto );
467 }
468
469 sub _parse_headers {
470     my $self = shift;
471
472     # Copy the buffer for header parsing, and remove the header block
473     # from the content buffer.
474     my $buf = $self->{inputbuf};
475     $self->{inputbuf} =~ s/.*?(\x0D\x0A?\x0D\x0A?|\x0A\x0D?\x0A\x0D?)//s;
476
477     # Parse headers
478     my $headers = HTTP::Headers->new;
479     my ($key, $val);
480     HEADER:
481     while ( $buf =~ s/^([^\012]*)\012// ) {
482         $_ = $1;
483         s/\015$//;
484         if ( /^([\w\-~]+)\s*:\s*(.*)/ ) {
485             $headers->push_header( $key, $val ) if $key;
486             ($key, $val) = ($1, $2);
487         }
488         elsif ( /^\s+(.*)/ ) {
489             $val .= " $1";
490         }
491         else {
492             last HEADER;
493         }
494     }
495     $headers->push_header( $key, $val ) if $key;
496     
497     DEBUG && warn "Parsed headers: " . dump($headers) . "\n";
498
499     # Convert headers into ENV vars
500     $headers->scan( sub {
501         my ( $key, $val ) = @_;
502         
503         $key = uc $key;
504         $key = 'COOKIE' if $key eq 'COOKIES';
505         $key =~ tr/-/_/;
506         $key = 'HTTP_' . $key
507             unless $key =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
508             
509         if ( exists $ENV{$key} ) {
510             $ENV{$key} .= ", $val";
511         }
512         else {
513             $ENV{$key} = $val;
514         }
515     } );
516 }
517
518 sub _socket_data {
519     my ( $self, $handle ) = @_;
520
521     my $remote_sockaddr       = getpeername($handle);
522     my ( undef, $iaddr )      = $remote_sockaddr 
523         ? sockaddr_in($remote_sockaddr) 
524         : (undef, undef);
525         
526     my $local_sockaddr        = getsockname($handle);
527     my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
528
529     # This mess is necessary to keep IE from crashing the server
530     my $data = {
531         peeraddr  => $iaddr 
532             ? ( inet_ntoa($iaddr) || '127.0.0.1' )
533             : '127.0.0.1',
534         localname => gethostbyaddr( $localiaddr, AF_INET ) || 'localhost',
535         localaddr => inet_ntoa($localiaddr) || '127.0.0.1',
536     };
537
538     return $data;
539 }
540
541 sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
542
543 =head2 options
544
545 Options hash passed to the http engine to control things like if keepalive
546 is supported.
547
548 =head1 SEE ALSO
549
550 L<Catalyst>, L<Catalyst::Engine>
551
552 =head1 AUTHORS
553
554 Catalyst Contributors, see Catalyst.pm
555
556 =head1 THANKS
557
558 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
559
560 =head1 COPYRIGHT
561
562 This library is free software. You can redistribute it and/or modify it under
563 the same terms as Perl itself.
564
565 =cut
566
567 1;