diff options
Diffstat (limited to 'actionpack/lib/action_controller/dispatch')
11 files changed, 440 insertions, 0 deletions
diff --git a/actionpack/lib/action_controller/dispatch/dispatcher.rb b/actionpack/lib/action_controller/dispatch/dispatcher.rb new file mode 100644 index 0000000000..e205245f13 --- /dev/null +++ b/actionpack/lib/action_controller/dispatch/dispatcher.rb @@ -0,0 +1,116 @@ +module ActionController + # Dispatches requests to the appropriate controller and takes care of + # reloading the app after each request when Dependencies.load? is true. + class Dispatcher + class << self + def define_dispatcher_callbacks(cache_classes) + unless cache_classes + # Development mode callbacks + before_dispatch :reload_application + after_dispatch :cleanup_application + + ActionView::Helpers::AssetTagHelper.cache_asset_timestamps = false + end + + if defined?(ActiveRecord) + after_dispatch :checkin_connections + to_prepare(:activerecord_instantiate_observers) { ActiveRecord::Base.instantiate_observers } + end + + after_dispatch :flush_logger if Base.logger && Base.logger.respond_to?(:flush) + + to_prepare do + I18n.reload! + end + end + + # DEPRECATE: Remove CGI support + def dispatch(cgi = nil, session_options = CgiRequest::DEFAULT_SESSION_OPTIONS, output = $stdout) + new(output).dispatch_cgi(cgi, session_options) + end + + # Add a preparation callback. Preparation callbacks are run before every + # request in development mode, and before the first request in production + # mode. + # + # An optional identifier may be supplied for the callback. If provided, + # to_prepare may be called again with the same identifier to replace the + # existing callback. Passing an identifier is a suggested practice if the + # code adding a preparation block may be reloaded. + def to_prepare(identifier = nil, &block) + @prepare_dispatch_callbacks ||= ActiveSupport::Callbacks::CallbackChain.new + callback = ActiveSupport::Callbacks::Callback.new(:prepare_dispatch, block, :identifier => identifier) + @prepare_dispatch_callbacks.replace_or_append!(callback) + end + end + + cattr_accessor :middleware + self.middleware = ActionDispatch::MiddlewareStack.new do |middleware| + middlewares = File.join(File.dirname(__FILE__), "middlewares.rb") + middleware.instance_eval(File.read(middlewares)) + end + + include ActiveSupport::Callbacks + define_callbacks :prepare_dispatch, :before_dispatch, :after_dispatch + + # DEPRECATE: Remove arguments, since they are only used by CGI + def initialize(output = $stdout, request = nil, response = nil) + @output = output + @app = @@middleware.build(lambda { |env| self.dup._call(env) }) + end + + def dispatch + begin + run_callbacks :before_dispatch + Routing::Routes.call(@env) + rescue Exception => exception + if controller ||= (::ApplicationController rescue Base) + controller.call_with_exception(@env, exception).to_a + else + raise exception + end + ensure + run_callbacks :after_dispatch, :enumerator => :reverse_each + end + end + + # DEPRECATE: Remove CGI support + def dispatch_cgi(cgi, session_options) + CGIHandler.dispatch_cgi(self, cgi, @output) + end + + def call(env) + @app.call(env) + end + + def _call(env) + @env = env + dispatch + end + + def reload_application + # Run prepare callbacks before every request in development mode + run_callbacks :prepare_dispatch + + Routing::Routes.reload + end + + # Cleanup the application by clearing out loaded classes so they can + # be reloaded on the next request without restarting the server. + def cleanup_application + ActiveRecord::Base.reset_subclasses if defined?(ActiveRecord) + ActiveSupport::Dependencies.clear + ActiveRecord::Base.clear_reloadable_connections! if defined?(ActiveRecord) + end + + def flush_logger + Base.logger.flush + end + + def checkin_connections + # Don't return connection (and peform implicit rollback) if this request is a part of integration test + return if @env.key?("rack.test") + ActiveRecord::Base.clear_active_connections! + end + end +end diff --git a/actionpack/lib/action_controller/dispatch/middlewares.rb b/actionpack/lib/action_controller/dispatch/middlewares.rb new file mode 100644 index 0000000000..3bf3dbebab --- /dev/null +++ b/actionpack/lib/action_controller/dispatch/middlewares.rb @@ -0,0 +1,21 @@ +use "Rack::Lock", :if => lambda { + !ActionController::Base.allow_concurrency +} + +use "ActionDispatch::Failsafe" + +["ActionDispatch::Session::CookieStore", + "ActionDispatch::Session::MemCacheStore", + "ActiveRecord::SessionStore"].each do |store| + use(store, ActionController::Base.session_options, + :if => lambda { + if session_store = ActionController::Base.session_store + session_store.name == store + end + } + ) +end + +use "ActionDispatch::RewindableInput" +use "ActionDispatch::ParamsParser" +use "Rack::MethodOverride" diff --git a/actionpack/lib/action_controller/dispatch/rescue.rb b/actionpack/lib/action_controller/dispatch/rescue.rb new file mode 100644 index 0000000000..df0a976204 --- /dev/null +++ b/actionpack/lib/action_controller/dispatch/rescue.rb @@ -0,0 +1,179 @@ +module ActionController #:nodoc: + # Actions that fail to perform as expected throw exceptions. These + # exceptions can either be rescued for the public view (with a nice + # user-friendly explanation) or for the developers view (with tons of + # debugging information). The developers view is already implemented by + # the Action Controller, but the public view should be tailored to your + # specific application. + # + # The default behavior for public exceptions is to render a static html + # file with the name of the error code thrown. If no such file exists, an + # empty response is sent with the correct status code. + # + # You can override what constitutes a local request by overriding the + # <tt>local_request?</tt> method in your own controller. Custom rescue + # behavior is achieved by overriding the <tt>rescue_action_in_public</tt> + # and <tt>rescue_action_locally</tt> methods. + module Rescue + LOCALHOST = '127.0.0.1'.freeze + + DEFAULT_RESCUE_RESPONSE = :internal_server_error + DEFAULT_RESCUE_RESPONSES = { + 'ActionController::RoutingError' => :not_found, + 'ActionController::UnknownAction' => :not_found, + 'ActiveRecord::RecordNotFound' => :not_found, + 'ActiveRecord::StaleObjectError' => :conflict, + 'ActiveRecord::RecordInvalid' => :unprocessable_entity, + 'ActiveRecord::RecordNotSaved' => :unprocessable_entity, + 'ActionController::MethodNotAllowed' => :method_not_allowed, + 'ActionController::NotImplemented' => :not_implemented, + 'ActionController::InvalidAuthenticityToken' => :unprocessable_entity + } + + DEFAULT_RESCUE_TEMPLATE = 'diagnostics' + DEFAULT_RESCUE_TEMPLATES = { + 'ActionView::MissingTemplate' => 'missing_template', + 'ActionController::RoutingError' => 'routing_error', + 'ActionController::UnknownAction' => 'unknown_action', + 'ActionView::TemplateError' => 'template_error' + } + + RESCUES_TEMPLATE_PATH = ActionView::Template::EagerPath.new( + File.join(File.dirname(__FILE__), "templates")) + + def self.included(base) #:nodoc: + base.cattr_accessor :rescue_responses + base.rescue_responses = Hash.new(DEFAULT_RESCUE_RESPONSE) + base.rescue_responses.update DEFAULT_RESCUE_RESPONSES + + base.cattr_accessor :rescue_templates + base.rescue_templates = Hash.new(DEFAULT_RESCUE_TEMPLATE) + base.rescue_templates.update DEFAULT_RESCUE_TEMPLATES + + base.extend(ClassMethods) + base.send :include, ActiveSupport::Rescuable + + base.class_eval do + alias_method_chain :perform_action, :rescue + end + end + + module ClassMethods + def call_with_exception(env, exception) #:nodoc: + request = env["action_controller.rescue.request"] ||= ActionDispatch::Request.new(env) + response = env["action_controller.rescue.response"] ||= ActionDispatch::Response.new + new.process(request, response, :rescue_action, exception) + end + end + + protected + # Exception handler called when the performance of an action raises + # an exception. + def rescue_action(exception) + rescue_with_handler(exception) || + rescue_action_without_handler(exception) + end + + # Overwrite to implement custom logging of errors. By default + # logs as fatal. + def log_error(exception) #:doc: + ActiveSupport::Deprecation.silence do + if ActionView::TemplateError === exception + logger.fatal(exception.to_s) + else + logger.fatal( + "\n#{exception.class} (#{exception.message}):\n " + + clean_backtrace(exception).join("\n ") + "\n\n" + ) + end + end + end + + # Overwrite to implement public exception handling (for requests + # answering false to <tt>local_request?</tt>). By default will call + # render_optional_error_file. Override this method to provide more + # user friendly error messages. + def rescue_action_in_public(exception) #:doc: + render_optional_error_file response_code_for_rescue(exception) + end + + # Attempts to render a static error page based on the + # <tt>status_code</tt> thrown, or just return headers if no such file + # exists. For example, if a 500 error is being handled Rails will first + # attempt to render the file at <tt>public/500.html</tt>. If the file + # doesn't exist, the body of the response will be left empty. + def render_optional_error_file(status_code) + status = interpret_status(status_code) + path = "#{Rails.public_path}/#{status.to_s[0,3]}.html" + if File.exist?(path) + render :file => path, :status => status, :content_type => Mime::HTML + else + head status + end + end + + # True if the request came from localhost, 127.0.0.1. Override this + # method if you wish to redefine the meaning of a local request to + # include remote IP addresses or other criteria. + def local_request? #:doc: + request.remote_addr == LOCALHOST && request.remote_ip == LOCALHOST + end + + # Render detailed diagnostics for unhandled exceptions rescued from + # a controller action. + def rescue_action_locally(exception) + @template.instance_variable_set("@exception", exception) + @template.instance_variable_set("@rescues_path", RESCUES_TEMPLATE_PATH) + @template.instance_variable_set("@contents", + @template._render_template(template_path_for_local_rescue(exception))) + + response.content_type = Mime::HTML + response.status = interpret_status(response_code_for_rescue(exception)) + + content = @template._render_template(rescues_path("layout")) + render_for_text(content) + end + + def rescue_action_without_handler(exception) + log_error(exception) if logger + erase_results if performed? + + # Let the exception alter the response if it wants. + # For example, MethodNotAllowed sets the Allow header. + if exception.respond_to?(:handle_response!) + exception.handle_response!(response) + end + + if consider_all_requests_local || local_request? + rescue_action_locally(exception) + else + rescue_action_in_public(exception) + end + end + + private + def perform_action_with_rescue #:nodoc: + perform_action_without_rescue + rescue Exception => exception + rescue_action(exception) + end + + def rescues_path(template_name) + RESCUES_TEMPLATE_PATH.find_template("rescues/#{template_name}.erb") + end + + def template_path_for_local_rescue(exception) + rescues_path(rescue_templates[exception.class.name]) + end + + def response_code_for_rescue(exception) + rescue_responses[exception.class.name] + end + + def clean_backtrace(exception) + defined?(Rails) && Rails.respond_to?(:backtrace_cleaner) ? + Rails.backtrace_cleaner.clean(exception.backtrace) : + exception.backtrace + end + end +end diff --git a/actionpack/lib/action_controller/dispatch/templates/rescues/_request_and_response.erb b/actionpack/lib/action_controller/dispatch/templates/rescues/_request_and_response.erb new file mode 100644 index 0000000000..64b34650b1 --- /dev/null +++ b/actionpack/lib/action_controller/dispatch/templates/rescues/_request_and_response.erb @@ -0,0 +1,24 @@ +<% unless @exception.blamed_files.blank? %> + <% if (hide = @exception.blamed_files.length > 8) %> + <a href="#" onclick="document.getElementById('blame_trace').style.display='block'; return false;">Show blamed files</a> + <% end %> + <pre id="blame_trace" <%='style="display:none"' if hide %>><code><%=h @exception.describe_blame %></code></pre> +<% end %> + +<% + clean_params = request.parameters.clone + clean_params.delete("action") + clean_params.delete("controller") + + request_dump = clean_params.empty? ? 'None' : clean_params.inspect.gsub(',', ",\n") +%> + +<h2 style="margin-top: 30px">Request</h2> +<p><b>Parameters</b>: <pre><%=h request_dump %></pre></p> + +<p><a href="#" onclick="document.getElementById('session_dump').style.display='block'; return false;">Show session dump</a></p> +<div id="session_dump" style="display:none"><%= debug(request.session.instance_variable_get("@data")) %></div> + + +<h2 style="margin-top: 30px">Response</h2> +<p><b>Headers</b>: <pre><%=h response ? response.headers.inspect.gsub(',', ",\n") : 'None' %></pre></p> diff --git a/actionpack/lib/action_controller/dispatch/templates/rescues/_trace.erb b/actionpack/lib/action_controller/dispatch/templates/rescues/_trace.erb new file mode 100644 index 0000000000..bb2d8375bd --- /dev/null +++ b/actionpack/lib/action_controller/dispatch/templates/rescues/_trace.erb @@ -0,0 +1,26 @@ +<% + traces = [ + ["Application Trace", @exception.application_backtrace], + ["Framework Trace", @exception.framework_backtrace], + ["Full Trace", @exception.clean_backtrace] + ] + names = traces.collect {|name, trace| name} +%> + +<p><code>RAILS_ROOT: <%= defined?(RAILS_ROOT) ? RAILS_ROOT : "unset" %></code></p> + +<div id="traces"> + <% names.each do |name| %> + <% + show = "document.getElementById('#{name.gsub /\s/, '-'}').style.display='block';" + hide = (names - [name]).collect {|hide_name| "document.getElementById('#{hide_name.gsub /\s/, '-'}').style.display='none';"} + %> + <a href="#" onclick="<%= hide %><%= show %>; return false;"><%= name %></a> <%= '|' unless names.last == name %> + <% end %> + + <% traces.each do |name, trace| %> + <div id="<%= name.gsub /\s/, '-' %>" style="display: <%= name == "Application Trace" ? 'block' : 'none' %>;"> + <pre><code><%= trace.join "\n" %></code></pre> + </div> + <% end %> +</div> diff --git a/actionpack/lib/action_controller/dispatch/templates/rescues/diagnostics.erb b/actionpack/lib/action_controller/dispatch/templates/rescues/diagnostics.erb new file mode 100644 index 0000000000..95be64511d --- /dev/null +++ b/actionpack/lib/action_controller/dispatch/templates/rescues/diagnostics.erb @@ -0,0 +1,10 @@ +<h1> + <%=h @exception.class.to_s %> + <% if request.parameters['controller'] %> + in <%=h request.parameters['controller'].humanize %>Controller<% if request.parameters['action'] %>#<%=h request.parameters['action'] %><% end %> + <% end %> +</h1> +<pre><%=h @exception.clean_message %></pre> + +<%= @template._render_template(@rescues_path.find_template("rescues/_trace.erb")) %> +<%= @template._render_template(@rescues_path.find_template("rescues/_request_and_response.erb")) %>
\ No newline at end of file diff --git a/actionpack/lib/action_controller/dispatch/templates/rescues/layout.erb b/actionpack/lib/action_controller/dispatch/templates/rescues/layout.erb new file mode 100644 index 0000000000..4a04742e40 --- /dev/null +++ b/actionpack/lib/action_controller/dispatch/templates/rescues/layout.erb @@ -0,0 +1,29 @@ +<html xmlns="http://www.w3.org/1999/xhtml"> +<head> + <title>Action Controller: Exception caught</title> + <style> + body { background-color: #fff; color: #333; } + + body, p, ol, ul, td { + font-family: verdana, arial, helvetica, sans-serif; + font-size: 13px; + line-height: 18px; + } + + pre { + background-color: #eee; + padding: 10px; + font-size: 11px; + } + + a { color: #000; } + a:visited { color: #666; } + a:hover { color: #fff; background-color:#000; } + </style> +</head> +<body> + +<%= @contents %> + +</body> +</html>
\ No newline at end of file diff --git a/actionpack/lib/action_controller/dispatch/templates/rescues/missing_template.erb b/actionpack/lib/action_controller/dispatch/templates/rescues/missing_template.erb new file mode 100644 index 0000000000..dbfdf76947 --- /dev/null +++ b/actionpack/lib/action_controller/dispatch/templates/rescues/missing_template.erb @@ -0,0 +1,2 @@ +<h1>Template is missing</h1> +<p><%=h @exception.message %></p> diff --git a/actionpack/lib/action_controller/dispatch/templates/rescues/routing_error.erb b/actionpack/lib/action_controller/dispatch/templates/rescues/routing_error.erb new file mode 100644 index 0000000000..ccfa858cce --- /dev/null +++ b/actionpack/lib/action_controller/dispatch/templates/rescues/routing_error.erb @@ -0,0 +1,10 @@ +<h1>Routing Error</h1> +<p><pre><%=h @exception.message %></pre></p> +<% unless @exception.failures.empty? %><p> + <h2>Failure reasons:</h2> + <ol> + <% @exception.failures.each do |route, reason| %> + <li><code><%=h route.inspect.gsub('\\', '') %></code> failed because <%=h reason.downcase %></li> + <% end %> + </ol> +</p><% end %> diff --git a/actionpack/lib/action_controller/dispatch/templates/rescues/template_error.erb b/actionpack/lib/action_controller/dispatch/templates/rescues/template_error.erb new file mode 100644 index 0000000000..2e34e03bd5 --- /dev/null +++ b/actionpack/lib/action_controller/dispatch/templates/rescues/template_error.erb @@ -0,0 +1,21 @@ +<h1> + <%=h @exception.original_exception.class.to_s %> in + <%=h request.parameters["controller"].capitalize if request.parameters["controller"]%>#<%=h request.parameters["action"] %> +</h1> + +<p> + Showing <i><%=h @exception.file_name %></i> where line <b>#<%=h @exception.line_number %></b> raised: + <pre><code><%=h @exception.message %></code></pre> +</p> + +<p>Extracted source (around line <b>#<%=h @exception.line_number %></b>): +<pre><code><%=h @exception.source_extract %></code></pre></p> + +<p><%=h @exception.sub_template_message %></p> + +<% @real_exception = @exception + @exception = @exception.original_exception || @exception %> +<%= render :file => @rescues_path["rescues/_trace.erb"] %> +<% @exception = @real_exception %> + +<%= render :file => @rescues_path["rescues/_request_and_response.erb"] %> diff --git a/actionpack/lib/action_controller/dispatch/templates/rescues/unknown_action.erb b/actionpack/lib/action_controller/dispatch/templates/rescues/unknown_action.erb new file mode 100644 index 0000000000..683379da10 --- /dev/null +++ b/actionpack/lib/action_controller/dispatch/templates/rescues/unknown_action.erb @@ -0,0 +1,2 @@ +<h1>Unknown action</h1> +<p><%=h @exception.message %></p> |