request.rb 12.9 KB
Newer Older
1 2
require 'stringio'

3
require 'active_support/inflector'
4
require 'action_dispatch/http/headers'
5
require 'action_controller/metal/exceptions'
A
Aaron Patterson 已提交
6 7 8 9 10 11 12 13
require 'rack/request'
require 'action_dispatch/http/cache'
require 'action_dispatch/http/mime_negotiation'
require 'action_dispatch/http/parameters'
require 'action_dispatch/http/filter_parameters'
require 'action_dispatch/http/upload'
require 'action_dispatch/http/url'
require 'active_support/core_ext/array/conversions'
14

15
module ActionDispatch
16 17
  class Request
    include Rack::Request::Helpers
18 19 20
    include ActionDispatch::Http::Cache::Request
    include ActionDispatch::Http::MimeNegotiation
    include ActionDispatch::Http::Parameters
21
    include ActionDispatch::Http::FilterParameters
22
    include ActionDispatch::Http::URL
23
    include Rack::Request::Env
24

25
    autoload :Session, 'action_dispatch/request/session'
26
    autoload :Utils,   'action_dispatch/request/utils'
27

28
    LOCALHOST   = Regexp.union [/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/, /^::1$/, /^0:0:0:0:0:0:0:1(%.*)?$/]
29

30
    ENV_METHODS = %w[ AUTH_TYPE GATEWAY_INTERFACE
31
        PATH_TRANSLATED REMOTE_HOST
32
        REMOTE_IDENT REMOTE_USER REMOTE_ADDR
33
        SERVER_NAME SERVER_PROTOCOL
34
        ORIGINAL_SCRIPT_NAME
35 36 37

        HTTP_ACCEPT HTTP_ACCEPT_CHARSET HTTP_ACCEPT_ENCODING
        HTTP_ACCEPT_LANGUAGE HTTP_CACHE_CONTROL HTTP_FROM
38
        HTTP_NEGOTIATE HTTP_PRAGMA HTTP_CLIENT_IP
39
        HTTP_X_FORWARDED_FOR HTTP_VERSION
40 41
        HTTP_X_REQUEST_ID HTTP_X_FORWARDED_HOST
        SERVER_ADDR
42
        ].freeze
43

44
    ENV_METHODS.each do |env|
45
      class_eval <<-METHOD, __FILE__, __LINE__ + 1
V
Vijay Dev 已提交
46
        def #{env.sub(/^HTTP_/n, '').downcase}  # def accept_charset
47
          get_header "#{env}".freeze            #   get_header "HTTP_ACCEPT_CHARSET".freeze
V
Vijay Dev 已提交
48
        end                                     # end
49
      METHOD
50 51
    end

A
Aaron Patterson 已提交
52 53 54 55 56 57 58 59 60
    def initialize(env)
      super
      @method            = nil
      @request_method    = nil
      @remote_ip         = nil
      @original_fullpath = nil
      @fullpath          = nil
      @ip                = nil
    end
61 62 63 64 65 66 67 68 69 70 71

    def check_path_parameters!
      # If any of the path parameters has an invalid encoding then
      # raise since it's likely to trigger errors further on.
      path_parameters.each do |key, value|
        next unless value.respond_to?(:valid_encoding?)
        unless value.valid_encoding?
          raise ActionController::BadRequest, "Invalid parameter: #{key} => #{value}"
        end
      end
    end
A
Aaron Patterson 已提交
72

73 74 75 76 77
    PASS_NOT_FOUND = Class.new { # :nodoc:
      def self.action(_); self; end
      def self.call(_); [404, {'X-Cascade' => 'pass'}, []]; end
    }

78 79 80 81
    def controller_class
      check_path_parameters!
      params = path_parameters

82 83 84 85 86 87 88 89
      if params.key?(:controller)
        controller_param = params[:controller].underscore
        params[:action] ||= 'index'
        const_name = "#{controller_param.camelize}Controller"
        ActiveSupport::Dependencies.constantize(const_name)
      else
        PASS_NOT_FOUND
      end
90 91
    end

92
    def key?(key)
93
      has_header? key
94 95
    end

