push Dev check to compile time (in BEGIN)
[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';
5use Errno 'EWOULDBLOCK';
6use HTTP::Status;
7use NEXT;
8use Socket;
6c7a1d2f 9use IO::Socket::INET ();
b5ecfcf0 10use IO::Select ();
45374ac6 11
71fd2e0f 12# For PAR
13require Catalyst::Engine::HTTP::Restarter;
14require Catalyst::Engine::HTTP::Restarter::Watcher;
15
45374ac6 16=head1 NAME
17
ca61af20 18Catalyst::Engine::HTTP - Catalyst HTTP Engine
45374ac6 19
20=head1 SYNOPSIS
21
ca61af20 22A script using the Catalyst::Engine::HTTP module might look like:
45374ac6 23
24 #!/usr/bin/perl -w
25
ca61af20 26 BEGIN { $ENV{CATALYST_ENGINE} = 'HTTP' }
45374ac6 27
28 use strict;
29 use lib '/path/to/MyApp/lib';
30 use MyApp;
31
32 MyApp->run;
33
34=head1 DESCRIPTION
35
36This is the Catalyst engine specialized for development and testing.
37
fbcc39ad 38=head1 METHODS
39
b5ecfcf0 40=head2 $self->finalize_headers($c)
fbcc39ad 41
42=cut
43
44sub finalize_headers {
45 my ( $self, $c ) = @_;
46 my $protocol = $c->request->protocol;
47 my $status = $c->response->status;
48 my $message = status_message($status);
49 print "$protocol $status $message\015\012";
50 $c->response->headers->date(time);
6c7a1d2f 51 $c->response->headers->header(
52 Connection => $self->_keep_alive ? 'keep-alive' : 'close' );
fbcc39ad 53 $self->NEXT::finalize_headers($c);
54}
55
b5ecfcf0 56=head2 $self->finalize_read($c)
fbcc39ad 57
58=cut
59
60sub finalize_read {
61 my ( $self, $c ) = @_;
62
63 # Never ever remove this, it would result in random length output
64 # streams if STDIN eq STDOUT (like in the HTTP engine)
4f5ebacd 65 *STDIN->blocking(1);
fbcc39ad 66
67 return $self->NEXT::finalize_read($c);
68}
69
b5ecfcf0 70=head2 $self->prepare_read($c)
fbcc39ad 71
72=cut
73
74sub prepare_read {
75 my ( $self, $c ) = @_;
76
77 # Set the input handle to non-blocking
4f5ebacd 78 *STDIN->blocking(0);
fbcc39ad 79
80 return $self->NEXT::prepare_read($c);
81}
82
b5ecfcf0 83=head2 $self->read_chunk($c, $buffer, $length)
fbcc39ad 84
85=cut
86
87sub read_chunk {
88 my $self = shift;
89 my $c = shift;
90
91 # support for non-blocking IO
4f5ebacd 92 my $rin = '';
93 vec( $rin, *STDIN->fileno, 1 ) = 1;
fbcc39ad 94
95 READ:
96 {
97 select( $rin, undef, undef, undef );
4f5ebacd 98 my $rc = *STDIN->sysread(@_);
fbcc39ad 99 if ( defined $rc ) {
100 return $rc;
101 }
102 else {
103 next READ if $! == EWOULDBLOCK;
104 return;
105 }
106 }
107}
108
b5ecfcf0 109=head2 run
fbcc39ad 110
111=cut
112
113# A very very simple HTTP server that initializes a CGI environment
114sub run {
37553dc8 115 my ( $self, $class, $port, $host, $options ) = @_;
fbcc39ad 116
4eeca0f2 117 $options ||= {};
1cf1c56a 118
57a87bb3 119 my $restart = 0;
31b426c0 120 local $SIG{CHLD} = 'IGNORE';
fbcc39ad 121
1cf1c56a 122 my $allowed = $options->{allowed} || { '127.0.0.1' => '255.255.255.255' };
6c7a1d2f 123 my $addr = $host ? inet_aton($host) : INADDR_ANY;
124 if ( $addr eq INADDR_ANY ) {
fbcc39ad 125 require Sys::Hostname;
6c7a1d2f 126 $host = lc Sys::Hostname::hostname();
fbcc39ad 127 }
128 else {
6c7a1d2f 129 $host = gethostbyaddr( $addr, AF_INET ) || inet_ntoa($addr);
fbcc39ad 130 }
6c7a1d2f 131
132 # Handle requests
133
134 # Setup socket
135 my $daemon = IO::Socket::INET->new(
136 Listen => SOMAXCONN,
137 LocalAddr => inet_ntoa($addr),
138 LocalPort => $port,
139 Proto => 'tcp',
140 ReuseAddr => 1,
141 Type => SOCK_STREAM,
142 )
143 or die "Couldn't create daemon: $!";
144
145 my $url = "http://$host";
146 $url .= ":$port" unless $port == 80;
147
fbcc39ad 148 print "You can connect to your server at $url\n";
fbcc39ad 149
6c7a1d2f 150 $self->_keep_alive( $options->{keepalive} || 0 );
151
57a87bb3 152 my $parent = $$;
153 my $pid = undef;
6c7a1d2f 154 while ( accept( Remote, $daemon ) )
155 { # TODO: get while ( my $remote = $daemon->accept ) to work
fbcc39ad 156
57a87bb3 157 select Remote;
fbcc39ad 158
159 # Request data
fbcc39ad 160
57a87bb3 161 Remote->blocking(1);
fbcc39ad 162
fbcc39ad 163 next
164 unless my ( $method, $uri, $protocol ) =
6c7a1d2f 165 $self->_parse_request_line( \*Remote );
fbcc39ad 166
57a87bb3 167 unless ( uc($method) eq 'RESTART' ) {
168
169 # Fork
170 if ( $options->{fork} ) { next if $pid = fork }
171
6c7a1d2f 172 $self->_handler( $class, $port, $method, $uri, $protocol );
173
174 $daemon->close if defined $pid;
fbcc39ad 175
1cf1c56a 176 }
177 else {
6c7a1d2f 178 my $sockdata = $self->_socket_data( \*Remote );
179 my $ipaddr = _inet_addr( $sockdata->{peeraddr} );
180 my $ready = 0;
c82ed742 181 foreach my $ip ( keys %$allowed ) {
182 my $mask = $allowed->{$ip};
1cf1c56a 183 $ready = ( $ipaddr & _inet_addr($mask) ) == _inet_addr($ip);
c82ed742 184 last if $ready;
1cf1c56a 185 }
186 if ($ready) {
57a87bb3 187 $restart = 1;
1cf1c56a 188 last;
189 }
190 }
57a87bb3 191
fbcc39ad 192 exit if defined $pid;
193 }
194 continue {
195 close Remote;
196 }
6c7a1d2f 197 $daemon->close;
37553dc8 198
57a87bb3 199 if ($restart) {
60c38e3e 200 $SIG{CHLD} = 'DEFAULT';
6844bc1c 201 wait;
e37e3977 202
203 ### if the standalone server was invoked with perl -I .. we will loose
204 ### those include dirs upon re-exec. So add them to PERL5LIB, so they
205 ### are available again for the exec'ed process --kane
206 use Config;
207 $ENV{PERL5LIB} .= join $Config{path_sep}, @INC;
208
1cf1c56a 209 exec $^X . ' "' . $0 . '" ' . join( ' ', @{ $options->{argv} } );
60c38e3e 210 }
57a87bb3 211
212 exit;
fbcc39ad 213}
214
6c7a1d2f 215sub _handler {
216 my ( $self, $class, $port, $method, $uri, $protocol ) = @_;
217
218 # Ignore broken pipes as an HTTP server should
219 local $SIG{PIPE} = sub { close Remote };
220
221 local *STDIN = \*Remote;
222 local *STDOUT = \*Remote;
223
224 # We better be careful and just use 1.0
225 $protocol = '1.0';
226
227 my $sockdata = $self->_socket_data( \*Remote );
228 my %copy_of_env = %ENV;
229
230 my $sel = IO::Select->new;
231 $sel->add( \*STDIN );
232
233 while (1) {
234 my ( $path, $query_string ) = split /\?/, $uri, 2;
235
236 # Initialize CGI environment
237 local %ENV = (
b5ecfcf0 238 PATH_INFO => $path || '',
239 QUERY_STRING => $query_string || '',
6c7a1d2f 240 REMOTE_ADDR => $sockdata->{peeraddr},
241 REMOTE_HOST => $sockdata->{peername},
242 REQUEST_METHOD => $method || '',
243 SERVER_NAME => $sockdata->{localname},
244 SERVER_PORT => $port,
245 SERVER_PROTOCOL => "HTTP/$protocol",
246 %copy_of_env,
247 );
248
249 # Parse headers
250 if ( $protocol >= 1 ) {
251 while (1) {
252 my $line = $self->_get_line( \*STDIN );
253 last if $line eq '';
254 next
255 unless my ( $name, $value ) =
256 $line =~ m/\A(\w(?:-?\w+)*):\s(.+)\z/;
257
258 $name = uc $name;
259 $name = 'COOKIE' if $name eq 'COOKIES';
260 $name =~ tr/-/_/;
261 $name = 'HTTP_' . $name
262 unless $name =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
263 if ( exists $ENV{$name} ) {
264 $ENV{$name} .= "; $value";
265 }
266 else {
267 $ENV{$name} = $value;
268 }
269 }
270 }
271
272 # Pass flow control to Catalyst
273 $class->handle_request;
274
275 my $connection = lc $ENV{HTTP_CONNECTION};
276 last
277 unless $self->_keep_alive()
278 && index( $connection, 'keep-alive' ) > -1
279 && index( $connection, 'te' ) == -1 # opera stuff
280 && $sel->can_read(5);
281
282 last
283 unless ( $method, $uri, $protocol ) =
284 $self->_parse_request_line( \*STDIN );
285 }
286
287 close Remote;
288}
289
290sub _keep_alive {
291 my ( $self, $keepalive ) = @_;
292
293 my $r = $self->{_keepalive} || 0;
294 $self->{_keepalive} = $keepalive if defined $keepalive;
295
296 return $r;
297
298}
299
300sub _parse_request_line {
301 my ( $self, $handle ) = @_;
302
303 # Parse request line
304 my $line = $self->_get_line($handle);
305 return ()
306 unless my ( $method, $uri, $protocol ) =
307 $line =~ m/\A(\w+)\s+(\S+)(?:\s+HTTP\/(\d+(?:\.\d+)?))?\z/;
308 return ( $method, $uri, $protocol );
309}
310
311sub _socket_data {
312 my ( $self, $handle ) = @_;
313
314 my $remote_sockaddr = getpeername($handle);
315 my ( undef, $iaddr ) = sockaddr_in($remote_sockaddr);
316 my $local_sockaddr = getsockname($handle);
317 my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
318
319 my $data = {
320 peername => gethostbyaddr( $iaddr, AF_INET ) || "localhost",
321 peeraddr => inet_ntoa($iaddr) || "127.0.0.1",
322 localname => gethostbyaddr( $localiaddr, AF_INET ) || "localhost",
323 localaddr => inet_ntoa($localiaddr) || "127.0.0.1",
324 };
325
326 return $data;
327}
328
fbcc39ad 329sub _get_line {
330 my ( $self, $handle ) = @_;
331
332 my $line = '';
333
334 while ( sysread( $handle, my $byte, 1 ) ) {
335 last if $byte eq "\012"; # eol
336 $line .= $byte;
337 }
338
339 1 while $line =~ s/\s\z//;
340
341 return $line;
342}
343
1cf1c56a 344sub _inet_addr { unpack "N*", inet_aton( $_[0] ) }
345
45374ac6 346=head1 SEE ALSO
347
fbcc39ad 348L<Catalyst>, L<Catalyst::Engine>.
349
350=head1 AUTHORS
351
352Sebastian Riedel, <sri@cpan.org>
353
354Dan Kubb, <dan.kubb-cpan@onautopilot.com>
45374ac6 355
6c7a1d2f 356Sascha Kiefer, <esskar@cpan.org>
357
fbcc39ad 358=head1 THANKS
45374ac6 359
fbcc39ad 360Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
45374ac6 361
362=head1 COPYRIGHT
363
364This program is free software, you can redistribute it and/or modify it under
365the same terms as Perl itself.
366
367=cut
368
45374ac6 3691;