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