Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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