Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 272 lines (231 sloc) 8.855 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 inst...
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
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
83 def get?; request_method == "GET" end
84 def post?; request_method == "POST" end
85 def put?; request_method == "PUT" end
86 def delete?; request_method == "DELETE" end
87 def head?; request_method == "HEAD" end
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
88
89 # The set of form-data media-types. Requests that do not indicate
90 # one of the media types presents in this list will not be eligible
91 # for form-data / param parsing.
92 FORM_DATA_MEDIA_TYPES = [
93 'application/x-www-form-urlencoded',
94 'multipart/form-data'
95 ]
96
6674f36 better multipart handling
eTM authored
97 # The set of media-types. Requests that do not indicate
98 # one of the media types presents in this list will not be eligible
99 # for param parsing like soap attachments or generic multiparts
100 PARSEABLE_DATA_MEDIA_TYPES = [
101 'multipart/related',
102 'multipart/mixed'
df22480 @josh rack.logger specification
josh authored
103 ]
6674f36 better multipart handling
eTM authored
104
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
105 # Determine whether the request body contains form-data by checking
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored
106 # the request Content-Type for one of the media-types:
107 # "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
108 # list of form-data media types can be modified through the
109 # +FORM_DATA_MEDIA_TYPES+ array.
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored
110 #
111 # A request body is also assumed to contain form-data when no
112 # 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
113 def form_data?
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored
114 type = media_type
115 meth = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD']
116 (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
117 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
118
6674f36 better multipart handling
eTM authored
119 # Determine whether the request body contains data by checking
120 # the request media_type against registered parse-data media-types
121 def parseable_data?
122 PARSEABLE_DATA_MEDIA_TYPES.include?(media_type)
123 end
124
376fa1e @chneukirchen Add RDocs
chneukirchen authored
125 # Returns the data recieved in the query string.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
126 def GET
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
127 if @env["rack.request.query_string"] == query_string
128 @env["rack.request.query_hash"]
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
129 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
130 @env["rack.request.query_string"] = query_string
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored
131 @env["rack.request.query_hash"] = parse_query(query_string)
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
132 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
133 end
134
376fa1e @chneukirchen Add RDocs
chneukirchen authored
135 # Returns the data recieved in the request body.
136 #
137 # This method support both application/x-www-form-urlencoded and
138 # multipart/form-data.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
139 def POST
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
140 if @env["rack.input"].nil?
01c1770 @jeremy Rack::Request#POST raises if rack.input is missing instead of returning ...
jeremy authored
141 raise "Missing rack.input"
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
142 elsif @env["rack.request.form_input"].eql? @env["rack.input"]
143 @env["rack.request.form_hash"]
6674f36 better multipart handling
eTM authored
144 elsif form_data? || parseable_data?
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
145 @env["rack.request.form_input"] = @env["rack.input"]
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored
146 unless @env["rack.request.form_hash"] = parse_multipart(env)
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
147 form_vars = @env["rack.input"].read
0f081dd @josh Clean up Safari's ajax POST body
josh authored
148
149 # Fix for Safari Ajax postings that always append \0
150 form_vars.sub!(/\0\z/, '')
151
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
152 @env["rack.request.form_vars"] = form_vars
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored
153 @env["rack.request.form_hash"] = parse_query(form_vars)
3513f4f @josh Add tests for multipart uploads. Also ensure multipart parser tries to r...
josh authored
154
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
155 @env["rack.input"].rewind
4fe5360 @chneukirchen Make Rack::Request read multipart form data
chneukirchen authored
156 end
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
157 @env["rack.request.form_hash"]
fe40ec2 @chneukirchen Fix that Request assumes form-data even when Content-Type says otherwise
chneukirchen authored
158 else
159 {}
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
160 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
161 end
162
376fa1e @chneukirchen Add RDocs
chneukirchen authored
163 # The union of GET and POST data.
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
164 def params
aea2d60 @rtomayko Use Content-Type to determine POST params parsing [#20]
rtomayko authored
165 self.GET.update(self.POST)
67a7507 @chneukirchen handle EOFError exception in Request#params
chneukirchen authored
166 rescue EOFError => e
167 self.GET
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
168 end
169
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored
170 # shortcut for request.params[key]
171 def [](key)
172 params[key.to_s]
173 end
174
175 # shortcut for request.params[key] = value
176 def []=(key, value)
177 params[key.to_s] = value
178 end
179
180 # like Hash#values_at
181 def values_at(*keys)
182 keys.map{|key| params[key] }
183 end
184
185 # the referer of the client or '/'
186 def referer
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
187 @env['HTTP_REFERER'] || '/'
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored
188 end
189 alias referrer referer
190
e2a1a64 @josh Request#user_agent
josh authored
191 def user_agent
192 @env['HTTP_USER_AGENT']
193 end
de7411c @manveru add some features to Request and the corresponding tests for them
manveru authored
194
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
195 def cookies
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
196 return {} unless @env["HTTP_COOKIE"]
b68c2d5 @chneukirchen Return empty hash on lack of cookies
chneukirchen authored
197
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
198 if @env["rack.request.cookie_string"] == @env["HTTP_COOKIE"]
199 @env["rack.request.cookie_hash"]
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
200 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
201 @env["rack.request.cookie_string"] = @env["HTTP_COOKIE"]
4a08f8a Conform to RFC 2109 regarding multiple values for same cookie
Aman Gupta authored
202 # According to RFC 2109:
203 # If multiple cookies satisfy the criteria above, they are ordered in
204 # the Cookie header such that those with more specific Path attributes
205 # precede those with less specific. Ordering with respect to other
206 # attributes (e.g., Domain) is unspecified.
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
207 @env["rack.request.cookie_hash"] =
208 Utils.parse_query(@env["rack.request.cookie_string"], ';,').inject({}) {|h,(k,v)|
acb8695 @chneukirchen Fix cookie parsing
chneukirchen authored
209 h[k] = Array === v ? v.first : v
4a08f8a Conform to RFC 2109 regarding multiple values for same cookie
Aman Gupta authored
210 h
211 }
6c80c6c @chneukirchen Cache the parsed things in Rack::Request
chneukirchen authored
212 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
213 end
214
215 def xhr?
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
216 @env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
217 end
fd51d36 @chneukirchen Add Request#url
chneukirchen authored
218
376fa1e @chneukirchen Add RDocs
chneukirchen authored
219 # Tries to return a remake of the original request URL as a string.
fd51d36 @chneukirchen Add Request#url
chneukirchen authored
220 def url
221 url = scheme + "://"
222 url << host
223
224 if scheme == "https" && port != 443 ||
225 scheme == "http" && port != 80
226 url << ":#{port}"
227 end
228
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored
229 url << fullpath
fd51d36 @chneukirchen Add Request#url
chneukirchen authored
230
231 url
232 end
df22480 @josh rack.logger specification
josh authored
233
3a544a7 @tj Added Rack::Request#path
tj authored
234 def path
235 script_name + path_info
236 end
df22480 @josh rack.logger specification
josh authored
237
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored
238 def fullpath
3a544a7 @tj Added Rack::Request#path
tj authored
239 query_string.empty? ? path : "#{path}?#{query_string}"
234c062 @chneukirchen Add Request#fullpath
chneukirchen authored
240 end
0f2dab5 @qerub Added support for Accept-Encoding (via Request#accept_encoding and Utils...
qerub authored
241
242 def accept_encoding
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
243 @env["HTTP_ACCEPT_ENCODING"].to_s.split(/,\s*/).map do |part|
0f2dab5 @qerub Added support for Accept-Encoding (via Request#accept_encoding and Utils...
qerub authored
244 m = /^([^\s,]+?)(?:;\s*q=(\d+(?:\.\d+)?))?$/.match(part) # From WEBrick
245
246 if m
247 [m[1], (m[2] || 1.0).to_f]
248 else
249 raise "Invalid value for Accept-Encoding: #{part.inspect}"
250 end
251 end
252 end
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored
253
254 def ip
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
255 if addr = @env['HTTP_X_FORWARDED_FOR']
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored
256 addr.split(',').last.strip
257 else
71030b9 @josh Revert "Add common HTTP strings to Rack::Const"
josh authored
258 @env['REMOTE_ADDR']
a48eb51 @manveru Add Request#ip and corresponding spec
manveru authored
259 end
260 end
d8ccbf3 @josh Extract parse_query and parse_multipart in Request so subclasses
josh authored
261
262 protected
263 def parse_query(qs)
264 Utils.parse_nested_query(qs)
265 end
266
267 def parse_multipart(env)
268 Utils::Multipart.parse_multipart(env)
269 end
5f13e3d @chneukirchen Add Rack::Request
chneukirchen authored
270 end
271 end
Something went wrong with that request. Please try again.