quiet some mismatched indentation warnings
[unicorn.git] / lib / unicorn / http_request.rb
blobd713b1985e1e967f56a2e397fdb23b2903cdf39d
1 # -*- encoding: binary -*-
2 # :enddoc:
3 # no stable API here
4 require 'unicorn_http'
5 require 'raindrops'
7 # TODO: remove redundant names
8 Unicorn.const_set(:HttpRequest, Unicorn::HttpParser)
9 class Unicorn::HttpParser
11   # default parameters we merge into the request env for Rack handlers
12   DEFAULTS = {
13     "rack.errors" => $stderr,
14     "rack.multiprocess" => true,
15     "rack.multithread" => false,
16     "rack.run_once" => false,
17     "rack.version" => [1, 2],
18     "rack.hijack?" => true,
19     "SCRIPT_NAME" => "",
21     # this is not in the Rack spec, but some apps may rely on it
22     "SERVER_SOFTWARE" => "Unicorn #{Unicorn::Const::UNICORN_VERSION}"
23   }
25   NULL_IO = StringIO.new("")
27   # :stopdoc:
28   HTTP_RESPONSE_START = [ 'HTTP'.freeze, '/1.1 '.freeze ]
29   EMPTY_ARRAY = [].freeze
30   @@input_class = Unicorn::TeeInput
31   @@check_client_connection = false
32   @@tcpi_inspect_ok = Socket.const_defined?(:TCP_INFO)
34   def self.input_class
35     @@input_class
36   end
38   def self.input_class=(klass)
39     @@input_class = klass
40   end
42   def self.check_client_connection
43     @@check_client_connection
44   end
46   def self.check_client_connection=(bool)
47     @@check_client_connection = bool
48   end
50   # :startdoc:
52   # Does the majority of the IO processing.  It has been written in
53   # Ruby using about 8 different IO processing strategies.
54   #
55   # It is currently carefully constructed to make sure that it gets
56   # the best possible performance for the common case: GET requests
57   # that are fully complete after a single read(2)
58   #
59   # Anyone who thinks they can make it faster is more than welcome to
60   # take a crack at it.
61   #
62   # returns an environment hash suitable for Rack if successful
63   # This does minimal exception trapping and it is up to the caller
64   # to handle any socket errors (e.g. user aborted upload).
65   def read(socket)
66     clear
67     e = env
69     # From http://www.ietf.org/rfc/rfc3875:
70     # "Script authors should be aware that the REMOTE_ADDR and
71     #  REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9)
72     #  may not identify the ultimate source of the request.  They
73     #  identify the client for the immediate request to the server;
74     #  that client may be a proxy, gateway, or other intermediary
75     #  acting on behalf of the actual source client."
76     e['REMOTE_ADDR'] = socket.kgio_addr
78     # short circuit the common case with small GET requests first
79     socket.kgio_read!(16384, buf)
80     if parse.nil?
81       # Parser is not done, queue up more data to read and continue parsing
82       # an Exception thrown from the parser will throw us out of the loop
83       false until add_parse(socket.kgio_read!(16384))
84     end
86     check_client_connection(socket) if @@check_client_connection
88     e['rack.input'] = 0 == content_length ?
89                       NULL_IO : @@input_class.new(socket, self)
91     # for Rack hijacking in Rack 1.5 and later
92     e['unicorn.socket'] = socket
93     e['rack.hijack'] = self
95     e.merge!(DEFAULTS)
96   end
98   # for rack.hijack, we respond to this method so no extra allocation
99   # of a proc object
100   def call
101     hijacked!
102     env['rack.hijack_io'] = env['unicorn.socket']
103   end
105   def hijacked?
106     env.include?('rack.hijack_io'.freeze)
107   end
109   if Raindrops.const_defined?(:TCP_Info)
110     TCPI = Raindrops::TCP_Info.allocate
112     def check_client_connection(socket) # :nodoc:
113       if Unicorn::TCPClient === socket
114         # Raindrops::TCP_Info#get!, #state (reads struct tcp_info#tcpi_state)
115         raise Errno::EPIPE, "client closed connection".freeze,
116               EMPTY_ARRAY if closed_state?(TCPI.get!(socket).state)
117       else
118         write_http_header(socket)
119       end
120     end
122     if Raindrops.const_defined?(:TCP)
123       # raindrops 0.18.0+ supports FreeBSD + Linux using the same names
124       # Evaluate these hash lookups at load time so we can
125       # generate an opt_case_dispatch instruction
126       eval <<-EOS
127       def closed_state?(state) # :nodoc:
128         case state
129         when #{Raindrops::TCP[:ESTABLISHED]}
130           false
131         when #{Raindrops::TCP.values_at(
132               :CLOSE_WAIT, :TIME_WAIT, :CLOSE, :LAST_ACK, :CLOSING).join(',')}
133           true
134         else
135           false
136         end
137       end
138       EOS
139     else
140       # raindrops before 0.18 only supported TCP_INFO under Linux
141       def closed_state?(state) # :nodoc:
142         case state
143         when 1 # ESTABLISHED
144           false
145         when 8, 6, 7, 9, 11 # CLOSE_WAIT, TIME_WAIT, CLOSE, LAST_ACK, CLOSING
146           true
147         else
148           false
149         end
150       end
151     end
152   else
154     # Ruby 2.2+ can show struct tcp_info as a string Socket::Option#inspect.
155     # Not that efficient, but probably still better than doing unnecessary
156     # work after a client gives up.
157     def check_client_connection(socket) # :nodoc:
158       if Unicorn::TCPClient === socket && @@tcpi_inspect_ok
159         opt = socket.getsockopt(Socket::IPPROTO_TCP, Socket::TCP_INFO).inspect
160         if opt =~ /\bstate=(\S+)/
161           raise Errno::EPIPE, "client closed connection".freeze,
162                 EMPTY_ARRAY if closed_state_str?($1)
163         else
164           @@tcpi_inspect_ok = false
165           write_http_header(socket)
166         end
167         opt.clear
168       else
169         write_http_header(socket)
170       end
171     end
173     def closed_state_str?(state)
174       case state
175       when 'ESTABLISHED'
176         false
177       # not a typo, ruby maps TCP_CLOSE (no 'D') to state=CLOSED (w/ 'D')
178       when 'CLOSE_WAIT', 'TIME_WAIT', 'CLOSED', 'LAST_ACK', 'CLOSING'
179         true
180       else
181         false
182       end
183     end
184   end
186   def write_http_header(socket) # :nodoc:
187     if headers?
188       self.response_start_sent = true
189       HTTP_RESPONSE_START.each { |c| socket.write(c) }
190     end
191   end