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