96 97 98 99 100 101 102
    # List of HTTP request methods from the following RFCs:
    # Hypertext Transfer Protocol -- HTTP/1.1 (http://www.ietf.org/rfc/rfc2616.txt)
    # HTTP Extensions for Distributed Authoring -- WEBDAV (http://www.ietf.org/rfc/rfc2518.txt)
    # Versioning Extensions to WebDAV (http://www.ietf.org/rfc/rfc3253.txt)
    # Ordered Collections Protocol (WebDAV) (http://www.ietf.org/rfc/rfc3648.txt)
    # Web Distributed Authoring and Versioning (WebDAV) Access Control Protocol (http://www.ietf.org/rfc/rfc3744.txt)
    # Web Distributed Authoring and Versioning (WebDAV) SEARCH (http://www.ietf.org/rfc/rfc5323.txt)
K
kasper 已提交
103
    # Calendar Extensions to WebDAV (http://www.ietf.org/rfc/rfc4791.txt)
104 105 106 107 108 109 110
    # PATCH Method for HTTP (http://www.ietf.org/rfc/rfc5789.txt)
    RFC2616 = %w(OPTIONS GET HEAD POST PUT DELETE TRACE CONNECT)
    RFC2518 = %w(PROPFIND PROPPATCH MKCOL COPY MOVE LOCK UNLOCK)
    RFC3253 = %w(VERSION-CONTROL REPORT CHECKOUT CHECKIN UNCHECKOUT MKWORKSPACE UPDATE LABEL MERGE BASELINE-CONTROL MKACTIVITY)
    RFC3648 = %w(ORDERPATCH)
    RFC3744 = %w(ACL)
    RFC5323 = %w(SEARCH)
K
kasper 已提交
111
    RFC4791 = %w(MKCALENDAR)
112 113
    RFC5789 = %w(PATCH)

K
kasper 已提交
114
    HTTP_METHODS = RFC2616 + RFC2518 + RFC3253 + RFC3648 + RFC3744 + RFC5323 + RFC4791 + RFC5789
115 116 117 118 119 120 121

    HTTP_METHOD_LOOKUP = {}

    # Populate the HTTP method lookup cache
    HTTP_METHODS.each { |method|
      HTTP_METHOD_LOOKUP[method] = method.underscore.to_sym
    }
122

123 124 125 126 127 128
    # Returns the HTTP \method that the application should see.
    # In the case where the \method was overridden by a middleware
    # (for instance, if a HEAD request was converted to a GET,
    # or if a _method parameter was used to determine the \method
    # the application should use), this \method returns the overridden
    # value, not the original.
129
    def request_method
130
      @request_method ||= check_method(super)
131 132
    end

133
    def routes # :nodoc:
134
      get_header("action_dispatch.routes".freeze)
135 136
    end

137
    def routes=(routes) # :nodoc:
138
      set_header("action_dispatch.routes".freeze, routes)
139 140
    end

141
    def engine_script_name(_routes) # :nodoc:
142
      get_header(_routes.env_key)
143 144
    end

145
    def engine_script_name=(name) # :nodoc:
146
      set_header(routes.env_key, name.dup)
147 148
    end

149 150
    def request_method=(request_method) #:nodoc:
      if check_method(request_method)
151
        @request_method = set_header("REQUEST_METHOD", request_method)
152 153 154
      end
    end

155
    def controller_instance # :nodoc:
156
      get_header('action_controller.instance'.freeze)
157 158 159
    end

    def controller_instance=(controller) # :nodoc:
160
      set_header('action_controller.instance'.freeze, controller)
161 162
    end

163 164 165 166
    def http_auth_salt
      get_header "action_dispatch.http_auth_salt"
    end

167 168 169 170
    def show_exceptions? # :nodoc:
      # We're treating `nil` as "unset", and we want the default setting to be
      # `true`.  This logic should be extracted to `env_config` and calculated
      # once.
171
      !(get_header('action_dispatch.show_exceptions'.freeze) == false)
172 173
    end

174 175 176
    # Returns a symbol form of the #request_method
    def request_method_symbol
      HTTP_METHOD_LOOKUP[request_method]
177 178
    end

179 180 181
    # Returns the original value of the environment's REQUEST_METHOD,
    # even if it was overridden by middleware. See #request_method for
    # more information.
