unicorn 0.8.4
[unicorn.git] / lib / unicorn / http_request.rb
blobd7078a3def9e6a92f2be2653f8b4e40392c20d54
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     attr_accessor :logger
17     # default parameters we merge into the request env for Rack handlers
18     DEFAULTS = {
19       "rack.errors" => $stderr,
20       "rack.multiprocess" => true,
21       "rack.multithread" => false,
22       "rack.run_once" => false,
23       "rack.version" => [1, 0].freeze,
24       "SCRIPT_NAME" => "".freeze,
26       # this is not in the Rack spec, but some apps may rely on it
27       "SERVER_SOFTWARE" => "Unicorn #{Const::UNICORN_VERSION}".freeze
28     }
30     # Optimize for the common case where there's no request body
31     # (GET/HEAD) requests.
32     NULL_IO = StringIO.new
33     LOCALHOST = '127.0.0.1'.freeze
35     # Being explicitly single-threaded, we have certain advantages in
36     # not having to worry about variables being clobbered :)
37     BUFFER = ' ' * Const::CHUNK_SIZE # initial size, may grow
38     PARSER = HttpParser.new
39     PARAMS = Hash.new
41     def initialize(logger = Configurator::DEFAULT_LOGGER)
42       @logger = logger
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       # reset the parser
60       unless NULL_IO == (input = PARAMS[Const::RACK_INPUT]) # unlikely
61         input.close rescue nil
62         input.close! rescue nil
63       end
64       PARAMS.clear
65       PARSER.reset
67       # From http://www.ietf.org/rfc/rfc3875:
68       # "Script authors should be aware that the REMOTE_ADDR and
69       #  REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9)
70       #  may not identify the ultimate source of the request.  They
71       #  identify the client for the immediate request to the server;
72       #  that client may be a proxy, gateway, or other intermediary
73       #  acting on behalf of the actual source client."
74       PARAMS[Const::REMOTE_ADDR] =
75                     TCPSocket === socket ? socket.peeraddr.last : LOCALHOST
77       # short circuit the common case with small GET requests first
78       PARSER.execute(PARAMS, socket.readpartial(Const::CHUNK_SIZE, BUFFER)) and
79           return handle_body(socket)
81       data = BUFFER.dup # socket.readpartial will clobber BUFFER
83       # Parser is not done, queue up more data to read and continue parsing
84       # an Exception thrown from the PARSER will throw us out of the loop
85       begin
86         data << socket.readpartial(Const::CHUNK_SIZE, BUFFER)
87         PARSER.execute(PARAMS, data) and return handle_body(socket)
88       end while true
89       rescue HttpParserError => e
90         @logger.error "HTTP parse error, malformed request " \
91                       "(#{PARAMS[Const::HTTP_X_FORWARDED_FOR] ||
92                           PARAMS[Const::REMOTE_ADDR]}): #{e.inspect}"
93         @logger.error "REQUEST DATA: #{data.inspect}\n---\n" \
94                       "PARAMS: #{PARAMS.inspect}\n---\n"
95         raise e
96     end
98     private
100     # Handles dealing with the rest of the request
101     # returns a Rack environment if successful, raises an exception if not
102     def handle_body(socket)
103       http_body = PARAMS.delete(:http_body)
104       content_length = PARAMS[Const::CONTENT_LENGTH].to_i
106       if content_length == 0 # short circuit the common case
107         PARAMS[Const::RACK_INPUT] = NULL_IO.closed? ? NULL_IO.reopen : NULL_IO
108         return PARAMS.update(DEFAULTS)
109       end
111       # must read more data to complete body
112       remain = content_length - http_body.length
114       body = PARAMS[Const::RACK_INPUT] = (remain < Const::MAX_BODY) ?
115           StringIO.new : Tempfile.new('unicorn')
117       body.binmode
118       body.write(http_body)
120       # Some clients (like FF1.0) report 0 for body and then send a body.
121       # This will probably truncate them but at least the request goes through
122       # usually.
123       read_body(socket, remain, body) if remain > 0
124       body.rewind
126       # in case read_body overread because the client tried to pipeline
127       # another request, we'll truncate it.  Again, we don't do pipelining
128       # or keepalive
129       body.truncate(content_length)
130       PARAMS.update(DEFAULTS)
131     end
133     # Does the heavy lifting of properly reading the larger body
134     # requests in small chunks.  It expects PARAMS['rack.input'] to be
135     # an IO object, socket to be valid, It also expects any initial part
136     # of the body that has been read to be in the PARAMS['rack.input']
137     # already.  It will return true if successful and false if not.
138     def read_body(socket, remain, body)
139       begin
140         # write always writes the requested amount on a POSIX filesystem
141         remain -= body.write(socket.readpartial(Const::CHUNK_SIZE, BUFFER))
142       end while remain > 0
143     rescue Object => e
144       @logger.error "Error reading HTTP body: #{e.inspect}"
146       # Any errors means we should delete the file, including if the file
147       # is dumped.  Truncate it ASAP to help avoid page flushes to disk.
148       body.truncate(0) rescue nil
149       reset
150       raise e
151     end
153   end