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