Updated to half working restarter with syntax check
[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     our $GOT_HUP;
115     local $GOT_HUP = 0;
116
117     local $SIG{HUP} = sub { $GOT_HUP = 1; };
118     local $SIG{CHLD} = 'IGNORE';
119
120     # Setup restarter
121     my $restarter;
122     if ( $options->{restart} ) {
123         my $parent = $$;
124         unless ( $restarter = fork ) {
125
126             # Prepare
127             close STDIN;
128             close STDOUT;
129
130             # Index parent directory
131             my $dir = File::Spec->catdir( $FindBin::Bin, '..' );
132
133             my $regex = $options->{restart_regex};
134             my $one   = _index( $dir, $regex );
135           RESTART: while (1) {
136                 sleep $options->{restart_delay};
137                 my $two     = _index( $dir,         $regex );
138                 my $changes = _compare_index( $one, $two );
139                 if (@$changes) {
140                     $one = $two;
141
142                     # Test modified pm's
143                     for my $file (@$changes) {
144                         next unless $file =~ /\.pm$/;
145                         if ( my $error = _test($file) ) {
146                             print STDERR
147                               qq/File "$file" modified, not restarting\n/;
148                             print STDERR '*' x 80, "\n";
149                             print STDERR $error;
150                             print STDERR '*' x 80, "\n";
151                             next RESTART;
152                         }
153                     }
154
155                     # Restart
156                     my $files = join ', ', @$changes;
157                     print STDERR qq/File(s) "$files" modified, restarting\n/;
158                     kill( 1, $parent );
159                     exit;
160                 }
161             }
162         }
163     }
164
165     # Handle requests
166
167     # Setup socket
168     $host = $host ? inet_aton($host) : INADDR_ANY;
169     socket( HTTPDaemon, PF_INET, SOCK_STREAM, getprotobyname('tcp') );
170     setsockopt( HTTPDaemon, SOL_SOCKET, SO_REUSEADDR, pack( "l", 1 ) );
171     bind( HTTPDaemon, sockaddr_in( $port, $host ) );
172     listen( HTTPDaemon, SOMAXCONN );
173     my $url = 'http://';
174     if ( $host eq INADDR_ANY ) {
175         require Sys::Hostname;
176         $url .= lc Sys::Hostname::hostname();
177     }
178     else {
179         $url .= gethostbyaddr( $host, AF_INET ) || inet_ntoa($host);
180     }
181     $url .= ":$port";
182     print "You can connect to your server at $url\n";
183     my $pid = undef;
184     while ( accept( Remote, HTTPDaemon ) ) {
185
186         # Fork
187         if ( $options->{fork} ) { next if $pid = fork }
188
189         close HTTPDaemon if defined $pid;
190
191         # Ignore broken pipes as an HTTP server should
192         local $SIG{PIPE} = sub { close Remote };
193         local $SIG{HUP} = ( defined $pid ? 'IGNORE' : $SIG{HUP} );
194
195         local *STDIN  = \*Remote;
196         local *STDOUT = \*Remote;
197         select STDOUT;
198
199         # Request data
200         my $remote_sockaddr = getpeername( \*Remote );
201         my ( undef, $iaddr ) = sockaddr_in($remote_sockaddr);
202         my $peername = gethostbyaddr( $iaddr, AF_INET ) || "localhost";
203         my $peeraddr = inet_ntoa($iaddr) || "127.0.0.1";
204         my $local_sockaddr = getsockname( \*Remote );
205         my ( undef, $localiaddr ) = sockaddr_in($local_sockaddr);
206         my $localname = gethostbyaddr( $localiaddr, AF_INET )
207           || "localhost";
208         my $localaddr = inet_ntoa($localiaddr) || "127.0.0.1";
209
210         STDIN->blocking(1);
211
212         # Parse request line
213         my $line = $self->_get_line( \*STDIN );
214         next
215           unless my ( $method, $uri, $protocol ) =
216           $line =~ m/\A(\w+)\s+(\S+)(?:\s+HTTP\/(\d+(?:\.\d+)?))?\z/;
217
218         # We better be careful and just use 1.0
219         $protocol = '1.0';
220
221         my ( $path, $query_string ) = split /\?/, $uri, 2;
222
223         # Initialize CGI environment
224         local %ENV = (
225             PATH_INFO      => $path         || '',
226             QUERY_STRING   => $query_string || '',
227             REMOTE_ADDR    => $peeraddr,
228             REMOTE_HOST    => $peername,
229             REQUEST_METHOD => $method       || '',
230             SERVER_NAME    => $localname,
231             SERVER_PORT    => $port,
232             SERVER_PROTOCOL => "HTTP/$protocol",
233             %ENV,
234         );
235
236         # Parse headers
237         if ( $protocol >= 1 ) {
238             while (1) {
239                 my $line = $self->_get_line( \*STDIN );
240                 last if $line eq '';
241                 next
242                   unless my ( $name, $value ) =
243                   $line =~ m/\A(\w(?:-?\w+)*):\s(.+)\z/;
244
245                 $name = uc $name;
246                 $name = 'COOKIE' if $name eq 'COOKIES';
247                 $name =~ tr/-/_/;
248                 $name = 'HTTP_' . $name
249                   unless $name =~ m/\A(?:CONTENT_(?:LENGTH|TYPE)|COOKIE)\z/;
250                 if ( exists $ENV{$name} ) {
251                     $ENV{$name} .= "; $value";
252                 }
253                 else {
254                     $ENV{$name} = $value;
255                 }
256             }
257         }
258
259         # Pass flow control to Catalyst
260         $class->handle_request;
261         exit if defined $pid;
262     }
263     continue {
264         close Remote;
265     }
266     close HTTPDaemon;
267
268     if ($GOT_HUP) {
269         $SIG{CHLD} = 'DEFAULT';
270         exec {$0}( ( ( -x $0 ) ? () : ($^X) ), $0, @ARGV );
271     }
272 }
273
274 sub _compare_index {
275     my ( $one, $two ) = @_;
276     my %clone = %$two;
277     my @changes;
278     while ( my ( $key, $val ) = each %$one ) {
279         if ( !$clone{$key} || ( $clone{$key} ne $val ) ) {
280             push @changes, $key;
281         }
282         delete $clone{$key};
283     }
284     for my $key ( keys %clone ) { push @changes, $key }
285     return \@changes;
286 }
287
288 sub _get_line {
289     my ( $self, $handle ) = @_;
290
291     my $line = '';
292
293     while ( sysread( $handle, my $byte, 1 ) ) {
294         last if $byte eq "\012";    # eol
295         $line .= $byte;
296     }
297
298     1 while $line =~ s/\s\z//;
299
300     return $line;
301 }
302
303 sub _index {
304     my ( $dir, $regex ) = @_;
305     my %index;
306     finddepth(
307         {
308             wanted => sub {
309                 my $file = File::Spec->rel2abs($File::Find::name);
310                 return unless $file =~ /$regex/;
311                 return unless -f $file;
312                 my $time = ( stat $file )[9];
313                 $index{$file} = $time;
314             },
315             no_chdir => 1
316         },
317         $dir
318     );
319     return \%index;
320 }
321
322 sub _test {
323     my $file = shift;
324     local $SIG{__WARN__} = sub { };
325     open my $olderr, '>&STDERR';
326     open STDERR, '>', File::Spec->devnull;
327     eval "require '$file'";
328     open STDERR, '>&', $olderr;
329     return $@ if $@;
330     return 0;
331 }
332
333 =back
334
335 =head1 SEE ALSO
336
337 L<Catalyst>, L<Catalyst::Engine>.
338
339 =head1 AUTHORS
340
341 Sebastian Riedel, <sri@cpan.org>
342
343 Dan Kubb, <dan.kubb-cpan@onautopilot.com>
344
345 =head1 THANKS
346
347 Many parts are ripped out of C<HTTP::Server::Simple> by Jesse Vincent.
348
349 =head1 COPYRIGHT
350
351 This program is free software, you can redistribute it and/or modify it under
352 the same terms as Perl itself.
353
354 =cut
355
356 1;