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