1 # -*- encoding: binary -*-
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
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,
20 # this is not in the Rack spec, but some apps may rely on it
21 "SERVER_SOFTWARE" => "Unicorn #{Unicorn::Const::UNICORN_VERSION}"
24 NULL_IO = StringIO.new("")
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)
37 def self.input_class=(klass)
41 def self.check_client_connection
42 @@check_client_connection
45 def self.check_client_connection=(bool)
46 @@check_client_connection = bool
51 # Does the majority of the IO processing. It has been written in
52 # Ruby using about 8 different IO processing strategies.
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)
58 # Anyone who thinks they can make it faster is more than welcome to
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).
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)
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))
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
96 # for rack.hijack, we respond to this method so no extra allocation
100 env['rack.hijack_io'] = env['unicorn.socket']
104 env.include?('rack.hijack_io'.freeze)
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)
116 write_http_header(socket)
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
125 def closed_state?(state) # :nodoc:
127 when #{Raindrops::TCP[:ESTABLISHED]}
129 when #{Raindrops::TCP.values_at(
130 :CLOSE_WAIT, :TIME_WAIT, :CLOSE, :LAST_ACK, :CLOSING).join(',')}
138 # raindrops before 0.18 only supported TCP_INFO under Linux
139 def closed_state?(state) # :nodoc:
143 when 8, 6, 7, 9, 11 # CLOSE_WAIT, TIME_WAIT, CLOSE, LAST_ACK, CLOSING
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)
162 @@tcpi_inspect_ok = false
163 write_http_header(socket)
167 write_http_header(socket)
171 def closed_state_str?(state)
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'
184 def write_http_header(socket) # :nodoc:
186 self.response_start_sent = true
187 HTTP_RESPONSE_START.each { |c| socket.write(c) }
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', []
198 return false unless vals.include?('chunked'.freeze)
199 raise Unicorn::HttpParserError, 'chunked not last', []