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