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