Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

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