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