1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
9 #include "base/base64.h"
10 #include "base/logging.h"
11 #include "chrome/browser/browser_process.h"
12 #include "chrome/browser/chrome_notification_types.h"
13 #include "chrome/browser/component_updater/component_updater_service.h"
14 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
15 #include "chrome/browser/content_settings/host_content_settings_map.h"
16 #include "chrome/browser/download/download_request_limiter.h"
17 #include "chrome/browser/download/download_resource_throttle.h"
18 #include "chrome/browser/extensions/api/streams_private/streams_private_api.h"
19 #include "chrome/browser/extensions/extension_renderer_state.h"
20 #include "chrome/browser/extensions/user_script_listener.h"
21 #include "chrome/browser/google/google_util.h"
22 #include "chrome/browser/metrics/variations/variations_http_header_provider.h"
23 #include "chrome/browser/prefetch/prefetch_field_trial.h"
24 #include "chrome/browser/prerender/prerender_manager.h"
25 #include "chrome/browser/prerender/prerender_pending_swap_throttle.h"
26 #include "chrome/browser/prerender/prerender_resource_throttle.h"
27 #include "chrome/browser/prerender/prerender_tracker.h"
28 #include "chrome/browser/prerender/prerender_util.h"
29 #include "chrome/browser/profiles/profile.h"
30 #include "chrome/browser/profiles/profile_io_data.h"
31 #include "chrome/browser/renderer_host/safe_browsing_resource_throttle_factory.h"
32 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
33 #include "chrome/browser/signin/signin_header_helper.h"
34 #include "chrome/browser/ui/auto_login_prompter.h"
35 #include "chrome/browser/ui/login/login_prompt.h"
36 #include "chrome/browser/ui/sync/one_click_signin_helper.h"
37 #include "chrome/common/extensions/extension_constants.h"
38 #include "chrome/common/extensions/mime_types_handler.h"
39 #include "chrome/common/render_messages.h"
40 #include "content/public/browser/browser_thread.h"
41 #include "content/public/browser/notification_service.h"
42 #include "content/public/browser/render_process_host.h"
43 #include "content/public/browser/render_view_host.h"
44 #include "content/public/browser/resource_context.h"
45 #include "content/public/browser/resource_dispatcher_host.h"
46 #include "content/public/browser/resource_request_info.h"
47 #include "content/public/browser/stream_handle.h"
48 #include "content/public/browser/web_contents.h"
49 #include "content/public/common/resource_response.h"
50 #include "extensions/browser/info_map.h"
51 #include "extensions/common/constants.h"
52 #include "extensions/common/user_script.h"
53 #include "net/base/load_flags.h"
54 #include "net/base/load_timing_info.h"
55 #include "net/base/request_priority.h"
56 #include "net/http/http_response_headers.h"
57 #include "net/url_request/url_request.h"
59 #if defined(ENABLE_CONFIGURATION_POLICY)
60 #include "components/policy/core/common/cloud/policy_header_io_helper.h"
63 #if defined(ENABLE_MANAGED_USERS)
64 #include "chrome/browser/managed_mode/managed_mode_resource_throttle.h"
67 #if defined(USE_SYSTEM_PROTOBUF)
68 #include <google/protobuf/repeated_field.h>
70 #include "third_party/protobuf/src/google/protobuf/repeated_field.h"
73 #if defined(OS_ANDROID)
74 #include "chrome/browser/android/intercept_download_resource_throttle.h"
75 #include "components/navigation_interception/intercept_navigation_delegate.h"
77 #include "chrome/browser/apps/app_url_redirector.h"
78 #include "chrome/browser/apps/ephemeral_app_throttle.h"
81 #if defined(OS_CHROMEOS)
82 #include "chrome/browser/chromeos/login/merge_session_throttle.h"
83 // TODO(oshima): Enable this for other platforms.
84 #include "chrome/browser/renderer_host/offline_resource_throttle.h"
87 using content::BrowserThread
;
88 using content::RenderViewHost
;
89 using content::ResourceDispatcherHostLoginDelegate
;
90 using content::ResourceRequestInfo
;
91 using extensions::Extension
;
92 using extensions::StreamsPrivateAPI
;
94 #if defined(OS_ANDROID)
95 using navigation_interception::InterceptNavigationDelegate
;
100 ExternalProtocolHandler::Delegate
* g_external_protocol_handler_delegate
= NULL
;
102 void NotifyDownloadInitiatedOnUI(int render_process_id
, int render_view_id
) {
103 RenderViewHost
* rvh
= RenderViewHost::FromID(render_process_id
,
108 content::NotificationService::current()->Notify(
109 chrome::NOTIFICATION_DOWNLOAD_INITIATED
,
110 content::Source
<RenderViewHost
>(rvh
),
111 content::NotificationService::NoDetails());
114 #if !defined(OS_ANDROID)
115 // Goes through the extension's file browser handlers and checks if there is one
116 // that can handle the |mime_type|.
117 // |extension| must not be NULL.
118 bool ExtensionCanHandleMimeType(const Extension
* extension
,
119 const std::string
& mime_type
) {
120 MimeTypesHandler
* handler
= MimeTypesHandler::GetHandler(extension
);
124 return handler
->CanHandleMIMEType(mime_type
);
127 void SendExecuteMimeTypeHandlerEvent(scoped_ptr
<content::StreamHandle
> stream
,
128 int64 expected_content_size
,
129 int render_process_id
,
131 const std::string
& extension_id
) {
132 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
134 content::RenderViewHost
* render_view_host
=
135 content::RenderViewHost::FromID(render_process_id
, render_view_id
);
136 if (!render_view_host
)
139 content::WebContents
* web_contents
=
140 content::WebContents::FromRenderViewHost(render_view_host
);
144 content::BrowserContext
* browser_context
= web_contents
->GetBrowserContext();
145 if (!browser_context
)
148 Profile
* profile
= Profile::FromBrowserContext(browser_context
);
152 StreamsPrivateAPI
* streams_private
= StreamsPrivateAPI::Get(profile
);
153 if (!streams_private
)
155 streams_private
->ExecuteMimeTypeHandler(
156 extension_id
, web_contents
, stream
.Pass(), expected_content_size
);
159 void LaunchURL(const GURL
& url
, int render_process_id
, int render_view_id
) {
160 // If there is no longer a WebContents, the request may have raced with tab
161 // closing. Don't fire the external request. (It may have been a prerender.)
162 content::RenderViewHost
* rvh
= content::RenderViewHost::FromID(
163 render_process_id
, render_view_id
);
166 content::WebContents
* web_contents
=
167 content::WebContents::FromRenderViewHost(rvh
);
171 // If the request was for a prerender, abort the prerender and do not
173 prerender::PrerenderContents
* prerender_contents
=
174 prerender::PrerenderContents::FromWebContents(web_contents
);
175 if (prerender_contents
) {
176 prerender_contents
->Destroy(prerender::FINAL_STATUS_UNSUPPORTED_SCHEME
);
177 prerender::ReportPrerenderExternalURL();
181 ExternalProtocolHandler::LaunchUrlWithDelegate(
182 url
, render_process_id
, render_view_id
,
183 g_external_protocol_handler_delegate
);
185 #endif // !defined(OS_ANDROID)
187 void AppendComponentUpdaterThrottles(
188 net::URLRequest
* request
,
189 content::ResourceContext
* resource_context
,
190 ResourceType::Type resource_type
,
191 ScopedVector
<content::ResourceThrottle
>* throttles
) {
192 const char* crx_id
= NULL
;
193 component_updater::ComponentUpdateService
* cus
=
194 g_browser_process
->component_updater();
197 // Check for PNaCl pexe request.
198 if (resource_type
== ResourceType::OBJECT
) {
199 const net::HttpRequestHeaders
& headers
= request
->extra_request_headers();
200 std::string accept_headers
;
201 if (headers
.GetHeader("Accept", &accept_headers
)) {
202 if (accept_headers
.find("application/x-pnacl") != std::string::npos
&&
203 pnacl::NeedsOnDemandUpdate())
204 crx_id
= "hnimpnehoodheedghdeeijklkeaacbdc";
209 // We got a component we need to install, so throttle the resource
210 // until the component is installed.
211 throttles
->push_back(cus
->GetOnDemandResourceThrottle(request
, crx_id
));
217 ChromeResourceDispatcherHostDelegate::ChromeResourceDispatcherHostDelegate(
218 prerender::PrerenderTracker
* prerender_tracker
)
219 : download_request_limiter_(g_browser_process
->download_request_limiter()),
220 safe_browsing_(g_browser_process
->safe_browsing_service()),
221 user_script_listener_(new extensions::UserScriptListener()),
222 prerender_tracker_(prerender_tracker
) {
225 ChromeResourceDispatcherHostDelegate::~ChromeResourceDispatcherHostDelegate() {
228 bool ChromeResourceDispatcherHostDelegate::ShouldBeginRequest(
231 const std::string
& method
,
233 ResourceType::Type resource_type
,
234 content::ResourceContext
* resource_context
) {
235 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO
));
237 // Handle a PREFETCH resource type. If prefetch is disabled, squelch the
238 // request. Otherwise, do a normal request to warm the cache.
239 if (resource_type
== ResourceType::PREFETCH
) {
240 // All PREFETCH requests should be GETs, but be defensive about it.
244 // If prefetch is disabled, kill the request.
245 if (!prefetch::IsPrefetchEnabled())
252 void ChromeResourceDispatcherHostDelegate::RequestBeginning(
253 net::URLRequest
* request
,
254 content::ResourceContext
* resource_context
,
255 appcache::AppCacheService
* appcache_service
,
256 ResourceType::Type resource_type
,
259 ScopedVector
<content::ResourceThrottle
>* throttles
) {
260 bool is_prerendering
= prerender_tracker_
->IsPrerenderingOnIOThread(
262 if (is_prerendering
) {
263 // Requests with the IGNORE_LIMITS flag set (i.e., sync XHRs)
264 // should remain at MAXIMUM_PRIORITY.
265 if (request
->load_flags() & net::LOAD_IGNORE_LIMITS
) {
266 DCHECK_EQ(request
->priority(), net::MAXIMUM_PRIORITY
);
268 request
->SetPriority(net::IDLE
);
272 ProfileIOData
* io_data
= ProfileIOData::FromResourceContext(
275 if (!is_prerendering
&& resource_type
== ResourceType::MAIN_FRAME
) {
276 #if defined(OS_ANDROID)
277 throttles
->push_back(
278 InterceptNavigationDelegate::CreateThrottleFor(request
));
280 // Redirect some navigations to apps that have registered matching URL
281 // handlers ('url_handlers' in the manifest).
282 content::ResourceThrottle
* url_to_app_throttle
=
283 AppUrlRedirector::MaybeCreateThrottleFor(request
, io_data
);
284 if (url_to_app_throttle
)
285 throttles
->push_back(url_to_app_throttle
);
287 // Experimental: Launch ephemeral apps from search results.
288 content::ResourceThrottle
* ephemeral_app_throttle
=
289 EphemeralAppThrottle::MaybeCreateThrottleForLaunch(
291 if (ephemeral_app_throttle
)
292 throttles
->push_back(ephemeral_app_throttle
);
296 #if defined(OS_CHROMEOS)
297 if (resource_type
== ResourceType::MAIN_FRAME
||
298 resource_type
== ResourceType::XHR
) {
299 // We check offline first, then check safe browsing so that we still can
300 // block unsafe site after we remove offline page.
301 throttles
->push_back(new OfflineResourceThrottle(request
,
303 // Add interstitial page while merge session process (cookie
304 // reconstruction from OAuth2 refresh token in ChromeOS login) is still in
305 // progress while we are attempting to load a google property.
306 if (!MergeSessionThrottle::AreAllSessionMergedAlready() &&
307 request
->url().SchemeIsHTTPOrHTTPS()) {
308 throttles
->push_back(new MergeSessionThrottle(request
, resource_type
));
313 // Don't attempt to append headers to requests that have already started.
314 // TODO(stevet): Remove this once the request ordering issues are resolved
315 // in crbug.com/128048.
316 if (!request
->is_pending()) {
317 net::HttpRequestHeaders headers
;
318 headers
.CopyFrom(request
->extra_request_headers());
319 bool incognito
= io_data
->is_incognito();
320 chrome_variations::VariationsHttpHeaderProvider::GetInstance()->
321 AppendHeaders(request
->url(),
323 !incognito
&& io_data
->GetMetricsEnabledStateOnIOThread(),
325 request
->SetExtraRequestHeaders(headers
);
328 #if defined(ENABLE_ONE_CLICK_SIGNIN)
329 AppendChromeSyncGaiaHeader(request
, resource_context
);
332 #if defined(ENABLE_CONFIGURATION_POLICY)
333 if (io_data
->policy_header_helper())
334 io_data
->policy_header_helper()->AddPolicyHeaders(request
);
337 const ResourceRequestInfo
* info
= ResourceRequestInfo::ForRequest(request
);
338 signin::AppendMirrorRequestHeaderIfPossible(
339 request
, GURL() /* redirect_url */,
340 io_data
, info
->GetChildID(), info
->GetRouteID());
342 AppendStandardResourceThrottles(request
,
346 if (!is_prerendering
) {
347 AppendComponentUpdaterThrottles(request
,
354 void ChromeResourceDispatcherHostDelegate::WillTransferRequestToNewProcess(
360 int new_request_id
) {
361 // If a prerender, it have should been aborted on cross-process
362 // navigation in PrerenderContents::WebContentsImpl::OpenURLFromTab.
363 DCHECK(!prerender_tracker_
->IsPrerenderingOnIOThread(old_child_id
,
367 void ChromeResourceDispatcherHostDelegate::DownloadStarting(
368 net::URLRequest
* request
,
369 content::ResourceContext
* resource_context
,
373 bool is_content_initiated
,
375 ScopedVector
<content::ResourceThrottle
>* throttles
) {
376 BrowserThread::PostTask(
377 BrowserThread::UI
, FROM_HERE
,
378 base::Bind(&NotifyDownloadInitiatedOnUI
, child_id
, route_id
));
380 // If it's from the web, we don't trust it, so we push the throttle on.
381 if (is_content_initiated
) {
382 throttles
->push_back(
383 new DownloadResourceThrottle(download_request_limiter_
.get(),
388 #if defined(OS_ANDROID)
389 throttles
->push_back(
390 new chrome::InterceptDownloadResourceThrottle(
391 request
, child_id
, route_id
, request_id
));
395 // If this isn't a new request, we've seen this before and added the standard
396 // resource throttles already so no need to add it again.
397 if (!request
->is_pending()) {
398 AppendStandardResourceThrottles(request
,
400 ResourceType::MAIN_FRAME
,
405 ResourceDispatcherHostLoginDelegate
*
406 ChromeResourceDispatcherHostDelegate::CreateLoginDelegate(
407 net::AuthChallengeInfo
* auth_info
, net::URLRequest
* request
) {
408 return CreateLoginPrompt(auth_info
, request
);
411 bool ChromeResourceDispatcherHostDelegate::HandleExternalProtocol(
412 const GURL
& url
, int child_id
, int route_id
) {
413 #if defined(OS_ANDROID)
414 // Android use a resource throttle to handle external as well as internal
419 ExtensionRendererState::WebViewInfo info
;
420 if (ExtensionRendererState::GetInstance()->GetWebViewInfo(child_id
,
426 BrowserThread::PostTask(
427 BrowserThread::UI
, FROM_HERE
,
428 base::Bind(&LaunchURL
, url
, child_id
, route_id
));
433 void ChromeResourceDispatcherHostDelegate::AppendStandardResourceThrottles(
434 net::URLRequest
* request
,
435 content::ResourceContext
* resource_context
,
436 ResourceType::Type resource_type
,
437 ScopedVector
<content::ResourceThrottle
>* throttles
) {
438 ProfileIOData
* io_data
= ProfileIOData::FromResourceContext(resource_context
);
439 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
440 // Insert safe browsing at the front of the list, so it gets to decide on
442 if (io_data
->safe_browsing_enabled()->GetValue()) {
443 bool is_subresource_request
= resource_type
!= ResourceType::MAIN_FRAME
;
444 content::ResourceThrottle
* throttle
=
445 SafeBrowsingResourceThrottleFactory::Create(request
,
446 is_subresource_request
,
447 safe_browsing_
.get());
449 throttles
->push_back(throttle
);
453 #if defined(ENABLE_MANAGED_USERS)
454 bool is_subresource_request
= resource_type
!= ResourceType::MAIN_FRAME
;
455 throttles
->push_back(new ManagedModeResourceThrottle(
456 request
, !is_subresource_request
,
457 io_data
->managed_mode_url_filter()));
460 content::ResourceThrottle
* throttle
=
461 user_script_listener_
->CreateResourceThrottle(request
->url(),
464 throttles
->push_back(throttle
);
466 const ResourceRequestInfo
* info
= ResourceRequestInfo::ForRequest(request
);
467 if (prerender_tracker_
->IsPrerenderingOnIOThread(info
->GetChildID(),
468 info
->GetRouteID())) {
469 throttles
->push_back(new prerender::PrerenderResourceThrottle(
470 request
, prerender_tracker_
));
472 if (prerender_tracker_
->IsPendingSwapRequestOnIOThread(
473 info
->GetChildID(), info
->GetRenderFrameID(), request
->url())) {
474 throttles
->push_back(new prerender::PrerenderPendingSwapThrottle(
475 request
, prerender_tracker_
));
479 #if defined(ENABLE_ONE_CLICK_SIGNIN)
480 void ChromeResourceDispatcherHostDelegate::AppendChromeSyncGaiaHeader(
481 net::URLRequest
* request
,
482 content::ResourceContext
* resource_context
) {
483 static const char kAllowChromeSignIn
[] = "Allow-Chrome-SignIn";
485 ProfileIOData
* io_data
= ProfileIOData::FromResourceContext(resource_context
);
486 OneClickSigninHelper::Offer offer
=
487 OneClickSigninHelper::CanOfferOnIOThread(request
, io_data
);
489 case OneClickSigninHelper::CAN_OFFER
:
490 request
->SetExtraRequestHeaderByName(kAllowChromeSignIn
, "1", false);
492 case OneClickSigninHelper::DONT_OFFER
:
493 request
->RemoveRequestHeaderByName(kAllowChromeSignIn
);
495 case OneClickSigninHelper::IGNORE_REQUEST
:
501 bool ChromeResourceDispatcherHostDelegate::ShouldForceDownloadResource(
502 const GURL
& url
, const std::string
& mime_type
) {
503 // Special-case user scripts to get downloaded instead of viewed.
504 return extensions::UserScript::IsURLUserScript(url
, mime_type
);
507 bool ChromeResourceDispatcherHostDelegate::ShouldInterceptResourceAsStream(
508 content::ResourceContext
* resource_context
,
510 const std::string
& mime_type
,
512 std::string
* target_id
) {
513 #if !defined(OS_ANDROID)
514 ProfileIOData
* io_data
=
515 ProfileIOData::FromResourceContext(resource_context
);
516 bool profile_is_incognito
= io_data
->is_incognito();
517 const scoped_refptr
<const extensions::InfoMap
> extension_info_map(
518 io_data
->GetExtensionInfoMap());
519 std::vector
<std::string
> whitelist
= MimeTypesHandler::GetMIMETypeWhitelist();
520 // Go through the white-listed extensions and try to use them to intercept
522 for (size_t i
= 0; i
< whitelist
.size(); ++i
) {
523 const char* extension_id
= whitelist
[i
].c_str();
524 const Extension
* extension
=
525 extension_info_map
->extensions().GetByID(extension_id
);
526 // The white-listed extension may not be installed, so we have to NULL check
529 (profile_is_incognito
&&
530 !extension_info_map
->IsIncognitoEnabled(extension_id
))) {
534 if (ExtensionCanHandleMimeType(extension
, mime_type
)) {
535 *origin
= Extension::GetBaseURLFromExtensionId(extension_id
);
536 *target_id
= extension_id
;
544 void ChromeResourceDispatcherHostDelegate::OnStreamCreated(
545 content::ResourceContext
* resource_context
,
546 int render_process_id
,
548 const std::string
& target_id
,
549 scoped_ptr
<content::StreamHandle
> stream
,
550 int64 expected_content_size
) {
551 #if !defined(OS_ANDROID)
552 content::BrowserThread::PostTask(
553 content::BrowserThread::UI
, FROM_HERE
,
554 base::Bind(&SendExecuteMimeTypeHandlerEvent
, base::Passed(&stream
),
555 expected_content_size
, render_process_id
, render_view_id
,
560 void ChromeResourceDispatcherHostDelegate::OnResponseStarted(
561 net::URLRequest
* request
,
562 content::ResourceContext
* resource_context
,
563 content::ResourceResponse
* response
,
564 IPC::Sender
* sender
) {
565 const ResourceRequestInfo
* info
= ResourceRequestInfo::ForRequest(request
);
567 // See if the response contains the X-Auto-Login header. If so, this was
568 // a request for a login page, and the server is allowing the browser to
569 // suggest auto-login, if available.
570 AutoLoginPrompter::ShowInfoBarIfPossible(request
, info
->GetChildID(),
573 ProfileIOData
* io_data
= ProfileIOData::FromResourceContext(resource_context
);
575 #if defined(ENABLE_ONE_CLICK_SIGNIN)
576 // See if the response contains the Google-Accounts-SignIn header. If so,
577 // then the user has just finished signing in, and the server is allowing the
578 // browser to suggest connecting the user's profile to the account.
579 OneClickSigninHelper::ShowInfoBarIfPossible(request
, io_data
,
584 // See if the response contains the X-Chrome-Manage-Accounts header. If so
585 // show the profile avatar bubble so that user can complete signin/out action
587 signin::ProcessMirrorResponseHeaderIfExists(request
, io_data
,
591 // Build in additional protection for the chrome web store origin.
592 GURL
webstore_url(extension_urls::GetWebstoreLaunchURL());
593 if (request
->url().DomainIs(webstore_url
.host().c_str())) {
594 net::HttpResponseHeaders
* response_headers
= request
->response_headers();
595 if (!response_headers
->HasHeaderValue("x-frame-options", "deny") &&
596 !response_headers
->HasHeaderValue("x-frame-options", "sameorigin")) {
597 response_headers
->RemoveHeader("x-frame-options");
598 response_headers
->AddHeader("x-frame-options: sameorigin");
602 prerender::URLRequestResponseStarted(request
);
605 void ChromeResourceDispatcherHostDelegate::OnRequestRedirected(
606 const GURL
& redirect_url
,
607 net::URLRequest
* request
,
608 content::ResourceContext
* resource_context
,
609 content::ResourceResponse
* response
) {
610 ProfileIOData
* io_data
= ProfileIOData::FromResourceContext(resource_context
);
611 const ResourceRequestInfo
* info
= ResourceRequestInfo::ForRequest(request
);
613 #if defined(ENABLE_ONE_CLICK_SIGNIN)
614 // See if the response contains the Google-Accounts-SignIn header. If so,
615 // then the user has just finished signing in, and the server is allowing the
616 // browser to suggest connecting the user's profile to the account.
617 OneClickSigninHelper::ShowInfoBarIfPossible(request
, io_data
,
620 AppendChromeSyncGaiaHeader(request
, resource_context
);
623 // In the Mirror world, Chrome should append a X-Chrome-Connected header to
624 // all Gaia requests from a connected profile so Gaia could return a 204
625 // response and let Chrome handle the action with native UI. The only
626 // exception is requests from gaia webview, since the native profile
627 // management UI is built on top of it.
628 signin::AppendMirrorRequestHeaderIfPossible(request
, redirect_url
, io_data
,
629 info
->GetChildID(), info
->GetRouteID());
633 void ChromeResourceDispatcherHostDelegate::
634 SetExternalProtocolHandlerDelegateForTesting(
635 ExternalProtocolHandler::Delegate
* delegate
) {
636 g_external_protocol_handler_delegate
= delegate
;