about summary refs log tree commit homepage
diff options
context:
space:
mode:
authorEric Wong <e@80x24.org>2017-03-08 04:56:46 +0000
committerEric Wong <e@80x24.org>2017-03-08 05:39:55 +0000
commit873218e317773462be2a72556d26dc4a723cc7be (patch)
treed51829f7830eca74d90325822a7a5a0e9514cee2
parent8ce88a3756b110e5e3001f640ebd53a5b11d8c65 (diff)
downloadunicorn-873218e317773462be2a72556d26dc4a723cc7be.tar.gz
Ruby 2.2+ can show "struct tcp_info" as a string via
Socket::Option#inspect, and we can attempt to parse it
out to extract the information we need.

Parsing this string is inefficient, but does not depend on the
ordering of the tcp_info struct.
-rw-r--r--lib/unicorn/http_request.rb32
1 files changed, 31 insertions, 1 deletions
diff --git a/lib/unicorn/http_request.rb b/lib/unicorn/http_request.rb
index 68bde16..c08097c 100644
--- a/lib/unicorn/http_request.rb
+++ b/lib/unicorn/http_request.rb
@@ -29,6 +29,7 @@ class Unicorn::HttpParser
   EMPTY_ARRAY = [].freeze
   @@input_class = Unicorn::TeeInput
   @@check_client_connection = false
+  @@tcpi_inspect_ok = true
 
   def self.input_class
     @@input_class
@@ -127,8 +128,37 @@ class Unicorn::HttpParser
       end
     end
   else
+
+    # Ruby 2.2+ can show struct tcp_info as a string Socket::Option#inspect.
+    # Not that efficient, but probably still better than doing unnecessary
+    # work after a client gives up.
     def check_client_connection(socket) # :nodoc:
-      write_http_header(socket)
+      if Unicorn::TCPClient === socket && @@tcpi_inspect_ok
+        opt = socket.getsockopt(:IPPROTO_TCP, :TCP_INFO).inspect
+        if opt =~ /\bstate=(\S+)/
+          @@tcpi_inspect_ok = true
+          raise Errno::EPIPE, "client closed connection".freeze,
+                EMPTY_ARRAY if closed_state_str?($1)
+        else
+          @@tcpi_inspect_ok = false
+          write_http_header(socket)
+        end
+        opt.clear
+      else
+        write_http_header(socket)
+      end
+    end
+
+    def closed_state_str?(state)
+      case state
+      when 'ESTABLISHED'
+        false
+      # not a typo, ruby maps TCP_CLOSE (no 'D') to state=CLOSED (w/ 'D')
+      when 'CLOSE_WAIT', 'TIME_WAIT', 'CLOSED', 'LAST_ACK', 'CLOSING'
+        true
+      else
+        false
+      end
     end
   end