Added docs
[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(qw[ enviroment request stdin stdout stderr ]);
13
14 our $VERSION = 0.1;
15
16 sub new {
17     my $class   = shift;
18     my $request = shift;
19     
20     unless ( @_ % 2 == 0 && eval { $request->isa('HTTP::Request') } ) {
21         croak(qq/usage: $class->new( \$request [, key => value] )/);
22     }
23
24     my $self = {
25         request  => $request,
26         restored => 0,
27         setuped  => 0,
28         stdin    => IO::File->new_tmpfile,
29         stdout   => IO::File->new_tmpfile
30     };
31
32     my $host = $request->header('Host');
33     my $uri  = $request->uri->clone;
34     $uri->scheme('http')    unless $uri->scheme;
35     $uri->host('localhost') unless $uri->host;
36     $uri->port(80)          unless $uri->port;
37     $uri->host_port($host)  unless !$host || ( $host eq $uri->host_port );
38
39     $self->{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($field);
61         $key =~ tr/-/_/;
62         $key = 'HTTP_' . $key unless $field =~ /^Content-(Length|Type)$/;
63
64         unless ( exists $self->{enviroment}->{$key} ) {
65             $self->{enviroment}->{$key} = $request->headers->header($field);
66         }
67     }
68
69     return $class->SUPER::new($self);
70 }
71
72 sub setup {
73     my $self = shift;
74
75     $self->{restore}->{enviroment} = {%ENV};
76
77     open( $self->{restore}->{stdin}, '>&', STDIN->fileno )
78       or croak("Can't dup stdin: $!");
79
80     open( STDIN, '<&=', $self->stdin->fileno )
81       or croak("Can't open stdin: $!");
82
83     binmode( $self->stdin );
84     binmode( 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     if ( $self->stdout ) {
96
97         open( $self->{restore}->{stdout}, '>&', STDOUT->fileno )
98           or croak("Can't dup stdout: $!");
99
100         open( STDOUT, '>&=', $self->stdout->fileno )
101           or croak("Can't open stdout: $!");
102
103         binmode( $self->stdout );
104         binmode( STDOUT);
105     }
106
107     if ( $self->stderr ) {
108
109         open( $self->{restore}->{stderr}, '>&', STDERR->fileno )
110           or croak("Can't dup stderr: $!");
111
112         open( STDERR, '>&=', $self->stderr->fileno )
113           or croak("Can't open stderr: $!");
114
115         binmode( $self->stderr );
116         binmode( STDERR );
117     }
118
119     {
120         no warnings 'uninitialized';
121         %ENV = %{ $self->enviroment };
122     }
123     
124     if ( $INC{'CGI.pm'} ) {
125         CGI::initialize_globals();
126     }    
127
128     $self->{setuped}++;
129
130     return $self;
131 }
132
133 sub response {
134     my ( $self, $callback ) = @_;
135
136     return undef unless $self->{setuped};
137     return undef unless $self->{restored};
138     return undef unless $self->{restore}->{stdout};
139
140     require HTTP::Response;
141
142     seek( $self->stdout, 0, SEEK_SET )
143       or croak("Can't seek stdout handle: $!");
144
145     my $message;
146     while ( my $line = $self->stdout->getline ) {
147         $message .= $line;
148         last if $message =~ /\x0d?\x0a\x0d?\x0a$/;
149     }
150
151     unless ( $message =~ /^HTTP/ ) {
152         $message = "HTTP/1.1 200 OK\x0d\x0a" . $message;
153     }
154
155     my $response = HTTP::Response->new;
156     my @headers  = split( /\x0d?\x0a/, $message );
157     my $status   = shift(@headers);
158
159     unless ( $status =~ s/^(HTTP\/\d\.\d) (\d{3}) (.*)$// ) {
160         croak( "Invalid Status-Line: '$status'" );
161     }
162
163     $response->protocol($1);
164     $response->code($2);
165     $response->message($3);
166
167     my $token = qr/[^][\x00-\x1f\x7f()<>@,;:\\"\/?={} \t]+/;
168
169     foreach my $header (@headers) {
170
171         unless( $header =~ s/^($token):[\t ]*// ) {
172             croak( "Invalid header field name : '$header'" );
173         }
174
175         $response->push_header( $1 => $header );
176     }    
177
178     if ( my $code = $response->header('Status') ) {
179         $response->code($code);
180         $response->message( HTTP::Status::status_message($code) );
181     }
182
183     $response->headers->date( time() );
184
185     if ($callback) {
186         $response->content( sub {
187             if ( $self->stdout->read( my $buffer, 4096 ) ) {
188                 return $buffer;
189             }
190             return undef;
191         });
192     }
193     else {
194         my $length = 0;
195         while ( $self->stdout->read( my $buffer, 4096 ) ) {
196             $length += length($buffer);
197             $response->add_content($buffer);
198         }
199         
200         if ( $length && !$response->content_length ) {
201             $response->content_length($length);
202         }
203     }
204
205     return $response;
206 }
207
208 sub restore {
209     my $self = shift;
210
211     %ENV = %{ $self->{restore}->{enviroment} };
212
213     open( STDIN, '>&', $self->{restore}->{stdin} )
214       or croak("Can't restore stdin: $!");
215
216     sysseek( $self->stdin, 0, SEEK_SET )
217       or croak("Can't seek stdin: $!");
218
219     if ( $self->{restore}->{stdout} ) {
220
221         STDOUT->flush
222           or croak("Can't flush stdout: $!");
223
224         open( STDOUT, '>&', $self->{restore}->{stdout} )
225           or croak("Can't restore stdout: $!");
226
227         sysseek( $self->stdout, 0, SEEK_SET )
228           or croak("Can't seek stdout: $!");
229     }
230
231     if ( $self->{restore}->{stderr} ) {
232
233         STDERR->flush
234           or croak("Can't flush stderr: $!");
235
236         open( STDERR, '>&', $self->{restore}->{stderr} )
237           or croak("Can't restore stderr: $!");
238
239         sysseek( $self->stderr, 0, SEEK_SET )
240           or croak("Can't seek stderr: $!");
241     }
242
243     $self->{restored}++;
244
245     return $self;
246 }
247
248 sub DESTROY {
249     my $self = shift;
250     $self->restore if $self->{setuped} && !$self->{restored};
251 }
252
253 1;
254
255 __END__
256
257 =head1 NAME
258
259 HTTP::Request::AsCGI - Setup a CGI enviroment from a HTTP::Request
260
261 =head1 SYNOPSIS
262
263     use CGI;
264     use HTTP::Request;
265     use HTTP::Request::AsCGI;
266     
267     my $request = HTTP::Request->new( GET => 'http://www.host.com/' );
268     my $stdout;
269     
270     {
271         my $c = HTTP::Request::AsCGI->new($request)->setup;
272         my $q = CGI->new;
273         
274         print $q->header,
275               $q->start_html('Hello World'),
276               $q->h1('Hello World'),
277               $q->end_html;
278         
279         $stdout = $c->stdout;
280         
281         # enviroment and descriptors will automatically be restored 
282         # when $c is destructed.
283     }
284     
285     while ( my $line = $stdout->getline ) {
286         print $line;
287     }
288     
289 =head1 DESCRIPTION
290
291 Provides a convinient way of setting up an CGI enviroment from a HTTP::Request.
292
293 =head1 METHODS
294
295 =over 4 
296
297 =item new ( $request [, key => value ] )
298
299 Contructor, first argument must be a instance of HTTP::Request
300 followed by optional pairs of environment keys and values.
301
302 =item enviroment
303
304 Returns a hashref containing the environment that will be used in setup. 
305 Changing the hashref after setup has been called will have no effect.
306
307 =item setup
308
309 Setups the environment and descriptors.
310
311 =item restore
312
313 Restores the enviroment and descriptors. Can only be called after setup.
314
315 =item request
316
317 Returns the request given to constructor.
318
319 =item response
320
321 Returns a HTTP::Response. Can only be called after restore.
322
323 =item stdin
324
325 Accessor for handle that will be used for STDIN, must be a real seekable
326 handle with an file descriptor. Defaults to a tempoary IO::File instance.
327
328 =item stdout
329
330 Accessor for handle that will be used for STDOUT, must be a real seekable
331 handle with an file descriptor. Defaults to a tempoary IO::File instance.
332
333 =item stderr
334
335 Accessor for handle that will be used for STDERR, must be a real seekable
336 handle with an file descriptor.
337
338 =back
339
340 =head1 THANKS TO
341
342 Thomas L. Shinnick for his valuable win32 testing.
343
344 =head1 AUTHOR
345
346 Christian Hansen, C<ch@ngmedia.com>
347
348 =head1 LICENSE
349
350 This library is free software. You can redistribute it and/or modify 
351 it under the same terms as perl itself.
352
353 =cut