Gave options hash a default value to allow older server scripts to still work
[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 FindBin;
7 use File::Find;
8 use File::Spec;
9 use HTTP::Status;
10 use NEXT;
11 use Socket;
12
13 =head1 NAME
14
15 Catalyst::Engine::HTTP - Catalyst HTTP Engine
16
17 =head1 SYNOPSIS
18
19 A script using the Catalyst::Engine::HTTP module might look like:
20
21     #!/usr/bin/perl -w
22
23     BEGIN {  $ENV{CATALYST_ENGINE} = 'HTTP' }
24
25     use strict;
26     use lib '/path/to/MyApp/lib';
27     use MyApp;
28
29     MyApp->run;
30
31 =head1 DESCRIPTION
32
33 This is the Catalyst engine specialized for development and testing.
34
35 =head1 METHODS
36
37 =over 4
38
39 =item $self->finalize_headers($c)
40
41 =cut
42
43 sub finalize_headers {
44     my ( $self, $c ) = @_;
45     my $protocol = $c->request->protocol;
46     my $status   = $c->response->status;
47     my $message  = status_message($status);
48     print "$protocol $status $message\015\012";
49     $c->response->headers->date(time);
50     $self->NEXT::finalize_headers($c);
51 }
52
53 =item $self->finalize_read($c)
54
55 =cut
56
57 sub finalize_read {
58     my ( $self, $c ) = @_;
59
60     # Never ever remove this, it would result in random length output
61     # streams if STDIN eq STDOUT (like in the HTTP engine)
62     *STDIN->blocking(1);
63
64     return $self->NEXT::finalize_read($c);
65 }
66
67 =item $self->prepare_read($c)
68
69 =cut
70
71 sub prepare_read {
72     my ( $self, $c ) = @_;
73
74     # Set the input handle to non-blocking
75     *STDIN->blocking(0);
76
77     return $self->NEXT::prepare_read($c);
78 }
79
80 =item $self->read_chunk($c, $buffer, $length)
81
82 =cut
83
84 sub read_chunk {
85     my $self = shift;
86     my $c    = shift;
87
88     # support for non-blocking IO
89     my $rin = '';
90     vec( $rin, *STDIN->fileno, 1 ) = 1;
91
92   READ:
93     {
94         select( $rin, undef, undef, undef );
95         my $rc = *STDIN->sysread(@_);
96         if ( defined $rc ) {
97             return $rc;
98         }
99         else {
100             next READ if $! == EWOULDBLOCK;
101             return;
102         }
103     }
104 }
105
106 =item run
107
108 =cut
109
110 # A very very simple HTTP server that initializes a CGI environment
111 sub run {
112     my ( $self, $class, $port, $host, $options ) = @_;
113
114     $options ||= {};
115
116     our $GOT_HUP;
117     local $GOT_HUP = 0;
118
119     local $SIG{HUP} = sub { $GOT_HUP = 1; };
120     local $SIG{CHLD} = 'IGNORE';
121
122     # Setup restarter
123     my $restarter;
124     if ( $options->{restart} ) {
125         my $parent = $$;
126         unless ( $restarter = fork ) {
127
128             # Prepare
129             close STDIN;
130             close STDOUT;
131
132             # Index parent directory
133             my $dir = File::Spec->catdir( $FindBin::Bin, '..' );
134
135             my $regex = $options->{restart_regex};
136             my $one   = _index( $dir, $regex );
137           RESTART: while (1) {
138                 sleep $options->{restart_delay};
139                 my $two     = _index( $dir,         $regex );
140                 my $changes = _compare_index( $one, $two );
141                 if (@$changes) {
142                     $one = $two;
143
144                     # Test modified pm's
145                     for my $file (@$changes) {
146                         next unless $file =~ /\.pm$/;
147                         if ( my $error = _test($file) ) {
148                             print STDERR
149                               qq/File "$file" modified, not restarting\n\n/;
150                             print STDERR '*' x 80, "\n";
151                             print STDERR $error;
152                             print STDERR '*' x 80, "\n";
153                             next RESTART;
154                         }
155                     }
156
157                     # Restart
158                     my $files = join ', ', @$changes;
159                     print STDERR qq/File(s) "$files" modified, restarting\n\n/;
160                     kill( 1, $parent );
161                     exit;
162                 }
163             }
164         }
165     }
166
167     # Handle requests
168
169     # Setup socket
170     $host = $host ? inet_aton($host) : INADDR_ANY;
171     socket( HTTPDaemon, PF_INET, SOCK_STREAM, getprotobyname('tcp') );
172     setsockopt( HTTPDaemon, SOL_SOCKET, SO_REUSEADDR, pack( "l", 1 ) );
173     bind( HTTPDaemon, sockaddr_in( $port, $host ) );
174     listen( HTTPDaemon, SOMAXCONN );
175     my $url = 'http://';
176     if ( $host eq INADDR_ANY ) {
177         require Sys::Hostname;
178         $url .= lc Sys::Hostname::hostname();
179     }
180     else {
181         $url .= gethostbyaddr( $host, AF_INET ) || inet_ntoa($host);
182     }
183     $url .= ":$port";
184     print "You can connect to your server at $url\n";
185     my $pid = undef;
186     while ( accept( Remote, HTTPDaemon ) ) {
187
188         # Fork
189         if ( $options->{fork} ) { next if $pid = fork }
190
191         close HTTPDaemon if defined $pid;
192
193         # Ignore broken pipes as an HTTP server should
194         local $SIG{PIPE} = sub { close Remote };
195         local $SIG{HUP} = ( defined $pid ? 'IGNORE' : $SIG{HUP} );
196
197         local *STDIN  = \*Remote;
198         local *STDOUT = \*Remote;
199         select STDOUT;
200
201         # Request data
202         my $remote_sockaddr = getpeername( \*Remote );
203         my ( undef, $iaddr ) = sockaddr_in($remote_sockaddr);
204         my $peername = gethostbyaddr( $iaddr, AF_INET ) || "localhost";
205         my $peeraddr = inet_ntoa($iaddr) || "127.0.0.1";
206         my $local_sockaddr = getsockname( \*Remote );
207         my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
208         my $localname = gethostbyaddr( $localiaddr, AF_INET )
209           || "localhost";
210         my $localaddr = inet_ntoa($localiaddr) || "127.0.0.1";
211
212         STDIN->blocking(1);
213
214         # Parse request line
215         my $line = $self->_get_line( \*STDIN );
216         next
217           unless my ( $method, $uri, $protocol ) =
218           $line =~ m/\A(\w+)\s+(\S+)(?:\s+HTTP\/(\d+(?:\.\d+)?))?\z/;
219
220         # We better be careful and just use 1.0
221         $protocol = '1.0';
222
223         my ( $path, $query_string ) = split /\?/, $uri, 2;
224
225         # Initialize CGI environment
226         local %ENV = (
227             PATH_INFO      => $path         || '',
228             QUERY_STRING   => $query_string || '',
229             REMOTE_ADDR    => $peeraddr,
230             REMOTE_HOST    => $peername,
231             REQUEST_METHOD => $method       || '',
232             SERVER_NAME    => $localname,
233             SERVER_PORT    => $port,
234             SERVER_PROTOCOL => "HTTP/$protocol",
235             %ENV,
236         );
237
238         # Parse headers
239         if ( $protocol >= 1 ) {
240             while (1) {
241                 my $line = $self->_get_line( \*STDIN );
242                 last if $line eq '';
243                 next
244                   unless my ( $name, $value ) =
245                   $line =~ m/\A(\w(?:-?\w+)*):\s(.+)\z/;
246
247                 $name = uc $name;
248                 $name = 'COOKIE' if $name eq 'COOKIES';
249                 $name =~ tr/-/_/;
250                 $name = 'HTTP_' . $name
251                   unless $name =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
252                 if ( exists $ENV{$name} ) {
253                     $ENV{$name} .= "; $value";
254                 }
255                 else {
256                     $ENV{$name} = $value;
257                 }
258             }
259         }
260
261         # Pass flow control to Catalyst
262         $class->handle_request;
263         exit if defined $pid;
264     }
265     continue {
266         close Remote;
267     }
268     close HTTPDaemon;
269
270     if ($GOT_HUP) {
271         $SIG{CHLD} = 'DEFAULT';
272         wait;
273         exec {$0}( ( ( -x $0 ) ? () : ($^X) ), $0, @{ $options->{argv} } );
274     }
275 }
276
277 sub _compare_index {
278     my ( $one, $two ) = @_;
279     my %clone = %$two;
280     my @changes;
281     while ( my ( $key, $val ) = each %$one ) {
282         if ( !$clone{$key} || ( $clone{$key} ne $val ) ) {
283             push @changes, $key;
284         }
285         delete $clone{$key};
286     }
287     for my $key ( keys %clone ) { push @changes, $key }
288     return \@changes;
289 }
290
291 sub _get_line {
292     my ( $self, $handle ) = @_;
293
294     my $line = '';
295
296     while ( sysread( $handle, my $byte, 1 ) ) {
297         last if $byte eq "\012";    # eol
298         $line .= $byte;
299     }
300
301     1 while $line =~ s/\s\z//;
302
303     return $line;
304 }
305
306 sub _index {
307     my ( $dir, $regex ) = @_;
308     my %index;
309     finddepth(
310         {
311             wanted => sub {
312                 my $file = File::Spec->rel2abs($File::Find::name);
313                 return unless $file =~ /$regex/;
314                 return unless -f $file;
315                 my $time = ( stat $file )[9];
316                 $index{$file} = $time;
317             },
318             no_chdir => 1
319         },
320         $dir
321     );
322     return \%index;
323 }
324
325 sub _test {
326     my $file = shift;
327     delete $INC{$file};
328     local $SIG{__WARN__} = sub { };
329     open my $olderr, '>&STDERR';
330     open STDERR, '>', File::Spec->devnull;
331     eval "require '$file'";
332     open STDERR, '>&', $olderr;
333     return $@ if $@;
334     return 0;
335 }
336
337 =back
338
339 =head1 SEE ALSO
340
341 L<Catalyst>, L<Catalyst::Engine>.
342
343 =head1 AUTHORS
344
345 Sebastian Riedel, <sri@cpan.org>
346
347 Dan Kubb, <dan.kubb-cpan@onautopilot.com>
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;