Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Newer
Older
100644 279 lines (236 sloc) 8.934 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 scheme; @env["rack.url_scheme"] end
26 def script_name; @env["SCRIPT_NAME"].to_s end
27 def path_info; @env["PATH_INFO"].to_s end
28 def request_method; @env["REQUEST_METHOD"] end
29 def query_string; @env["QUERY_STRING"].to_s end
30 def content_length; @env['CONTENT_LENGTH'] end
31 def content_type; @env['CONTENT_TYPE'] end
32 def session; @env['rack.session'] ||= {} end
33 def session_options; @env['rack.session.options'] ||= {} end
df22480 @josh rack.logger specification
josh authored
34 def logger; @env['rack.logger'] end
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
35
36 # The media type (type/subtype) portion of the CONTENT_TYPE header
37 # without any media type parameters. e.g., when CONTENT_TYPE is
38 # "text/plain;charset=utf-8", the media-type is "text/plain".
39 #
40 # For more information on the use of media types in HTTP, see:
41 # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7
42 def media_type
939fa7d @tj Refactored Rack::Request#media_type
tj authored
43 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
44 end
45
46 # The media type parameters provided in CONTENT_TYPE as a Hash, or
47 # an empty Hash if no CONTENT_TYPE or media-type parameters were
48 # provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8",
49 # this method responds with the following Hash:
50 # { 'charset' => 'utf-8' }
51 def media_type_params
52 return {} if content_type.nil?
53 content_type.split(/\s*[;,]\s*/)[1..-1].
54 collect { |s| s.split('=', 2) }.
55 inject({}) { |hash,(k,v)| hash[k.downcase] = v ; hash }
56 end
57
58 # The character set of the request body if a "charset" media type
59 # parameter was given, or nil if no "charset" was specified. Note
60 # that, per RFC2616, text/* media types that specify no explicit
61 # charset are to be considered ISO-8859-1.
62 def content_charset
63 media_type_params['charset']
64 end
a18fc32 @chneukirchen Rename Request#method to #request_method to not confuse stdlibs
chneukirchen authored
65
fb32ff7 @josh Request#host knows about forwared host [#77 state:resolved]
josh authored
66 def host_with_port
67 if forwarded = @env["HTTP_X_FORWARDED_HOST"]
68 forwarded.split(/,\s?/).last
69 else
70 @env['HTTP_HOST'] || "#{@env['SERVER_NAME'] || @env['SERVER_ADDR']}:#{@env['SERVER_PORT']}"
71 end
72 end
4bfe1d7 @brasten Modified Rack::Request#port to respect HTTP_X_FORWARDED_HOST port inf…
brasten authored
73
74 def port
75 host, port = host_with_port.split(/:/)
76
77 (port || @env["SERVER_PORT"]).to_i
78 end
fb32ff7 @josh Request#host knows about forwared host [#77 state:resolved]
josh authored
79
c95b751 @chneukirchen Remove the port number of HTTP_HOST and SERVER_NAME
chneukirchen authored
80 def host
81 # Remove port number.
fb32ff7 @josh Request#host knows about forwared host [#77 state:resolved]
josh authored
82 host_with_port.to_s.gsub(/:\d+\z/, '')
c95b751 @chneukirchen Remove the port number of HTTP_HOST and SERVER_NAME
chneukirchen authored
83 end
84
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
85 def script_name=(s); @env["SCRIPT_NAME"] = s.to_s end
86 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
87
320d800 @manveru Add Request.trace? and Request.options?
manveru authored
88 def delete?; request_method == "DELETE" end
89 def get?; request_method == "GET" end
90 def head?; request_method == "HEAD" end
91 def options?; request_method == "OPTIONS" end
92 def post?; request_method == "POST" end
93 def put?; request_method == "PUT" end
94 def trace?; request_method == "TRACE" end
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
95
96 # The set of form-data media-types. Requests that do not indicate
97 # one of the media types presents in this list will not be eligible
98 # for form-data / param parsing.
99 FORM_DATA_MEDIA_TYPES = [
100 'application/x-www-form-urlencoded',
101 'multipart/form-data'
102 ]
103
6674f36 better multipart handling
eTM authored
104 # The set of media-types. Requests that do not indicate
105 # one of the media types presents in this list will not be eligible
106 # for param parsing like soap attachments or generic multiparts
107 PARSEABLE_DATA_MEDIA_TYPES = [
108 'multipart/related',
109 'multipart/mixed'
df22480 @josh rack.logger specification
josh authored
110 ]
6674f36 better multipart handling
eTM authored
111
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
112 # Determine whether the request body contains form-data by checking
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored
113 # the request Content-Type for one of the media-types:
114 # "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
115 # list of form-data media types can be modified through the
116 # +FORM_DATA_MEDIA_TYPES+ array.
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored
117 #
118 # A request body is also assumed to contain form-data when no
119 # 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
120 def form_data?
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored
121 type = media_type
122 meth = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD']
123 (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
124 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
125
6674f36 better multipart handling
eTM authored
126 # Determine whether the request body contains data by checking
127 # the request media_type against registered parse-data media-types
128 def parseable_data?
129 PARSEABLE_DATA_MEDIA_TYPES.include?(media_type)
130 end
131
376fa1e @chneukirchen Add RDocs
chneukirchen authored
132 # Returns the data recieved in the query string.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
133 def GET
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
134 if @env["rack.request.query_string"] == query_string
135 @env["rack.request.query_hash"]
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
136 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
137 @env["rack.request.query_string"] = query_string
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored
138 @env["rack.request.query_hash"] = parse_query(query_string)
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
139 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
140 end
141
376fa1e @chneukirchen Add RDocs
chneukirchen authored
142 # Returns the data recieved in the request body.
143 #
144 # This method support both application/x-www-form-urlencoded and
145 # multipart/form-data.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
146 def POST
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
147 if @env["rack.input"].nil?
01c1770 @jeremy Rack::Request#POST raises if rack.input is missing instead of returni…
jeremy authored
148 raise "Missing rack.input"
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
149 elsif @env["rack.request.form_input"].eql? @env["rack.input"]
150 @env["rack.request.form_hash"]
6674f36 better multipart handling
eTM authored
151 elsif form_data? || parseable_data?
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
152 @env["rack.request.form_input"] = @env["rack.input"]
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored
153 unless @env["rack.request.form_hash"] = parse_multipart(env)
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
154 form_vars = @env["rack.input"].read
0f081dd @josh Clean up Safari's ajax POST body
josh authored
155
156 # Fix for Safari Ajax postings that always append \0
157 form_vars.sub!(/\0\z/, '')
158
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
159 @env["rack.request.form_vars"] = form_vars
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored
160 @env["rack.request.form_hash"] = parse_query(form_vars)
3513f4f @josh Add tests for multipart uploads. Also ensure multipart parser tries t…
josh authored
161
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
162 @env["rack.input"].rewind
4fe5360 @chneukirchen Make Rack::Request read multipart form data
chneukirchen authored
163 end
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
164 @env["rack.request.form_hash"]
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
165 else
166 {}
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
167 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
168 end
169
376fa1e @chneukirchen Add RDocs
chneukirchen authored
170 # The union of GET and POST data.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
171 def params
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored
172 self.GET.update(self.POST)
67a7507 @chneukirchen handle EOFError exception in Request#params
chneukirchen authored
173 rescue EOFError => e
174 self.GET
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
175 end
176
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored
177 # shortcut for request.params[key]
178 def [](key)
179 params[key.to_s]
180 end
181
182 # shortcut for request.params[key] = value
183 def []=(key, value)
184 params[key.to_s] = value
185 end
186
187 # like Hash#values_at
188 def values_at(*keys)
189 keys.map{|key| params[key] }
190 end
191
aa7ce77 @ghazel do not default referer to '/'
ghazel authored
192 # the referer of the client
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored
193 def referer
aa7ce77 @ghazel do not default referer to '/'
ghazel authored
194 @env['HTTP_REFERER']
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored
195 end
196 alias referrer referer
197
e2a1a64 @josh Request#user_agent
josh authored
198 def user_agent
199 @env['HTTP_USER_AGENT']
200 end
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored
201
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
202 def cookies
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
203 return {} unless @env["HTTP_COOKIE"]
b68c2d5 @chneukirchen Return empty hash on lack of cookies
chneukirchen authored
204
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
205 if @env["rack.request.cookie_string"] == @env["HTTP_COOKIE"]
206 @env["rack.request.cookie_hash"]
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
207 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
208 @env["rack.request.cookie_string"] = @env["HTTP_COOKIE"]
4a08f8a Conform to RFC 2109 regarding multiple values for same cookie
Aman Gupta authored
209 # According to RFC 2109:
210 # If multiple cookies satisfy the criteria above, they are ordered in
211 # the Cookie header such that those with more specific Path attributes
212 # precede those with less specific. Ordering with respect to other
213 # attributes (e.g., Domain) is unspecified.
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
214 @env["rack.request.cookie_hash"] =
215 Utils.parse_query(@env["rack.request.cookie_string"], ';,').inject({}) {|h,(k,v)|
acb8695 @chneukirchen Fix cookie parsing
chneukirchen authored
216 h[k] = Array === v ? v.first : v
4a08f8a Conform to RFC 2109 regarding multiple values for same cookie
Aman Gupta authored
217 h
218 }
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
219 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
220 end
221
222 def xhr?
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
223 @env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
224 end
fd51d36 @chneukirchen Add Request#url
chneukirchen authored
225
376fa1e @chneukirchen Add RDocs
chneukirchen authored
226 # Tries to return a remake of the original request URL as a string.
fd51d36 @chneukirchen Add Request#url
chneukirchen authored
227 def url
228 url = scheme + "://"
229 url << host
230
231 if scheme == "https" && port != 443 ||
232 scheme == "http" && port != 80
233 url << ":#{port}"
234 end
235
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored
236 url << fullpath
fd51d36 @chneukirchen Add Request#url
chneukirchen authored
237
238 url
239 end
df22480 @josh rack.logger specification
josh authored
240
3a544a7 @tj Added Rack::Request#path
tj authored
241 def path
242 script_name + path_info
243 end
df22480 @josh rack.logger specification
josh authored
244
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored
245 def fullpath
3a544a7 @tj Added Rack::Request#path
tj authored
246 query_string.empty? ? path : "#{path}?#{query_string}"
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored
247 end
0f2dab5 @qerub Added support for Accept-Encoding (via Request#accept_encoding and Ut…
qerub authored
248
249 def accept_encoding
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
250 @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
251 m = /^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$/.match(part) # From WEBrick
252
253 if m
254 [m[1], (m[2] || 1.0).to_f]
255 else
256 raise "Invalid value for Accept-Encoding: #{part.inspect}"
257 end
258 end
259 end
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored
260
261 def ip
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
262 if addr = @env['HTTP_X_FORWARDED_FOR']
fa324e3 @manveru Don't use 'unknown' in HTTP_X_FORWARDED_FOR
manveru authored
263 (addr.split(',').grep(/\d\./).first || @env['REMOTE_ADDR']).to_s.strip
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored
264 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
265 @env['REMOTE_ADDR']
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored
266 end
267 end
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored
268
269 protected
270 def parse_query(qs)
271 Utils.parse_nested_query(qs)
272 end
273
274 def parse_multipart(env)
275 Utils::Multipart.parse_multipart(env)
276 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
277 end
278 end
Something went wrong with that request. Please try again.