1 package HTTP::Request::AsCGI;
6 use base 'Class::Accessor::Fast';
9 use HTTP::Response qw[];
10 use IO::File qw[SEEK_SET];
14 __PACKAGE__->mk_accessors( qw[ is_setup
29 our $VERSION = 0.6_01;
32 my $class = ref $_[0] ? ref shift : shift;
39 $params = { request => shift, environment => { @_ } };
42 return bless( {}, $class )->initialize($params);
46 my ( $self, $params ) = @_;
48 if ( exists $params->{request} ) {
49 $self->request( $params->{request} );
52 croak("Mandatory parameter 'request' is missing.");
55 if ( exists $params->{environment} ) {
56 $self->environment( { %{ $params->{environment} } } );
59 $self->environment( {} );
62 if ( exists $params->{stdin} ) {
63 $self->stdin( $params->{stdin} );
66 $self->stdin( IO::File->new_tmpfile );
69 if ( exists $params->{stdout} ) {
70 $self->stdout( $params->{stdout} );
73 $self->stdout( IO::File->new_tmpfile );
76 if ( exists $params->{stderr} ) {
77 $self->stderr( $params->{stderr} );
80 if ( exists $params->{dup} ) {
81 $self->should_dup( $params->{dup} ? 1 : 0 );
87 if ( exists $params->{restore} ) {
88 $self->should_restore( $params->{restore} ? 1 : 0 );
91 $self->should_restore(1);
94 if ( exists $params->{rewind} ) {
95 $self->should_rewind( $params->{rewind} ? 1 : 0 );
98 $self->should_rewind(1);
101 if ( exists $params->{content} ) {
102 $self->should_setup_content( $params->{content} ? 1 : 0 );
105 $self->should_setup_content(1);
113 *enviroment = \&environment;
115 sub has_stdin { return defined $_[0]->stdin }
116 sub has_stdout { return defined $_[0]->stdout }
117 sub has_stderr { return defined $_[0]->stderr }
119 my $HTTP_Token = qr/[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7A\x7C\x7E]/;
120 my $HTTP_Version = qr/HTTP\/[0-9]+\.[0-9]+/;
125 my $environment = $self->environment;
126 my $request = $self->request;
128 my $host = $request->header('Host');
129 my $uri = $request->uri->clone;
131 $uri->scheme('http') unless $uri->scheme;
132 $uri->host('localhost') unless $uri->host;
133 $uri->port(80) unless $uri->port;
134 $uri->host_port($host) unless !$host || ( $host eq $uri->host_port );
136 $uri = $uri->canonical;
139 GATEWAY_INTERFACE => 'CGI/1.1',
140 HTTP_HOST => $uri->host_port,
141 HTTPS => ( $uri->scheme eq 'https' ) ? 'ON' : 'OFF', # not in RFC 3875
142 PATH_INFO => URI::Escape::uri_unescape($uri->path),
143 QUERY_STRING => $uri->query || '',
145 SERVER_NAME => $uri->host,
146 SERVER_PORT => $uri->port,
147 SERVER_PROTOCOL => $request->protocol || 'HTTP/1.1',
148 SERVER_SOFTWARE => "HTTP-Request-AsCGI/$VERSION",
149 REMOTE_ADDR => '127.0.0.1',
150 REMOTE_HOST => 'localhost',
151 REMOTE_PORT => int( rand(64000) + 1000 ), # not in RFC 3875
152 REQUEST_URI => $uri->path_query, # not in RFC 3875
153 REQUEST_METHOD => $request->method
156 if ( my $authorization = $request->header('Authorization') ) {
158 ( my $scheme ) = $authorization =~ /^($HTTP_Token+)/o;
160 if ( $scheme =~ /^Basic/i ) {
162 if ( ( my $username ) = $request->headers->authorization_basic ) {
163 $cgi{AUTH_TYPE} = 'Basic';
164 $cgi{REMOTE_USER} = $username;
167 elsif ( $scheme =~ /^Digest/i ) {
169 if ( ( my $username ) = $authorization =~ /username="([^"]+)"/ ) {
170 $cgi{AUTH_TYPE} = 'Digest';
171 $cgi{REMOTE_USER} = $username;
176 foreach my $key ( keys %cgi ) {
178 unless ( exists $environment->{ $key } ) {
179 $environment->{ $key } = $cgi{ $key };
183 foreach my $field ( $request->headers->header_field_names ) {
185 my $key = uc("HTTP_$field");
187 $key =~ s/^HTTP_// if $field =~ /^Content-(Length|Type)$/;
189 unless ( exists $environment->{ $key } ) {
190 $environment->{ $key } = $request->headers->header($field);
194 if ( $environment->{SCRIPT_NAME} ne '/' && $environment->{PATH_INFO} ) {
195 $environment->{PATH_INFO} =~ s/^\Q$environment->{SCRIPT_NAME}\E/\//;
196 $environment->{PATH_INFO} =~ s/^\/+/\//;
199 $self->is_prepared(1);
205 if ( $self->is_setup ) {
206 croak( 'An attempt was made to setup environment variables and '
207 . 'standard filehandles which has already been setup.' );
210 if ( $self->should_setup_content && $self->has_stdin ) {
211 $self->setup_content;
214 if ( $self->has_stdin ) {
216 if ( $self->should_dup ) {
218 if ( $self->should_restore ) {
220 open( my $stdin, '<&STDIN' )
221 or croak("Couldn't dup STDIN: '$!'");
223 $self->{restore}->{stdin} = $stdin;
226 open( STDIN, '<&' . fileno($self->stdin) )
227 or croak("Couldn't dup stdin filehandle to STDIN: '$!'");
231 my $stdin = Symbol::qualify_to_ref('STDIN');
233 if ( $self->should_restore ) {
235 $self->{restore}->{stdin} = *$stdin;
236 $self->{restore}->{stdin_ref} = \*$stdin;
239 *$stdin = $self->stdin;
242 binmode( $self->stdin );
246 if ( $self->has_stdout ) {
248 if ( $self->should_dup ) {
250 if ( $self->should_restore ) {
252 open( my $stdout, '>&STDOUT' )
253 or croak("Couldn't dup STDOUT: '$!'");
255 $self->{restore}->{stdout} = $stdout;
258 open( STDOUT, '>&' . fileno($self->stdout) )
259 or croak("Couldn't dup stdout filehandle to STDOUT: '$!'");
263 my $stdout = Symbol::qualify_to_ref('STDOUT');
265 if ( $self->should_restore ) {
267 $self->{restore}->{stdout} = *$stdout;
268 $self->{restore}->{stdout_ref} = \*$stdout;
271 *$stdout = $self->stdout;
274 binmode( $self->stdout );
278 if ( $self->has_stderr ) {
280 if ( $self->should_dup ) {
282 if ( $self->should_restore ) {
284 open( my $stderr, '>&STDERR' )
285 or croak("Couldn't dup STDERR: '$!'");
287 $self->{restore}->{stderr} = $stderr;
290 open( STDERR, '>&' . fileno($self->stderr) )
291 or croak("Couldn't dup stdout filehandle to STDOUT: '$!'");
295 my $stderr = Symbol::qualify_to_ref('STDERR');
297 if ( $self->should_restore ) {
299 $self->{restore}->{stderr} = *$stderr;
300 $self->{restore}->{stderr_ref} = \*$stderr;
303 *$stderr = $self->stderr;
306 binmode( $self->stderr );
311 no warnings 'uninitialized';
313 if ( $self->should_restore ) {
314 $self->{restore}->{environment} = { %ENV };
317 %ENV = %{ $self->environment };
320 if ( $INC{'CGI.pm'} ) {
321 CGI::initialize_globals();
331 my $stdin = shift || $self->stdin;
333 my $content = $self->request->content_ref;
335 if ( ref($content) eq 'SCALAR' ) {
337 if ( defined($$content) && length($$content) ) {
339 print( { $stdin } $$content )
340 or croak("Couldn't write request content SCALAR to stdin filehandle: '$!'");
342 if ( $self->should_rewind ) {
344 seek( $stdin, 0, SEEK_SET )
345 or croak("Couldn't rewind stdin filehandle: '$!'");
349 elsif ( ref($content) eq 'CODE' ) {
353 my $chunk = &$content();
355 if ( defined($chunk) && length($chunk) ) {
357 print( { $stdin } $chunk )
358 or croak("Couldn't write request content callback to stdin filehandle: '$!'");
365 if ( $self->should_rewind ) {
367 seek( $stdin, 0, SEEK_SET )
368 or croak("Couldn't rewind stdin filehandle: '$!'");
372 croak("Couldn't write request content to stdin filehandle: 'Unknown request content $content'");
378 my %params = ( headers_only => 0, sync => 0, @_ );
380 return undef unless $self->has_stdout;
382 if ( $self->should_rewind ) {
384 seek( $self->stdout, 0, SEEK_SET )
385 or croak("Couldn't rewind stdout filehandle: '$!'");
389 my $response = HTTP::Response->new( 200, 'OK' );
390 $response->protocol('HTTP/1.1');
392 while ( my $line = readline($self->stdout) ) {
394 if ( !$message && $line =~ /^\x0d?\x0a$/ ) {
401 last if $message =~ /\x0d?\x0a\x0d?\x0a$/;
405 $response->code(500);
406 $response->message('Internal Server Error');
407 $response->date( time() );
408 $response->content( $response->error_as_HTML );
409 $response->content_type('text/html');
410 $response->content_length( length $response->content );
415 if ( $message =~ s/^($HTTP_Version)[\x09\x20]+(\d\d\d)[\x09\x20]+([\x20-\xFF]*)\x0D?\x0A//o ) {
416 $response->protocol($1);
418 $response->message($3);
421 $message =~ s/\x0D?\x0A[\x09\x20]+/\x20/gs;
423 foreach ( split /\x0D?\x0A/, $message ) {
427 if ( /^($HTTP_Token+)[\x09\x20]*:[\x09\x20]*([\x20-\xFF]+)$/o ) {
428 $response->headers->push_header( $1 => $2 );
431 # XXX what should we do on bad headers?
435 my $status = $response->header('Status');
437 if ( $status && $status =~ /^(\d\d\d)[\x09\x20]+([\x20-\xFF]+)$/ ) {
439 $response->message($2);
442 if ( !$response->date ) {
443 $response->date(time());
446 if ( $params{headers_only} ) {
448 if ( $params{sync} ) {
450 my $position = tell( $self->stdout )
451 or croak("Couldn't get file position from stdout filehandle: '$!'");
453 sysseek( $self->stdout, $position, SEEK_SET )
454 or croak("Couldn't seek stdout filehandle: '$!'");
461 my $content_length = 0;
465 my $r = read( $self->stdout, $content, 65536, $content_length );
473 $content_length += $r;
477 croak("Couldn't read response content from stdin filehandle: '$!'");
481 if ( $content_length ) {
483 $response->content_ref(\$content);
485 if ( !$response->content_length ) {
486 $response->content_length($content_length);
496 if ( !$self->should_restore ) {
497 croak( 'An attempt was made to restore environment variables and '
498 . 'standard filehandles which has not been saved.' );
501 if ( !$self->is_setup ) {
502 croak( 'An attempt was made to restore environment variables and '
503 . 'standard filehandles which has not been setup.' );
506 if ( $self->is_restored ) {
507 croak( 'An attempt was made to restore environment variables and '
508 . 'standard filehandles which has already been restored.' );
512 no warnings 'uninitialized';
513 %ENV = %{ $self->{restore}->{environment} };
516 if ( $self->has_stdin ) {
518 my $stdin = $self->{restore}->{stdin};
520 if ( $self->should_dup ) {
522 STDIN->fdopen( fileno($stdin), '<' )
523 or croak("Couldn't restore STDIN: '$!'");
527 my $stdin_ref = $self->{restore}->{stdin_ref};
528 *$stdin_ref = $stdin;
531 if ( $self->should_rewind ) {
533 seek( $self->stdin, 0, SEEK_SET )
534 or croak("Couldn't rewind stdin filehandle: '$!'");
538 if ( $self->has_stdout ) {
540 my $stdout = $self->{restore}->{stdout};
542 if ( $self->should_dup ) {
545 or croak("Couldn't flush STDOUT: '$!'");
547 STDOUT->fdopen( fileno($stdout), '>' )
548 or croak("Couldn't restore STDOUT: '$!'");
552 my $stdout_ref = $self->{restore}->{stdout_ref};
553 *$stdout_ref = $stdout;
556 if ( $self->should_rewind ) {
558 seek( $self->stdout, 0, SEEK_SET )
559 or croak("Couldn't rewind stdout filehandle: '$!'");
563 if ( $self->has_stderr ) {
565 my $stderr = $self->{restore}->{stderr};
567 if ( $self->should_dup ) {
570 or croak("Couldn't flush STDERR: '$!'");
572 STDERR->fdopen( fileno($stderr), '>' )
573 or croak("Couldn't restore STDERR: '$!'");
577 my $stderr_ref = $self->{restore}->{stderr_ref};
578 *$stderr_ref = $stderr;
581 if ( $self->should_rewind ) {
583 seek( $self->stderr, 0, SEEK_SET )
584 or croak("Couldn't rewind stderr filehandle: '$!'");
588 $self->{restore} = {};
590 $self->is_restored(1);
598 if ( $self->should_restore && $self->is_setup && !$self->is_restored ) {
609 HTTP::Request::AsCGI - Setup a Common Gateway Interface environment from a HTTP::Request
615 use HTTP::Request::AsCGI;
617 my $request = HTTP::Request->new( GET => 'http://www.host.com/' );
621 my $c = HTTP::Request::AsCGI->new($request)->setup;
625 $q->start_html('Hello World'),
626 $q->h1('Hello World'),
629 $stdout = $c->stdout;
631 # environment and descriptors is automatically restored
632 # when $c is destructed.
635 while ( my $line = $stdout->getline ) {
641 Provides a convinient way of setting up an CGI environment from a HTTP::Request.
649 Contructor, this method takes a hash of parameters. The following parameters are
656 request => HTTP::Request->new( GET => 'http://www.host.com/' )
660 A filehandle to be used as standard input, defaults to a temporary filehandle.
661 If C<stdin> is C<undef>, standard input will be left as is.
663 stdin => IO::File->new_tmpfile
664 stdin => IO::String->new
670 A filehandle to be used as standard output, defaults to a temporary filehandle.
671 If C<stdout> is C<undef>, standard output will be left as is.
673 stdout => IO::File->new_tmpfile
674 stdout => IO::String->new
680 A filehandle to be used as standard error, defaults to C<undef>. If C<stderr> is
681 C<undef>, standard error will be left as is.
683 stderr => IO::File->new_tmpfile
684 stderr => IO::String->new
690 A C<HASH> of additional environment variables to be used in CGI.
691 C<HTTP::Request::AsCGI> doesn't autmatically merge C<%ENV>, it has to be
692 explicitly given if that is desired. Environment variables given in this
693 C<HASH> isn't overridden by C<HTTP::Request::AsCGI>.
696 environment => { PATH => '/bin:/usr/bin', SERVER_SOFTWARE => 'Apache/1.3' }
698 Following standard meta-variables (in addition to protocol-specific) is setup:
716 Following non-standard but common meta-variables is setup:
722 Following meta-variables is B<not> setup but B<must> be provided in CGI:
726 Following meta-variables is B<not> setup but common in CGI:
734 Boolean to indicate whether to C<dup> standard filehandle or to assign the
735 typeglob representing the standard filehandle. Defaults to C<true>.
742 Boolean to indicate whether or not to restore environment variables and standard
743 filehandles. Defaults to C<true>.
748 If C<true> standard filehandles and environment variables will be saved duiring
749 C<setup> for later use in C<restore>.
753 Boolean to indicate whether or not to rewind standard filehandles. Defaults
761 Boolean to indicate whether or not to request content should be written to
762 C<stdin> filehandle when C<setup> is invoked. Defaults to C<true>.
771 Attempts to setup standard filehandles and environment variables.
775 Attempts to restore standard filehandles and environment variables.
779 Attempts to parse C<stdout> filehandle into a L<HTTP::Response>.
783 Accessor for L<HTTP::Request> that was given to constructor.
787 Accessor for environment variables to be used in C<setup>.
791 Accessor/Mutator for standard input filehandle.
795 Accessor/Mutator for standard output filehandle.
799 Accessor/Mutator for standard error filehandle.
811 =item examples directory in this distribution.
813 =item L<WWW::Mechanize::CGI>
815 =item L<Test::WWW::Mechanize::CGI>
821 Thomas L. Shinnick for his valuable win32 testing.
825 Christian Hansen, C<ch@ngmedia.com>
829 This library is free software. You can redistribute it and/or modify
830 it under the same terms as perl itself.