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