fix content-length for CGI scripts that don't print any headers
[catagits/HTTP-Request-AsCGI.git] / lib / HTTP / Request / AsCGI.pm
index 4cc479a..decddd6 100644 (file)
 package HTTP::Request::AsCGI;
-
+# ABSTRACT: Set up a CGI environment from an HTTP::Request
 use strict;
 use warnings;
 use bytes;
 use base 'Class::Accessor::Fast';
 
-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[ is_setuped
-                               is_prepared
-                               is_restored
-
-                               should_dup
-                               should_restore
-                               should_rewind
-                               should_setup_content
-
-                               environment
-                               request
-                               stdin
-                               stdout
-                               stderr ] );
-
-our $VERSION = 0.6_01;
-
-sub new {
-    my $class  = ref $_[0] ? ref shift : shift;
-    my $params = {};
+use Carp;
+use HTTP::Response;
+use IO::Handle;
+use IO::File;
+use URI ();
+use URI::Escape ();
 
-    if ( @_ % 2 == 0 ) {
-        $params = { @_ };
-    }
-    else {
-        $params = { request => shift, environment => { @_ } };
-    }
+__PACKAGE__->mk_accessors(qw[ environment request stdin stdout stderr ]);
 
-    return bless( {}, $class )->initialize($params);
-}
+# old typo
 
-sub initialize {
-    my ( $self, $params ) = @_;
+=begin Pod::Coverage
 
-    if ( exists $params->{request} ) {
-        $self->request( $params->{request} );
-    }
-    else {
-        croak("Mandatory parameter 'request' is missing.");
-    }
+  enviroment
 
-    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} );
-    }
+=end Pod::Coverage
 
-    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);
-    }
+=cut
 
-    $self->prepare;
+*enviroment = \&environment;
 
-    return $self;
+my %reserved = map { sprintf('%02x', ord($_)) => 1 } split //, $URI::reserved;
+sub _uri_safe_unescape {
+    my ($s) = @_;
+    $s =~ s/%([a-fA-F0-9]{2})/$reserved{lc($1)} ? "%$1" : pack('C', hex($1))/ge;
+    $s
 }
 
