Get rid of UNICORN_TMP_BASE constant
[unicorn.git] / lib / unicorn / http_request.rb
blob24da08594705bffaf0489451dc5afbae660c31ce
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].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     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       # From http://www.ietf.org/rfc/rfc3875:
59       # "Script authors should be aware that the REMOTE_ADDR and
60       #  REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9)
61       #  may not identify the ultimate source of the request.  They
62       #  identify the client for the immediate request to the server;
63       #  that client may be a proxy, gateway, or other intermediary
64       #  acting on behalf of the actual source client."
65       @params[Const::REMOTE_ADDR] =
66                     TCPSocket === socket ? socket.peeraddr.last : '127.0.0.1'
68       # short circuit the common case with small GET requests first
69       @parser.execute(@params, read_socket(socket)) and
70           return handle_body(socket)
72       data = @buffer.dup # read_socket will clobber @buffer
74       # Parser is not done, queue up more data to read and continue parsing
75       # an Exception thrown from the @parser will throw us out of the loop
76       loop do
77         data << read_socket(socket)
78         @parser.execute(@params, data) and return handle_body(socket)
79       end
80       rescue HttpParserError => e
81         @logger.error "HTTP parse error, malformed request " \
82                       "(#{@params[Const::HTTP_X_FORWARDED_FOR] ||
83                           @params[Const::REMOTE_ADDR]}): #{e.inspect}"
84         @logger.error "REQUEST DATA: #{data.inspect}\n---\n" \
85                       "PARAMS: #{@params.inspect}\n---\n"
86         raise e
87     end
89     private
91     # Handles dealing with the rest of the request
92     # returns a Rack environment if successful, raises an exception if not
93     def handle_body(socket)
94       http_body = @params.delete(:http_body)
95       content_length = @params[Const::CONTENT_LENGTH].to_i
96       remain = content_length - http_body.length
98       # must read more data to complete body
99       @body = remain < Const::MAX_BODY ? StringIO.new : Tempfile.new('unicorn')
100       @body.binmode
101       @body.sync = true
102       @body.syswrite(http_body)
104       # Some clients (like FF1.0) report 0 for body and then send a body.
105       # This will probably truncate them but at least the request goes through
106       # usually.
107       read_body(socket, remain) if remain > 0
108       @body.rewind
109       @body.sysseek(0) if @body.respond_to?(:sysseek)
111       # in case read_body overread because the client tried to pipeline
112       # another request, we'll truncate it.  Again, we don't do pipelining
113       # or keepalive
114       @body.truncate(content_length)
115       rack_env(socket)
116     end
118     # Returns an environment which is rackable:
119     # http://rack.rubyforge.org/doc/files/SPEC.html
120     # Based on Rack's old Mongrel handler.
121     def rack_env(socket)
122       # I'm considering enabling "unicorn.client".  It gives
123       # applications some rope to do some "interesting" things like
124       # replacing a worker with another process that has full control
125       # over the HTTP response.
126       # @params["unicorn.client"] = socket
128       @params[Const::RACK_INPUT] = @body
129       @params.update(DEF_PARAMS)
130     end
132     # Does the heavy lifting of properly reading the larger body requests in
133     # small chunks.  It expects @body to be an IO object, socket to be valid,
134     # It also expects any initial part of the body that has been read to be in
135     # the @body already.  It will return true if successful and false if not.
136     def read_body(socket, remain)
137       while remain > 0
138         # writes always write the requested amount on a POSIX filesystem
139         remain -= @body.syswrite(read_socket(socket))
140       end
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     # read(2) on "slow" devices like sockets can be interrupted by signals
152     def read_socket(socket)
153       begin
154         socket.sysread(Const::CHUNK_SIZE, @buffer)
155       rescue Errno::EINTR
156         retry
157       end
158     end
160   end