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