http11: handle "X-Forwarded-Proto: https"
[unicorn.git] / lib / unicorn / http_request.rb
bloba3a1d4de5bb1de4b4b927c3d80cdfe1132f43e94
1 require 'tempfile'
2 require 'uri'
3 require 'stringio'
5 # compiled extension
6 require 'unicorn/http11'
8 module Unicorn
9   #
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.
13   # 
14   class HttpRequest
16      # default parameters we merge into the request env for Rack handlers
17      DEF_PARAMS = {
18        "rack.errors" => $stderr,
19        "rack.multiprocess" => true,
20        "rack.multithread" => false,
21        "rack.run_once" => false,
22        "rack.version" => [0, 1],
23        "SCRIPT_NAME" => "",
25        # this is not in the Rack spec, but some apps may rely on it
26        "SERVER_SOFTWARE" => "Unicorn #{Const::UNICORN_VERSION}"
27      }.freeze
29     def initialize(logger)
30       @logger = logger
31       @body = nil
32       @buffer = ' ' * Const::CHUNK_SIZE # initial size, may grow
33       @parser = HttpParser.new
34       @params = Hash.new
35     end
37     def reset
38       @parser.reset
39       @params.clear
40       @body.close rescue nil
41       @body.close! rescue nil
42       @body = nil
43     end
45     # Does the majority of the IO processing.  It has been written in
46     # Ruby using about 8 different IO processing strategies.
47     #
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)
51     #
52     # Anyone who thinks they can make it faster is more than welcome to
53     # take a crack at it.
54     #
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).
58     def read(socket)
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
67       loop do
68         data << read_socket(socket)
69         @parser.execute(@params, data) and return handle_body(socket)
70       end
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"
77         raise e
78     end
80     private
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)
95         @body.binmode
96         @body.sync = true
97         @body.syswrite(http_body)
98       end
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
102       # usually.
103       read_body(socket, remain) if remain > 0
104       @body.rewind
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
109       # or keepalive
110       @body.truncate(content_length)
111       rack_env(socket)
112     end
114     # Returns an environment which is rackable:
115     # http://rack.rubyforge.org/doc/files/SPEC.html
116     # Based on Rack's old Mongrel handler.
117     def rack_env(socket)
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)
142     end
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)
149       while remain > 0
150         # writes always write the requested amount on a POSIX filesystem
151         remain -= @body.syswrite(read_socket(socket))
152       end
153     rescue Object => e
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
159       reset
160       raise e
161     end
163     # read(2) on "slow" devices like sockets can be interrupted by signals
164     def read_socket(socket)
165       begin
166         socket.sysread(Const::CHUNK_SIZE, @buffer)
167       rescue Errno::EINTR
168         retry
169       end
170     end
172   end