Let dzil handle $VERSION.
[catagits/HTTP-Request-AsCGI.git] / lib / HTTP / Request / AsCGI.pm
1 package HTTP::Request::AsCGI;
2 # ABSTRACT: Set up a CGI environment from an HTTP::Request
3 use strict;
4 use warnings;
5 use bytes;
6 use base 'Class::Accessor::Fast';
7
8 use Carp;
9 use HTTP::Response;
10 use IO::Handle;
11 use IO::File;
12 use URI ();
13 use URI::Escape ();
14
15 __PACKAGE__->mk_accessors(qw[ environment request stdin stdout stderr ]);
16
17 # old typo
18 =begin Pod::Coverage
19
20   enviroment
21
22 =end Pod::Coverage
23
24 =cut
25
26 *enviroment = \&environment;
27
28 my %reserved = map { sprintf('%02x', ord($_)) => 1 } split //, $URI::reserved;
29 sub _uri_safe_unescape {
30     my ($s) = @_;
31     $s =~ s/%([a-fA-F0-9]{2})/$reserved{lc($1)} ? "%$1" : pack('C', hex($1))/ge;
32     $s
33 }
34
35 sub new {
36     my $class   = shift;
37     my $request = shift;
38
39     unless ( @_ % 2 == 0 && eval { $request->isa('HTTP::Request') } ) {
40         croak(qq/usage: $class->new( \$request [, key => value] )/);
41     }
42
43     my $self = $class->SUPER::new( { restored => 0, setuped => 0 } );
44     $self->request($request);
45     $self->stdin( IO::File->new_tmpfile );
46     $self->stdout( IO::File->new_tmpfile );
47
48     my $host = $request->header('Host');
49     my $uri  = $request->uri->clone;
50     $uri->scheme('http')    unless $uri->scheme;
51     $uri->host('localhost') unless $uri->host;
52     $uri->port(80)          unless $uri->port;
53     $uri->host_port($host)  unless !$host || ( $host eq $uri->host_port );
54
55     # Get it before canonicalized so REQUEST_URI can be as raw as possible
56     my $request_uri = $uri->path_query;
57
58     $uri = $uri->canonical;
59
60     my $environment = {
61         GATEWAY_INTERFACE => 'CGI/1.1',
62         HTTP_HOST         => $uri->host_port,
63         HTTPS             => ( $uri->scheme eq 'https' ) ? 'ON' : 'OFF',  # not in RFC 3875
64         PATH_INFO         => $uri->path,
65         QUERY_STRING      => $uri->query || '',
66         SCRIPT_NAME       => '/',
67         SERVER_NAME       => $uri->host,
68         SERVER_PORT       => $uri->port,
69         SERVER_PROTOCOL   => $request->protocol || 'HTTP/1.1',
70         SERVER_SOFTWARE   => "HTTP-Request-AsCGI/$VERSION",
71         REMOTE_ADDR       => '127.0.0.1',
72         REMOTE_HOST       => 'localhost',
73         REMOTE_PORT       => int( rand(64000) + 1000 ),                   # not in RFC 3875
74         REQUEST_URI       => $request_uri,                                # not in RFC 3875
75         REQUEST_METHOD    => $request->method,
76         @_
77     };
78
79     # RFC 3875 says PATH_INFO is not URI-encoded. That's really
80     # annoying for applications that you can't tell "%2F" vs "/", but
81     # doing the partial decoding then makes it impossible to tell
82     # "%252F" vs "%2F". Encoding everything is more compatible to what
83     # web servers like Apache or lighttpd do, anyways.
84     $environment->{PATH_INFO} = URI::Escape::uri_unescape($environment->{PATH_INFO});
85
86     foreach my $field ( $request->headers->header_field_names ) {
87
88         my $key = uc("HTTP_$field");
89         $key =~ tr/-/_/;
90         $key =~ s/^HTTP_// if $field =~ /^Content-(Length|Type)$/;
91
92         unless ( exists $environment->{$key} ) {
93             $environment->{$key} = $request->headers->header($field);
94         }
95     }
96
97     unless ( $environment->{SCRIPT_NAME} eq '/' && $environment->{PATH_INFO} ) {
98         $environment->{PATH_INFO} =~ s/^\Q$environment->{SCRIPT_NAME}\E/\//;
99         $environment->{PATH_INFO} =~ s/^\/+/\//;
100     }
101
102     $self->environment($environment);
103
104     return $self;
105 }
106
107 sub setup {
108     my $self = shift;
109
110     $self->{restore}->{environment} = {%ENV};
111
112     binmode( $self->stdin );
113
114     if ( $self->request->content_length ) {
115
116         $self->stdin->print($self->request->content)
117           or croak("Can't write request content to stdin handle: $!");
118
119         $self->stdin->seek(0, SEEK_SET)
120           or croak("Can't seek stdin handle: $!");
121
122         $self->stdin->flush
123           or croak("Can't flush stdin handle: $!");
124     }
125
126     open( $self->{restore}->{stdin}, '<&'. STDIN->fileno )
127       or croak("Can't dup stdin: $!");
128
129     open( STDIN, '<&='. $self->stdin->fileno )
130       or croak("Can't open stdin: $!");
131
132     binmode( STDIN );
133
134     if ( $self->stdout ) {
135
136         open( $self->{restore}->{stdout}, '>&'. STDOUT->fileno )
137           or croak("Can't dup stdout: $!");
138
139         open( STDOUT, '>&='. $self->stdout->fileno )
140           or croak("Can't open stdout: $!");
141
142         binmode( $self->stdout );
143         binmode( STDOUT);
144     }
145
146     if ( $self->stderr ) {
147
148         open( $self->{restore}->{stderr}, '>&'. STDERR->fileno )
149           or croak("Can't dup stderr: $!");
150
151         open( STDERR, '>&='. $self->stderr->fileno )
152           or croak("Can't open stderr: $!");
153
154         binmode( $self->stderr );
155         binmode( STDERR );
156     }
157
158     {
159         no warnings 'uninitialized';
160         %ENV = (%ENV, %{ $self->environment });
161     }
162
163     if ( $INC{'CGI.pm'} ) {
164         CGI::initialize_globals();
165     }
166
167     $self->{setuped}++;
168
169     return $self;
170 }
171
172 sub response {
173     my ( $self, $callback ) = @_;
174
175     return undef unless $self->stdout;
176
177     seek( $self->stdout, 0, SEEK_SET )
178       or croak("Can't seek stdout handle: $!");
179
180     my $headers;
181     while ( my $line = $self->stdout->getline ) {
182         $headers .= $line;
183         last if $headers =~ /\x0d?\x0a\x0d?\x0a$/;
184     }
185
186     unless ( defined $headers ) {
187         $headers = "HTTP/1.1 500 Internal Server Error\x0d\x0a";
188     }
189
190     unless ( $headers =~ /^HTTP/ ) {
191         $headers = "HTTP/1.1 200 OK\x0d\x0a" . $headers;
192     }
193
194     my $response = HTTP::Response->parse($headers);
195     $response->date( time() ) unless $response->date;
196
197     my $message = $response->message;
198     my $status  = $response->header('Status');
199
200     if ( $message && $message =~ /^(.+)\x0d$/ ) {
201         $response->message($1);
202     }
203
204     if ( $status && $status =~ /^(\d\d\d)\s?(.+)?$/ ) {
205
206         my $code    = $1;
207         my $message = $2 || HTTP::Status::status_message($code);
208
209         $response->code($code);
210         $response->message($message);
211     }
212
213     my $length = ( stat( $self->stdout ) )[7] - tell( $self->stdout );
214
215     if ( $response->code == 500 && !$length ) {
216
217         $response->content( $response->error_as_HTML );
218         $response->content_type('text/html');
219
220         return $response;
221     }
222
223     if ($callback) {
224
225         my $handle = $self->stdout;
226
227         $response->content( sub {
228
229             if ( $handle->read( my $buffer, 4096 ) ) {
230                 return $buffer;
231             }
232
233             return undef;
234         });
235     }
236     else {
237
238         my $length = 0;
239
240         while ( $self->stdout->read( my $buffer, 4096 ) ) {
241             $length += length($buffer);
242             $response->add_content($buffer);
243         }
244
245         if ( $length && !$response->content_length ) {
246             $response->content_length($length);
247         }
248     }
249
250     return $response;
251 }
252
253 sub restore {
254     my $self = shift;
255
256     {
257         no warnings 'uninitialized';
258         %ENV = %{ $self->{restore}->{environment} };
259     }
260
261     open( STDIN, '<&'. fileno($self->{restore}->{stdin}) )
262       or croak("Can't restore stdin: $!");
263
264     sysseek( $self->stdin, 0, SEEK_SET )
265       or croak("Can't seek stdin: $!");
266
267     if ( $self->{restore}->{stdout} ) {
268
269         STDOUT->flush
270           or croak("Can't flush stdout: $!");
271
272         open( STDOUT, '>&'. fileno($self->{restore}->{stdout}) )
273           or croak("Can't restore stdout: $!");
274
275         sysseek( $self->stdout, 0, SEEK_SET )
276           or croak("Can't seek stdout: $!");
277     }
278
279     if ( $self->{restore}->{stderr} ) {
280
281         STDERR->flush
282           or croak("Can't flush stderr: $!");
283
284         open( STDERR, '>&'. fileno($self->{restore}->{stderr}) )
285           or croak("Can't restore stderr: $!");
286
287         sysseek( $self->stderr, 0, SEEK_SET )
288           or croak("Can't seek stderr: $!");
289     }
290
291     $self->{restored}++;
292
293     return $self;
294 }
295
296 sub DESTROY {
297     my $self = shift;
298     $self->restore if $self->{setuped} && !$self->{restored};
299 }
300
301 1;
302
303 __END__
304
305 =head1 SYNOPSIS
306
307     use CGI;
308     use HTTP::Request;
309     use HTTP::Request::AsCGI;
310
311     my $request = HTTP::Request->new( GET => 'http://www.host.com/' );
312     my $stdout;
313
314     {
315         my $c = HTTP::Request::AsCGI->new($request)->setup;
316         my $q = CGI->new;
317
318         print $q->header,
319               $q->start_html('Hello World'),
320               $q->h1('Hello World'),
321               $q->end_html;
322
323         $stdout = $c->stdout;
324
325         # environment and descriptors will automatically be restored
326         # when $c is destructed.
327     }
328
329     while ( my $line = $stdout->getline ) {
330         print $line;
331     }
332
333 =head1 DESCRIPTION
334
335 Provides a convenient way of setting up an CGI environment from an HTTP::Request.
336
337 =head1 METHODS
338
339 =over 4
340
341 =item new ( $request [, key => value ] )
342
343 Constructor.  The first argument must be a instance of HTTP::Request, followed
344 by optional pairs of environment key and value.
345
346 =item environment
347
348 Returns a hashref containing the environment that will be used in setup.
349 Changing the hashref after setup has been called will have no effect.
350
351 =item setup
352
353 Sets up the environment and descriptors.
354
355 =item restore
356
357 Restores the environment and descriptors. Can only be called after setup.
358
359 =item request
360
361 Returns the request given to constructor.
362
363 =item response
364
365 Returns a HTTP::Response. Can only be called after restore.
366
367 =item stdin
368
369 Accessor for handle that will be used for STDIN, must be a real seekable
370 handle with an file descriptor. Defaults to a tempoary IO::File instance.
371
372 =item stdout
373
374 Accessor for handle that will be used for STDOUT, must be a real seekable
375 handle with an file descriptor. Defaults to a tempoary IO::File instance.
376
377 =item stderr
378
379 Accessor for handle that will be used for STDERR, must be a real seekable
380 handle with an file descriptor.
381
382 =back
383
384 =head1 SEE ALSO
385
386 =over 4
387
388 =item examples directory in this distribution.
389
390 =item L<WWW::Mechanize::CGI>
391
392 =item L<Test::WWW::Mechanize::CGI>
393
394 =back
395
396 =head1 THANKS TO
397
398 Thomas L. Shinnick for his valuable win32 testing.
399
400 =cut