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