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