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