6 require 'unicorn/http11'
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.
16 # default parameters we merge into the request env for Rack handlers
18 "rack.errors" => $stderr,
19 "rack.multiprocess" => true,
20 "rack.multithread" => false,
21 "rack.run_once" => false,
22 "rack.version" => [0, 1],
25 # this is not in the Rack spec, but some apps may rely on it
26 "SERVER_SOFTWARE" => "Unicorn #{Const::UNICORN_VERSION}"
29 def initialize(logger)
32 @buffer = ' ' * Const::CHUNK_SIZE # initial size, may grow
33 @parser = HttpParser.new
40 @body.close rescue nil
41 @body.close! rescue nil
45 # Does the majority of the IO processing. It has been written in
46 # Ruby using about 8 different IO processing strategies.
48 # It is currently carefully constructed to make sure that it gets
49 # the best possible performance for the common case: GET requests
50 # that are fully complete after a single read(2)
52 # Anyone who thinks they can make it faster is more than welcome to
55 # returns an environment hash suitable for Rack if successful
56 # This does minimal exception trapping and it is up to the caller
57 # to handle any socket errors (e.g. user aborted upload).
59 # short circuit the common case with small GET requests first
60 @parser.execute(@params, read_socket(socket)) and
61 return handle_body(socket)
63 data = @buffer.dup # read_socket will clobber @buffer
65 # Parser is not done, queue up more data to read and continue parsing
66 # an Exception thrown from the @parser will throw us out of the loop
68 data << read_socket(socket)
69 @parser.execute(@params, data) and return handle_body(socket)
71 rescue HttpParserError => e
72 @logger.error "HTTP parse error, malformed request " \
73 "(#{@params[Const::HTTP_X_FORWARDED_FOR] ||
74 socket.unicorn_peeraddr}): #{e.inspect}"
75 @logger.error "REQUEST DATA: #{data.inspect}\n---\n" \
76 "PARAMS: #{@params.inspect}\n---\n"
82 # Handles dealing with the rest of the request
83 # returns a Rack environment if successful, raises an exception if not
84 def handle_body(socket)
85 http_body = @params.delete(:http_body)
86 content_length = @params[Const::CONTENT_LENGTH].to_i
87 remain = content_length - http_body.length
89 # must read more data to complete body
90 if remain < Const::MAX_BODY
91 # small body, just use that
92 @body = StringIO.new(http_body)
93 else # huge body, put it in a tempfile
94 @body = Tempfile.new(Const::UNICORN_TMP_BASE)
97 @body.syswrite(http_body)
100 # Some clients (like FF1.0) report 0 for body and then send a body.
101 # This will probably truncate them but at least the request goes through
103 read_body(socket, remain) if remain > 0
105 @body.sysseek(0) if @body.respond_to?(:sysseek)
107 # in case read_body overread because the client tried to pipeline
108 # another request, we'll truncate it. Again, we don't do pipelining
110 @body.truncate(content_length)
114 # Returns an environment which is rackable:
115 # http://rack.rubyforge.org/doc/files/SPEC.html
116 # Based on Rack's old Mongrel handler.
118 # I'm considering enabling "unicorn.client". It gives
119 # applications some rope to do some "interesting" things like
120 # replacing a worker with another process that has full control
121 # over the HTTP response.
122 # @params["unicorn.client"] = socket
124 # From http://www.ietf.org/rfc/rfc3875:
125 # "Script authors should be aware that the REMOTE_ADDR and
126 # REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9)
127 # may not identify the ultimate source of the request. They
128 # identify the client for the immediate request to the server;
129 # that client may be a proxy, gateway, or other intermediary
130 # acting on behalf of the actual source client."
131 @params[Const::REMOTE_ADDR] = socket.unicorn_peeraddr
133 # It might be a dumbass full host request header
134 @params[Const::PATH_INFO] = (
135 @params[Const::REQUEST_PATH] ||=
136 URI.parse(@params[Const::REQUEST_URI]).path) or
137 raise "No REQUEST_PATH"
139 @params[Const::QUERY_STRING] ||= ''
140 @params[Const::RACK_INPUT] = @body
141 @params.update(DEF_PARAMS)
144 # Does the heavy lifting of properly reading the larger body requests in
145 # small chunks. It expects @body to be an IO object, socket to be valid,
146 # It also expects any initial part of the body that has been read to be in
147 # the @body already. It will return true if successful and false if not.
148 def read_body(socket, remain)
150 # writes always write the requested amount on a POSIX filesystem
151 remain -= @body.syswrite(read_socket(socket))
154 @logger.error "Error reading HTTP body: #{e.inspect}"
156 # Any errors means we should delete the file, including if the file
157 # is dumped. Truncate it ASAP to help avoid page flushes to disk.
158 @body.truncate(0) rescue nil
163 # read(2) on "slow" devices like sockets can be interrupted by signals
164 def read_socket(socket)
166 socket.sysread(Const::CHUNK_SIZE, @buffer)