a0435d610bb23c6d0f436484fe7ff8f3ead86e7c
[unicorn.git] / lib / unicorn / http_request.rb
bloba0435d610bb23c6d0f436484fe7ff8f3ead86e7c
1 # -*- encoding: binary -*-
2 # :enddoc:
3 # no stable API here
4 require 'unicorn_http'
6 # TODO: remove redundant names
7 Unicorn.const_set(:HttpRequest, Unicorn::HttpParser)
8 class Unicorn::HttpParser
10   # default parameters we merge into the request env for Rack handlers
11   DEFAULTS = {
12     "rack.errors" => $stderr,
13     "rack.multiprocess" => true,
14     "rack.multithread" => false,
15     "rack.run_once" => false,
16     "rack.version" => [1, 1],
17     "SCRIPT_NAME" => "",
19     # this is not in the Rack spec, but some apps may rely on it
20     "SERVER_SOFTWARE" => "Unicorn #{Unicorn::Const::UNICORN_VERSION}"
21   }
23   NULL_IO = StringIO.new("")
25   # :stopdoc:
26   # A frozen format for this is about 15% faster
27   REMOTE_ADDR = 'REMOTE_ADDR'.freeze
28   RACK_INPUT = 'rack.input'.freeze
29   @@input_class = Unicorn::TeeInput
31   def self.input_class
32     @@input_class
33   end
35   def self.input_class=(klass)
36     @@input_class = klass
37   end
38   # :startdoc:
40   # Does the majority of the IO processing.  It has been written in
41   # Ruby using about 8 different IO processing strategies.
42   #
43   # It is currently carefully constructed to make sure that it gets
44   # the best possible performance for the common case: GET requests
45   # that are fully complete after a single read(2)
46   #
47   # Anyone who thinks they can make it faster is more than welcome to
48   # take a crack at it.
49   #
50   # returns an environment hash suitable for Rack if successful
51   # This does minimal exception trapping and it is up to the caller
52   # to handle any socket errors (e.g. user aborted upload).
53   def read(socket)
54     clear
55     e = env
57     # From http://www.ietf.org/rfc/rfc3875:
58     # "Script authors should be aware that the REMOTE_ADDR and
59     #  REMOTE_HOST meta-variables (see sections 4.1.8 and 4.1.9)
60     #  may not identify the ultimate source of the request.  They
61     #  identify the client for the immediate request to the server;
62     #  that client may be a proxy, gateway, or other intermediary
63     #  acting on behalf of the actual source client."
64     e[REMOTE_ADDR] = socket.kgio_addr
66     # short circuit the common case with small GET requests first
67     socket.kgio_read!(16384, buf)
68     if parse.nil?
69       # Parser is not done, queue up more data to read and continue parsing
70       # an Exception thrown from the parser will throw us out of the loop
71       false until add_parse(socket.kgio_read!(16384))
72     end
73     e[RACK_INPUT] = 0 == content_length ?
74                     NULL_IO : @@input_class.new(socket, self)
75     e.merge!(DEFAULTS)
76   end
77 end