Remove set_cloexec wrapper and require FD_CLOEXEC
[unicorn.git] / lib / unicorn / http_request.rb
blob750deea804435de0b64ab1bba3d57bb8904de6c1
1 require 'tempfile'
2 require 'uri'
3 require 'stringio'
5 # compiled extension
6 require 'unicorn/http11'
8 module Unicorn
9   #
10   # The HttpRequest.initialize method will convert any request that is larger than
11   # Const::MAX_BODY into a Tempfile and use that as the body.  Otherwise it uses 
12   # a StringIO object.  To be safe, you should assume it works like a file.
13   # 
14   class HttpRequest
16      # default parameters we merge into the request env for Rack handlers
17      DEF_PARAMS = {
18        "rack.errors" => $stderr,
19        "rack.multiprocess" => true,
20        "rack.multithread" => false,
21        "rack.run_once" => false,
22        "rack.url_scheme" => "http",
23        "rack.version" => [0, 1],
24        "SCRIPT_NAME" => "",
26        # this is not in the Rack spec, but some apps may rely on it
27        "SERVER_SOFTWARE" => "Unicorn #{Const::UNICORN_VERSION}"
28      }.freeze
30     def initialize(logger)
31       @logger = logger
32       @body = nil
33       @buffer = ' ' * Const::CHUNK_SIZE # initial size, may grow
34       @parser = HttpParser.new
35       @params = Hash.new
36     end
38     def reset
39       @parser.reset
40       @params.clear
41       @body.close rescue nil
42       @body.close! rescue nil
43       @body = nil
44     end
46     # Does the majority of the IO processing.  It has been written in
47     # Ruby using about 8 different IO processing strategies.
48     #
49     # It is currently carefully constructed to make sure that it gets
50     # the best possible performance for the common case: GET requests
51     # that are fully complete after a single read(2)
52     #
53     # Anyone who thinks they can make it faster is more than welcome to
54     # take a crack at it.
55     #
56     # returns an environment hash suitable for Rack if successful
57     # This does minimal exception trapping and it is up to the caller
58     # to handle any socket errors (e.g. user aborted upload).
59     def read(socket)
60       # short circuit the common case with small GET requests first
61       @parser.execute(@params, read_socket(socket)) and
62           return handle_body(socket)
64       data = @buffer.dup # read_socket will clobber @buffer
66       # Parser is not done, queue up more data to read and continue parsing
67       # an Exception thrown from the @parser will throw us out of the loop
68       loop do
69         data << read_socket(socket)
70         @parser.execute(@params, data) and return handle_body(socket)
71       end
72       rescue HttpParserError => e
73         @logger.error "HTTP parse error, malformed request " \
74                       "(#{@params[Const::HTTP_X_FORWARDED_FOR] ||
75                           socket.unicorn_peeraddr}): #{e.inspect}"
76         @logger.error "REQUEST DATA: #{data.inspect}\n---\n" \
77                       "PARAMS: #{@params.inspect}\n---\n"
78         raise e
79     end
81     private
83     # Handles dealing with the rest of the request
84     # returns a Rack environment if successful, raises an exception if not
85     def handle_body(socket)
86       http_body = @params.delete(:http_body)
87       content_length = @params[Const::CONTENT_LENGTH].to_i
88       remain = content_length - http_body.length
90       # must read more data to complete body
91       if remain < Const::MAX_BODY
92         # small body, just use that
93         @body = StringIO.new(http_body)
94       else # huge body, put it in a tempfile
95         @body = Tempfile.new(Const::UNICORN_TMP_BASE)
96         @body.binmode
97         @body.sync = true
98         @body.syswrite(http_body)
99       end
101       # Some clients (like FF1.0) report 0 for body and then send a body.
102       # This will probably truncate them but at least the request goes through
103       # usually.
104       read_body(socket, remain) if remain > 0
105       @body.rewind
106       @body.sysseek(0) if @body.respond_to?(:sysseek)
108       # in case read_body overread because the client tried to pipeline
109       # another request, we'll truncate it.  Again, we don't do pipelining
110       # or keepalive
111       @body.truncate(content_length)
112       rack_env(socket)
113     end
115     # Returns an environment which is rackable:
116     # http://rack.rubyforge.org/doc/files/SPEC.html
117     # Based on Rack's old Mongrel handler.
118     def rack_env(socket)
119       # I'm considering enabling "unicorn.client".  It gives
120       # applications some rope to do some "interesting" things like
121       # replacing a worker with another process that has full control
122       # over the HTTP response.
123       # @params["unicorn.client"] = socket
125       # From http://www.ietf.org/rfc/rfc3875:
126       # "Script authors should be aware that the REMOTE_ADDR and
127       #  REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9)
128       #  may not identify the ultimate source of the request.  They
129       #  identify the client for the immediate request to the server;
130       #  that client may be a proxy, gateway, or other intermediary
131       #  acting on behalf of the actual source client."
132       @params[Const::REMOTE_ADDR] = socket.unicorn_peeraddr
134       # It might be a dumbass full host request header
135       @params[Const::PATH_INFO] = (
136           @params[Const::REQUEST_PATH] ||=
137               URI.parse(@params[Const::REQUEST_URI]).path) or
138          raise "No REQUEST_PATH"
140       @params[Const::QUERY_STRING] ||= ''
141       @params[Const::RACK_INPUT] = @body
142       @params.update(DEF_PARAMS)
143     end
145     # Does the heavy lifting of properly reading the larger body requests in
146     # small chunks.  It expects @body to be an IO object, socket to be valid,
147     # It also expects any initial part of the body that has been read to be in
148     # the @body already.  It will return true if successful and false if not.
149     def read_body(socket, remain)
150       while remain > 0
151         # writes always write the requested amount on a POSIX filesystem
152         remain -= @body.syswrite(read_socket(socket))
153       end
154     rescue Object => e
155       @logger.error "Error reading HTTP body: #{e.inspect}"
157       # Any errors means we should delete the file, including if the file
158       # is dumped.  Truncate it ASAP to help avoid page flushes to disk.
159       @body.truncate(0) rescue nil
160       reset
161       raise e
162     end
164     # read(2) on "slow" devices like sockets can be interrupted by signals
165     def read_socket(socket)
166       begin
167         socket.sysread(Const::CHUNK_SIZE, @buffer)
168       rescue Errno::EINTR
169         retry
170       end
171     end
173   end