avoid needlessly preallocating read buffer
[unicorn.git] / lib / unicorn / http_request.rb
blob65b09fafc5c2a945c32e693f4495997adbcc869a
1 # -*- encoding: binary -*-
3 require 'stringio'
4 require 'unicorn_http'
6 module Unicorn
7   class HttpRequest
9     # default parameters we merge into the request env for Rack handlers
10     DEFAULTS = {
11       "rack.errors" => $stderr,
12       "rack.multiprocess" => true,
13       "rack.multithread" => false,
14       "rack.run_once" => false,
15       "rack.version" => [1, 1],
16       "SCRIPT_NAME" => "",
18       # this is not in the Rack spec, but some apps may rely on it
19       "SERVER_SOFTWARE" => "Unicorn #{Const::UNICORN_VERSION}"
20     }
22     NULL_IO = StringIO.new("")
23     LOCALHOST = '127.0.0.1'
25     # Being explicitly single-threaded, we have certain advantages in
26     # not having to worry about variables being clobbered :)
27     BUF = ""
28     PARSER = HttpParser.new
29     REQ = {}
31     # Does the majority of the IO processing.  It has been written in
32     # Ruby using about 8 different IO processing strategies.
33     #
34     # It is currently carefully constructed to make sure that it gets
35     # the best possible performance for the common case: GET requests
36     # that are fully complete after a single read(2)
37     #
38     # Anyone who thinks they can make it faster is more than welcome to
39     # take a crack at it.
40     #
41     # returns an environment hash suitable for Rack if successful
42     # This does minimal exception trapping and it is up to the caller
43     # to handle any socket errors (e.g. user aborted upload).
44     def read(socket)
45       REQ.clear
46       PARSER.reset
48       # From http://www.ietf.org/rfc/rfc3875:
49       # "Script authors should be aware that the REMOTE_ADDR and
50       #  REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9)
51       #  may not identify the ultimate source of the request.  They
52       #  identify the client for the immediate request to the server;
53       #  that client may be a proxy, gateway, or other intermediary
54       #  acting on behalf of the actual source client."
55       REQ[Const::REMOTE_ADDR] =
56                     TCPSocket === socket ? socket.peeraddr.last : LOCALHOST
58       # short circuit the common case with small GET requests first
59       if PARSER.headers(REQ, socket.readpartial(Const::CHUNK_SIZE, BUF)).nil?
60         # Parser is not done, queue up more data to read and continue parsing
61         # an Exception thrown from the PARSER will throw us out of the loop
62         begin
63           BUF << socket.readpartial(Const::CHUNK_SIZE)
64         end while PARSER.headers(REQ, BUF).nil?
65       end
66       REQ[Const::RACK_INPUT] = 0 == PARSER.content_length ?
67                    NULL_IO : Unicorn::TeeInput.new(socket, REQ, PARSER, BUF)
68       REQ.update(DEFAULTS)
69     end
71   end
72 end