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