-*enviroment = \&environment;
-
-sub has_stdin  { return defined $_[0]->stdin  }
-sub has_stdout { return defined $_[0]->stdout }
-sub has_stderr { return defined $_[0]->stderr }
+sub new {
+    my $class   = shift;
+    my $request = shift;
 
-sub prepare {
-    my $self = shift;
+    unless ( @_ % 2 == 0 && eval { $request->isa('HTTP::Request') } ) {
+        croak(qq/usage: $class->new( \$request [, key => value] )/);
+    }
 
-    my $environment = $self->environment;
-    my $request     = $self->request;
+    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 $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 );
 
+    # Get it before canonicalized so REQUEST_URI can be as raw as possible
+    my $request_uri = $uri->path_query;
+
     $uri = $uri->canonical;
 
-    my %cgi = (
+    my $environment = {
         GATEWAY_INTERFACE => 'CGI/1.1',
         HTTP_HOST         => $uri->host_port,
         HTTPS             => ( $uri->scheme eq 'https' ) ? 'ON' : 'OFF',  # not in RFC 3875
@@ -142,29 +68,30 @@ sub prepare {
         SERVER_NAME       => $uri->host,
         SERVER_PORT       => $uri->port,
         SERVER_PROTOCOL   => $request->protocol || 'HTTP/1.1',
-        SERVER_SOFTWARE   => "HTTP-Request-AsCGI/$VERSION",
+        SERVER_SOFTWARE   => 'HTTP-Request-AsCGI/' . our $VERSION,
         REMOTE_ADDR       => '127.0.0.1',
         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
-    );
-
-    foreach my $key ( keys %cgi ) {
+        REQUEST_URI       => $request_uri,                                # not in RFC 3875
+        REQUEST_METHOD    => $request->method,
+        @_
+    };
 
-        unless ( exists $environment->{ $key } ) {
-            $environment->{ $key } = $cgi{ $key };
-        }
-    }
+    # RFC 3875 says PATH_INFO is not URI-encoded. That's really
+    # annoying for applications that you can't tell "%2F" vs "/", but
+    # doing the partial decoding then makes it impossible to tell
+    # "%252F" vs "%2F". Encoding everything is more compatible to what
+    # web servers like Apache or lighttpd do, anyways.
+    $environment->{PATH_INFO} = URI::Escape::uri_unescape($environment->{PATH_INFO});
 
-    foreach my $field ( $self->request->headers->header_field_names ) {
+    foreach my $field ( $request->headers->header_field_names ) {
 
         my $key = uc("HTTP_$field");
         $key =~ tr/-/_/;
         $key =~ s/^HTTP_// if $field =~ /^Content-(Length|Type)$/;
 
-        unless ( exists $environment->{ $key } ) {
-            $environment->{ $key } = $self->request->headers->header($field);
+        unless ( exists $environment->{$key} ) {
+            $environment->{$key} = $request->headers->header($field);
         }
     }
 
@@ -173,308 +100,151 @@ sub prepare {
         $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->is_setuped(1);
+    $self->environment($environment);
 
     return $self;
 }
 
-sub write_content {
-    my ( $self, $handle ) = @_;
-
-    my $content = $self->request->content_ref;
-
-    if ( ref($content) eq 'SCALAR' ) {
-
-        if ( defined($$content) && length($$content) ) {
-
-            print( { $self->stdin } $$content )
-              or croak("Couldn't write request content to stdin handle: '$!'");
-
-            if ( $self->should_rewind ) {
-
-                seek( $self->stdin, 0, SEEK_SET )
-                  or croak("Couldn't seek stdin handle: '$!'");
-            }
-        }
-    }
-    elsif ( ref($content) eq 'CODE' ) {
-
-        while () {
-
-            my $chunk = &$content();
-
-            if ( defined($chunk) && length($chunk) ) {
-
-                print( { $self->stdin } $chunk )
-                  or croak("Couldn't write request content chunk to stdin handle: '$!'");
-            }
-            else {
-                last;
-            }
-        }
-
-        if ( $self->should_rewind ) {
-
-            seek( $self->stdin, 0, SEEK_SET )
-              or croak("Couldn't seek stdin handle: '$!'");
-        }
-    }
-    else {
-        croak("Couldn't write request content to stdin handle: 'Unknown request content $content'");
-    }
-}
-
-sub setup_content {
-    my $self = shift;
-
-    if ( $self->has_stdin && $self->should_setup_content ) {
-        $self->write_content($self->stdin);
-    }
-}
-
-sub setup_stdin {
+sub setup {
     my $self = shift;
 
-    if ( $self->has_stdin ) {
-
-        if ( $self->should_dup ) {
-
-            if ( $self->should_restore ) {
+    $self->{restore}->{environment} = {%ENV};
 
-                open( my $stdin, '<&STDIN' )
-                  or croak("Couldn't dup STDIN: '$!'");
+    binmode( $self->stdin );
 
-                $self->{restore}->{stdin} = $stdin;
-            }
-
-            STDIN->fdopen( $self->stdin, '<' )
-              or croak("Couldn't dup stdin handle to STDIN: '$!'");
-        }
-        else {
+    if ( $self->request->content_length ) {
 
-            my $stdin = Symbol::qualify_to_ref('STDIN');
+        $self->stdin->print($self->request->content)
+          or croak("Can't write request content to stdin handle: $!");
 
-            if ( $self->should_restore ) {
+        $self->stdin->seek(0, SEEK_SET)
+          or croak("Can't seek stdin handle: $!");
 
-                $self->{restore}->{stdin}     = *$stdin;
-                $self->{restore}->{stdin_ref} = \*$stdin;
-            }
-
-            *$stdin = $self->stdin;
-        }
-
-        binmode( $self->stdin );
-        binmode( STDIN );
+        $self->stdin->flush
+          or croak("Can't flush stdin handle: $!");
     }
-}
 
-sub setup_stdout {
-    my $self = shift;
+    open( $self->{restore}->{stdin}, '<&'. STDIN->fileno )
+      or croak("Can't dup stdin: $!");
 
-    if ( $self->has_stdout ) {
+    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 $stdout, '>&STDOUT' )
-                  or croak("Couldn't dup STDOUT: '$!'");
+        open( $self->{restore}->{stdout}, '>&'. STDOUT->fileno )
+          or croak("Can'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;
-        }
+        open( STDOUT, '>&='. $self->stdout->fileno )
+          or croak("Can't open stdout: $!");
 
         binmode( $self->stdout );
         binmode( STDOUT);
     }
-}
 
-sub setup_stderr {
-    my $self = shift;
+    if ( $self->stderr ) {
 
-    if ( $self->has_stderr ) {
+        open( $self->{restore}->{stderr}, '>&'. STDERR->fileno )
+          or croak("Can't dup 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;
-        }
+        open( STDERR, '>&='. $self->stderr->fileno )
+          or croak("Can't open stderr: $!");
 
         binmode( $self->stderr );
         binmode( STDERR );
     }
-}
 
-sub setup_environment {
-    my $self = shift;
-
-    no warnings 'uninitialized';
+    {
+        no warnings 'uninitialized';
+        %ENV = (%ENV, %{ $self->environment });
+    }
 
-    if ( $self->should_restore ) {
-        $self->{restore}->{environment} = { %ENV };
+    if ( $INC{'CGI.pm'} ) {
+        CGI::initialize_globals();
     }
 
-    %ENV = %{ $self->environment };
-}
+    $self->{setuped}++;
 
-my $HTTP_Token   = qr/[\x21\x23-\x27\x2A\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7A\x7C\x7E]/;
-my $HTTP_Version = qr/HTTP\/[0-9]+\.[0-9]+/;
+    return $self;
+}
 
 sub response {
-    my $self   = shift;
-    my %params = ( headers_only => 0, sync => 0, @_ );
+    my ( $self, $callback ) = @_;
 
-    return undef unless $self->has_stdout;
+    return undef unless $self->stdout;
 
-    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 $headers;
+    while ( my $line = $self->stdout->getline ) {
+        $headers .= $line;
+        last if $headers =~ /\x0d?\x0a\x0d?\x0a$/;
     }
 
-    my $message  = undef;
-    my $response = HTTP::Response->new( 200, 'OK' );
-       $response->protocol('HTTP/1.1');
-
-    while ( my $line = readline($self->stdout) ) {
-        $message .= $line;
-        last if $message =~ /\x0d?\x0a\x0d?\x0a$/;
-    }
-
-    if ( !$message ) {
-        $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 );
-
-        return $response;
+    unless ( defined $headers ) {
+        $headers = "HTTP/1.1 500 Internal Server Error\x0d\x0a";
     }
 
-    if ( $message =~ s/^($HTTP_Version)[\x09\x20]+(\d\d\d)[\x09\x20]+([\x20-\xFF]*)\x0D?\x0A//o ) {
-        $response->protocol($1);
-        $response->code($2);
-        $response->message($3);
+    unless ( $headers =~ /^HTTP/ ) {
+        $headers = "HTTP/1.1 200 OK\x0d\x0a" . $headers;
     }
 
-    $message =~ s/\x0D?\x0A[\x09\x20]+/\x20/gs;
+    my $response = HTTP::Response->parse($headers);
+    $response->date( time() ) unless $response->date;
 
-    foreach ( split /\x0D?\x0A/, $message ) {
+    my $message = $response->message;
+    my $status  = $response->header('Status');
 
-        s/[\x09\x20]*$//;
-
-        if ( /^($HTTP_Token+)[\x09\x20]*:[\x09\x20]*([\x20-\xFF]+)$/o ) {
-            $response->headers->push_header( $1 => $2 );
-        }
-        else {
-            # XXX what should we do on bad headers?
-        }
+    if ( $message && $message =~ /^(.+)\x0d$/ ) {
+        $response->message($1);
     }
 
-    my $status = $response->header('Status');
+    if ( $status && $status =~ /^(\d\d\d)\s?(.+)?$/ ) {
 
-    if ( $status && $status =~ /^(\d\d\d)[\x09\x20]+([\x20-\xFF]+)$/ ) {
-        $response->code($1);
-        $response->message($2);
-    }
+        my $code    = $1;
+        my $message = $2 || HTTP::Status::status_message($code);
 
-    if ( !$response->date ) {
-        $response->date(time);
+        $response->code($code);
+        $response->message($message);
     }
 
-    if ( $params{headers_only} ) {
+    my $length = ( stat( $self->stdout ) )[7] - tell( $self->stdout );
 
-        if ( $params{sync} ) {
+    if ( $response->code == 500 && !$length ) {
 
-            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: '$!'");
-        }
+        $response->content( $response->error_as_HTML );
+        $response->content_type('text/html');
 
         return $response;
     }
 
-    my $content        = undef;
-    my $content_length = 0;
-
-    while () {
+    if ($callback) {
 
-        my $r = read( $self->stdout, $content, 65536, $content_length );
+        my $handle = $self->stdout;
 
-        if ( defined $r ) {
+        $response->content( sub {
 
-            if ( $r == 0 ) {
-                last;
-            }
-            else {
-                $content_length += $r;
+            if ( $handle->read( my $buffer, 4096 ) ) {
+                return $buffer;
             }
-        }
-        else {
-            croak("Couldn't read response content from stdin handle: '$!'");
-        }
+
+            return undef;
+        });
     }
+    else {
 
-    if ( $content_length ) {
+        my $length = defined $response->content ? length( $response->content ) : 0;
 
-        $response->content_ref(\$content);
+        while ( $self->stdout->read( my $buffer, 4096 ) ) {
+            $length += length($buffer);
+            $response->add_content($buffer);
+        }
 
-        if ( !$response->content_length ) {
-            $response->content_length($content_length);
+        if ( $length && !$response->content_length ) {
+            $response->content_length($length);
         }
     }
 
@@ -484,129 +254,55 @@ sub response {
 sub restore {
     my $self = shift;
 
-    if ( $self->should_restore ) {
-
-        $self->restore_environment;
-        $self->restore_stdin;
-        $self->restore_stdout;
-        $self->restore_stderr;
-
-        $self->{restore} = {};
-
-        $self->is_restored(1);
+    {
+        no warnings 'uninitialized';
+        %ENV = %{ $self->{restore}->{environment} };
     }
 
-    return $self;
-}
-
-sub restore_environment {
-    my $self = shift;
-
-    no warnings 'uninitialized';
-
-    %ENV = %{ $self->{restore}->{environment} };
-}
-
-sub restore_stdin {
-    my $self = shift;
+    open( STDIN, '<&'. fileno($self->{restore}->{stdin}) )
+      or croak("Can't restore stdin: $!");
 
-    if ( $self->has_stdin ) {
+    sysseek( $self->stdin, 0, SEEK_SET )
+      or croak("Can't seek stdin: $!");
 
-        my $stdin = $self->{restore}->{stdin};
+    if ( $self->{restore}->{stdout} ) {
 
-        if ( $self->should_dup ) {
+        STDOUT->flush
+          or croak("Can't flush stdout: $!");
 
-            STDIN->fdopen( $stdin, '<' )
-              or croak("Couldn't restore STDIN: '$!'");
-        }
-        else {
+        open( STDOUT, '>&'. fileno($self->{restore}->{stdout}) )
+          or croak("Can't restore stdout: $!");
 
-            my $stdin_ref = $self->{restore}->{stdin_ref};
-              *$stdin_ref = $stdin;
-        }
-
-        if ( $self->should_rewind ) {
-
-            seek( $self->stdin, 0, SEEK_SET )
-              or croak("Couldn't seek stdin handle: '$!'");
-        }
+        sysseek( $self->stdout, 0, SEEK_SET )
+          or croak("Can't seek stdout: $!");
     }
-}
-
-sub restore_stdout {
-    my $self = shift;
-
-    if ( $self->has_stdout ) {
-
-        my $stdout = $self->{restore}->{stdout};
-
-        if ( $self->should_dup ) {
 
-            STDOUT->flush
-              or croak("Couldn't flush STDOUT: '$!'");
+    if ( $self->{restore}->{stderr} ) {
 
-            STDOUT->fdopen( $stdout, '>' )
-              or croak("Couldn't restore STDOUT: '$!'");
-        }
-        else {
-
-            my $stdout_ref = $self->{restore}->{stdout_ref};
-              *$stdout_ref = $stdout;
-        }
+        STDERR->flush
+          or croak("Can't flush stderr: $!");
 
-        if ( $self->should_rewind ) {
+        open( STDERR, '>&'. fileno($self->{restore}->{stderr}) )
+          or croak("Can't restore stderr: $!");
 
-            seek( $self->stdout, 0, SEEK_SET )
-              or croak("Couldn't seek stdout handle: '$!'");
-        }
+        sysseek( $self->stderr, 0, SEEK_SET )
+          or croak("Can't seek stderr: $!");
     }
-}
-
-sub restore_stderr {
-    my $self = shift;
-
-    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 ) {
+    $self->{restored}++;
 
-            seek( $self->stderr, 0, SEEK_SET )
-              or croak("Couldn't seek stderr handle: '$!'");
-        }
-    }
+    return $self;
 }
 
 sub DESTROY {
     my $self = shift;
-
-    if ( $self->should_restore && $self->is_setuped && !$self->is_restored ) {
-        $self->restore;
-    }
+    $self->restore if $self->{setuped} && !$self->{restored};
 }
 
 1;
 
 __END__
 
-=head1 NAME
-
-HTTP::Request::AsCGI - Setup a CGI environment from a HTTP::Request
-
 =head1 SYNOPSIS
 
     use CGI;
@@ -637,7 +333,7 @@ HTTP::Request::AsCGI - Setup a CGI environment from a HTTP::Request
 
 =head1 DESCRIPTION
 
-Provides a convinient way of setting up an CGI environment from a HTTP::Request.
+Provides a convenient way of setting up an CGI environment from an HTTP::Request.
 
 =head1 METHODS
 
@@ -645,8 +341,8 @@ Provides a convinient way of setting up an CGI environment from a HTTP::Request.
 
 =item new ( $request [, key => value ] )
 
-Contructor, first argument must be a instance of HTTP::Request
-followed by optional pairs of environment key and value.
+Constructor.  The first argument must be a instance of HTTP::Request, followed
+by optional pairs of environment key and value.
 
 =item environment
 
@@ -655,7 +351,7 @@ Changing the hashref after setup has been called will have no effect.
 
 =item setup
 
-Setups the environment and descriptors.
+Sets up the environment and descriptors.
 
 =item restore
 
@@ -702,13 +398,4 @@ handle with an file descriptor.
 
 Thomas L. Shinnick for his valuable win32 testing.
 
-=head1 AUTHOR
-
-Christian Hansen, C<ch@ngmedia.com>
-
-=head1 LICENSE
-
-This library is free software. You can redistribute it and/or modify
-it under the same terms as perl itself.
-
 =cut