request.rb 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. require 'rack/utils'
  2. module Rack
  3. # Rack::Request provides a convenient interface to a Rack
  4. # environment. It is stateless, the environment +env+ passed to the
  5. # constructor will be directly modified.
  6. #
  7. # req = Rack::Request.new(env)
  8. # req.post?
  9. # req.params["data"]
  10. #
  11. # The environment hash passed will store a reference to the Request object
  12. # instantiated so that it will only instantiate if an instance of the Request
  13. # object doesn't already exist.
  14. class Request
  15. # The environment of the request.
  16. attr_reader :env
  17. def initialize(env)
  18. @env = env
  19. end
  20. def body; @env["rack.input"] end
  21. def script_name; @env["SCRIPT_NAME"].to_s end
  22. def path_info; @env["PATH_INFO"].to_s end
  23. def request_method; @env["REQUEST_METHOD"] end
  24. def query_string; @env["QUERY_STRING"].to_s end
  25. def content_length; @env['CONTENT_LENGTH'] end
  26. def content_type
  27. content_type = @env['CONTENT_TYPE']
  28. content_type.nil? || content_type.empty? ? nil : content_type
  29. end
  30. def session; @env['rack.session'] ||= {} end
  31. def session_options; @env['rack.session.options'] ||= {} end
  32. def logger; @env['rack.logger'] end
  33. # The media type (type/subtype) portion of the CONTENT_TYPE header
  34. # without any media type parameters. e.g., when CONTENT_TYPE is
  35. # "text/plain;charset=utf-8", the media-type is "text/plain".
  36. #
  37. # For more information on the use of media types in HTTP, see:
  38. # http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.7
  39. def media_type
  40. content_type && content_type.split(/\s*[;,]\s*/, 2).first.downcase
  41. end
  42. # The media type parameters provided in CONTENT_TYPE as a Hash, or
  43. # an empty Hash if no CONTENT_TYPE or media-type parameters were
  44. # provided. e.g., when the CONTENT_TYPE is "text/plain;charset=utf-8",
  45. # this method responds with the following Hash:
  46. # { 'charset' => 'utf-8' }
  47. def media_type_params
  48. return {} if content_type.nil?
  49. Hash[*content_type.split(/\s*[;,]\s*/)[1..-1].
  50. collect { |s| s.split('=', 2) }.
  51. map { |k,v| [k.downcase, v] }.flatten]
  52. end
  53. # The character set of the request body if a "charset" media type
  54. # parameter was given, or nil if no "charset" was specified. Note
  55. # that, per RFC2616, text/* media types that specify no explicit
  56. # charset are to be considered ISO-8859-1.
  57. def content_charset
  58. media_type_params['charset']
  59. end
  60. def scheme
  61. if @env['HTTPS'] == 'on'
  62. 'https'
  63. elsif @env['HTTP_X_FORWARDED_SSL'] == 'on'
  64. 'https'
  65. elsif @env['HTTP_X_FORWARDED_SCHEME']
  66. @env['HTTP_X_FORWARDED_SCHEME']
  67. elsif @env['HTTP_X_FORWARDED_PROTO']
  68. @env['HTTP_X_FORWARDED_PROTO'].split(',')[0]
  69. else
  70. @env["rack.url_scheme"]
  71. end
  72. end
  73. def ssl?
  74. scheme == 'https'
  75. end
  76. def host_with_port
  77. if forwarded = @env["HTTP_X_FORWARDED_HOST"]
  78. forwarded.split(/,\s?/).last
  79. else
  80. @env['HTTP_HOST'] || "#{@env['SERVER_NAME'] || @env['SERVER_ADDR']}:#{@env['SERVER_PORT']}"
  81. end
  82. end
  83. def port
  84. if port = host_with_port.split(/:/)[1]
  85. port.to_i
  86. elsif port = @env['HTTP_X_FORWARDED_PORT']
  87. port.to_i
  88. elsif ssl?
  89. 443
  90. elsif @env.has_key?("HTTP_X_FORWARDED_HOST")
  91. 80
  92. else
  93. @env["SERVER_PORT"].to_i
  94. end
  95. end
  96. def host
  97. # Remove port number.
  98. host_with_port.to_s.gsub(/:\d+\z/, '')
  99. end
  100. def script_name=(s); @env["SCRIPT_NAME"] = s.to_s end
  101. def path_info=(s); @env["PATH_INFO"] = s.to_s end
  102. # Checks the HTTP request method (or verb) to see if it was of type DELETE
  103. def delete?; request_method == "DELETE" end
  104. # Checks the HTTP request method (or verb) to see if it was of type GET
  105. def get?; request_method == "GET" end
  106. # Checks the HTTP request method (or verb) to see if it was of type HEAD
  107. def head?; request_method == "HEAD" end
  108. # Checks the HTTP request method (or verb) to see if it was of type OPTIONS
  109. def options?; request_method == "OPTIONS" end
  110. # Checks the HTTP request method (or verb) to see if it was of type PATCH
  111. def patch?; request_method == "PATCH" end
  112. # Checks the HTTP request method (or verb) to see if it was of type POST
  113. def post?; request_method == "POST" end
  114. # Checks the HTTP request method (or verb) to see if it was of type PUT
  115. def put?; request_method == "PUT" end
  116. # Checks the HTTP request method (or verb) to see if it was of type TRACE
  117. def trace?; request_method == "TRACE" end
  118. # The set of form-data media-types. Requests that do not indicate
  119. # one of the media types presents in this list will not be eligible
  120. # for form-data / param parsing.
  121. FORM_DATA_MEDIA_TYPES = [
  122. 'application/x-www-form-urlencoded',
  123. 'multipart/form-data'
  124. ]
  125. # The set of media-types. Requests that do not indicate
  126. # one of the media types presents in this list will not be eligible
  127. # for param parsing like soap attachments or generic multiparts
  128. PARSEABLE_DATA_MEDIA_TYPES = [
  129. 'multipart/related',
  130. 'multipart/mixed'
  131. ]
  132. # Determine whether the request body contains form-data by checking
  133. # the request Content-Type for one of the media-types:
  134. # "application/x-www-form-urlencoded" or "multipart/form-data". The
  135. # list of form-data media types can be modified through the
  136. # +FORM_DATA_MEDIA_TYPES+ array.
  137. #
  138. # A request body is also assumed to contain form-data when no
  139. # Content-Type header is provided and the request_method is POST.
  140. def form_data?
  141. type = media_type
  142. meth = env["rack.methodoverride.original_method"] || env['REQUEST_METHOD']
  143. (meth == 'POST' && type.nil?) || FORM_DATA_MEDIA_TYPES.include?(type)
  144. end
  145. # Determine whether the request body contains data by checking
  146. # the request media_type against registered parse-data media-types
  147. def parseable_data?
  148. PARSEABLE_DATA_MEDIA_TYPES.include?(media_type)
  149. end
  150. # Returns the data received in the query string.
  151. def GET
  152. if @env["rack.request.query_string"] == query_string
  153. @env["rack.request.query_hash"]
  154. else
  155. @env["rack.request.query_string"] = query_string
  156. @env["rack.request.query_hash"] = parse_query(query_string)
  157. end
  158. end
  159. # Returns the data received in the request body.
  160. #
  161. # This method support both application/x-www-form-urlencoded and
  162. # multipart/form-data.
  163. def POST
  164. if @env["rack.input"].nil?
  165. raise "Missing rack.input"
  166. elsif @env["rack.request.form_input"].eql? @env["rack.input"]
  167. @env["rack.request.form_hash"]
  168. elsif form_data? || parseable_data?
  169. @env["rack.request.form_input"] = @env["rack.input"]
  170. unless @env["rack.request.form_hash"] = parse_multipart(env)
  171. form_vars = @env["rack.input"].read
  172. # Fix for Safari Ajax postings that always append \0
  173. # form_vars.sub!(/\0\z/, '') # performance replacement:
  174. form_vars.slice!(-1) if form_vars[-1] == ?\0
  175. @env["rack.request.form_vars"] = form_vars
  176. @env["rack.request.form_hash"] = parse_query(form_vars)
  177. @env["rack.input"].rewind
  178. end
  179. @env["rack.request.form_hash"]
  180. else
  181. {}
  182. end
  183. end
  184. # The union of GET and POST data.
  185. def params
  186. @params ||= self.GET.merge(self.POST)
  187. rescue EOFError
  188. self.GET
  189. end
  190. # shortcut for request.params[key]
  191. def [](key)
  192. params[key.to_s]
  193. end
  194. # shortcut for request.params[key] = value
  195. def []=(key, value)
  196. params[key.to_s] = value
  197. end
  198. # like Hash#values_at
  199. def values_at(*keys)
  200. keys.map{|key| params[key] }
  201. end
  202. # the referer of the client
  203. def referer
  204. @env['HTTP_REFERER']
  205. end
  206. alias referrer referer
  207. def user_agent
  208. @env['HTTP_USER_AGENT']
  209. end
  210. def cookies
  211. hash = @env["rack.request.cookie_hash"] ||= {}
  212. string = @env["HTTP_COOKIE"]
  213. return hash if string == @env["rack.request.cookie_string"]
  214. hash.clear
  215. # According to RFC 2109:
  216. # If multiple cookies satisfy the criteria above, they are ordered in
  217. # the Cookie header such that those with more specific Path attributes
  218. # precede those with less specific. Ordering with respect to other
  219. # attributes (e.g., Domain) is unspecified.
  220. Utils.parse_query(string, ';,').each { |k,v| hash[k] = Array === v ? v.first : v }
  221. @env["rack.request.cookie_string"] = string
  222. hash
  223. rescue => error
  224. error.message.replace "cannot parse Cookie header: #{error.message}"
  225. raise
  226. end
  227. def xhr?
  228. @env["HTTP_X_REQUESTED_WITH"] == "XMLHttpRequest"
  229. end
  230. def base_url
  231. url = scheme + "://"
  232. url << host
  233. if scheme == "https" && port != 443 ||
  234. scheme == "http" && port != 80
  235. url << ":#{port}"
  236. end
  237. url
  238. end
  239. # Tries to return a remake of the original request URL as a string.
  240. def url
  241. base_url + fullpath
  242. end
  243. def path
  244. script_name + path_info
  245. end
  246. def fullpath
  247. query_string.empty? ? path : "#{path}?#{query_string}"
  248. end
  249. def accept_encoding
  250. @env["HTTP_ACCEPT_ENCODING"].to_s.split(/\s*,\s*/).map do |part|
  251. encoding, parameters = part.split(/\s*;\s*/, 2)
  252. quality = 1.0
  253. if parameters and /\Aq=([\d.]+)/ =~ parameters
  254. quality = $1.to_f
  255. end
  256. [encoding, quality]
  257. end
  258. end
  259. def trusted_proxy?(ip)
  260. ip =~ /^127\.0\.0\.1$|^(10|172\.(1[6-9]|2[0-9]|30|31)|192\.168)\.|^::1$|^fd[0-9a-f]{2}:.+|^localhost$/i
  261. end
  262. def ip
  263. remote_addrs = @env['REMOTE_ADDR'] ? @env['REMOTE_ADDR'].split(/[,\s]+/) : []
  264. remote_addrs.reject! { |addr| trusted_proxy?(addr) }
  265. return remote_addrs.first if remote_addrs.any?
  266. forwarded_ips = @env['HTTP_X_FORWARDED_FOR'] ? @env['HTTP_X_FORWARDED_FOR'].strip.split(/[,\s]+/) : []
  267. if client_ip = @env['HTTP_CLIENT_IP']
  268. # If forwarded_ips doesn't include the client_ip, it might be an
  269. # ip spoofing attempt, so we ignore HTTP_CLIENT_IP
  270. return client_ip if forwarded_ips.include?(client_ip)
  271. end
  272. return forwarded_ips.reject { |ip| trusted_proxy?(ip) }.last || @env["REMOTE_ADDR"]
  273. end
  274. protected
  275. def parse_query(qs)
  276. Utils.parse_nested_query(qs)
  277. end
  278. def parse_multipart(env)
  279. Rack::Multipart.parse_multipart(env)
  280. end
  281. end
  282. end