t/lib.perl: fix Perl integration tests w/o installation
[unicorn.git] / lib / unicorn / http_request.rb
bloba48dab7d02903d1250e029ad23a87b4c258d54d0
1 # -*- encoding: binary -*-
2 # frozen_string_literal: false
3 # :enddoc:
4 # no stable API here
5 require 'unicorn_http'
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_headers(socket, ai)
66     e = env
68     # From https://www.ietf.org/rfc/rfc3875:
69     # "Script authors should be aware that the REMOTE_ADDR and
70     #  REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9)
71     #  may not identify the ultimate source of the request.  They
72     #  identify the client for the immediate request to the server;
73     #  that client may be a proxy, gateway, or other intermediary
74     #  acting on behalf of the actual source client."
75     e['REMOTE_ADDR'] = ai.unix? ? '127.0.0.1' : ai.ip_address
77     # short circuit the common case with small GET requests first
78     socket.readpartial(16384, buf)
79     if parse.nil?
80       # Parser is not done, queue up more data to read and continue parsing
81       # an Exception thrown from the parser will throw us out of the loop
82       false until add_parse(socket.readpartial(16384))
83     end
85     check_client_connection(socket, ai) if @@check_client_connection
87     e['rack.input'] = 0 == content_length ?
88                       NULL_IO : @@input_class.new(socket, self)
90     # for Rack hijacking in Rack 1.5 and later
91     e['unicorn.socket'] = socket
92     e['rack.hijack'] = self
94     e.merge!(DEFAULTS)
95   end
97   # for rack.hijack, we respond to this method so no extra allocation
98   # of a proc object
99   def call
100     hijacked!
101     env['rack.hijack_io'] = env['unicorn.socket']
102   end
104   def hijacked?
105     env.include?('rack.hijack_io'.freeze)
106   end
108   if Raindrops.const_defined?(:TCP_Info)
109     TCPI = Raindrops::TCP_Info.allocate
111     def check_client_connection(socket, ai) # :nodoc:
112       if ai.ip?
113         # Raindrops::TCP_Info#get!, #state (reads struct tcp_info#tcpi_state)
114         raise Errno::EPIPE, "client closed connection".freeze,
115               EMPTY_ARRAY if closed_state?(TCPI.get!(socket).state)
116       else
117         write_http_header(socket)
118       end
119     end
121     if Raindrops.const_defined?(:TCP)
122       # raindrops 0.18.0+ supports FreeBSD + Linux using the same names
123       # Evaluate these hash lookups at load time so we can
124       # generate an opt_case_dispatch instruction
125       eval <<-EOS
126       def closed_state?(state) # :nodoc:
127         case state
128         when #{Raindrops::TCP[:ESTABLISHED]}
129           false
130         when #{Raindrops::TCP.values_at(
131               :CLOSE_WAIT, :TIME_WAIT, :CLOSE, :LAST_ACK, :CLOSING).join(',')}
132           true
133         else
134           false
135         end
136       end
137       EOS
138     else
139       # raindrops before 0.18 only supported TCP_INFO under Linux
140       def closed_state?(state) # :nodoc:
141         case state
142         when 1 # ESTABLISHED
143           false
144         when 8, 6, 7, 9, 11 # CLOSE_WAIT, TIME_WAIT, CLOSE, LAST_ACK, CLOSING
145           true
146         else
147           false
148         end
149       end
150     end
151   else
153     # Ruby 2.2+ can show struct tcp_info as a string Socket::Option#inspect.
154     # Not that efficient, but probably still better than doing unnecessary
155     # work after a client gives up.
156     def check_client_connection(socket, ai) # :nodoc:
157       if @@tcpi_inspect_ok && ai.ip?
158         opt = socket.getsockopt(Socket::IPPROTO_TCP, Socket::TCP_INFO).inspect
159         if opt =~ /\bstate=(\S+)/
160           raise Errno::EPIPE, "client closed connection".freeze,
161                 EMPTY_ARRAY if closed_state_str?($1)
162         else
163           @@tcpi_inspect_ok = false
164           write_http_header(socket)
165         end
166         opt.clear
167       else
168         write_http_header(socket)
169       end
170     end
172     def closed_state_str?(state)
173       case state
174       when 'ESTABLISHED'
175         false
176       # not a typo, ruby maps TCP_CLOSE (no 'D') to state=CLOSED (w/ 'D')
177       when 'CLOSE_WAIT', 'TIME_WAIT', 'CLOSED', 'LAST_ACK', 'CLOSING'
178         true
179       else
180         false
181       end
182     end
183   end
185   def write_http_header(socket) # :nodoc:
186     if headers?
187       self.response_start_sent = true
188       HTTP_RESPONSE_START.each { |c| socket.write(c) }
189     end
190   end
192   # called by ext/unicorn_http/unicorn_http.rl via rb_funcall
193   def self.is_chunked?(v) # :nodoc:
194     vals = v.split(/[ \t]*,[ \t]*/).map!(&:downcase)
195     if vals.pop == 'chunked'.freeze
196       return true unless vals.include?('chunked'.freeze)
197       raise Unicorn::HttpParserError, 'double chunked', []
198     end
199     return false unless vals.include?('chunked'.freeze)
200     raise Unicorn::HttpParserError, 'chunked not last', []
201   end