9 # default parameters we merge into the request env for Rack handlers
11 "rack.errors" => $stderr,
12 "rack.multiprocess" => true,
13 "rack.multithread" => false,
14 "rack.run_once" => false,
15 "rack.version" => [1, 0].freeze,
16 "SCRIPT_NAME" => "".freeze,
18 # this is not in the Rack spec, but some apps may rely on it
19 "SERVER_SOFTWARE" => "Unicorn #{Const::UNICORN_VERSION}".freeze
22 NULL_IO = StringIO.new(Z)
23 LOCALHOST = '127.0.0.1'.freeze
28 # Being explicitly single-threaded, we have certain advantages in
29 # not having to worry about variables being clobbered :)
30 BUFFER = ' ' * Const::CHUNK_SIZE # initial size, may grow
31 BUFFER.force_encoding(Encoding::BINARY) if Z.respond_to?(:force_encoding)
32 PARSER = HttpParser.new
35 # Does the majority of the IO processing. It has been written in
36 # Ruby using about 8 different IO processing strategies.
38 # It is currently carefully constructed to make sure that it gets
39 # the best possible performance for the common case: GET requests
40 # that are fully complete after a single read(2)
42 # Anyone who thinks they can make it faster is more than welcome to
45 # returns an environment hash suitable for Rack if successful
46 # This does minimal exception trapping and it is up to the caller
47 # to handle any socket errors (e.g. user aborted upload).
52 # From http://www.ietf.org/rfc/rfc3875:
53 # "Script authors should be aware that the REMOTE_ADDR and
54 # REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9)
55 # may not identify the ultimate source of the request. They
56 # identify the client for the immediate request to the server;
57 # that client may be a proxy, gateway, or other intermediary
58 # acting on behalf of the actual source client."
59 PARAMS[Const::REMOTE_ADDR] =
60 TCPSocket === socket ? socket.peeraddr.last : LOCALHOST
62 # short circuit the common case with small GET requests first
63 PARSER.execute(PARAMS, socket.readpartial(Const::CHUNK_SIZE, BUFFER)) and
64 return handle_body(socket)
66 data = BUFFER.dup # socket.readpartial will clobber BUFFER
68 # Parser is not done, queue up more data to read and continue parsing
69 # an Exception thrown from the PARSER will throw us out of the loop
71 data << socket.readpartial(Const::CHUNK_SIZE, BUFFER)
72 PARSER.execute(PARAMS, data) and return handle_body(socket)
78 # Handles dealing with the rest of the request
79 # returns a Rack environment if successful
80 def handle_body(socket)
81 PARAMS[Const::RACK_INPUT] = if (body = PARAMS.delete(:http_body))
82 length = PARAMS[Const::CONTENT_LENGTH].to_i
84 if /\Achunked\z/i =~ PARAMS[Const::HTTP_TRANSFER_ENCODING]
85 socket = ChunkedReader.new(PARAMS, socket, body)
89 TeeInput.new(socket, length, body)
94 PARAMS.update(DEFAULTS)