D
Initial  
David Heinemeier Hansson 已提交
182
    def method
183
      @method ||= check_method(get_header("rack.methodoverride.original_method") || get_header('REQUEST_METHOD'))
184 185 186 187 188
    end

    # Returns a symbol form of the #method
    def method_symbol
      HTTP_METHOD_LOOKUP[method]
D
Initial  
David Heinemeier Hansson 已提交
189 190
    end

P
Pratik Naik 已提交
191
    # Provides access to the request's HTTP headers, for example:
P
Pratik Naik 已提交
192 193
    #
    #   request.headers["Content-Type"] # => "text/plain"
194
    def headers
195
      @headers ||= Http::Headers.new(self)
196 197
    end

198 199 200 201 202 203 204
    # Returns a +String+ with the last requested path including their params.
    #
    #    # get '/foo'
    #    request.original_fullpath # => '/foo'
    #
    #    # get '/foo?bar'
    #    request.original_fullpath # => '/foo?bar'
205
    def original_fullpath
206
      @original_fullpath ||= (get_header("ORIGINAL_FULLPATH") || fullpath)
207 208
    end

209 210
    # Returns the +String+ full path including params of the last URL requested.
    #
211 212
    #    # get "/articles"
    #    request.fullpath # => "/articles"
213
    #
214 215
    #    # get "/articles?page=2"
    #    request.fullpath # => "/articles?page=2"
216 217 218 219
    def fullpath
      @fullpath ||= super
    end

220
    # Returns the original request URL as a +String+.
221
    #
222 223
    #    # get "/articles?page=2"
    #    request.original_url # => "http://www.example.com/articles?page=2"
224 225 226 227
    def original_url
      base_url + original_fullpath
    end

228
    # The +String+ MIME type of the request.
229
    #
230 231
    #    # get "/articles"
    #    request.media_type # => "application/x-www-form-urlencoded"
J
Joshua Peek 已提交
232
    def media_type
233
      content_mime_type.to_s
J
Joshua Peek 已提交
234 235
    end

236 237 238
    # Returns the content length of the request as an integer.
    def content_length
      super.to_i
239 240
    end

241
    # Returns true if the "X-Requested-With" header contains "XMLHttpRequest"
S
ShunsukeAida 已提交
242 243
    # (case-insensitive), which may need to be manually added depending on the
    # choice of JavaScript libraries and frameworks.
244
    def xml_http_request?
245
      get_header('HTTP_X_REQUESTED_WITH') =~ /XMLHttpRequest/i
246
    end
247
    alias :xhr? :xml_http_request?
248

249
    # Returns the IP address of client as a +String+.
250 251 252 253
    def ip
      @ip ||= super
    end

254 255
    # Returns the IP address of client as a +String+,
    # usually set by the RemoteIp middleware.
D
Initial  
David Heinemeier Hansson 已提交
256
    def remote_ip
257
      @remote_ip ||= (get_header("action_dispatch.remote_ip") || ip).to_s
D
Initial  
David Heinemeier Hansson 已提交
258 259
    end

260
    def remote_ip=(remote_ip)
261
      set_header "action_dispatch.remote_ip".freeze, remote_ip
262 263
    end

264 265
    ACTION_DISPATCH_REQUEST_ID = "action_dispatch.request_id".freeze # :nodoc:

266
    # Returns the unique request id, which is based on either the X-Request-Id header that can
267 268 269 270 271
    # be generated by a firewall, load balancer, or web server or by the RequestId middleware
    # (which sets the action_dispatch.request_id environment variable).
    #
    # This unique ID is useful for tracing a request from end-to-end as part of logging or debugging.
    # This relies on the rack variable set by the ActionDispatch::RequestId middleware.
272
    def request_id
273
      get_header ACTION_DISPATCH_REQUEST_ID
274 275
    end

276
    def request_id=(id) # :nodoc:
277
      set_header ACTION_DISPATCH_REQUEST_ID, id
278 279
    end

280
    alias_method :uuid, :request_id
281

282 283
    # Returns the lowercase name of the HTTP server software.
    def server_software
284
      (get_header('SERVER_SOFTWARE') && /^([a-zA-Z]+)/ =~ get_header('SERVER_SOFTWARE')) ? $1.downcase : nil
285 286
    end

