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