Move absolute URI parsing into HTTP parser
[unicorn.git] / lib / unicorn / http_request.rb
blobc9c9503503cdcb05e74a62fd342ef7bd53b52a3e
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" => [0, 1],
22        "SCRIPT_NAME" => "",
24        # this is not in the Rack spec, but some apps may rely on it
25        "SERVER_SOFTWARE" => "Unicorn #{Const::UNICORN_VERSION}"
26      }.freeze
28     def initialize(logger)
29       @logger = logger
30       @body = nil
31       @buffer = ' ' * Const::CHUNK_SIZE # initial size, may grow
32       @parser = HttpParser.new
33       @params = Hash.new
34     end
36     def reset
37       @parser.reset
38       @params.clear
39       @body.close rescue nil
40       @body.close! rescue nil
41       @body = nil
42     end
44     # Does the majority of the IO processing.  It has been written in
45     # Ruby using about 8 different IO processing strategies.
46     #
47     # It is currently carefully constructed to make sure that it gets
48     # the best possible performance for the common case: GET requests
49     # that are fully complete after a single read(2)
50     #
51     # Anyone who thinks they can make it faster is more than welcome to
52     # take a crack at it.
53     #
54     # returns an environment hash suitable for Rack if successful
55     # This does minimal exception trapping and it is up to the caller
56     # to handle any socket errors (e.g. user aborted upload).
57     def read(socket)
58       # short circuit the common case with small GET requests first
59       @parser.execute(@params, read_socket(socket)) and
60           return handle_body(socket)
62       data = @buffer.dup # read_socket will clobber @buffer
64       # Parser is not done, queue up more data to read and continue parsing
65       # an Exception thrown from the @parser will throw us out of the loop
66       loop do
67         data << read_socket(socket)
68         @parser.execute(@params, data) and return handle_body(socket)
69       end
70       rescue HttpParserError => e
71         @logger.error "HTTP parse error, malformed request " \
72                       "(#{@params[Const::HTTP_X_FORWARDED_FOR] ||
73                           socket.unicorn_peeraddr}): #{e.inspect}"
74         @logger.error "REQUEST DATA: #{data.inspect}\n---\n" \
75                       "PARAMS: #{@params.inspect}\n---\n"
76         raise e
77     end
79     private
81     # Handles dealing with the rest of the request
82     # returns a Rack environment if successful, raises an exception if not
83     def handle_body(socket)
84       http_body = @params.delete(:http_body)
85       content_length = @params[Const::CONTENT_LENGTH].to_i
86       remain = content_length - http_body.length
88       # must read more data to complete body
89       if remain < Const::MAX_BODY
90         # small body, just use that
91         @body = StringIO.new(http_body)
92       else # huge body, put it in a tempfile
93         @body = Tempfile.new(Const::UNICORN_TMP_BASE)
94         @body.binmode
95         @body.sync = true
96         @body.syswrite(http_body)
97       end
99       # Some clients (like FF1.0) report 0 for body and then send a body.
100       # This will probably truncate them but at least the request goes through
101       # usually.
102       read_body(socket, remain) if remain > 0
103       @body.rewind
104       @body.sysseek(0) if @body.respond_to?(:sysseek)
106       # in case read_body overread because the client tried to pipeline
107       # another request, we'll truncate it.  Again, we don't do pipelining
108       # or keepalive
109       @body.truncate(content_length)
110       rack_env(socket)
111     end
113     # Returns an environment which is rackable:
114     # http://rack.rubyforge.org/doc/files/SPEC.html
115     # Based on Rack's old Mongrel handler.
116     def rack_env(socket)
117       # I'm considering enabling "unicorn.client".  It gives
118       # applications some rope to do some "interesting" things like
119       # replacing a worker with another process that has full control
120       # over the HTTP response.
121       # @params["unicorn.client"] = socket
123       # From http://www.ietf.org/rfc/rfc3875:
124       # "Script authors should be aware that the REMOTE_ADDR and
125       #  REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9)
126       #  may not identify the ultimate source of the request.  They
127       #  identify the client for the immediate request to the server;
128       #  that client may be a proxy, gateway, or other intermediary
129       #  acting on behalf of the actual source client."
130       @params[Const::REMOTE_ADDR] = socket.unicorn_peeraddr
131       @params[Const::QUERY_STRING] ||= ''
132       @params[Const::RACK_INPUT] = @body
133       @params.update(DEF_PARAMS)
134     end
136     # Does the heavy lifting of properly reading the larger body requests in
137     # small chunks.  It expects @body to be an IO object, socket to be valid,
138     # It also expects any initial part of the body that has been read to be in
139     # the @body already.  It will return true if successful and false if not.
140     def read_body(socket, remain)
141       while remain > 0
142         # writes always write the requested amount on a POSIX filesystem
143         remain -= @body.syswrite(read_socket(socket))
144       end
145     rescue Object => e
146       @logger.error "Error reading HTTP body: #{e.inspect}"
148       # Any errors means we should delete the file, including if the file
149       # is dumped.  Truncate it ASAP to help avoid page flushes to disk.
150       @body.truncate(0) rescue nil
151       reset
152       raise e
153     end
155     # read(2) on "slow" devices like sockets can be interrupted by signals
156     def read_socket(socket)
157       begin
158         socket.sysread(Const::CHUNK_SIZE, @buffer)
159       rescue Errno::EINTR
160         retry
161       end
162     end
164   end