Permalink
Newer
Older
100644 339 lines (279 sloc) 10.7 KB
1
require 'rack/utils'
2
Feb 16, 2007
3
module Rack
Mar 1, 2007
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"]
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.
Feb 16, 2007
16
class Request
Mar 1, 2007
17
# The environment of the request.
18
attr_reader :env
Feb 16, 2007
20
def initialize(env)
21
@env = env
22
end
23
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
30
31
def content_type
32
content_type = @env['CONTENT_TYPE']
33
content_type.nil? || content_type.empty? ? nil : content_type
34
end
35
36
def session; @env['rack.session'] ||= {} end
37
def session_options; @env['rack.session.options'] ||= {} end
38
def logger; @env['rack.logger'] end
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
47
content_type && content_type.split(/\s*[;,]\s*/, 2).first.downcase
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?
Oct 3, 2010
57
Hash[*content_type.split(/\s*[;,]\s*/)[1..-1].
Oct 3, 2010
59
map { |k,v| [k.downcase, v] }.flatten]
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
70
def scheme
71
if @env['HTTPS'] == 'on'
72
'https'
73
elsif @env['HTTP_X_FORWARDED_SSL'] == 'on'
74
'https'
75
elsif @env['HTTP_X_FORWARDED_PROTO']
76
@env['HTTP_X_FORWARDED_PROTO'].split(',')[0]
77
else
78
@env["rack.url_scheme"]
79
end
80
end
81
82
def ssl?
83
scheme == 'https'
84
end
85
Dec 21, 2009
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
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
101
elsif @env.has_key?("HTTP_X_FORWARDED_HOST")
102
80
103
else
104
@env["SERVER_PORT"].to_i
105
end
Dec 21, 2009
107
108
def host
109
# Remove port number.
Dec 21, 2009
110
host_with_port.to_s.gsub(/:\d+\z/, '')
113
def script_name=(s); @env["SCRIPT_NAME"] = s.to_s end
114
def path_info=(s); @env["PATH_INFO"] = s.to_s end
116
117
# Checks the HTTP request method (or verb) to see if it was of type DELETE
118
def delete?; request_method == "DELETE" end
119
120
# Checks the HTTP request method (or verb) to see if it was of type GET
121
def get?; request_method == "GET" end
122
123
# Checks the HTTP request method (or verb) to see if it was of type HEAD
124
def head?; request_method == "HEAD" end
125
126
# Checks the HTTP request method (or verb) to see if it was of type OPTIONS
127
def options?; request_method == "OPTIONS" end
128
129
# Checks the HTTP request method (or verb) to see if it was of type PATCH
130
def patch?; request_method == "PATCH" end
131
132
# Checks the HTTP request method (or verb) to see if it was of type POST
133
def post?; request_method == "POST" end
134
135
# Checks the HTTP request method (or verb) to see if it was of type PUT
136
def put?; request_method == "PUT" end
137
138
# Checks the HTTP request method (or verb) to see if it was of type TRACE
139
def trace?; request_method == "TRACE" end
142
# The set of form-data media-types. Requests that do not indicate
143
# one of the media types presents in this list will not be eligible
144
# for form-data / param parsing.
145
FORM_DATA_MEDIA_TYPES = [
146
'application/x-www-form-urlencoded',
147
'multipart/form-data'
148
]
149
150
# The set of media-types. Requests that do not indicate
151
# one of the media types presents in this list will not be eligible
152
# for param parsing like soap attachments or generic multiparts
153
PARSEABLE_DATA_MEDIA_TYPES = [
154
'multipart/related',
155
'multipart/mixed'
156
]
158
# Determine whether the request body contains form-data by checking
159
# the request Content-Type for one of the media-types:
160
# "application/x-www-form-urlencoded" or "multipart/form-data". The
161
# list of form-data media types can be modified through the
162
# +FORM_DATA_MEDIA_TYPES+ array.
163
#
164
# A request body is also assumed to contain form-data when no
165
# Content-Type header is provided and the request_method is POST.
167
type = media_type
168
meth = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD']
169
(meth == 'POST' && type.nil?) || FORM_DATA_MEDIA_TYPES.include?(type)
Feb 16, 2007
171
172
# Determine whether the request body contains data by checking
173
# the request media_type against registered parse-data media-types
174
def parseable_data?
175
PARSEABLE_DATA_MEDIA_TYPES.include?(media_type)
176
end
177
Mar 1, 2007
178
# Returns the data recieved in the query string.
Feb 16, 2007
179
def GET
180
if @env["rack.request.query_string"] == query_string
181
@env["rack.request.query_hash"]
183
@env["rack.request.query_string"] = query_string
184
@env["rack.request.query_hash"] = parse_query(query_string)
Feb 16, 2007
186
end
187
Mar 1, 2007
188
# Returns the data recieved in the request body.
189
#
190
# This method support both application/x-www-form-urlencoded and
191
# multipart/form-data.
Feb 16, 2007
192
def POST
193
if @env["rack.input"].nil?
195
elsif @env["rack.request.form_input"].eql? @env["rack.input"]
196
@env["rack.request.form_hash"]
197
elsif form_data? || parseable_data?
198
@env["rack.request.form_input"] = @env["rack.input"]
199
unless @env["rack.request.form_hash"] = parse_multipart(env)
200
form_vars = @env["rack.input"].read
201
202
# Fix for Safari Ajax postings that always append \0
203
# form_vars.sub!(/\0\z/, '') # performance replacement:
204
form_vars.slice!(-1) if form_vars[-1] == ?\0
206
@env["rack.request.form_vars"] = form_vars
207
@env["rack.request.form_hash"] = parse_query(form_vars)
209
@env["rack.input"].rewind
211
@env["rack.request.form_hash"]
Feb 16, 2007
215
end
216
Mar 1, 2007
217
# The union of GET and POST data.
Feb 16, 2007
218
def params
219
@params ||= self.GET.merge(self.POST)
220
rescue EOFError
Feb 16, 2007
222
end
223
224
# shortcut for request.params[key]
225
def [](key)
226
params[key.to_s]
227
end
228
229
# shortcut for request.params[key] = value
230
def []=(key, value)
231
params[key.to_s] = value
232
end
233
234
# like Hash#values_at
235
def values_at(*keys)
236
keys.map{|key| params[key] }
237
end
238
239
# the referer of the client
241
@env['HTTP_REFERER']
242
end
243
alias referrer referer
244
Dec 21, 2009
245
def user_agent
246
@env['HTTP_USER_AGENT']
247
end
Feb 16, 2007
249
def cookies
250
hash = @env["rack.request.cookie_hash"] ||= {}
251
string = @env["HTTP_COOKIE"]
252
253
return hash if string == @env["rack.request.cookie_string"]
255
256
# According to RFC 2109:
257
# If multiple cookies satisfy the criteria above, they are ordered in
258
# the Cookie header such that those with more specific Path attributes
259
# precede those with less specific. Ordering with respect to other
260
# attributes (e.g., Domain) is unspecified.
261
Utils.parse_query(string, ';,').each { |k,v| hash[k] = Array === v ? v.first : v }
262
@env["rack.request.cookie_string"] = string
263
hash
264
rescue => error
265
raise error.class, "cannot parse Cookie header: #{error.message}"
Feb 16, 2007
266
end
267
268
def xhr?
269
@env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"
Feb 16, 2007
270
end
Feb 21, 2007
271
272
def base_url
Feb 21, 2007
273
url = scheme + "://"
274
url << host
275
276
if scheme == "https" && port != 443 ||
277
scheme == "http" && port != 80
278
url << ":#{port}"
279
end
280
281
url
282
end
284
# Tries to return a remake of the original request URL as a string.
285
def url
286
base_url + fullpath
287
end
288
289
def path
290
script_name + path_info
291
end
Mar 30, 2007
293
def fullpath
294
query_string.empty? ? path : "#{path}?#{query_string}"
Mar 30, 2007
295
end
298
@env["HTTP_ACCEPT_ENCODING"].to_s.split(/\s*,\s*/).map do |part|
299
encoding, parameters = part.split(/\s*;\s*/, 2)
300
quality = 1.0
301
if parameters and /\Aq=([\d.]+)/ =~ parameters
302
quality = $1.to_f
304
[encoding, quality]
307
308
def ip
309
# Copied from https://github.com/rails/rails/blob/master/actionpack/lib/
310
# action_dispatch/middleware/remote_ip.rb
311
trusted_proxies = /(^127\.0\.0\.1$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\.)/i
312
313
remote_addrs = @env['REMOTE_ADDR'] ? @env['REMOTE_ADDR'].split(/[,\s]+/) : []
314
remote_addrs.reject! { |addr| addr =~ trusted_proxies }
315
316
return remote_addrs.first if remote_addrs.any?
317
318
forwarded_ips = @env['HTTP_X_FORWARDED_FOR'] ? @env['HTTP_X_FORWARDED_FOR'].strip.split(/[,\s]+/) : []
319
320
if client_ip = @env['HTTP_CLIENT_IP']
321
# If forwarded_ips doesn't include the client_ip, it might be an
322
# ip spoofing attempt, so we ignore HTTP_CLIENT_IP
323
return client_ip if forwarded_ips.include?(client_ip)
325
326
return forwarded_ips.reject { |ip| ip =~ trusted_proxies }.last || @env["REMOTE_ADDR"]
328
329
protected
330
def parse_query(qs)
331
Utils.parse_nested_query(qs)
332
end
333
334
def parse_multipart(env)
335
Rack::Multipart.parse_multipart(env)
Feb 16, 2007
337
end
338
end