don't set the address in the hostname if lookup fails
[catagits/Catalyst-Runtime.git] / lib / Catalyst / Request.pm
index 3bcc6c2..53aa8ca 100644 (file)
@@ -1,6 +1,6 @@
 package Catalyst::Request;
 
-use IO::Socket qw[AF_INET inet_aton];
+use Socket qw( getaddrinfo getnameinfo AI_NUMERICHOST NI_NAMEREQD NIx_NOSERV );
 use Carp;
 use utf8;
 use URI::http;
@@ -293,7 +293,10 @@ sub prepare_body {
     # Check for definedness as you could read '0'
     while ( defined ( my $chunk = $self->read() ) ) {
         $self->prepare_body_chunk($chunk);
-        $stream_buffer->print($chunk) if $stream_buffer;
+        next unless $stream_buffer;
+
+        $stream_buffer->print($chunk)
+            || die sprintf "Failed to write %d bytes to psgi.input file: $!", length( $chunk );
     }
 
     # Ok, we read the body.  Lets play nice for any PSGI app down the pipe
@@ -429,11 +432,30 @@ sub body {
 
 has hostname => (
   is        => 'rw',
-  required  => 1,
   lazy      => 1,
   default   => sub {
     my ($self) = @_;
-    gethostbyaddr( inet_aton( $self->address ), AF_INET ) || $self->address
+    my ( $err, $sockaddr ) = getaddrinfo(
+        $self->address,
+        # no service
+        '',
+        { flags => AI_NUMERICHOST }
+    );
+    if ( $err ) {
+        $self->_log->warn("resolve of hostname failed: $err");
+        return $self->address;
+    }
+    ( $err, my $hostname ) = getnameinfo(
+        $sockaddr->{addr},
+        NI_NAMEREQD,
+        # we are only interested in the hostname, not the servicename
+        NIx_NOSERV
+    );
+    if ( $err ) {
+        $self->_log->warn("resolve of hostname failed: $err");
+        return $self->address;
+    }
+    return $hostname;
   },
 );