HttpRequest::DEF_PARAMS => HttpRequest::DEFAULTS
[unicorn.git] / lib / unicorn / http_request.rb
blob368305f83861807b2ca5638bb7e19513d4b39e01
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     DEFAULTS = {
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     }
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     end
43     # Does the majority of the IO processing.  It has been written in
44     # Ruby using about 8 different IO processing strategies.
45     #
46     # It is currently carefully constructed to make sure that it gets
47     # the best possible performance for the common case: GET requests
48     # that are fully complete after a single read(2)
49     #
50     # Anyone who thinks they can make it faster is more than welcome to
51     # take a crack at it.
52     #
53     # returns an environment hash suitable for Rack if successful
54     # This does minimal exception trapping and it is up to the caller
55     # to handle any socket errors (e.g. user aborted upload).
56     def read(socket)
57       # reset the parser
58       unless NULL_IO == (input = PARAMS[Const::RACK_INPUT]) # unlikely
59         input.close rescue nil
60         input.close! rescue nil
61       end
62       PARAMS.clear
63       PARSER.reset
65       # From http://www.ietf.org/rfc/rfc3875:
66       # "Script authors should be aware that the REMOTE_ADDR and
67       #  REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9)
68       #  may not identify the ultimate source of the request.  They
69       #  identify the client for the immediate request to the server;
70       #  that client may be a proxy, gateway, or other intermediary
71       #  acting on behalf of the actual source client."
72       PARAMS[Const::REMOTE_ADDR] =
73                     TCPSocket === socket ? socket.peeraddr.last : LOCALHOST
75       # short circuit the common case with small GET requests first
76       PARSER.execute(PARAMS, socket.readpartial(Const::CHUNK_SIZE, BUFFER)) and
77           return handle_body(socket)
79       data = BUFFER.dup # socket.readpartial will clobber BUFFER
81       # Parser is not done, queue up more data to read and continue parsing
82       # an Exception thrown from the PARSER will throw us out of the loop
83       begin
84         data << socket.readpartial(Const::CHUNK_SIZE, BUFFER)
85         PARSER.execute(PARAMS, data) and return handle_body(socket)
86       end while true
87       rescue HttpParserError => e
88         @logger.error "HTTP parse error, malformed request " \
89                       "(#{PARAMS[Const::HTTP_X_FORWARDED_FOR] ||
90                           PARAMS[Const::REMOTE_ADDR]}): #{e.inspect}"
91         @logger.error "REQUEST DATA: #{data.inspect}\n---\n" \
92                       "PARAMS: #{PARAMS.inspect}\n---\n"
93         raise e
94     end
96     private
98     # Handles dealing with the rest of the request
99     # returns a Rack environment if successful, raises an exception if not
100     def handle_body(socket)
101       http_body = PARAMS.delete(:http_body)
102       content_length = PARAMS[Const::CONTENT_LENGTH].to_i
104       if content_length == 0 # short circuit the common case
105         PARAMS[Const::RACK_INPUT] = NULL_IO.closed? ? NULL_IO.reopen : NULL_IO
106         return PARAMS.update(DEFAULTS)
107       end
109       # must read more data to complete body
110       remain = content_length - http_body.length
112       body = PARAMS[Const::RACK_INPUT] = (remain < Const::MAX_BODY) ?
113           StringIO.new : Tempfile.new('unicorn')
115       body.binmode
116       body.write(http_body)
118       # Some clients (like FF1.0) report 0 for body and then send a body.
119       # This will probably truncate them but at least the request goes through
120       # usually.
121       read_body(socket, remain, body) if remain > 0
122       body.rewind
124       # in case read_body overread because the client tried to pipeline
125       # another request, we'll truncate it.  Again, we don't do pipelining
126       # or keepalive
127       body.truncate(content_length)
128       PARAMS.update(DEFAULTS)
129     end
131     # Does the heavy lifting of properly reading the larger body
132     # requests in small chunks.  It expects PARAMS['rack.input'] to be
133     # an IO object, socket to be valid, It also expects any initial part
134     # of the body that has been read to be in the PARAMS['rack.input']
135     # already.  It will return true if successful and false if not.
136     def read_body(socket, remain, body)
137       begin
138         # write always writes the requested amount on a POSIX filesystem
139         remain -= body.write(socket.readpartial(Const::CHUNK_SIZE, BUFFER))
140       end while remain > 0
141     rescue Object => e
142       @logger.error "Error reading HTTP body: #{e.inspect}"
144       # Any errors means we should delete the file, including if the file
145       # is dumped.  Truncate it ASAP to help avoid page flushes to disk.
146       body.truncate(0) rescue nil
147       reset
148       raise e
149     end
151   end