Added a forking test
[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.2;
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     %ENV = %{ $self->{restore}->{enviroment} };
217
218     open( STDIN, '>&', $self->{restore}->{stdin} )
219       or croak("Can't restore stdin: $!");
220
221     sysseek( $self->stdin, 0, SEEK_SET )
222       or croak("Can't seek stdin: $!");
223
224     if ( $self->{restore}->{stdout} ) {
225
226         STDOUT->flush
227           or croak("Can't flush stdout: $!");
228
229         open( STDOUT, '>&', $self->{restore}->{stdout} )
230           or croak("Can't restore stdout: $!");
231
232         sysseek( $self->stdout, 0, SEEK_SET )
233           or croak("Can't seek stdout: $!");
234     }
235
236     if ( $self->{restore}->{stderr} ) {
237
238         STDERR->flush
239           or croak("Can't flush stderr: $!");
240
241         open( STDERR, '>&', $self->{restore}->{stderr} )
242           or croak("Can't restore stderr: $!");
243
244         sysseek( $self->stderr, 0, SEEK_SET )
245           or croak("Can't seek stderr: $!");
246     }
247
248     $self->{restored}++;
249
250     return $self;
251 }
252
253 sub DESTROY {
254     my $self = shift;
255     $self->restore if $self->{setuped} && !$self->{restored};
256 }
257
258 1;
259
260 __END__
261
262 =head1 NAME
263
264 HTTP::Request::AsCGI - Setup a CGI enviroment from a HTTP::Request
265
266 =head1 SYNOPSIS
267
268     use CGI;
269     use HTTP::Request;
270     use HTTP::Request::AsCGI;
271     
272     my $request = HTTP::Request->new( GET => 'http://www.host.com/' );
273     my $stdout;
274     
275     {
276         my $c = HTTP::Request::AsCGI->new($request)->setup;
277         my $q = CGI->new;
278         
279         print $q->header,
280               $q->start_html('Hello World'),
281               $q->h1('Hello World'),
282               $q->end_html;
283         
284         $stdout = $c->stdout;
285         
286         # enviroment and descriptors will automatically be restored 
287         # when $c is destructed.
288     }
289     
290     while ( my $line = $stdout->getline ) {
291         print $line;
292     }
293     
294 =head1 DESCRIPTION
295
296 Provides a convinient way of setting up an CGI enviroment from a HTTP::Request.
297
298 =head1 METHODS
299
300 =over 4 
301
302 =item new ( $request [, key => value ] )
303
304 Contructor, first argument must be a instance of HTTP::Request
305 followed by optional pairs of environment key and value.
306
307 =item enviroment
308
309 Returns a hashref containing the environment that will be used in setup. 
310 Changing the hashref after setup has been called will have no effect.
311
312 =item setup
313
314 Setups the environment and descriptors.
315
316 =item restore
317
318 Restores the enviroment and descriptors. Can only be called after setup.
319
320 =item request
321
322 Returns the request given to constructor.
323
324 =item response
325
326 Returns a HTTP::Response. Can only be called after restore.
327
328 =item stdin
329
330 Accessor for handle that will be used for STDIN, must be a real seekable
331 handle with an file descriptor. Defaults to a tempoary IO::File instance.
332
333 =item stdout
334
335 Accessor for handle that will be used for STDOUT, must be a real seekable
336 handle with an file descriptor. Defaults to a tempoary IO::File instance.
337
338 =item stderr
339
340 Accessor for handle that will be used for STDERR, must be a real seekable
341 handle with an file descriptor.
342
343 =back
344
345 =head1 SEE ALSO
346
347 =over 4
348
349 =item examples directory in this distribution.
350
351 =item L<WWW::Mechanize::CGI>
352
353 =item L<Test::WWW::Mechanize::CGI>
354
355 =back
356
357 =head1 THANKS TO
358
359 Thomas L. Shinnick for his valuable win32 testing.
360
361 =head1 AUTHOR
362
363 Christian Hansen, C<ch@ngmedia.com>
364
365 =head1 LICENSE
366
367 This library is free software. You can redistribute it and/or modify 
368 it under the same terms as perl itself.
369
370 =cut