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