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