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