Fix pod coverage on HTTP engine
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Engine / HTTP.pm
CommitLineData
ca61af20 1package Catalyst::Engine::HTTP;
45374ac6 2
3use strict;
fbcc39ad 4use base 'Catalyst::Engine::CGI';
4bb8bd62 5use Data::Dump qw(dump);
fbcc39ad 6use Errno 'EWOULDBLOCK';
055ff026 7use HTTP::Date ();
06744540 8use HTTP::Headers;
fbcc39ad 9use HTTP::Status;
10use NEXT;
11use Socket;
6c7a1d2f 12use IO::Socket::INET ();
b5ecfcf0 13use IO::Select ();
45374ac6 14
71fd2e0f 15# For PAR
16require Catalyst::Engine::HTTP::Restarter;
17require Catalyst::Engine::HTTP::Restarter::Watcher;
18
4bb8bd62 19sub CHUNKSIZE () { 64 * 1024 }
20
21sub DEBUG () { $ENV{CATALYST_HTTP_DEBUG} || 0 }
22
45374ac6 23=head1 NAME
24
ca61af20 25Catalyst::Engine::HTTP - Catalyst HTTP Engine
45374ac6 26
27=head1 SYNOPSIS
28
ca61af20 29A script using the Catalyst::Engine::HTTP module might look like:
45374ac6 30
31 #!/usr/bin/perl -w
32
ca61af20 33 BEGIN { $ENV{CATALYST_ENGINE} = 'HTTP' }
45374ac6 34
35 use strict;
36 use lib '/path/to/MyApp/lib';
37 use MyApp;
38
39 MyApp->run;
40
41=head1 DESCRIPTION
42
43This is the Catalyst engine specialized for development and testing.
44
fbcc39ad 45=head1 METHODS
46
b5ecfcf0 47=head2 $self->finalize_headers($c)
fbcc39ad 48
49=cut
50
51sub finalize_headers {
52 my ( $self, $c ) = @_;
53 my $protocol = $c->request->protocol;
54 my $status = $c->response->status;
55 my $message = status_message($status);
055ff026 56
06744540 57 my @headers;
58 push @headers, "$protocol $status $message";
055ff026 59
60 $c->response->headers->header( Date => HTTP::Date::time2str(time) );
055ff026 61 $c->response->headers->header( Status => $status );
06744540 62
cf26c39c 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
06744540 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, '');
fbcc39ad 81}
82
b5ecfcf0 83=head2 $self->finalize_read($c)
fbcc39ad 84
85=cut
86
87sub 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)
4f5ebacd 92 *STDIN->blocking(1);
fbcc39ad 93
94 return $self->NEXT::finalize_read($c);
95}
96
b5ecfcf0 97=head2 $self->prepare_read($c)
fbcc39ad 98
99=cut
100
101sub prepare_read {
102 my ( $self, $c ) = @_;
103
104 # Set the input handle to non-blocking
4f5ebacd 105 *STDIN->blocking(0);
fbcc39ad 106
107 return $self->NEXT::prepare_read($c);
108}
109
b5ecfcf0 110=head2 $self->read_chunk($c, $buffer, $length)
fbcc39ad 111
112=cut
113
114sub read_chunk {
115 my $self = shift;
116 my $c = shift;
4bb8bd62 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 }
fbcc39ad 124
125 # support for non-blocking IO
4f5ebacd 126 my $rin = '';
127 vec( $rin, *STDIN->fileno, 1 ) = 1;
fbcc39ad 128
129 READ:
130 {
131 select( $rin, undef, undef, undef );
4f5ebacd 132 my $rc = *STDIN->sysread(@_);
fbcc39ad 133 if ( defined $rc ) {
4bb8bd62 134 DEBUG && warn "read_chunk: Read $rc bytes from socket\n";
fbcc39ad 135 return $rc;
136 }
137 else {
138 next READ if $! == EWOULDBLOCK;
139 return;
140 }
141 }
142}
143
00c99324 144=head2 $self->write($c, $buffer)
145
146Writes the buffer to the client. Can only be called once for a request.
147
148=cut
149
150sub write {
4bb8bd62 151 my ( $self, $c, $buffer ) = @_;
152
00c99324 153 # Avoid 'print() on closed filehandle Remote' warnings when using IE
154 return unless *STDOUT->opened();
155
4bb8bd62 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;
00c99324 173}
174
b5ecfcf0 175=head2 run
fbcc39ad 176
177=cut
178
179# A very very simple HTTP server that initializes a CGI environment
180sub run {
37553dc8 181 my ( $self, $class, $port, $host, $options ) = @_;
fbcc39ad 182
4eeca0f2 183 $options ||= {};
3bcb3aae 184
185 $self->{options} = $options;
1cf1c56a 186
e1576f62 187 if ($options->{background}) {
188 my $child = fork;
189 die "Can't fork: $!" unless defined($child);
190 exit if $child;
191 }
192
57a87bb3 193 my $restart = 0;
31b426c0 194 local $SIG{CHLD} = 'IGNORE';
fbcc39ad 195
1cf1c56a 196 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
6c7a1d2f 197 my $addr = $host ? inet_aton($host) : INADDR_ANY;
198 if ( $addr eq INADDR_ANY ) {
fbcc39ad 199 require Sys::Hostname;
6c7a1d2f 200 $host = lc Sys::Hostname::hostname();
fbcc39ad 201 }
202 else {
6c7a1d2f 203 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
fbcc39ad 204 }
6c7a1d2f 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
fbcc39ad 222 print "You can connect to your server at $url\n";
fbcc39ad 223
e1576f62 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
4bb8bd62 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";
fbcc39ad 252
4bb8bd62 253 select Remote;
fbcc39ad 254
4bb8bd62 255 Remote->blocking(1);
256
cf26c39c 257 # Read until we see all headers
4bb8bd62 258 $self->{inputbuf} = '';
4bb8bd62 259
cf26c39c 260 if ( !$self->_read_headers ) {
261 # Error reading, give up
262 next LISTEN;
4bb8bd62 263 }
fbcc39ad 264
4bb8bd62 265 my ( $method, $uri, $protocol ) = $self->_parse_request_line;
266
267 DEBUG && warn "Parsed request: $method $uri $protocol\n";
268
269 next unless $method;
57a87bb3 270
4bb8bd62 271 unless ( uc($method) eq 'RESTART' ) {
57a87bb3 272
4bb8bd62 273 # Fork
274 if ( $options->{fork} ) { next if $pid = fork }
6c7a1d2f 275
4bb8bd62 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 }
fbcc39ad 283
4bb8bd62 284 $daemon->close if defined $pid;
1cf1c56a 285 }
4bb8bd62 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 }
1cf1c56a 299 }
57a87bb3 300
4bb8bd62 301 exit if defined $pid;
302 }
303 continue {
304 close Remote;
305 }
fbcc39ad 306 }
4bb8bd62 307
6c7a1d2f 308 $daemon->close;
4bb8bd62 309
310 DEBUG && warn "Shutting down\n";
37553dc8 311
57a87bb3 312 if ($restart) {
60c38e3e 313 $SIG{CHLD} = 'DEFAULT';
6844bc1c 314 wait;
e37e3977 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
1cf1c56a 322 exec $^X . ' "' . $0 . '" ' . join( ' ', @{ $options->{argv} } );
60c38e3e 323 }
57a87bb3 324
325 exit;
fbcc39ad 326}
327
6c7a1d2f 328sub _handler {
329 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
330
6c7a1d2f 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 );
3bcb3aae 342
343 REQUEST:
cf26c39c 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 }
6c7a1d2f 364
cf26c39c 365 # Pass flow control to Catalyst
366 $class->handle_request;
3bcb3aae 367
cf26c39c 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 }
3bcb3aae 397
cf26c39c 398 DEBUG && warn "Closing connection\n";
06744540 399
400 close Remote;
3bcb3aae 401}
402
cf26c39c 403sub _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
4bb8bd62 422sub _parse_request_line {
423 my $self = shift;
6c7a1d2f 424
4bb8bd62 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 );
6c7a1d2f 435}
436
4bb8bd62 437sub _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";
6c7a1d2f 466
4bb8bd62 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 } );
6c7a1d2f 484}
485
486sub _socket_data {
487 my ( $self, $handle ) = @_;
488
8b9d0298 489 my $remote_sockaddr = getpeername($handle);
3150d774 490 my ( undef, $iaddr ) = $remote_sockaddr
491 ? sockaddr_in($remote_sockaddr)
492 : (undef, undef);
493
8b9d0298 494 my $local_sockaddr = getsockname($handle);
6c7a1d2f 495 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
496
8b9d0298 497 # This mess is necessary to keep IE from crashing the server
6c7a1d2f 498 my $data = {
8b9d0298 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',
6c7a1d2f 507 };
508
509 return $data;
510}
511
1cf1c56a 512sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
513
b794df46 514=head1 CONSTANTS
515
516=head2 CHUNKSIZE
517
518How much data to read at once. This value is set to 64K.
519
520=head2 DEBUG
521
522Enables debugging via the environment variable CATALYST_HTTP_DEBUG.
523
45374ac6 524=head1 SEE ALSO
525
fbcc39ad 526L<Catalyst>, L<Catalyst::Engine>.
527
528=head1 AUTHORS
529
530Sebastian Riedel, <sri@cpan.org>
531
532Dan Kubb, <dan.kubb-cpan@onautopilot.com>
45374ac6 533
6c7a1d2f 534Sascha Kiefer, <esskar@cpan.org>
535
4bb8bd62 536Andy Grundman, <andy@hybridized.org>
537
fbcc39ad 538=head1 THANKS
45374ac6 539
fbcc39ad 540Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
45374ac6 541
542=head1 COPYRIGHT
543
544This program is free software, you can redistribute it and/or modify it under
545the same terms as Perl itself.
546
547=cut
548
45374ac6 5491;