More tweaks to H::R::AsCGI, should now be possible to use pipes/sockets as std handles.
[catagits/HTTP-Request-AsCGI.git] / lib / HTTP / Request / AsCGI.pm
index 226420c..d6b3de2 100644 (file)
@@ -5,37 +5,134 @@ use warnings;
 use bytes;
 use base 'Class::Accessor::Fast';
 
-use Carp;
-use IO::Handle;
-use IO::File;
+use Carp            qw[croak];
+use HTTP::Response  qw[];
+use IO::Handle      qw[];
+use IO::File        qw[SEEK_SET];
+use Symbol          qw[];
 
-__PACKAGE__->mk_accessors(qw[ enviroment request stdin stdout stderr ]);
+__PACKAGE__->mk_accessors( qw[ is_setuped
+                               is_prepared
+                               is_restored
 
-our $VERSION = 0.2;
+                               should_dup
+                               should_restore
+                               should_rewind
+                               should_setup_content
+
+                               environment
+                               request
+                               stdin
+                               stdout
+                               stderr ] );
+
+our $VERSION = 0.6_01;
 
 sub new {
-    my $class   = shift;
-    my $request = shift;
-    
-    unless ( @_ % 2 == 0 && eval { $request->isa('HTTP::Request') } ) {
-        croak(qq/usage: $class->new( \$request [, key => value] )/);
-    }
-    
-    my $self = $class->SUPER::new( { restored => 0, setuped => 0 } );
-    $self->request($request);
-    $self->stdin( IO::File->new_tmpfile );
-    $self->stdout( IO::File->new_tmpfile );
+    my $class  = ref $_[0] ? ref shift : shift;
+    my $params = {};
+
+    if ( @_ % 2 == 0 ) {
+        $params = { @_ };
+    }
+    else {
+        $params = { request => shift, environment => { @_ } };
+    }
+
+    return bless( {}, $class )->initialize($params);
+}
+
+sub initialize {
+    my ( $self, $params ) = @_;
+
+    if ( exists $params->{request} ) {
+        $self->request( $params->{request} );
+    }
+    else {
+        croak("Mandatory parameter 'request' is missing.");
+    }
+
+    if ( exists $params->{environment} ) {
+        $self->environment( $params->{environment} );
+    }
+    else {
+        $self->environment( {} );
+    }
+
+    if ( exists $params->{stdin} ) {
+        $self->stdin( $params->{stdin} );
+    }
+    else {
+        $self->stdin( IO::File->new_tmpfile );
+    }
+
+    if ( exists $params->{stdout} ) {
+        $self->stdout( $params->{stdout} );
+    }
+    else {
+        $self->stdout( IO::File->new_tmpfile );
+    }
+
+    if ( exists $params->{stderr} ) {
+        $self->stderr( $params->{stderr} );
+    }
+
+    if ( exists $params->{dup} ) {
+        $self->should_dup( $params->{dup} ? 1 : 0 );
+    }
+    else {
+        $self->should_dup(1);
+    }
+
+    if ( exists $params->{restore} ) {
+        $self->should_restore( $params->{restore} ? 1 : 0 );
+    }
+    else {
+        $self->should_restore(1);
+    }
+
+    if ( exists $params->{rewind} ) {
+        $self->should_rewind( $params->{rewind} ? 1 : 0 );
+    }
+    else {
+        $self->should_rewind(1);
+    }
+
+    if ( exists $params->{content} ) {
+        $self->should_setup_content( $params->{content} ? 1 : 0 );
+    }
+    else {
+        $self->should_setup_content(1);
+    }
+
+    $self->prepare;
+
+    return $self;
+}
+
+*enviroment = \&environment;
+
+sub has_stdin  { return defined $_[0]->stdin  }
+sub has_stdout { return defined $_[0]->stdout }
+sub has_stderr { return defined $_[0]->stderr }
+
+sub prepare {
+    my $self = shift;
+
+    my $environment = $self->environment;
+    my $request     = $self->request;
 
     my $host = $request->header('Host');
     my $uri  = $request->uri->clone;
+
     $uri->scheme('http')    unless $uri->scheme;
     $uri->host('localhost') unless $uri->host;
     $uri->port(80)          unless $uri->port;
     $uri->host_port($host)  unless !$host || ( $host eq $uri->host_port );
-    
+
     $uri = $uri->canonical;
 
-    my $enviroment = {
+    my %cgi = (
         GATEWAY_INTERFACE => 'CGI/1.1',
         HTTP_HOST         => $uri->host_port,
         HTTPS             => ( $uri->scheme eq 'https' ) ? 'ON' : 'OFF',  # not in RFC 3875
@@ -50,162 +147,307 @@ sub new {
         REMOTE_HOST       => 'localhost',
         REMOTE_PORT       => int( rand(64000) + 1000 ),                   # not in RFC 3875
         REQUEST_URI       => $uri->path_query,                            # not in RFC 3875
-        REQUEST_METHOD    => $request->method,
-        @_
-    };
+        REQUEST_METHOD    => $request->method
+    );
 
-    foreach my $field ( $request->headers->header_field_names ) {
+    foreach my $key ( keys %cgi ) {
+
+        unless ( exists $environment->{ $key } ) {
+            $environment->{ $key } = $cgi{ $key };
+        }
+    }
+
+    foreach my $field ( $self->request->headers->header_field_names ) {
 
         my $key = uc("HTTP_$field");
         $key =~ tr/-/_/;
         $key =~ s/^HTTP_// if $field =~ /^Content-(Length|Type)$/;
 
-        unless ( exists $enviroment->{$key} ) {
-            $enviroment->{$key} = $request->headers->header($field);
+        unless ( exists $environment->{ $key } ) {
+            $environment->{ $key } = $self->request->headers->header($field);
         }
     }
 
-    unless ( $enviroment->{SCRIPT_NAME} eq '/' && $enviroment->{PATH_INFO} ) {
-        $enviroment->{PATH_INFO} =~ s/^\Q$enviroment->{SCRIPT_NAME}\E/\//;
-        $enviroment->{PATH_INFO} =~ s/^\/+/\//;
+    unless ( $environment->{SCRIPT_NAME} eq '/' && $environment->{PATH_INFO} ) {
+        $environment->{PATH_INFO} =~ s/^\Q$environment->{SCRIPT_NAME}\E/\//;
+        $environment->{PATH_INFO} =~ s/^\/+/\//;
+    }
+
+    $self->is_prepared(1);
+}
+
+sub setup {
+    my $self = shift;
+
+    $self->setup_content;
+    $self->setup_stdin;
+    $self->setup_stdout;
+    $self->setup_stderr;
+    $self->setup_environment;
+
+    if ( $INC{'CGI.pm'} ) {
+        CGI::initialize_globals();
     }
 
-    $self->enviroment($enviroment);
+    $self->is_setuped(1);
 
     return $self;
 }
 
-sub setup {
+sub setup_content {
     my $self = shift;
 
-    $self->{restore}->{enviroment} = {%ENV};
+    if ( $self->should_setup_content && $self->has_stdin ) {
+
+        if ( $self->request->content_length ) {
+
+            my $content = $self->request->content_ref;
+
+            if ( ref $content eq 'SCALAR' ) {
 
-    binmode( $self->stdin );
+                if ( defined $$content && length $$content ) {
 
-    if ( $self->request->content_length ) {
+                    print( { $self->stdin } $$content )
+                      or croak("Couldn't write request content to stdin handle: '$!'");
 
-        syswrite( $self->stdin, $self->request->content )
-          or croak("Can't write request content to stdin handle: $!");
+                    if ( $self->should_rewind ) {
 
-        sysseek( $self->stdin, 0, SEEK_SET )
-          or croak("Can't seek stdin handle: $!");
+                        seek( $self->stdin, 0, SEEK_SET )
+                          or croak("Couldn't seek stdin handle: '$!'");
+                    }
+                }
+            }
+            else {
+                croak("Can't handle request content of '$content'");
+            }
+        }
     }
+}
+
+sub setup_stdin {
+    my $self = shift;
 
-    open( $self->{restore}->{stdin}, '>&', STDIN->fileno )
-      or croak("Can't dup stdin: $!");
+    if ( $self->has_stdin ) {
 
-    open( STDIN, '<&=', $self->stdin->fileno )
-      or croak("Can't open stdin: $!");
+        if ( $self->should_dup ) {
 
-    binmode( STDIN );
+            if ( $self->should_restore ) {
 
-    if ( $self->stdout ) {
+                open( my $stdin, '<&STDIN' )
+                  or croak("Couldn't dup STDIN: '$!'");
 
-        open( $self->{restore}->{stdout}, '>&', STDOUT->fileno )
-          or croak("Can't dup stdout: $!");
+                $self->{restore}->{stdin} = $stdin;
+            }
+
+            STDIN->fdopen( $self->stdin, '<' )
+              or croak("Couldn't dup stdin handle to STDIN: '$!'");
+        }
+        else {
 
-        open( STDOUT, '>&=', $self->stdout->fileno )
-          or croak("Can't open stdout: $!");
+            my $stdin = Symbol::qualify_to_ref('STDIN');
+
+            if ( $self->should_restore ) {
+
+                $self->{restore}->{stdin}     = *$stdin;
+                $self->{restore}->{stdin_ref} = \*$stdin;
+            }
+
+            *$stdin = $self->stdin;
+        }
+
+        binmode( $self->stdin );
+        binmode( STDIN );
+    }
+}
+
+sub setup_stdout {
+    my $self = shift;
+
+    if ( $self->has_stdout ) {
+
+        if ( $self->should_dup ) {
+
+            if ( $self->should_restore ) {
+
+                open( my $stdout, '>&STDOUT' )
+                  or croak("Couldn't dup STDOUT: '$!'");
+
+                $self->{restore}->{stdout} = $stdout;
+            }
+
+            STDOUT->fdopen( $self->stdout, '>' )
+              or croak("Couldn't dup stdout handle to STDOUT: '$!'");
+        }
+        else {
+
+            my $stdout = Symbol::qualify_to_ref('STDOUT');
+
+            if ( $self->should_restore ) {
+
+                $self->{restore}->{stdout}     = *$stdout;
+                $self->{restore}->{stdout_ref} = \*$stdout;
+            }
+
+            *$stdout = $self->stdout;
+        }
 
         binmode( $self->stdout );
         binmode( STDOUT);
     }
+}
 
-    if ( $self->stderr ) {
+sub setup_stderr {
+    my $self = shift;
 
-        open( $self->{restore}->{stderr}, '>&', STDERR->fileno )
-          or croak("Can't dup stderr: $!");
+    if ( $self->has_stderr ) {
 
-        open( STDERR, '>&=', $self->stderr->fileno )
-          or croak("Can't open stderr: $!");
+        if ( $self->should_dup ) {
+
+            if ( $self->should_restore ) {
+
+                open( my $stderr, '>&STDERR' )
+                  or croak("Couldn't dup STDERR: '$!'");
+
+                $self->{restore}->{stderr} = $stderr;
+            }
+
+            STDERR->fdopen( $self->stderr, '>' )
+              or croak("Couldn't dup stderr handle to STDERR: '$!'");
+        }
+        else {
+
+            my $stderr = Symbol::qualify_to_ref('STDERR');
+
+            if ( $self->should_restore ) {
+
+                $self->{restore}->{stderr}     = *$stderr;
+                $self->{restore}->{stderr_ref} = \*$stderr;
+            }
+
+            *$stderr = $self->stderr;
+        }
 
         binmode( $self->stderr );
         binmode( STDERR );
     }
+}
 
-    {
-        no warnings 'uninitialized';
-        %ENV = %{ $self->enviroment };
-    }
-    
-    if ( $INC{'CGI.pm'} ) {
-        CGI::initialize_globals();
-    }    
+sub setup_environment {
+    my $self = shift;
 
-    $self->{setuped}++;
+    no warnings 'uninitialized';
 
-    return $self;
+    if ( $self->should_restore ) {
+        $self->{restore}->{environment} = { %ENV };
+    }
+
+    %ENV = %{ $self->environment };
 }
 
 sub response {
-    my ( $self, $callback ) = @_;
+    my $self   = shift;
+    my %params = ( headers_only => 0, sync => 0, @_ );
 
-    return undef unless $self->{setuped};
-    return undef unless $self->{restored};
-    return undef unless $self->{restore}->{stdout};
+    return undef unless $self->has_stdout;
 
-    require HTTP::Response;
+    if ( $self->should_rewind ) {
 
-    seek( $self->stdout, 0, SEEK_SET )
-      or croak("Can't seek stdout handle: $!");
+        seek( $self->stdout, 0, SEEK_SET )
+          or croak("Couldn't seek stdout handle: '$!'");
+    }
+
+    my $message  = undef;
+    my $response = HTTP::Response->new( 200, 'OK' );
+       $response->protocol('HTTP/1.1');
 
-    my $message;
     while ( my $line = $self->stdout->getline ) {
         $message .= $line;
         last if $message =~ /\x0d?\x0a\x0d?\x0a$/;
     }
 
-    unless ( $message =~ /^HTTP/ ) {
-        $message = "HTTP/1.1 200 OK\x0d\x0a" . $message;
-    }
+    if ( !$message ) {
 
-    my $response = HTTP::Response->new;
-    my @headers  = split( /\x0d?\x0a/, $message );
-    my $status   = shift(@headers);
+        $response->code(500);
+        $response->message('Internal Server Error');
+        $response->date( time );
+        $response->content( $response->error_as_HTML );
+        $response->content_type('text/html');
+        $response->content_length( length $response->content );
 
-    unless ( $status =~ s/^(HTTP\/\d\.\d) (\d{3}) (.*)$// ) {
-        croak( "Invalid Status-Line: '$status'" );
+        return $response;
     }
 
-    $response->protocol($1);
-    $response->code($2);
-    $response->message($3);
+    my $Token   = qr/[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7A\x7C\x7E]/;
+    my $Version = qr/HTTP\/[0-9]+\.[0-9]+/;
+
+    if ( $message =~ s/^($Version)[\x09\x20]+(\d{3})[\x09\x20]+([\x20-\xFF]*)\x0D?\x0A//o ) {
+
+        $response->protocol($1);
+        $response->code($2);
+        $response->message($3);
+    }
 
-    my $token = qr/[^][\x00-\x1f\x7f()<>@,;:\\"\/?={} \t]+/;
+    $message =~ s/\x0D?\x0A[\x09\x20]+/\x20/gs;
 
-    foreach my $header (@headers) {
+    foreach ( split /\x0D?\x0A/, $message ) {
 
-        unless( $header =~ s/^($token):[\t ]*// ) {
-            croak( "Invalid header field name : '$header'" );
+        if ( /^($Token+)[\x09\x20]*:[\x09\x20]*([\x20-\xFF]+)[\x09\x20]*$/o ) {
+            $response->headers->push_header( $1 => $2 );
         }
+        else {
+            # XXX what should we do on bad headers?
+        }
+    }
 
-        $response->push_header( $1 => $header );
-    }    
+    my $status = $response->header('Status');
 
-    if ( my $code = $response->header('Status') ) {
-        $response->code($code);
-        $response->message( HTTP::Status::status_message($code) );
+    if ( $status && $status =~ /^(\d{3})[\x09\x20]+([\x20-\xFF]+)$/ ) {
+        $response->code($1);
+        $response->message($2);
     }
 
-    $response->headers->date( time() );
+    if ( !$response->date ) {
+        $response->date(time);
+    }
 
-    if ($callback) {
-        $response->content( sub {
-            if ( $self->stdout->read( my $buffer, 4096 ) ) {
-                return $buffer;
-            }
-            return undef;
-        });
+    if ( $params{headers_only} ) {
+
+        if ( $params{sync} ) {
+
+            my $position = tell( $self->stdout )
+              or croak("Couldn't get file position from stdout handle: '$!'");
+
+            sysseek( $self->stdout, $position, SEEK_SET )
+              or croak("Couldn't seek stdout handle: '$!'");
+        }
+
+        return $response;
     }
-    else {
-        my $length = 0;
-        while ( $self->stdout->read( my $buffer, 4096 ) ) {
-            $length += length($buffer);
-            $response->add_content($buffer);
+
+    my $content        = undef;
+    my $content_length = 0;
+
+    while () {
+
+        my $r = $self->stdout->read( $content, 65536, $content_length );
+
+        if ( defined $r ) {
+
+            $content_length += $r;
+
+            last unless $r;
         }
-        
-        if ( $length && !$response->content_length ) {
-            $response->content_length($length);
+        else {
+            croak("Couldn't read response content from stdin handle: '$!'");
+        }
+    }
+
+    if ( $content_length ) {
+
+        $response->content_ref(\$content);
+
+        if ( !$response->content_length ) {
+            $response->content_length($content_length);
         }
     }
 
@@ -215,46 +457,119 @@ sub response {
 sub restore {
     my $self = shift;
 
-    %ENV = %{ $self->{restore}->{enviroment} };
+    if ( $self->should_restore ) {
+
+        $self->restore_environment;
+        $self->restore_stdin;
+        $self->restore_stdout;
+        $self->restore_stderr;
+
+        $self->{restore} = {};
+
+        $self->is_restored(1);
+    }
+
+    return $self;
+}
+
+sub restore_environment {
+    my $self = shift;
+
+    no warnings 'uninitialized';
+
+    %ENV = %{ $self->{restore}->{environment} };
+}
+
+sub restore_stdin {
+    my $self = shift;
+
+    if ( $self->has_stdin ) {
 
-    open( STDIN, '>&', $self->{restore}->{stdin} )
-      or croak("Can't restore stdin: $!");
+        my $stdin = $self->{restore}->{stdin};
 
-    sysseek( $self->stdin, 0, SEEK_SET )
-      or croak("Can't seek stdin: $!");
+        if ( $self->should_dup ) {
 
-    if ( $self->{restore}->{stdout} ) {
+            STDIN->fdopen( $stdin, '<' )
+              or croak("Couldn't restore STDIN: '$!'");
+        }
+        else {
 
-        STDOUT->flush
-          or croak("Can't flush stdout: $!");
+            my $stdin_ref = $self->{restore}->{stdin_ref};
+              *$stdin_ref = $stdin;
+        }
 
-        open( STDOUT, '>&', $self->{restore}->{stdout} )
-          or croak("Can't restore stdout: $!");
+        if ( $self->should_rewind ) {
 
-        sysseek( $self->stdout, 0, SEEK_SET )
-          or croak("Can't seek stdout: $!");
+            seek( $self->stdin, 0, SEEK_SET )
+              or croak("Couldn't seek stdin handle: '$!'");
+        }
     }
+}
 
-    if ( $self->{restore}->{stderr} ) {
+sub restore_stdout {
+    my $self = shift;
+
+    if ( $self->has_stdout ) {
+
+        my $stdout = $self->{restore}->{stdout};
+
+        if ( $self->should_dup ) {
 
-        STDERR->flush
-          or croak("Can't flush stderr: $!");
+            STDOUT->flush
+              or croak("Couldn't flush STDOUT: '$!'");
 
-        open( STDERR, '>&', $self->{restore}->{stderr} )
-          or croak("Can't restore stderr: $!");
+            STDOUT->fdopen( $stdout, '>' )
+              or croak("Couldn't restore STDOUT: '$!'");
+        }
+        else {
+
+            my $stdout_ref = $self->{restore}->{stdout_ref};
+              *$stdout_ref = $stdout;
+        }
 
-        sysseek( $self->stderr, 0, SEEK_SET )
-          or croak("Can't seek stderr: $!");
+        if ( $self->should_rewind ) {
+
+            seek( $self->stdout, 0, SEEK_SET )
+              or croak("Couldn't seek stdout handle: '$!'");
+        }
     }
+}
 
-    $self->{restored}++;
+sub restore_stderr {
+    my $self = shift;
 
-    return $self;
+    if ( $self->has_stderr ) {
+
+        my $stderr = $self->{restore}->{stderr};
+
+        if ( $self->should_dup ) {
+
+            STDERR->flush
+              or croak("Couldn't flush STDERR: '$!'");
+
+            STDERR->fdopen( $stderr, '>' )
+              or croak("Couldn't restore STDERR: '$!'");
+        }
+        else {
+
+            my $stderr_ref = $self->{restore}->{stderr_ref};
+              *$stderr_ref = $stderr;
+        }
+
+        if ( $self->should_rewind ) {
+
+            seek( $self->stderr, 0, SEEK_SET )
+              or croak("Couldn't seek stderr handle: '$!'");
+        }
+    }
 }
 
 sub DESTROY {
     my $self = shift;
-    $self->restore if $self->{setuped} && !$self->{restored};
+
+    if ( $self->should_restore && $self->is_setuped && !$self->is_restored ) {
+        $self->restore;
+    }
 }
 
 1;
@@ -263,52 +578,52 @@ __END__
 
 =head1 NAME
 
-HTTP::Request::AsCGI - Setup a CGI enviroment from a HTTP::Request
+HTTP::Request::AsCGI - Setup a CGI environment from a HTTP::Request
 
 =head1 SYNOPSIS
 
     use CGI;
     use HTTP::Request;
     use HTTP::Request::AsCGI;
-    
+
     my $request = HTTP::Request->new( GET => 'http://www.host.com/' );
     my $stdout;
-    
+
     {
         my $c = HTTP::Request::AsCGI->new($request)->setup;
         my $q = CGI->new;
-        
+
         print $q->header,
               $q->start_html('Hello World'),
               $q->h1('Hello World'),
               $q->end_html;
-        
+
         $stdout = $c->stdout;
-        
-        # enviroment and descriptors will automatically be restored 
+
+        # environment and descriptors will automatically be restored
         # when $c is destructed.
     }
-    
+
     while ( my $line = $stdout->getline ) {
         print $line;
     }
-    
+
 =head1 DESCRIPTION
 
-Provides a convinient way of setting up an CGI enviroment from a HTTP::Request.
+Provides a convinient way of setting up an CGI environment from a HTTP::Request.
 
 =head1 METHODS
 
-=over 4 
+=over 4
 
 =item new ( $request [, key => value ] )
 
 Contructor, first argument must be a instance of HTTP::Request
 followed by optional pairs of environment key and value.
 
-=item enviroment
+=item environment
 
-Returns a hashref containing the environment that will be used in setup. 
+Returns a hashref containing the environment that will be used in setup.
 Changing the hashref after setup has been called will have no effect.
 
 =item setup
@@ -317,7 +632,7 @@ Setups the environment and descriptors.
 
 =item restore
 
-Restores the enviroment and descriptors. Can only be called after setup.
+Restores the environment and descriptors. Can only be called after setup.
 
 =item request
 
@@ -344,6 +659,18 @@ handle with an file descriptor.
 
 =back
 
+=head1 SEE ALSO
+
+=over 4
+
+=item examples directory in this distribution.
+
+=item L<WWW::Mechanize::CGI>
+
+=item L<Test::WWW::Mechanize::CGI>
+
+=back
+
 =head1 THANKS TO
 
 Thomas L. Shinnick for his valuable win32 testing.
@@ -354,7 +681,7 @@ Christian Hansen, C<ch@ngmedia.com>
 
 =head1 LICENSE
 
-This library is free software. You can redistribute it and/or modify 
+This library is free software. You can redistribute it and/or modify
 it under the same terms as perl itself.
 
 =cut