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