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