http_request: avoid StringIO.new for GET/HEAD requests
[unicorn.git] / lib / unicorn / http_request.rb
bloba51e02962bca641f1289b31bae8204b3ae076a7a
1 require 'tempfile'
2 require 'stringio'
4 # compiled extension
5 require 'unicorn/http11'
7 module Unicorn
8   #
9   # The HttpRequest.initialize method will convert any request that is larger than
10   # Const::MAX_BODY into a Tempfile and use that as the body.  Otherwise it uses 
11   # a StringIO object.  To be safe, you should assume it works like a file.
12   # 
13   class HttpRequest
15      # default parameters we merge into the request env for Rack handlers
16      DEF_PARAMS = {
17        "rack.errors" => $stderr,
18        "rack.multiprocess" => true,
19        "rack.multithread" => false,
20        "rack.run_once" => false,
21        "rack.version" => [1, 0].freeze,
22        "SCRIPT_NAME" => "".freeze,
24        # this is not in the Rack spec, but some apps may rely on it
25        "SERVER_SOFTWARE" => "Unicorn #{Const::UNICORN_VERSION}".freeze
26      }.freeze
28     # Optimize for the common case where there's no request body
29     # (GET/HEAD) requests.
30     NULL_IO = StringIO.new
31     LOCALHOST = '127.0.0.1'.freeze
33     # Being explicitly single-threaded, we have certain advantages in
34     # not having to worry about variables being clobbered :)
35     BUFFER = ' ' * Const::CHUNK_SIZE # initial size, may grow
36     PARSER = HttpParser.new
37     PARAMS = Hash.new
39     def initialize(logger)
40       @logger = logger
41       reset
42     end
44     def reset
45       input = PARAMS[Const::RACK_INPUT]
46       if input != NULL_IO
47         input.close rescue nil
48         input.close! rescue nil
49       end
50       PARAMS.clear
51       PARSER.reset
52     end
54     # Does the majority of the IO processing.  It has been written in
55     # Ruby using about 8 different IO processing strategies.
56     #
57     # It is currently carefully constructed to make sure that it gets
58     # the best possible performance for the common case: GET requests
59     # that are fully complete after a single read(2)
60     #
61     # Anyone who thinks they can make it faster is more than welcome to
62     # take a crack at it.
63     #
64     # returns an environment hash suitable for Rack if successful
65     # This does minimal exception trapping and it is up to the caller
66     # to handle any socket errors (e.g. user aborted upload).
67     def read(socket)
68       # From http://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       PARAMS[Const::REMOTE_ADDR] =
76                     TCPSocket === socket ? socket.peeraddr.last : LOCALHOST
78       # short circuit the common case with small GET requests first
79       PARSER.execute(PARAMS, read_socket(socket)) and
80           return handle_body(socket)
82       data = BUFFER.dup # read_socket will clobber BUFFER
84       # Parser is not done, queue up more data to read and continue parsing
85       # an Exception thrown from the PARSER will throw us out of the loop
86       begin
87         data << read_socket(socket)
88         PARSER.execute(PARAMS, data) and return handle_body(socket)
89       end while true
90       rescue HttpParserError => e
91         @logger.error "HTTP parse error, malformed request " \
92                       "(#{PARAMS[Const::HTTP_X_FORWARDED_FOR] ||
93                           PARAMS[Const::REMOTE_ADDR]}): #{e.inspect}"
94         @logger.error "REQUEST DATA: #{data.inspect}\n---\n" \
95                       "PARAMS: #{PARAMS.inspect}\n---\n"
96         raise e
97     end
99     private
101     # Handles dealing with the rest of the request
102     # returns a Rack environment if successful, raises an exception if not
103     def handle_body(socket)
104       http_body = PARAMS.delete(:http_body)
105       content_length = PARAMS[Const::CONTENT_LENGTH].to_i
107       if content_length == 0 # short circuit the common case
108         PARAMS[Const::RACK_INPUT] = NULL_IO.closed? ? NULL_IO.reopen : NULL_IO
109         return PARAMS.update(DEF_PARAMS)
110       end
112       # must read more data to complete body
113       remain = content_length - http_body.length
115       body = PARAMS[Const::RACK_INPUT] = (remain < Const::MAX_BODY) ?
116           StringIO.new : Tempfile.new('unicorn')
118       body.binmode
119       body.sync = true
120       body.syswrite(http_body)
122       # Some clients (like FF1.0) report 0 for body and then send a body.
123       # This will probably truncate them but at least the request goes through
124       # usually.
125       read_body(socket, remain, body) if remain > 0
126       body.rewind
127       body.sysseek(0) if body.respond_to?(:sysseek)
129       # in case read_body overread because the client tried to pipeline
130       # another request, we'll truncate it.  Again, we don't do pipelining
131       # or keepalive
132       body.truncate(content_length)
133       PARAMS.update(DEF_PARAMS)
134     end
136     # Does the heavy lifting of properly reading the larger body
137     # requests in small chunks.  It expects PARAMS['rack.input'] to be
138     # an IO object, socket to be valid, It also expects any initial part
139     # of the body that has been read to be in the PARAMS['rack.input']
140     # already.  It will return true if successful and false if not.
141     def read_body(socket, remain, body)
142       while remain > 0
143         # writes always write the requested amount on a POSIX filesystem
144         remain -= body.syswrite(read_socket(socket))
145       end
146     rescue Object => e
147       @logger.error "Error reading HTTP body: #{e.inspect}"
149       # Any errors means we should delete the file, including if the file
150       # is dumped.  Truncate it ASAP to help avoid page flushes to disk.
151       body.truncate(0) rescue nil
152       reset
153       raise e
154     end
156     # read(2) on "slow" devices like sockets can be interrupted by signals
157     def read_socket(socket)
158       begin
159         socket.sysread(Const::CHUNK_SIZE, BUFFER)
160       rescue Errno::EINTR
161         retry
162       end
163     end
165   end