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