P
Pratik Naik 已提交
287
    # Read the request \body. This is useful for web services that need to
288
    # work with raw requests directly.
289
    def raw_post
290
      unless has_header? 'RAW_POST_DATA'
291
        raw_post_body = body
292
        set_header('RAW_POST_DATA', raw_post_body.read(content_length))
293
        raw_post_body.rewind if raw_post_body.respond_to?(:rewind)
294
      end
295
      get_header 'RAW_POST_DATA'
296 297
    end

298 299
    # The request body is an IO input stream. If the RAW_POST_DATA environment
    # variable is already set, wrap it in a StringIO.
300
    def body
301
      if raw_post = get_header('RAW_POST_DATA')
302
        raw_post.force_encoding(Encoding::BINARY)
303 304
        StringIO.new(raw_post)
      else
305
        body_stream
306 307 308
      end
    end

309
    # Returns true if the request's content MIME type is
310
    # +application/x-www-form-urlencoded+ or +multipart/form-data+.
311
    def form_data?
312
      FORM_DATA_MEDIA_TYPES.include?(content_mime_type.to_s)
313
    end
314

315
    def body_stream #:nodoc:
316
      get_header('rack.input')
D
Initial  
David Heinemeier Hansson 已提交
317 318
    end

319 320
    # TODO This should be broken apart into AD::Request::Session and probably
    # be included by the session middleware.
321
    def reset_session
322 323 324 325 326
      if session && session.respond_to?(:destroy)
        session.destroy
      else
        self.session = {}
      end
A
Aaron Patterson 已提交
327
      self.flash = nil
D
Initial  
David Heinemeier Hansson 已提交
328 329
    end

330
    def session=(session) #:nodoc:
331
      Session.set self, session
332 333
    end

334
    def session_options=(options)
335
      Session::Options.set self, options
336 337
    end

338 339
    # Override Rack's GET method to support indifferent access
    def GET
340
      fetch_header("action_dispatch.request.query_parameters") do |k|
M
Marcin Olichwirowicz 已提交
341
        set_header k, Request::Utils.normalize_encode_params(super || {})
342
      end
343
    rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e
344
      raise ActionController::BadRequest.new(:query, e)
345 346 347 348 349
    end
    alias :query_parameters :GET

    # Override Rack's POST method to support indifferent access
    def POST
350
      fetch_header("action_dispatch.request.request_parameters") do
351
        pr = parse_formatted_parameters(self, params_parsers) do |params|
352
          super || {}
353
        end
354
        self.request_parameters = Request::Utils.normalize_encode_params(pr)
355
      end
356 357 358
    rescue ParamsParser::ParseError # one of the parse strategies blew up
      self.request_parameters = Request::Utils.normalize_encode_params(super || {})
      raise
359
    rescue Rack::Utils::ParameterTypeError, Rack::Utils::InvalidParameterError => e
360
      raise ActionController::BadRequest.new(:request, e)
361 362 363
    end
    alias :request_parameters :POST

364 365 366
    # Returns the authorization header regardless of whether it was specified directly or through one of the
    # proxy alternatives.
    def authorization
367 368 369 370
      get_header('HTTP_AUTHORIZATION')   ||
      get_header('X-HTTP_AUTHORIZATION') ||
      get_header('X_HTTP_AUTHORIZATION') ||
      get_header('REDIRECT_X_HTTP_AUTHORIZATION')
371
    end
372

A
Anshul Sharma 已提交
373
    # True if the request came from localhost, 127.0.0.1, or ::1.
374
    def local?
375
      LOCALHOST =~ remote_addr && LOCALHOST =~ remote_ip
376
    end
377

378
    def request_parameters=(params)
379
      raise if params.nil?
380
      set_header("action_dispatch.request.request_parameters".freeze, params)
381 382 383
    end

    def logger
384
      get_header("action_dispatch.logger".freeze)
385 386
    end

387
    private
388
      def check_method(name)
389
        HTTP_METHOD_LOOKUP[name] || raise(ActionController::UnknownHttpMethod, "#{name}, accepted HTTP methods are #{HTTP_METHODS[0...-1].join(', ')}, and #{HTTP_METHODS[-1]}")
390 391
        name
      end
392
  end
393
end