Skip to content
Newer
Older
100644 310 lines (264 sloc) 9.36 KB
7ed819a @chneukirchen Add Rack::Response and Rack::Utils
chneukirchen authored
1 require 'rack/utils'
2
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
3 module Rack
376fa1e @chneukirchen Add RDocs
chneukirchen authored
4 # Rack::Request provides a convenient interface to a Rack
5 # environment. It is stateless, the environment +env+ passed to the
6 # constructor will be directly modified.
7 #
8 # req = Rack::Request.new(env)
9 # req.post?
10 # req.params["data"]
eefbed8 @mtodd Added Rack::Request initialization memoization to reduce repetitive i…
mtodd authored
11 #
12 # The environment hash passed will store a reference to the Request object
13 # instantiated so that it will only instantiate if an instance of the Request
14 # object doesn't already exist.
230d62c @chneukirchen Fix trailing whitespace. Sigh.
chneukirchen authored
15
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
16 class Request
376fa1e @chneukirchen Add RDocs
chneukirchen authored
17 # The environment of the request.
05ab0f9 @chneukirchen More convenience for Rack::Request
chneukirchen authored
18 attr_reader :env
230d62c @chneukirchen Fix trailing whitespace. Sigh.
chneukirchen authored
19
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
20 def initialize(env)
21 @env = env
22 end
23
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
24 def body; @env["rack.input"] end
25 def script_name; @env["SCRIPT_NAME"].to_s end
26 def path_info; @env["PATH_INFO"].to_s end
27 def request_method; @env["REQUEST_METHOD"] end
28 def query_string; @env["QUERY_STRING"].to_s end
29 def content_length; @env['CONTENT_LENGTH'] end
8810d69 @richmeyers Treat an empty content type as nil content type (issue #40)
richmeyers authored
30
31 def content_type
32 content_type = @env['CONTENT_TYPE']
33 content_type.nil? || content_type.empty? ? nil : content_type
34 end
35
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
36 def session; @env['rack.session'] ||= {} end
37 def session_options; @env['rack.session.options'] ||= {} end
df22480 @josh rack.logger specification
josh authored
38 def logger; @env['rack.logger'] end
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
39
40 # The media type (type/subtype) portion of the CONTENT_TYPE header
41 # without any media type parameters. e.g., when CONTENT_TYPE is
42 # "text/plain;charset=utf-8", the media-type is "text/plain".
43 #
44 # For more information on the use of media types in HTTP, see:
45 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7
46 def media_type
939fa7d @tj Refactored Rack::Request#media_type
tj authored
47 content_type && content_type.split(/\s*[;,]\s*/, 2).first.downcase
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
48 end
49
50 # The media type parameters provided in CONTENT_TYPE as a Hash, or
51 # an empty Hash if no CONTENT_TYPE or media-type parameters were
52 # provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8",
53 # this method responds with the following Hash:
54 # { 'charset' => 'utf-8' }
55 def media_type_params
56 return {} if content_type.nil?
d3893c2 @raggi 186 bro :'(
raggi authored
57 Hash[*content_type.split(/\s*[;,]\s*/)[1..-1].
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
58 collect { |s| s.split('=', 2) }.
d3893c2 @raggi 186 bro :'(
raggi authored
59 map { |k,v| [k.downcase, v] }.flatten]
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
60 end
61
62 # The character set of the request body if a "charset" media type
63 # parameter was given, or nil if no "charset" was specified. Note
64 # that, per RFC2616, text/* media types that specify no explicit
65 # charset are to be considered ISO-8859-1.
66 def content_charset
67 media_type_params['charset']
68 end
a18fc32 @chneukirchen Rename Request#method to #request_method to not confuse stdlibs
chneukirchen authored
69
dda892d @josh Request#scheme returns 'https' if forwarded protocol headers are set
josh authored
70 def scheme
71 if @env['HTTPS'] == 'on'
72 'https'
35bb5ba @stephencelis Rack::Request support for HTTP_X_FORWARDED_{PORT,SSL}
stephencelis authored
73 elsif @env['HTTP_X_FORWARDED_SSL'] == 'on'
74 'https'
dda892d @josh Request#scheme returns 'https' if forwarded protocol headers are set
josh authored
75 elsif @env['HTTP_X_FORWARDED_PROTO']
85ca454 @martoche HTTP_X_FORWARDED_PROTO can be a list of chained values, eg 'https, ht…
martoche authored
76 @env['HTTP_X_FORWARDED_PROTO'].split(',')[0]
dda892d @josh Request#scheme returns 'https' if forwarded protocol headers are set
josh authored
77 else
78 @env["rack.url_scheme"]
79 end
80 end
81
82 def ssl?
83 scheme == 'https'
84 end
85
fb32ff7 @josh Request#host knows about forwared host [#77 state:resolved]
josh authored
86 def host_with_port
87 if forwarded = @env["HTTP_X_FORWARDED_HOST"]
88 forwarded.split(/,\s?/).last
89 else
90 @env['HTTP_HOST'] || "#{@env['SERVER_NAME'] || @env['SERVER_ADDR']}:#{@env['SERVER_PORT']}"
91 end
92 end
35bb5ba @stephencelis Rack::Request support for HTTP_X_FORWARDED_{PORT,SSL}
stephencelis authored
93
4bfe1d7 @brasten Modified Rack::Request#port to respect HTTP_X_FORWARDED_HOST port inf…
brasten authored
94 def port
35bb5ba @stephencelis Rack::Request support for HTTP_X_FORWARDED_{PORT,SSL}
stephencelis authored
95 if port = host_with_port.split(/:/)[1]
96 port.to_i
97 elsif port = @env['HTTP_X_FORWARDED_PORT']
98 port.to_i
99 elsif ssl?
100 443
1c27157 @jonleighton If there is an X-Forwarded-Host header, we should take the absence of…
jonleighton authored
101 elsif @env.has_key?("HTTP_X_FORWARDED_HOST")
102 80
35bb5ba @stephencelis Rack::Request support for HTTP_X_FORWARDED_{PORT,SSL}
stephencelis authored
103 else
104 @env["SERVER_PORT"].to_i
105 end
4bfe1d7 @brasten Modified Rack::Request#port to respect HTTP_X_FORWARDED_HOST port inf…
brasten authored
106 end
fb32ff7 @josh Request#host knows about forwared host [#77 state:resolved]
josh authored
107
c95b751 @chneukirchen Remove the port number of HTTP_HOST and SERVER_NAME
chneukirchen authored
108 def host
109 # Remove port number.
fb32ff7 @josh Request#host knows about forwared host [#77 state:resolved]
josh authored
110 host_with_port.to_s.gsub(/:\d+\z/, '')
c95b751 @chneukirchen Remove the port number of HTTP_HOST and SERVER_NAME
chneukirchen authored
111 end
112
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
113 def script_name=(s); @env["SCRIPT_NAME"] = s.to_s end
114 def path_info=(s); @env["PATH_INFO"] = s.to_s end
a18fc32 @chneukirchen Rename Request#method to #request_method to not confuse stdlibs
chneukirchen authored
115
320d800 @manveru Add Request.trace? and Request.options?
manveru authored
116 def delete?; request_method == "DELETE" end
117 def get?; request_method == "GET" end
118 def head?; request_method == "HEAD" end
119 def options?; request_method == "OPTIONS" end
828e2ab @rkh add Rack::Request#patch?
rkh authored
120 def patch?; request_method == "PATCH" end
320d800 @manveru Add Request.trace? and Request.options?
manveru authored
121 def post?; request_method == "POST" end
122 def put?; request_method == "PUT" end
123 def trace?; request_method == "TRACE" end
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
124
125 # The set of form-data media-types. Requests that do not indicate
126 # one of the media types presents in this list will not be eligible
127 # for form-data / param parsing.
128 FORM_DATA_MEDIA_TYPES = [
129 'application/x-www-form-urlencoded',
130 'multipart/form-data'
131 ]
132
6674f36 better multipart handling
eTM authored
133 # The set of media-types. Requests that do not indicate
134 # one of the media types presents in this list will not be eligible
135 # for param parsing like soap attachments or generic multiparts
136 PARSEABLE_DATA_MEDIA_TYPES = [
137 'multipart/related',
138 'multipart/mixed'
df22480 @josh rack.logger specification
josh authored
139 ]
6674f36 better multipart handling
eTM authored
140
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
141 # Determine whether the request body contains form-data by checking
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored
142 # the request Content-Type for one of the media-types:
143 # "application/x-www-form-urlencoded" or "multipart/form-data". The
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
144 # list of form-data media types can be modified through the
145 # +FORM_DATA_MEDIA_TYPES+ array.
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored
146 #
147 # A request body is also assumed to contain form-data when no
148 # Content-Type header is provided and the request_method is POST.
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
149 def form_data?
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored
150 type = media_type
151 meth = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD']
152 (meth == 'POST' && type.nil?) || FORM_DATA_MEDIA_TYPES.include?(type)
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
153 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
154
6674f36 better multipart handling
eTM authored
155 # Determine whether the request body contains data by checking
156 # the request media_type against registered parse-data media-types
157 def parseable_data?
158 PARSEABLE_DATA_MEDIA_TYPES.include?(media_type)
159 end
160
376fa1e @chneukirchen Add RDocs
chneukirchen authored
161 # Returns the data recieved in the query string.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
162 def GET
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
163 if @env["rack.request.query_string"] == query_string
164 @env["rack.request.query_hash"]
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
165 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
166 @env["rack.request.query_string"] = query_string
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored
167 @env["rack.request.query_hash"] = parse_query(query_string)
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
168 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
169 end
170
376fa1e @chneukirchen Add RDocs
chneukirchen authored
171 # Returns the data recieved in the request body.
172 #
173 # This method support both application/x-www-form-urlencoded and
174 # multipart/form-data.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
175 def POST
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
176 if @env["rack.input"].nil?
01c1770 @jeremy Rack::Request#POST raises if rack.input is missing instead of returni…
jeremy authored
177 raise "Missing rack.input"
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
178 elsif @env["rack.request.form_input"].eql? @env["rack.input"]
179 @env["rack.request.form_hash"]
6674f36 better multipart handling
eTM authored
180 elsif form_data? || parseable_data?
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
181 @env["rack.request.form_input"] = @env["rack.input"]
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored
182 unless @env["rack.request.form_hash"] = parse_multipart(env)
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
183 form_vars = @env["rack.input"].read
0f081dd @josh Clean up Safari's ajax POST body
josh authored
184
185 # Fix for Safari Ajax postings that always append \0
51fc864 @raggi slice is about double the speed on MRI, and slightly faster on 1.9
raggi authored
186 # form_vars.sub!(/\0\z/, '') # performance replacement:
187 form_vars.slice!(-1) if form_vars[-1] == ?\0
0f081dd @josh Clean up Safari's ajax POST body
josh authored
188
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
189 @env["rack.request.form_vars"] = form_vars
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored
190 @env["rack.request.form_hash"] = parse_query(form_vars)
3513f4f @josh Add tests for multipart uploads. Also ensure multipart parser tries t…
josh authored
191
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
192 @env["rack.input"].rewind
4fe5360 @chneukirchen Make Rack::Request read multipart form data
chneukirchen authored
193 end
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
194 @env["rack.request.form_hash"]
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
195 else
196 {}
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
197 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
198 end
199
376fa1e @chneukirchen Add RDocs
chneukirchen authored
200 # The union of GET and POST data.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
201 def params
91bbcea @skade Keep #params from merging POST into GET
skade authored
202 @params ||= self.GET.merge(self.POST)
cbcae3a @tenderlove fixing unused variable warnings in 1.9.3
tenderlove authored
203 rescue EOFError
67a7507 @chneukirchen handle EOFError exception in Request#params
chneukirchen authored
204 self.GET
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
205 end
206
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored
207 # shortcut for request.params[key]
208 def [](key)
209 params[key.to_s]
210 end
211
212 # shortcut for request.params[key] = value
213 def []=(key, value)
214 params[key.to_s] = value
215 end
216
217 # like Hash#values_at
218 def values_at(*keys)
219 keys.map{|key| params[key] }
220 end
221
aa7ce77 @ghazel do not default referer to '/'
ghazel authored
222 # the referer of the client
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored
223 def referer
aa7ce77 @ghazel do not default referer to '/'
ghazel authored
224 @env['HTTP_REFERER']
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored
225 end
226 alias referrer referer
227
e2a1a64 @josh Request#user_agent
josh authored
228 def user_agent
229 @env['HTTP_USER_AGENT']
230 end
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored
231
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
232 def cookies
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
233 return {} unless @env["HTTP_COOKIE"]
b68c2d5 @chneukirchen Return empty hash on lack of cookies
chneukirchen authored
234
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
235 if @env["rack.request.cookie_string"] == @env["HTTP_COOKIE"]
236 @env["rack.request.cookie_hash"]
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
237 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
238 @env["rack.request.cookie_string"] = @env["HTTP_COOKIE"]
4a08f8a Conform to RFC 2109 regarding multiple values for same cookie
Aman Gupta authored
239 # According to RFC 2109:
240 # If multiple cookies satisfy the criteria above, they are ordered in
241 # the Cookie header such that those with more specific Path attributes
242 # precede those with less specific. Ordering with respect to other
243 # attributes (e.g., Domain) is unspecified.
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
244 @env["rack.request.cookie_hash"] =
d3893c2 @raggi 186 bro :'(
raggi authored
245 Hash[*Utils.parse_query(@env["rack.request.cookie_string"], ';,').map {|k,v|
e9d7699 @spastorino PERF: change inject({}) to Hash + map
spastorino authored
246 [k, Array === v ? v.first : v]
d3893c2 @raggi 186 bro :'(
raggi authored
247 }.flatten]
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
248 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
249 end
250
251 def xhr?
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
252 @env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
253 end
fd51d36 @chneukirchen Add Request#url
chneukirchen authored
254
d7a3bb2 @josh Extract Request#base_url
josh authored
255 def base_url
fd51d36 @chneukirchen Add Request#url
chneukirchen authored
256 url = scheme + "://"
257 url << host
258
259 if scheme == "https" && port != 443 ||
260 scheme == "http" && port != 80
261 url << ":#{port}"
262 end
263
264 url
265 end
df22480 @josh rack.logger specification
josh authored
266
d7a3bb2 @josh Extract Request#base_url
josh authored
267 # Tries to return a remake of the original request URL as a string.
268 def url
269 base_url + fullpath
270 end
271
3a544a7 @tj Added Rack::Request#path
tj authored
272 def path
273 script_name + path_info
274 end
df22480 @josh rack.logger specification
josh authored
275
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored
276 def fullpath
3a544a7 @tj Added Rack::Request#path
tj authored
277 query_string.empty? ? path : "#{path}?#{query_string}"
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored
278 end
0f2dab5 @qerub Added support for Accept-Encoding (via Request#accept_encoding and Ut…
qerub authored
279
280 def accept_encoding
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
281 @env["HTTP_ACCEPT_ENCODING"].to_s.split(/,\s*/).map do |part|
0f2dab5 @qerub Added support for Accept-Encoding (via Request#accept_encoding and Ut…
qerub authored
282 m = /^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$/.match(part) # From WEBrick
283
284 if m
285 [m[1], (m[2] || 1.0).to_f]
286 else
287 raise "Invalid value for Accept-Encoding: #{part.inspect}"
288 end
289 end
290 end
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored
291
292 def ip
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
293 if addr = @env['HTTP_X_FORWARDED_FOR']
fa324e3 @manveru Don't use 'unknown' in HTTP_X_FORWARDED_FOR
manveru authored
294 (addr.split(',').grep(/\d\./).first || @env['REMOTE_ADDR']).to_s.strip
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored
295 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
296 @env['REMOTE_ADDR']
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored
297 end
298 end
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored
299
300 protected
301 def parse_query(qs)
302 Utils.parse_nested_query(qs)
303 end
304
305 def parse_multipart(env)
297f638 @raggi Autoloads, requires, and using new api
raggi authored
306 Rack::Multipart.parse_multipart(env)
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored
307 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
308 end
309 end
Something went wrong with that request. Please try again.