// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // See http://dev.chromium.org/developers/design-documents/multi-process-resource-loading #include "content/browser/loader/resource_dispatcher_host_impl.h" #include #include #include #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/debug/alias.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/memory/shared_memory.h" #include "base/message_loop/message_loop.h" #include "base/metrics/histogram_macros.h" #include "base/metrics/sparse_histogram.h" #include "base/profiler/scoped_tracker.h" #include "base/stl_util.h" #include "base/third_party/dynamic_annotations/dynamic_annotations.h" #include "base/time/time.h" #include "content/browser/appcache/appcache_interceptor.h" #include "content/browser/appcache/chrome_appcache_service.h" #include "content/browser/bad_message.h" #include "content/browser/cert_store_impl.h" #include "content/browser/child_process_security_policy_impl.h" #include "content/browser/download/download_resource_handler.h" #include "content/browser/download/save_file_manager.h" #include "content/browser/download/save_file_resource_handler.h" #include "content/browser/fileapi/chrome_blob_storage_context.h" #include "content/browser/frame_host/navigation_request_info.h" #include "content/browser/frame_host/navigator.h" #include "content/browser/loader/async_resource_handler.h" #include "content/browser/loader/cross_site_resource_handler.h" #include "content/browser/loader/detachable_resource_handler.h" #include "content/browser/loader/mime_type_resource_handler.h" #include "content/browser/loader/navigation_resource_handler.h" #include "content/browser/loader/navigation_url_loader_impl_core.h" #include "content/browser/loader/power_save_block_resource_throttle.h" #include "content/browser/loader/redirect_to_file_resource_handler.h" #include "content/browser/loader/resource_message_filter.h" #include "content/browser/loader/resource_request_info_impl.h" #include "content/browser/loader/stream_resource_handler.h" #include "content/browser/loader/sync_resource_handler.h" #include "content/browser/loader/throttling_resource_handler.h" #include "content/browser/loader/upload_data_stream_builder.h" #include "content/browser/renderer_host/render_view_host_delegate.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/resource_context_impl.h" #include "content/browser/service_worker/service_worker_request_handler.h" #include "content/browser/streams/stream.h" #include "content/browser/streams/stream_context.h" #include "content/browser/streams/stream_registry.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/common/appcache_interfaces.h" #include "content/common/navigation_params.h" #include "content/common/resource_messages.h" #include "content/common/site_isolation_policy.h" #include "content/common/ssl_status_serialization.h" #include "content/common/view_messages.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/content_browser_client.h" #include "content/public/browser/download_manager.h" #include "content/public/browser/download_url_parameters.h" #include "content/public/browser/global_request_id.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/resource_dispatcher_host_delegate.h" #include "content/public/browser/resource_request_details.h" #include "content/public/browser/resource_throttle.h" #include "content/public/browser/stream_handle.h" #include "content/public/browser/stream_info.h" #include "content/public/browser/user_metrics.h" #include "content/public/common/content_switches.h" #include "content/public/common/process_type.h" #include "ipc/ipc_message_macros.h" #include "ipc/ipc_message_start.h" #include "net/base/auth.h" #include "net/base/load_flags.h" #include "net/base/mime_util.h" #include "net/base/net_errors.h" #include "net/base/registry_controlled_domains/registry_controlled_domain.h" #include "net/base/request_priority.h" #include "net/base/upload_data_stream.h" #include "net/cert/cert_status_flags.h" #include "net/cookies/cookie_monster.h" #include "net/http/http_response_headers.h" #include "net/http/http_response_info.h" #include "net/ssl/ssl_cert_request_info.h" #include "net/url_request/url_request.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_job_factory.h" #include "storage/browser/blob/blob_data_handle.h" #include "storage/browser/blob/blob_storage_context.h" #include "storage/browser/blob/blob_url_request_job_factory.h" #include "storage/browser/blob/shareable_file_reference.h" #include "storage/browser/fileapi/file_permission_policy.h" #include "storage/browser/fileapi/file_system_context.h" #include "url/url_constants.h" using base::Time; using base::TimeDelta; using base::TimeTicks; using storage::ShareableFileReference; // ---------------------------------------------------------------------------- namespace content { namespace { static ResourceDispatcherHostImpl* g_resource_dispatcher_host; // The interval for calls to ResourceDispatcherHostImpl::UpdateLoadStates const int kUpdateLoadStatesIntervalMsec = 250; // Maximum byte "cost" of all the outstanding requests for a renderer. // See delcaration of |max_outstanding_requests_cost_per_process_| for details. // This bound is 25MB, which allows for around 6000 outstanding requests. const int kMaxOutstandingRequestsCostPerProcess = 26214400; // The number of milliseconds after noting a user gesture that we will // tag newly-created URLRequest objects with the // net::LOAD_MAYBE_USER_GESTURE load flag. This is a fairly arbitrary // guess at how long to expect direct impact from a user gesture, but // this should be OK as the load flag is a best-effort thing only, // rather than being intended as fully accurate. const int kUserGestureWindowMs = 3500; // Ratio of |max_num_in_flight_requests_| that any one renderer is allowed to // use. Arbitrarily chosen. const double kMaxRequestsPerProcessRatio = 0.45; // TODO(jkarlin): The value is high to reduce the chance of the detachable // request timing out, forcing a blocked second request to open a new connection // and start over. Reduce this value once we have a better idea of what it // should be and once we stop blocking multiple simultaneous requests for the // same resource (see bugs 46104 and 31014). const int kDefaultDetachableCancelDelayMs = 30000; enum SHA1HistogramTypes { // SHA-1 is not present in the certificate chain. SHA1_NOT_PRESENT = 0, // SHA-1 is present in the certificate chain, and the leaf expires on or // after January 1, 2017. SHA1_EXPIRES_AFTER_JANUARY_2017 = 1, // SHA-1 is present in the certificate chain, and the leaf expires on or // after June 1, 2016. SHA1_EXPIRES_AFTER_JUNE_2016 = 2, // SHA-1 is present in the certificate chain, and the leaf expires on or // after January 1, 2016. SHA1_EXPIRES_AFTER_JANUARY_2016 = 3, // SHA-1 is present in the certificate chain, but the leaf expires before // January 1, 2016 SHA1_PRESENT = 4, // Always keep this at the end. SHA1_HISTOGRAM_TYPES_MAX, }; void RecordCertificateHistograms(const net::SSLInfo& ssl_info, ResourceType resource_type) { // The internal representation of the dates for UI treatment of SHA-1. // See http://crbug.com/401365 for details static const int64_t kJanuary2017 = INT64_C(13127702400000000); static const int64_t kJune2016 = INT64_C(13109213000000000); static const int64_t kJanuary2016 = INT64_C(13096080000000000); SHA1HistogramTypes sha1_histogram = SHA1_NOT_PRESENT; if (ssl_info.cert_status & net::CERT_STATUS_SHA1_SIGNATURE_PRESENT) { DCHECK(ssl_info.cert.get()); if (ssl_info.cert->valid_expiry() >= base::Time::FromInternalValue(kJanuary2017)) { sha1_histogram = SHA1_EXPIRES_AFTER_JANUARY_2017; } else if (ssl_info.cert->valid_expiry() >= base::Time::FromInternalValue(kJune2016)) { sha1_histogram = SHA1_EXPIRES_AFTER_JUNE_2016; } else if (ssl_info.cert->valid_expiry() >= base::Time::FromInternalValue(kJanuary2016)) { sha1_histogram = SHA1_EXPIRES_AFTER_JANUARY_2016; } else { sha1_histogram = SHA1_PRESENT; } } if (resource_type == RESOURCE_TYPE_MAIN_FRAME) { UMA_HISTOGRAM_ENUMERATION("Net.Certificate.SHA1.MainFrame", sha1_histogram, SHA1_HISTOGRAM_TYPES_MAX); } else { UMA_HISTOGRAM_ENUMERATION("Net.Certificate.SHA1.Subresource", sha1_histogram, SHA1_HISTOGRAM_TYPES_MAX); } } bool IsDetachableResourceType(ResourceType type) { switch (type) { case RESOURCE_TYPE_PREFETCH: case RESOURCE_TYPE_PING: return true; default: return false; } } // Aborts a request before an URLRequest has actually been created. void AbortRequestBeforeItStarts(ResourceMessageFilter* filter, IPC::Message* sync_result, int request_id) { if (sync_result) { SyncLoadResult result; result.error_code = net::ERR_ABORTED; ResourceHostMsg_SyncLoad::WriteReplyParams(sync_result, result); filter->Send(sync_result); } else { // Tell the renderer that this request was disallowed. ResourceMsg_RequestCompleteData request_complete_data; request_complete_data.error_code = net::ERR_ABORTED; request_complete_data.was_ignored_by_handler = false; request_complete_data.exists_in_cache = false; // No security info needed, connection not established. request_complete_data.completion_time = base::TimeTicks(); request_complete_data.encoded_data_length = 0; filter->Send(new ResourceMsg_RequestComplete( request_id, request_complete_data)); } } void SetReferrerForRequest(net::URLRequest* request, const Referrer& referrer) { base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); if (!referrer.url.is_valid() || command_line->HasSwitch(switches::kNoReferrers)) { request->SetReferrer(std::string()); } else { request->SetReferrer(referrer.url.spec()); } net::URLRequest::ReferrerPolicy net_referrer_policy = net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE; switch (referrer.policy) { case blink::WebReferrerPolicyAlways: case blink::WebReferrerPolicyNever: case blink::WebReferrerPolicyOrigin: net_referrer_policy = net::URLRequest::NEVER_CLEAR_REFERRER; break; case blink::WebReferrerPolicyNoReferrerWhenDowngrade: net_referrer_policy = net::URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE; break; case blink::WebReferrerPolicyOriginWhenCrossOrigin: net_referrer_policy = net::URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN; break; case blink::WebReferrerPolicyDefault: default: net_referrer_policy = command_line->HasSwitch(switches::kReducedReferrerGranularity) ? net::URLRequest:: REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN : net::URLRequest:: CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE; break; } request->set_referrer_policy(net_referrer_policy); } // Consults the RendererSecurity policy to determine whether the // ResourceDispatcherHostImpl should service this request. A request might be // disallowed if the renderer is not authorized to retrieve the request URL or // if the renderer is attempting to upload an unauthorized file. bool ShouldServiceRequest(int process_type, int child_id, const ResourceHostMsg_Request& request_data, storage::FileSystemContext* file_system_context) { if (process_type == PROCESS_TYPE_PLUGIN) return true; ChildProcessSecurityPolicyImpl* policy = ChildProcessSecurityPolicyImpl::GetInstance(); // Check if the renderer is permitted to request the requested URL. if (!policy->CanRequestURL(child_id, request_data.url)) { VLOG(1) << "Denied unauthorized request for " << request_data.url.possibly_invalid_spec(); return false; } // Check if the renderer is permitted to upload the requested files. if (request_data.request_body.get()) { const std::vector* uploads = request_data.request_body->elements(); std::vector::const_iterator iter; for (iter = uploads->begin(); iter != uploads->end(); ++iter) { if (iter->type() == ResourceRequestBody::Element::TYPE_FILE && !policy->CanReadFile(child_id, iter->path())) { NOTREACHED() << "Denied unauthorized upload of " << iter->path().value(); return false; } if (iter->type() == ResourceRequestBody::Element::TYPE_FILE_FILESYSTEM) { storage::FileSystemURL url = file_system_context->CrackURL(iter->filesystem_url()); if (!policy->CanReadFileSystemFile(child_id, url)) { NOTREACHED() << "Denied unauthorized upload of " << iter->filesystem_url().spec(); return false; } } } } return true; } void RemoveDownloadFileFromChildSecurityPolicy(int child_id, const base::FilePath& path) { ChildProcessSecurityPolicyImpl::GetInstance()->RevokeAllPermissionsForFile( child_id, path); } DownloadInterruptReason CallbackAndReturn( const DownloadUrlParameters::OnStartedCallback& started_cb, DownloadInterruptReason interrupt_reason) { if (started_cb.is_null()) return interrupt_reason; BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( started_cb, static_cast(NULL), interrupt_reason)); return interrupt_reason; } int GetCertID(net::URLRequest* request, int child_id) { if (request->ssl_info().cert.get()) { return CertStore::GetInstance()->StoreCert(request->ssl_info().cert.get(), child_id); } return 0; } void NotifyRedirectOnUI(int render_process_id, int render_frame_host, scoped_ptr details) { RenderFrameHostImpl* host = RenderFrameHostImpl::FromID(render_process_id, render_frame_host); WebContentsImpl* web_contents = static_cast(WebContents::FromRenderFrameHost(host)); if (!web_contents) return; web_contents->DidGetRedirectForResourceRequest(host, *details.get()); } void NotifyResponseOnUI(int render_process_id, int render_frame_host, scoped_ptr details) { RenderFrameHostImpl* host = RenderFrameHostImpl::FromID(render_process_id, render_frame_host); WebContentsImpl* web_contents = static_cast(WebContents::FromRenderFrameHost(host)); if (!web_contents) return; web_contents->DidGetResourceResponseStart(*details.get()); } bool IsValidatedSCT( const net::SignedCertificateTimestampAndStatus& sct_status) { return sct_status.status == net::ct::SCT_STATUS_OK; } storage::BlobStorageContext* GetBlobStorageContext( ChromeBlobStorageContext* blob_storage_context) { if (!blob_storage_context) return NULL; return blob_storage_context->context(); } void AttachRequestBodyBlobDataHandles( ResourceRequestBody* body, storage::BlobStorageContext* blob_context) { DCHECK(blob_context); for (size_t i = 0; i < body->elements()->size(); ++i) { const ResourceRequestBody::Element& element = (*body->elements())[i]; if (element.type() != ResourceRequestBody::Element::TYPE_BLOB) continue; scoped_ptr handle = blob_context->GetBlobDataFromUUID(element.blob_uuid()); DCHECK(handle); if (!handle) continue; // Ensure the blob and any attached shareable files survive until // upload completion. The |body| takes ownership of |handle|. const void* key = handle.get(); body->SetUserData(key, handle.release()); } } // PlzNavigate // This method is called in the UI thread to send the timestamp of a resource // request to the respective Navigator (for an UMA histogram). void LogResourceRequestTimeOnUI( base::TimeTicks timestamp, int render_process_id, int render_frame_id, const GURL& url) { DCHECK_CURRENTLY_ON(BrowserThread::UI); RenderFrameHostImpl* host = RenderFrameHostImpl::FromID(render_process_id, render_frame_id); if (host != NULL) { DCHECK(host->frame_tree_node()->IsMainFrame()); host->frame_tree_node()->navigator()->LogResourceRequestTime( timestamp, url); } } } // namespace // static ResourceDispatcherHost* ResourceDispatcherHost::Get() { return g_resource_dispatcher_host; } ResourceDispatcherHostImpl::ResourceDispatcherHostImpl() : save_file_manager_(new SaveFileManager()), request_id_(-1), is_shutdown_(false), num_in_flight_requests_(0), max_num_in_flight_requests_(base::SharedMemory::GetHandleLimit()), max_num_in_flight_requests_per_process_( static_cast( max_num_in_flight_requests_ * kMaxRequestsPerProcessRatio)), max_outstanding_requests_cost_per_process_( kMaxOutstandingRequestsCostPerProcess), filter_(NULL), delegate_(NULL), allow_cross_origin_auth_prompt_(false) { DCHECK_CURRENTLY_ON(BrowserThread::UI); DCHECK(!g_resource_dispatcher_host); g_resource_dispatcher_host = this; GetContentClient()->browser()->ResourceDispatcherHostCreated(); ANNOTATE_BENIGN_RACE( &last_user_gesture_time_, "We don't care about the precise value, see http://crbug.com/92889"); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&ResourceDispatcherHostImpl::OnInit, base::Unretained(this))); update_load_states_timer_.reset( new base::RepeatingTimer()); } ResourceDispatcherHostImpl::~ResourceDispatcherHostImpl() { DCHECK(outstanding_requests_stats_map_.empty()); DCHECK(g_resource_dispatcher_host); g_resource_dispatcher_host = NULL; } // static ResourceDispatcherHostImpl* ResourceDispatcherHostImpl::Get() { return g_resource_dispatcher_host; } void ResourceDispatcherHostImpl::SetDelegate( ResourceDispatcherHostDelegate* delegate) { delegate_ = delegate; } void ResourceDispatcherHostImpl::SetAllowCrossOriginAuthPrompt(bool value) { allow_cross_origin_auth_prompt_ = value; } void ResourceDispatcherHostImpl::AddResourceContext(ResourceContext* context) { active_resource_contexts_.insert(context); } void ResourceDispatcherHostImpl::RemoveResourceContext( ResourceContext* context) { CHECK(ContainsKey(active_resource_contexts_, context)); active_resource_contexts_.erase(context); } void ResourceDispatcherHostImpl::CancelRequestsForContext( ResourceContext* context) { DCHECK_CURRENTLY_ON(BrowserThread::IO); DCHECK(context); CHECK(ContainsKey(active_resource_contexts_, context)); // Note that request cancellation has side effects. Therefore, we gather all // the requests to cancel first, and then we start cancelling. We assert at // the end that there are no more to cancel since the context is about to go // away. typedef std::vector> LoaderList; LoaderList loaders_to_cancel; for (LoaderMap::iterator i = pending_loaders_.begin(); i != pending_loaders_.end();) { if (i->second->GetRequestInfo()->GetContext() == context) { loaders_to_cancel.push_back(i->second); IncrementOutstandingRequestsMemory(-1, *i->second->GetRequestInfo()); pending_loaders_.erase(i++); } else { ++i; } } for (BlockedLoadersMap::iterator i = blocked_loaders_map_.begin(); i != blocked_loaders_map_.end();) { BlockedLoadersList* loaders = i->second; if (loaders->empty()) { // This can happen if BlockRequestsForRoute() has been called for a route, // but we haven't blocked any matching requests yet. ++i; continue; } ResourceRequestInfoImpl* info = loaders->front()->GetRequestInfo(); if (info->GetContext() == context) { blocked_loaders_map_.erase(i++); for (BlockedLoadersList::const_iterator it = loaders->begin(); it != loaders->end(); ++it) { linked_ptr loader = *it; info = loader->GetRequestInfo(); // We make the assumption that all requests on the list have the same // ResourceContext. DCHECK_EQ(context, info->GetContext()); IncrementOutstandingRequestsMemory(-1, *info); loaders_to_cancel.push_back(loader); } delete loaders; } else { ++i; } } #ifndef NDEBUG for (LoaderList::iterator i = loaders_to_cancel.begin(); i != loaders_to_cancel.end(); ++i) { // There is no strict requirement that this be the case, but currently // downloads, streams, detachable requests, transferred requests, and // browser-owned requests are the only requests that aren't cancelled when // the associated processes go away. It may be OK for this invariant to // change in the future, but if this assertion fires without the invariant // changing, then it's indicative of a leak. DCHECK((*i)->GetRequestInfo()->IsDownload() || (*i)->GetRequestInfo()->is_stream() || ((*i)->GetRequestInfo()->detachable_handler() && (*i)->GetRequestInfo()->detachable_handler()->is_detached()) || (*i)->GetRequestInfo()->GetProcessType() == PROCESS_TYPE_BROWSER || (*i)->is_transferring()); } #endif loaders_to_cancel.clear(); // Validate that no more requests for this context were added. for (LoaderMap::const_iterator i = pending_loaders_.begin(); i != pending_loaders_.end(); ++i) { // http://crbug.com/90971 CHECK_NE(i->second->GetRequestInfo()->GetContext(), context); } for (BlockedLoadersMap::const_iterator i = blocked_loaders_map_.begin(); i != blocked_loaders_map_.end(); ++i) { BlockedLoadersList* loaders = i->second; if (!loaders->empty()) { ResourceRequestInfoImpl* info = loaders->front()->GetRequestInfo(); // http://crbug.com/90971 CHECK_NE(info->GetContext(), context); } } } DownloadInterruptReason ResourceDispatcherHostImpl::BeginDownload( scoped_ptr request, const Referrer& referrer, bool is_content_initiated, ResourceContext* context, int child_id, int route_id, bool prefer_cache, bool do_not_prompt_for_login, scoped_ptr save_info, uint32 download_id, const DownloadStartedCallback& started_callback) { if (is_shutdown_) return CallbackAndReturn(started_callback, DOWNLOAD_INTERRUPT_REASON_USER_SHUTDOWN); const GURL& url = request->original_url(); // http://crbug.com/90971 char url_buf[128]; base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf)); base::debug::Alias(url_buf); CHECK(ContainsKey(active_resource_contexts_, context)); SetReferrerForRequest(request.get(), referrer); int extra_load_flags = net::LOAD_NORMAL; if (prefer_cache) { // If there is upload data attached, only retrieve from cache because there // is no current mechanism to prompt the user for their consent for a // re-post. For GETs, try to retrieve data from the cache and skip // validating the entry if present. if (request->get_upload() != NULL) extra_load_flags |= net::LOAD_ONLY_FROM_CACHE; else extra_load_flags |= net::LOAD_PREFERRING_CACHE; } else { extra_load_flags |= net::LOAD_DISABLE_CACHE; } request->SetLoadFlags(request->load_flags() | extra_load_flags); // We treat a download as a main frame load, and thus update the policy URL on // redirects. // // TODO(davidben): Is this correct? If this came from a // ViewHostMsg_DownloadUrl in a frame, should it have first-party URL set // appropriately? request->set_first_party_url_policy( net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT); // Check if the renderer is permitted to request the requested URL. if (!ChildProcessSecurityPolicyImpl::GetInstance()-> CanRequestURL(child_id, url)) { VLOG(1) << "Denied unauthorized download request for " << url.possibly_invalid_spec(); return CallbackAndReturn(started_callback, DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST); } request_id_--; const net::URLRequestContext* request_context = context->GetRequestContext(); if (!request_context->job_factory()->IsHandledURL(url)) { VLOG(1) << "Download request for unsupported protocol: " << url.possibly_invalid_spec(); return CallbackAndReturn(started_callback, DOWNLOAD_INTERRUPT_REASON_NETWORK_INVALID_REQUEST); } ResourceRequestInfoImpl* extra_info = CreateRequestInfo(child_id, route_id, true, context); extra_info->set_do_not_prompt_for_login(do_not_prompt_for_login); extra_info->AssociateWithRequest(request.get()); // Request takes ownership. if (request->url().SchemeIs(url::kBlobScheme)) { ChromeBlobStorageContext* blob_context = GetChromeBlobStorageContextForResourceContext(context); storage::BlobProtocolHandler::SetRequestedBlobDataHandle( request.get(), blob_context->context()->GetBlobDataFromPublicURL(request->url())); } // From this point forward, the |DownloadResourceHandler| is responsible for // |started_callback|. scoped_ptr handler( CreateResourceHandlerForDownload(request.get(), is_content_initiated, true, download_id, save_info.Pass(), started_callback)); BeginRequestInternal(request.Pass(), handler.Pass()); return DOWNLOAD_INTERRUPT_REASON_NONE; } void ResourceDispatcherHostImpl::ClearLoginDelegateForRequest( net::URLRequest* request) { ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); if (info) { ResourceLoader* loader = GetLoader(info->GetGlobalRequestID()); if (loader) loader->ClearLoginDelegate(); } } void ResourceDispatcherHostImpl::Shutdown() { DCHECK_CURRENTLY_ON(BrowserThread::UI); BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(&ResourceDispatcherHostImpl::OnShutdown, base::Unretained(this))); } scoped_ptr ResourceDispatcherHostImpl::CreateResourceHandlerForDownload( net::URLRequest* request, bool is_content_initiated, bool must_download, uint32 id, scoped_ptr save_info, const DownloadUrlParameters::OnStartedCallback& started_cb) { scoped_ptr handler( new DownloadResourceHandler(id, request, started_cb, save_info.Pass())); if (delegate_) { const ResourceRequestInfo* request_info( ResourceRequestInfo::ForRequest(request)); ScopedVector throttles; delegate_->DownloadStarting( request, request_info->GetContext(), request_info->GetChildID(), request_info->GetRouteID(), request_info->GetRequestID(), is_content_initiated, must_download, &throttles); if (!throttles.empty()) { handler.reset( new ThrottlingResourceHandler( handler.Pass(), request, throttles.Pass())); } } return handler.Pass(); } scoped_ptr ResourceDispatcherHostImpl::MaybeInterceptAsStream( const base::FilePath& plugin_path, net::URLRequest* request, ResourceResponse* response, std::string* payload) { payload->clear(); ResourceRequestInfoImpl* info = ResourceRequestInfoImpl::ForRequest(request); const std::string& mime_type = response->head.mime_type; GURL origin; if (!delegate_ || !delegate_->ShouldInterceptResourceAsStream( request, plugin_path, mime_type, &origin, payload)) { return scoped_ptr(); } StreamContext* stream_context = GetStreamContextForResourceContext(info->GetContext()); scoped_ptr handler( new StreamResourceHandler(request, stream_context->registry(), origin)); info->set_is_stream(true); scoped_ptr stream_info(new StreamInfo); stream_info->handle = handler->stream()->CreateHandle(); stream_info->original_url = request->url(); stream_info->mime_type = mime_type; // Make a copy of the response headers so it is safe to pass across threads; // the old handler (AsyncResourceHandler) may modify it in parallel via the // ResourceDispatcherHostDelegate. if (response->head.headers.get()) { stream_info->response_headers = new net::HttpResponseHeaders(response->head.headers->raw_headers()); } delegate_->OnStreamCreated(request, stream_info.Pass()); return handler.Pass(); } ResourceDispatcherHostLoginDelegate* ResourceDispatcherHostImpl::CreateLoginDelegate( ResourceLoader* loader, net::AuthChallengeInfo* auth_info) { if (!delegate_) return NULL; return delegate_->CreateLoginDelegate(auth_info, loader->request()); } bool ResourceDispatcherHostImpl::HandleExternalProtocol(ResourceLoader* loader, const GURL& url) { if (!delegate_) return false; ResourceRequestInfoImpl* info = loader->GetRequestInfo(); if (!IsResourceTypeFrame(info->GetResourceType())) return false; const net::URLRequestJobFactory* job_factory = info->GetContext()->GetRequestContext()->job_factory(); if (job_factory->IsHandledURL(url)) return false; return delegate_->HandleExternalProtocol( url, info->GetChildID(), info->GetRouteID(), info->IsMainFrame(), info->GetPageTransition(), info->HasUserGesture()); } void ResourceDispatcherHostImpl::DidStartRequest(ResourceLoader* loader) { // Make sure we have the load state monitor running. if (!update_load_states_timer_->IsRunning() && scheduler_->HasLoadingClients()) { update_load_states_timer_->Start( FROM_HERE, TimeDelta::FromMilliseconds(kUpdateLoadStatesIntervalMsec), this, &ResourceDispatcherHostImpl::UpdateLoadInfo); } } void ResourceDispatcherHostImpl::DidReceiveRedirect(ResourceLoader* loader, const GURL& new_url) { ResourceRequestInfoImpl* info = loader->GetRequestInfo(); int render_process_id, render_frame_host; if (!info->GetAssociatedRenderFrame(&render_process_id, &render_frame_host)) return; // Notify the observers on the UI thread. scoped_ptr detail(new ResourceRedirectDetails( loader->request(), GetCertID(loader->request(), info->GetChildID()), new_url)); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &NotifyRedirectOnUI, render_process_id, render_frame_host, base::Passed(&detail))); } void ResourceDispatcherHostImpl::DidReceiveResponse(ResourceLoader* loader) { ResourceRequestInfoImpl* info = loader->GetRequestInfo(); net::URLRequest* request = loader->request(); if (request->was_fetched_via_proxy() && request->was_fetched_via_spdy() && request->url().SchemeIs(url::kHttpScheme)) { scheduler_->OnReceivedSpdyProxiedHttpResponse( info->GetChildID(), info->GetRouteID()); } int render_process_id, render_frame_host; if (!info->GetAssociatedRenderFrame(&render_process_id, &render_frame_host)) return; // Notify the observers on the UI thread. scoped_ptr detail(new ResourceRequestDetails( request, GetCertID(request, info->GetChildID()))); BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind( &NotifyResponseOnUI, render_process_id, render_frame_host, base::Passed(&detail))); } void ResourceDispatcherHostImpl::DidFinishLoading(ResourceLoader* loader) { ResourceRequestInfo* info = loader->GetRequestInfo(); // Record final result of all resource loads. if (info->GetResourceType() == RESOURCE_TYPE_MAIN_FRAME) { // This enumeration has "3" appended to its name to distinguish it from // older versions. UMA_HISTOGRAM_SPARSE_SLOWLY( "Net.ErrorCodesForMainFrame3", -loader->request()->status().error()); // Record time to success and error for the most common errors, and for // the aggregate remainder errors. base::TimeDelta request_loading_time( base::TimeTicks::Now() - loader->request()->creation_time()); switch (loader->request()->status().error()) { case net::OK: UMA_HISTOGRAM_LONG_TIMES( "Net.RequestTime2.Success", request_loading_time); break; case net::ERR_ABORTED: UMA_HISTOGRAM_LONG_TIMES( "Net.RequestTime2.ErrAborted", request_loading_time); break; case net::ERR_CONNECTION_RESET: UMA_HISTOGRAM_LONG_TIMES( "Net.RequestTime2.ErrConnectionReset", request_loading_time); break; case net::ERR_CONNECTION_TIMED_OUT: UMA_HISTOGRAM_LONG_TIMES( "Net.RequestTime2.ErrConnectionTimedOut", request_loading_time); break; case net::ERR_INTERNET_DISCONNECTED: UMA_HISTOGRAM_LONG_TIMES( "Net.RequestTime2.ErrInternetDisconnected", request_loading_time); break; case net::ERR_NAME_NOT_RESOLVED: UMA_HISTOGRAM_LONG_TIMES( "Net.RequestTime2.ErrNameNotResolved", request_loading_time); break; case net::ERR_TIMED_OUT: UMA_HISTOGRAM_LONG_TIMES( "Net.RequestTime2.ErrTimedOut", request_loading_time); break; default: UMA_HISTOGRAM_LONG_TIMES( "Net.RequestTime2.MiscError", request_loading_time); break; } if (loader->request()->url().SchemeIsCryptographic()) { if (loader->request()->url().host() == "www.google.com") { UMA_HISTOGRAM_SPARSE_SLOWLY("Net.ErrorCodesForHTTPSGoogleMainFrame2", -loader->request()->status().error()); } int num_valid_scts = std::count_if( loader->request()->ssl_info().signed_certificate_timestamps.begin(), loader->request()->ssl_info().signed_certificate_timestamps.end(), IsValidatedSCT); UMA_HISTOGRAM_COUNTS_100( "Net.CertificateTransparency.MainFrameValidSCTCount", num_valid_scts); } } else { if (info->GetResourceType() == RESOURCE_TYPE_IMAGE) { UMA_HISTOGRAM_SPARSE_SLOWLY( "Net.ErrorCodesForImages", -loader->request()->status().error()); } // This enumeration has "2" appended to distinguish it from older versions. UMA_HISTOGRAM_SPARSE_SLOWLY( "Net.ErrorCodesForSubresources2", -loader->request()->status().error()); } if (loader->request()->url().SchemeIsCryptographic()) { RecordCertificateHistograms(loader->request()->ssl_info(), info->GetResourceType()); } if (delegate_) delegate_->RequestComplete(loader->request()); // Destroy the ResourceLoader. RemovePendingRequest(info->GetChildID(), info->GetRequestID()); } void ResourceDispatcherHostImpl::OnInit() { scheduler_.reset(new ResourceScheduler); } void ResourceDispatcherHostImpl::OnShutdown() { DCHECK_CURRENTLY_ON(BrowserThread::IO); is_shutdown_ = true; pending_loaders_.clear(); // Make sure we shutdown the timer now, otherwise by the time our destructor // runs if the timer is still running the Task is deleted twice (once by // the MessageLoop and the second time by RepeatingTimer). update_load_states_timer_.reset(); // Clear blocked requests if any left. // Note that we have to do this in 2 passes as we cannot call // CancelBlockedRequestsForRoute while iterating over // blocked_loaders_map_, as it modifies it. std::set ids; for (BlockedLoadersMap::const_iterator iter = blocked_loaders_map_.begin(); iter != blocked_loaders_map_.end(); ++iter) { std::pair::iterator, bool> result = ids.insert(iter->first); // We should not have duplicates. DCHECK(result.second); } for (std::set::const_iterator iter = ids.begin(); iter != ids.end(); ++iter) { CancelBlockedRequestsForRoute(iter->child_id, iter->route_id); } scheduler_.reset(); } bool ResourceDispatcherHostImpl::OnMessageReceived( const IPC::Message& message, ResourceMessageFilter* filter) { filter_ = filter; bool handled = true; IPC_BEGIN_MESSAGE_MAP(ResourceDispatcherHostImpl, message) IPC_MESSAGE_HANDLER(ResourceHostMsg_RequestResource, OnRequestResource) IPC_MESSAGE_HANDLER_DELAY_REPLY(ResourceHostMsg_SyncLoad, OnSyncLoad) IPC_MESSAGE_HANDLER(ResourceHostMsg_ReleaseDownloadedFile, OnReleaseDownloadedFile) IPC_MESSAGE_HANDLER(ResourceHostMsg_DataDownloaded_ACK, OnDataDownloadedACK) IPC_MESSAGE_HANDLER(ResourceHostMsg_UploadProgress_ACK, OnUploadProgressACK) IPC_MESSAGE_HANDLER(ResourceHostMsg_CancelRequest, OnCancelRequest) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() if (!handled && IPC_MESSAGE_ID_CLASS(message.type()) == ResourceMsgStart) { base::PickleIterator iter(message); int request_id = -1; bool ok = iter.ReadInt(&request_id); DCHECK(ok); GlobalRequestID id(filter_->child_id(), request_id); DelegateMap::iterator it = delegate_map_.find(id); if (it != delegate_map_.end()) { base::ObserverList::Iterator del_it(it->second); ResourceMessageDelegate* delegate; while (!handled && (delegate = del_it.GetNext()) != NULL) { handled = delegate->OnMessageReceived(message); } } // As the unhandled resource message effectively has no consumer, mark it as // handled to prevent needless propagation through the filter pipeline. handled = true; } filter_ = NULL; return handled; } void ResourceDispatcherHostImpl::OnRequestResource( int routing_id, int request_id, const ResourceHostMsg_Request& request_data) { // TODO(pkasting): Remove ScopedTracker below once crbug.com/477117 is fixed. tracked_objects::ScopedTracker tracking_profile( FROM_HERE_WITH_EXPLICIT_FUNCTION( "477117 ResourceDispatcherHostImpl::OnRequestResource")); // When logging time-to-network only care about main frame and non-transfer // navigations. if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME && request_data.transferred_request_request_id == -1 && !base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableBrowserSideNavigation)) { BrowserThread::PostTask( BrowserThread::UI, FROM_HERE, base::Bind(&LogResourceRequestTimeOnUI, TimeTicks::Now(), filter_->child_id(), request_data.render_frame_id, request_data.url)); } BeginRequest(request_id, request_data, NULL, routing_id); } // Begins a resource request with the given params on behalf of the specified // child process. Responses will be dispatched through the given receiver. The // process ID is used to lookup WebContentsImpl from routing_id's in the case of // a request from a renderer. request_context is the cookie/cache context to be // used for this request. // // If sync_result is non-null, then a SyncLoad reply will be generated, else // a normal asynchronous set of response messages will be generated. void ResourceDispatcherHostImpl::OnSyncLoad( int request_id, const ResourceHostMsg_Request& request_data, IPC::Message* sync_result) { BeginRequest(request_id, request_data, sync_result, sync_result->routing_id()); } void ResourceDispatcherHostImpl::UpdateRequestForTransfer( int child_id, int route_id, int request_id, const ResourceHostMsg_Request& request_data, const linked_ptr& loader) { ResourceRequestInfoImpl* info = loader->GetRequestInfo(); GlobalRoutingID old_routing_id( request_data.transferred_request_child_id, info->GetRouteID()); GlobalRequestID old_request_id(request_data.transferred_request_child_id, request_data.transferred_request_request_id); GlobalRoutingID new_routing_id(child_id, route_id); GlobalRequestID new_request_id(child_id, request_id); // Clear out data that depends on |info| before updating it. // We always need to move the memory stats to the new process. In contrast, // stats.num_requests is only tracked for some requests (those that require // file descriptors for their shared memory buffer). IncrementOutstandingRequestsMemory(-1, *info); bool should_update_count = info->counted_as_in_flight_request(); if (should_update_count) IncrementOutstandingRequestsCount(-1, info); pending_loaders_.erase(old_request_id); // ResourceHandlers should always get state related to the request from the // ResourceRequestInfo rather than caching it locally. This lets us update // the info object when a transfer occurs. info->UpdateForTransfer(child_id, route_id, request_data.origin_pid, request_id, request_data.parent_render_frame_id, filter_->GetWeakPtr()); // Update maps that used the old IDs, if necessary. Some transfers in tests // do not actually use a different ID, so not all maps need to be updated. pending_loaders_[new_request_id] = loader; IncrementOutstandingRequestsMemory(1, *info); if (should_update_count) IncrementOutstandingRequestsCount(1, info); if (old_routing_id != new_routing_id) { if (blocked_loaders_map_.find(old_routing_id) != blocked_loaders_map_.end()) { blocked_loaders_map_[new_routing_id] = blocked_loaders_map_[old_routing_id]; blocked_loaders_map_.erase(old_routing_id); } } if (old_request_id != new_request_id) { DelegateMap::iterator it = delegate_map_.find(old_request_id); if (it != delegate_map_.end()) { // Tell each delegate that the request ID has changed. base::ObserverList::Iterator del_it(it->second); ResourceMessageDelegate* delegate; while ((delegate = del_it.GetNext()) != NULL) { delegate->set_request_id(new_request_id); } // Now store the observer list under the new request ID. delegate_map_[new_request_id] = delegate_map_[old_request_id]; delegate_map_.erase(old_request_id); } } AppCacheInterceptor::CompleteCrossSiteTransfer( loader->request(), child_id, request_data.appcache_host_id); ServiceWorkerRequestHandler* handler = ServiceWorkerRequestHandler::GetHandler(loader->request()); if (handler) { handler->CompleteCrossSiteTransfer( child_id, request_data.service_worker_provider_id); } // We should have a CrossSiteResourceHandler to finish the transfer. DCHECK(info->cross_site_handler()); } void ResourceDispatcherHostImpl::BeginRequest( int request_id, const ResourceHostMsg_Request& request_data, IPC::Message* sync_result, // only valid for sync int route_id) { int process_type = filter_->process_type(); int child_id = filter_->child_id(); // Reject invalid priority. if (request_data.priority < net::MINIMUM_PRIORITY || request_data.priority > net::MAXIMUM_PRIORITY) { bad_message::ReceivedBadMessage(filter_, bad_message::RDH_INVALID_PRIORITY); return; } // If we crash here, figure out what URL the renderer was requesting. // http://crbug.com/91398 char url_buf[128]; base::strlcpy(url_buf, request_data.url.spec().c_str(), arraysize(url_buf)); base::debug::Alias(url_buf); // If the request that's coming in is being transferred from another process, // we want to reuse and resume the old loader rather than start a new one. LoaderMap::iterator it = pending_loaders_.find( GlobalRequestID(request_data.transferred_request_child_id, request_data.transferred_request_request_id)); if (it != pending_loaders_.end()) { // If the request is transferring to a new process, we can update our // state and let it resume with its existing ResourceHandlers. if (it->second->is_transferring()) { linked_ptr deferred_loader = it->second; UpdateRequestForTransfer(child_id, route_id, request_id, request_data, deferred_loader); deferred_loader->CompleteTransfer(); } else { bad_message::ReceivedBadMessage( filter_, bad_message::RDH_REQUEST_NOT_TRANSFERRING); } return; } ResourceContext* resource_context = NULL; net::URLRequestContext* request_context = NULL; filter_->GetContexts(request_data, &resource_context, &request_context); // http://crbug.com/90971 CHECK(ContainsKey(active_resource_contexts_, resource_context)); if (is_shutdown_ || !ShouldServiceRequest(process_type, child_id, request_data, filter_->file_system_context())) { AbortRequestBeforeItStarts(filter_, sync_result, request_id); return; } // Allow the observer to block/handle the request. if (delegate_ && !delegate_->ShouldBeginRequest(request_data.method, request_data.url, request_data.resource_type, resource_context)) { AbortRequestBeforeItStarts(filter_, sync_result, request_id); return; } // Construct the request. scoped_ptr new_request = request_context->CreateRequest( request_data.url, request_data.priority, NULL); new_request->set_method(request_data.method); new_request->set_first_party_for_cookies( request_data.first_party_for_cookies); // If the request is a MAIN_FRAME request, the first-party URL gets updated on // redirects. if (request_data.resource_type == RESOURCE_TYPE_MAIN_FRAME) { new_request->set_first_party_url_policy( net::URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT); } const Referrer referrer(request_data.referrer, request_data.referrer_policy); SetReferrerForRequest(new_request.get(), referrer); net::HttpRequestHeaders headers; headers.AddHeadersFromString(request_data.headers); new_request->SetExtraRequestHeaders(headers); storage::BlobStorageContext* blob_context = GetBlobStorageContext(filter_->blob_storage_context()); // Resolve elements from request_body and prepare upload data. if (request_data.request_body.get()) { // |blob_context| could be null when the request is from the plugins because // ResourceMessageFilters created in PluginProcessHost don't have the blob // context. if (blob_context) { // Attaches the BlobDataHandles to request_body not to free the blobs and // any attached shareable files until upload completion. These data will // be used in UploadDataStream and ServiceWorkerURLRequestJob. AttachRequestBodyBlobDataHandles( request_data.request_body.get(), blob_context); } new_request->set_upload(UploadDataStreamBuilder::Build( request_data.request_body.get(), blob_context, filter_->file_system_context(), BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE) .get())); } bool allow_download = request_data.allow_download && IsResourceTypeFrame(request_data.resource_type); bool do_not_prompt_for_login = request_data.do_not_prompt_for_login; bool is_sync_load = sync_result != NULL; int load_flags = BuildLoadFlagsForRequest(request_data, child_id, is_sync_load); if (request_data.resource_type == RESOURCE_TYPE_PREFETCH || request_data.resource_type == RESOURCE_TYPE_FAVICON) { do_not_prompt_for_login = true; } if (request_data.resource_type == RESOURCE_TYPE_IMAGE && HTTP_AUTH_RELATION_BLOCKED_CROSS == HttpAuthRelationTypeOf(request_data.url, request_data.first_party_for_cookies)) { // Prevent third-party image content from prompting for login, as this // is often a scam to extract credentials for another domain from the user. // Only block image loads, as the attack applies largely to the "src" // property of the tag. It is common for web properties to allow // untrusted values for ; this is considered a fair thing for an // HTML sanitizer to do. Conversely, any HTML sanitizer that didn't // filter sources for