Added rawhandles option to bypass a Perl bug
[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 IO::Handle;
10 use IO::File;
11
12 __PACKAGE__->mk_accessors(
13     qw[ enviroment request rawhandles stdin stdout stderr ]);
14
15 our $VERSION = 0.4;
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
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     if ( $self->rawhandles ) {
83         $self->stdin( \*STDIN );
84         $self->stdout( \*STDOUT );
85     }
86     else {
87         $self->stdin( IO::File->new_tmpfile );
88         $self->stdout( IO::File->new_tmpfile );
89     }
90
91     binmode( $self->stdin );
92
93     if ( $self->request->content_length ) {
94
95         syswrite( $self->stdin, $self->request->content )
96           or croak("Can't write request content to stdin handle: $!");
97
98         sysseek( $self->stdin, 0, SEEK_SET )
99           or croak("Can't seek stdin handle: $!");
100     }
101
102     unless ( $self->rawhandles ) {
103
104         open( $self->{restore}->{stdin}, '>&', STDIN->fileno )
105           or croak("Can't dup stdin: $!");
106
107         open( STDIN, '<&=', $self->stdin->fileno )
108           or croak("Can't open stdin: $!");
109
110         binmode(STDIN);
111
112         if ( $self->stdout ) {
113
114             open( $self->{restore}->{stdout}, '>&', STDOUT->fileno )
115               or croak("Can't dup stdout: $!");
116
117             open( STDOUT, '>&=', $self->stdout->fileno )
118               or croak("Can't open stdout: $!");
119
120             binmode( $self->stdout );
121             binmode(STDOUT);
122         }
123
124         if ( $self->stderr ) {
125
126             open( $self->{restore}->{stderr}, '>&', STDERR->fileno )
127               or croak("Can't dup stderr: $!");
128
129             open( STDERR, '>&=', $self->stderr->fileno )
130               or croak("Can't open stderr: $!");
131
132             binmode( $self->stderr );
133             binmode(STDERR);
134         }
135
136     }
137
138     {
139         no warnings 'uninitialized';
140         %ENV = %{ $self->enviroment };
141     }
142
143     if ( $INC{'CGI.pm'} ) {
144         CGI::initialize_globals();
145     }
146
147     $self->{setuped}++;
148
149     return $self;
150 }
151
152 sub response {
153     my ( $self, $callback ) = @_;
154
155     return undef unless $self->stdout;
156
157     require HTTP::Response;
158
159     seek( $self->stdout, 0, SEEK_SET )
160       or croak("Can't seek stdout handle: $!");
161
162     my $message;
163     while ( my $line = $self->stdout->getline ) {
164         $message .= $line;
165         last if $message =~ /\x0d?\x0a\x0d?\x0a$/;
166     }
167
168     unless ( $message =~ /^HTTP/ ) {
169         $message = "HTTP/1.1 200 OK\x0d\x0a" . $message;
170     }
171
172     my $response = HTTP::Response->new;
173     my @headers  = split( /\x0d?\x0a/, $message );
174     my $status   = shift(@headers);
175
176     unless ( $status =~ s/^(HTTP\/\d\.\d) (\d{3}) (.*)$// ) {
177         croak("Invalid Status-Line: '$status'");
178     }
179
180     $response->protocol($1);
181     $response->code($2);
182     $response->message($3);
183
184     my $token = qr/[^][\x00-\x1f\x7f()<>@,;:\\"\/?={} \t]+/;
185
186     foreach my $header (@headers) {
187
188         unless ( $header =~ s/^($token):[\t ]*// ) {
189             croak("Invalid header field name : '$header'");
190         }
191
192         $response->push_header( $1 => $header );
193     }
194
195     if ( my $code = $response->header('Status') ) {
196         $response->code($code);
197         $response->message( HTTP::Status::status_message($code) );
198     }
199
200     $response->headers->date( time() );
201
202     if ($callback) {
203         $response->content(
204             sub {
205                 if ( $self->stdout->read( my $buffer, 4096 ) ) {
206                     return $buffer;
207                 }
208                 return undef;
209             }
210         );
211     }
212     else {
213         my $length = 0;
214         while ( $self->stdout->read( my $buffer, 4096 ) ) {
215             $length += length($buffer);
216             $response->add_content($buffer);
217         }
218
219         if ( $length && !$response->content_length ) {
220             $response->content_length($length);
221         }
222     }
223
224     return $response;
225 }
226
227 sub restore {
228     my $self = shift;
229
230     {
231         no warnings 'uninitialized';
232         %ENV = %{ $self->{restore}->{enviroment} };
233     }
234
235     unless ( $self->rawhandles ) {
236
237         open( STDIN, '>&', $self->{restore}->{stdin} )
238           or croak("Can't restore stdin: $!");
239
240         sysseek( $self->stdin, 0, SEEK_SET )
241           or croak("Can't seek stdin: $!");
242
243         if ( $self->{restore}->{stdout} ) {
244
245             STDOUT->flush
246               or croak("Can't flush stdout: $!");
247
248             open( STDOUT, '>&', $self->{restore}->{stdout} )
249               or croak("Can't restore stdout: $!");
250
251             sysseek( $self->stdout, 0, SEEK_SET )
252               or croak("Can't seek stdout: $!");
253         }
254
255         if ( $self->{restore}->{stderr} ) {
256
257             STDERR->flush
258               or croak("Can't flush stderr: $!");
259
260             open( STDERR, '>&', $self->{restore}->{stderr} )
261               or croak("Can't restore stderr: $!");
262
263             sysseek( $self->stderr, 0, SEEK_SET )
264               or croak("Can't seek stderr: $!");
265         }
266
267     }
268
269     $self->{restored}++;
270
271     return $self;
272 }
273
274 sub DESTROY {
275     my $self = shift;
276     $self->restore if $self->{setuped} && !$self->{restored};
277 }
278
279 1;
280
281 __END__
282
283 =head1 NAME
284
285 HTTP::Request::AsCGI - Setup a CGI enviroment from a HTTP::Request
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         # enviroment 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 convinient way of setting up an CGI enviroment from a HTTP::Request.
318
319 =head1 METHODS
320
321 =over 4 
322
323 =item new ( $request [, key => value ] )
324
325 Contructor, first argument must be a instance of HTTP::Request
326 followed by optional pairs of environment key and value.
327
328 =item enviroment
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 Setups the environment and descriptors.
336
337 =item rawhandles
338
339 Don't redefine STDIN/STDOUT/STDERR internally.
340
341 =item restore
342
343 Restores the enviroment and descriptors. Can only be called after setup.
344
345 =item request
346
347 Returns the request given to constructor.
348
349 =item response
350
351 Returns a HTTP::Response. Can only be called after restore.
352
353 =item stdin
354
355 Accessor for handle that will be used for STDIN, must be a real seekable
356 handle with an file descriptor. Defaults to a tempoary IO::File instance.
357
358 =item stdout
359
360 Accessor for handle that will be used for STDOUT, must be a real seekable
361 handle with an file descriptor. Defaults to a tempoary IO::File instance.
362
363 =item stderr
364
365 Accessor for handle that will be used for STDERR, must be a real seekable
366 handle with an file descriptor.
367
368 =back
369
370 =head1 SEE ALSO
371
372 =over 4
373
374 =item examples directory in this distribution.
375
376 =item L<WWW::Mechanize::CGI>
377
378 =item L<Test::WWW::Mechanize::CGI>
379
380 =back
381
382 =head1 THANKS TO
383
384 Thomas L. Shinnick for his valuable win32 testing.
385
386 =head1 AUTHOR
387
388 Christian Hansen, C<ch@ngmedia.com>
389
390 =head1 LICENSE
391
392 This library is free software. You can redistribute it and/or modify 
393 it under the same terms as perl itself.
394
395 =cut