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