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