Check USB device path access when prompting users to select a device.
[chromium-blink-merge.git] / chrome / browser / renderer_host / chrome_resource_dispatcher_host_delegate.cc
blob1630c3fd98eb814ea5a10b09a7cb8bd3a3d1eacd
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"
7 #include <string>
8 #include <vector>
10 #include "base/base64.h"
11 #include "base/guid.h"
12 #include "base/logging.h"
13 #include "chrome/browser/browser_process.h"
14 #include "chrome/browser/chrome_notification_types.h"
15 #include "chrome/browser/component_updater/component_updater_resource_throttle.h"
16 #include "chrome/browser/download/download_request_limiter.h"
17 #include "chrome/browser/download/download_resource_throttle.h"
18 #include "chrome/browser/net/resource_prefetch_predictor_observer.h"
19 #include "chrome/browser/plugins/plugin_prefs.h"
20 #include "chrome/browser/prefetch/prefetch.h"
21 #include "chrome/browser/prerender/prerender_manager.h"
22 #include "chrome/browser/prerender/prerender_manager_factory.h"
23 #include "chrome/browser/prerender/prerender_resource_throttle.h"
24 #include "chrome/browser/prerender/prerender_util.h"
25 #include "chrome/browser/profiles/profile.h"
26 #include "chrome/browser/profiles/profile_io_data.h"
27 #include "chrome/browser/renderer_host/safe_browsing_resource_throttle_factory.h"
28 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
29 #include "chrome/browser/signin/signin_header_helper.h"
30 #include "chrome/browser/tab_contents/tab_util.h"
31 #include "chrome/browser/ui/login/login_prompt.h"
32 #include "chrome/common/chrome_switches.h"
33 #include "chrome/common/render_messages.h"
34 #include "chrome/common/url_constants.h"
35 #include "components/content_settings/core/browser/host_content_settings_map.h"
36 #include "components/google/core/browser/google_util.h"
37 #include "components/variations/net/variations_http_header_provider.h"
38 #include "content/public/browser/browser_thread.h"
39 #include "content/public/browser/notification_service.h"
40 #include "content/public/browser/plugin_service.h"
41 #include "content/public/browser/plugin_service_filter.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/service_worker_context.h"
48 #include "content/public/browser/stream_info.h"
49 #include "content/public/browser/web_contents.h"
50 #include "content/public/common/resource_response.h"
51 #include "net/base/load_flags.h"
52 #include "net/base/load_timing_info.h"
53 #include "net/base/request_priority.h"
54 #include "net/http/http_response_headers.h"
55 #include "net/url_request/url_request.h"
57 #if !defined(DISABLE_NACL)
58 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
59 #endif
61 #if defined(ENABLE_CONFIGURATION_POLICY)
62 #include "components/policy/core/common/cloud/policy_header_io_helper.h"
63 #endif
65 #if defined(ENABLE_EXTENSIONS)
66 #include "chrome/browser/apps/app_url_redirector.h"
67 #include "chrome/browser/apps/ephemeral_app_throttle.h"
68 #include "chrome/browser/extensions/api/streams_private/streams_private_api.h"
69 #include "chrome/browser/extensions/user_script_listener.h"
70 #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
71 #include "extensions/browser/info_map.h"
72 #include "extensions/common/constants.h"
73 #include "extensions/common/extension_urls.h"
74 #include "extensions/common/manifest_handlers/mime_types_handler.h"
75 #include "extensions/common/user_script.h"
76 #endif
78 #if defined(ENABLE_SUPERVISED_USERS)
79 #include "chrome/browser/supervised_user/supervised_user_resource_throttle.h"
80 #endif
82 #if defined(USE_SYSTEM_PROTOBUF)
83 #include <google/protobuf/repeated_field.h>
84 #else
85 #include "third_party/protobuf/src/google/protobuf/repeated_field.h"
86 #endif
88 #if defined(OS_ANDROID)
89 #include "chrome/browser/android/intercept_download_resource_throttle.h"
90 #include "components/navigation_interception/intercept_navigation_delegate.h"
91 #endif
93 #if defined(ENABLE_DATA_REDUCTION_PROXY_DEBUGGING)
94 #include "components/data_reduction_proxy/content/browser/data_reduction_proxy_debug_resource_throttle.h"
95 #endif
97 #if defined(OS_CHROMEOS)
98 #include "chrome/browser/chromeos/login/signin/merge_session_throttle.h"
99 // TODO(oshima): Enable this for other platforms.
100 #include "chrome/browser/renderer_host/offline_resource_throttle.h"
101 #endif
103 using content::BrowserThread;
104 using content::RenderViewHost;
105 using content::ResourceDispatcherHostLoginDelegate;
106 using content::ResourceRequestInfo;
107 using content::ResourceType;
109 #if defined(ENABLE_EXTENSIONS)
110 using extensions::Extension;
111 using extensions::StreamsPrivateAPI;
112 #endif
114 #if defined(OS_ANDROID)
115 using navigation_interception::InterceptNavigationDelegate;
116 #endif
118 namespace {
120 ExternalProtocolHandler::Delegate* g_external_protocol_handler_delegate = NULL;
122 void NotifyDownloadInitiatedOnUI(int render_process_id, int render_view_id) {
123 RenderViewHost* rvh = RenderViewHost::FromID(render_process_id,
124 render_view_id);
125 if (!rvh)
126 return;
128 content::NotificationService::current()->Notify(
129 chrome::NOTIFICATION_DOWNLOAD_INITIATED,
130 content::Source<RenderViewHost>(rvh),
131 content::NotificationService::NoDetails());
134 prerender::PrerenderManager* GetPrerenderManager(int render_process_id,
135 int render_view_id) {
136 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
138 content::WebContents* web_contents =
139 tab_util::GetWebContentsByID(render_process_id, render_view_id);
140 if (!web_contents)
141 return NULL;
143 content::BrowserContext* browser_context = web_contents->GetBrowserContext();
144 if (!browser_context)
145 return NULL;
147 Profile* profile = Profile::FromBrowserContext(browser_context);
148 if (!profile)
149 return NULL;
151 return prerender::PrerenderManagerFactory::GetForProfile(profile);
154 void UpdatePrerenderNetworkBytesCallback(int render_process_id,
155 int render_view_id,
156 int64 bytes) {
157 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
159 content::WebContents* web_contents =
160 tab_util::GetWebContentsByID(render_process_id, render_view_id);
161 // PrerenderContents::FromWebContents handles the NULL case.
162 prerender::PrerenderContents* prerender_contents =
163 prerender::PrerenderContents::FromWebContents(web_contents);
165 if (prerender_contents)
166 prerender_contents->AddNetworkBytes(bytes);
168 prerender::PrerenderManager* prerender_manager =
169 GetPrerenderManager(render_process_id, render_view_id);
170 if (prerender_manager)
171 prerender_manager->AddProfileNetworkBytesIfEnabled(bytes);
174 #if defined(ENABLE_EXTENSIONS)
175 void SendExecuteMimeTypeHandlerEvent(scoped_ptr<content::StreamInfo> stream,
176 int64 expected_content_size,
177 int render_process_id,
178 int render_frame_id,
179 const std::string& extension_id,
180 const std::string& view_id,
181 bool embedded) {
182 DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
184 content::WebContents* web_contents =
185 tab_util::GetWebContentsByFrameID(render_process_id, render_frame_id);
186 if (!web_contents)
187 return;
189 // If the request was for a prerender, abort the prerender and do not
190 // continue.
191 prerender::PrerenderContents* prerender_contents =
192 prerender::PrerenderContents::FromWebContents(web_contents);
193 if (prerender_contents) {
194 prerender_contents->Destroy(prerender::FINAL_STATUS_DOWNLOAD);
195 return;
198 Profile* profile =
199 Profile::FromBrowserContext(web_contents->GetBrowserContext());
201 StreamsPrivateAPI* streams_private = StreamsPrivateAPI::Get(profile);
202 if (!streams_private)
203 return;
204 streams_private->ExecuteMimeTypeHandler(
205 extension_id, web_contents, stream.Pass(), view_id, expected_content_size,
206 embedded, render_process_id, render_frame_id);
209 // TODO(raymes): This won't return the right result if plugins haven't been
210 // loaded yet. Fixing this properly really requires fixing crbug.com/443466.
211 bool IsPluginEnabledForExtension(const Extension* extension,
212 const ResourceRequestInfo* info,
213 const std::string& mime_type,
214 const GURL& url) {
215 content::PluginService* service = content::PluginService::GetInstance();
216 std::vector<content::WebPluginInfo> plugins;
217 service->GetPluginInfoArray(url, mime_type, true, &plugins, nullptr);
218 content::PluginServiceFilter* filter = service->GetFilter();
220 for (auto& plugin : plugins) {
221 // Check that the plugin is running the extension.
222 if (plugin.path !=
223 base::FilePath::FromUTF8Unsafe(extension->url().spec())) {
224 continue;
226 // Check that the plugin is actually enabled.
227 if (!filter || filter->IsPluginAvailable(info->GetChildID(),
228 info->GetRenderFrameID(),
229 info->GetContext(),
230 url,
231 GURL(),
232 &plugin)) {
233 return true;
236 return false;
238 #endif // !defined(ENABLE_EXTENSIONS)
240 #if !defined(OS_ANDROID)
241 void LaunchURL(const GURL& url, int render_process_id, int render_view_id) {
242 // If there is no longer a WebContents, the request may have raced with tab
243 // closing. Don't fire the external request. (It may have been a prerender.)
244 content::WebContents* web_contents =
245 tab_util::GetWebContentsByID(render_process_id, render_view_id);
246 if (!web_contents)
247 return;
249 // Do not launch external requests attached to unswapped prerenders.
250 prerender::PrerenderContents* prerender_contents =
251 prerender::PrerenderContents::FromWebContents(web_contents);
252 if (prerender_contents) {
253 prerender_contents->Destroy(prerender::FINAL_STATUS_UNSUPPORTED_SCHEME);
254 prerender::ReportPrerenderExternalURL();
255 return;
258 ExternalProtocolHandler::LaunchUrlWithDelegate(
259 url,
260 render_process_id,
261 render_view_id,
262 g_external_protocol_handler_delegate);
264 #endif // !defined(OS_ANDROID)
266 #if !defined(DISABLE_NACL)
267 void AppendComponentUpdaterThrottles(
268 net::URLRequest* request,
269 content::ResourceContext* resource_context,
270 ResourceType resource_type,
271 ScopedVector<content::ResourceThrottle>* throttles) {
272 const char* crx_id = NULL;
273 component_updater::ComponentUpdateService* cus =
274 g_browser_process->component_updater();
275 if (!cus)
276 return;
277 // Check for PNaCl pexe request.
278 if (resource_type == content::RESOURCE_TYPE_OBJECT) {
279 const net::HttpRequestHeaders& headers = request->extra_request_headers();
280 std::string accept_headers;
281 if (headers.GetHeader("Accept", &accept_headers)) {
282 if (accept_headers.find("application/x-pnacl") != std::string::npos &&
283 pnacl::NeedsOnDemandUpdate())
284 crx_id = "hnimpnehoodheedghdeeijklkeaacbdc";
288 if (crx_id) {
289 // We got a component we need to install, so throttle the resource
290 // until the component is installed.
291 throttles->push_back(
292 component_updater::GetOnDemandResourceThrottle(cus, crx_id));
295 #endif // !defined(DISABLE_NACL)
297 } // namespace
299 ChromeResourceDispatcherHostDelegate::ChromeResourceDispatcherHostDelegate()
300 : download_request_limiter_(g_browser_process->download_request_limiter()),
301 safe_browsing_(g_browser_process->safe_browsing_service())
302 #if defined(ENABLE_EXTENSIONS)
303 , user_script_listener_(new extensions::UserScriptListener())
304 #endif
306 BrowserThread::PostTask(
307 BrowserThread::IO,
308 FROM_HERE,
309 base::Bind(content::ServiceWorkerContext::AddExcludedHeadersForFetchEvent,
310 variations::VariationsHttpHeaderProvider::GetInstance()
311 ->GetVariationHeaderNames()));
314 ChromeResourceDispatcherHostDelegate::~ChromeResourceDispatcherHostDelegate() {
315 #if defined(ENABLE_EXTENSIONS)
316 CHECK(stream_target_info_.empty());
317 #endif
320 bool ChromeResourceDispatcherHostDelegate::ShouldBeginRequest(
321 const std::string& method,
322 const GURL& url,
323 ResourceType resource_type,
324 content::ResourceContext* resource_context) {
325 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
327 // Handle a PREFETCH resource type. If prefetch is disabled, squelch the
328 // request. Otherwise, do a normal request to warm the cache.
329 if (resource_type == content::RESOURCE_TYPE_PREFETCH) {
330 // All PREFETCH requests should be GETs, but be defensive about it.
331 if (method != "GET")
332 return false;
334 // If prefetch is disabled, kill the request.
335 if (!prefetch::IsPrefetchEnabled(resource_context))
336 return false;
339 return true;
342 void ChromeResourceDispatcherHostDelegate::RequestBeginning(
343 net::URLRequest* request,
344 content::ResourceContext* resource_context,
345 content::AppCacheService* appcache_service,
346 ResourceType resource_type,
347 ScopedVector<content::ResourceThrottle>* throttles) {
348 if (safe_browsing_.get())
349 safe_browsing_->OnResourceRequest(request);
351 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
352 bool is_prerendering =
353 info->GetVisibilityState() == blink::WebPageVisibilityStatePrerender;
354 if (is_prerendering) {
355 // Requests with the IGNORE_LIMITS flag set (i.e., sync XHRs)
356 // should remain at MAXIMUM_PRIORITY.
357 if (request->load_flags() & net::LOAD_IGNORE_LIMITS) {
358 DCHECK_EQ(request->priority(), net::MAXIMUM_PRIORITY);
359 } else {
360 request->SetPriority(net::IDLE);
364 ProfileIOData* io_data = ProfileIOData::FromResourceContext(
365 resource_context);
367 #if defined(OS_ANDROID)
368 // TODO(davidben): This is insufficient to integrate with prerender properly.
369 // https://crbug.com/370595
370 if (!is_prerendering) {
371 if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME) {
372 throttles->push_back(
373 InterceptNavigationDelegate::CreateThrottleFor(request));
374 } else if (resource_type == content::RESOURCE_TYPE_XHR) {
375 InterceptNavigationDelegate::UpdateUserGestureCarryoverInfo(request);
378 #else
379 if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME) {
380 // Redirect some navigations to apps that have registered matching URL
381 // handlers ('url_handlers' in the manifest).
382 content::ResourceThrottle* url_to_app_throttle =
383 AppUrlRedirector::MaybeCreateThrottleFor(request, io_data);
384 if (url_to_app_throttle)
385 throttles->push_back(url_to_app_throttle);
387 if (!is_prerendering) {
388 // Experimental: Launch ephemeral apps from search results.
389 content::ResourceThrottle* ephemeral_app_throttle =
390 EphemeralAppThrottle::MaybeCreateThrottleForLaunch(
391 request, io_data);
392 if (ephemeral_app_throttle)
393 throttles->push_back(ephemeral_app_throttle);
396 #endif
398 #if defined(OS_CHROMEOS)
399 // Check if we need to add offline throttle. This should be done only
400 // for main frames.
401 // We will fall back to the old ChromeOS offline error page if the
402 // --disable-new-offline-error-page command-line switch is defined.
403 bool new_error_page_enabled = switches::NewOfflineErrorPageEnabled();
404 if (!new_error_page_enabled &&
405 resource_type == content::RESOURCE_TYPE_MAIN_FRAME) {
406 // We check offline first, then check safe browsing so that we still can
407 // block unsafe site after we remove offline page.
408 throttles->push_back(new OfflineResourceThrottle(request,
409 appcache_service));
412 // Check if we need to add merge session throttle. This throttle will postpone
413 // loading of main frames and XHR request.
414 if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME ||
415 resource_type == content::RESOURCE_TYPE_XHR) {
416 // Add interstitial page while merge session process (cookie
417 // reconstruction from OAuth2 refresh token in ChromeOS login) is still in
418 // progress while we are attempting to load a google property.
419 if (!MergeSessionThrottle::AreAllSessionMergedAlready() &&
420 request->url().SchemeIsHTTPOrHTTPS()) {
421 throttles->push_back(new MergeSessionThrottle(request, resource_type));
424 #endif
426 // Don't attempt to append headers to requests that have already started.
427 // TODO(stevet): Remove this once the request ordering issues are resolved
428 // in crbug.com/128048.
429 if (!request->is_pending()) {
430 net::HttpRequestHeaders headers;
431 headers.CopyFrom(request->extra_request_headers());
432 bool is_off_the_record = io_data->IsOffTheRecord();
433 variations::VariationsHttpHeaderProvider::GetInstance()->
434 AppendHeaders(request->url(),
435 is_off_the_record,
436 !is_off_the_record &&
437 io_data->GetMetricsEnabledStateOnIOThread(),
438 &headers);
439 request->SetExtraRequestHeaders(headers);
442 #if defined(ENABLE_CONFIGURATION_POLICY)
443 if (io_data->policy_header_helper())
444 io_data->policy_header_helper()->AddPolicyHeaders(request->url(), request);
445 #endif
447 signin::AppendMirrorRequestHeaderIfPossible(
448 request, GURL() /* redirect_url */, io_data,
449 info->GetChildID(), info->GetRouteID());
451 AppendStandardResourceThrottles(request,
452 resource_context,
453 resource_type,
454 throttles);
455 #if !defined(DISABLE_NACL)
456 if (!is_prerendering) {
457 AppendComponentUpdaterThrottles(request,
458 resource_context,
459 resource_type,
460 throttles);
462 #endif
464 if (io_data->resource_prefetch_predictor_observer()) {
465 io_data->resource_prefetch_predictor_observer()->OnRequestStarted(
466 request, resource_type, info->GetChildID(), info->GetRenderFrameID());
470 void ChromeResourceDispatcherHostDelegate::DownloadStarting(
471 net::URLRequest* request,
472 content::ResourceContext* resource_context,
473 int child_id,
474 int route_id,
475 int request_id,
476 bool is_content_initiated,
477 bool must_download,
478 ScopedVector<content::ResourceThrottle>* throttles) {
479 BrowserThread::PostTask(
480 BrowserThread::UI, FROM_HERE,
481 base::Bind(&NotifyDownloadInitiatedOnUI, child_id, route_id));
483 // If it's from the web, we don't trust it, so we push the throttle on.
484 if (is_content_initiated) {
485 throttles->push_back(
486 new DownloadResourceThrottle(download_request_limiter_.get(),
487 child_id,
488 route_id,
489 request->url(),
490 request->method()));
491 #if defined(OS_ANDROID)
492 throttles->push_back(
493 new chrome::InterceptDownloadResourceThrottle(
494 request, child_id, route_id, request_id));
495 #endif
498 // If this isn't a new request, we've seen this before and added the standard
499 // resource throttles already so no need to add it again.
500 if (!request->is_pending()) {
501 AppendStandardResourceThrottles(request,
502 resource_context,
503 content::RESOURCE_TYPE_MAIN_FRAME,
504 throttles);
508 ResourceDispatcherHostLoginDelegate*
509 ChromeResourceDispatcherHostDelegate::CreateLoginDelegate(
510 net::AuthChallengeInfo* auth_info, net::URLRequest* request) {
511 return CreateLoginPrompt(auth_info, request);
514 bool ChromeResourceDispatcherHostDelegate::HandleExternalProtocol(
515 const GURL& url,
516 int child_id,
517 int route_id) {
518 #if defined(OS_ANDROID)
519 // Android use a resource throttle to handle external as well as internal
520 // protocols.
521 return false;
522 #else
524 #if defined(ENABLE_EXTENSIONS)
525 if (extensions::WebViewRendererState::GetInstance()->IsGuest(child_id))
526 return false;
528 #endif // defined(ENABLE_EXTENSIONS)
530 BrowserThread::PostTask(BrowserThread::UI,
531 FROM_HERE,
532 base::Bind(&LaunchURL, url, child_id, route_id));
533 return true;
534 #endif
537 void ChromeResourceDispatcherHostDelegate::AppendStandardResourceThrottles(
538 net::URLRequest* request,
539 content::ResourceContext* resource_context,
540 ResourceType resource_type,
541 ScopedVector<content::ResourceThrottle>* throttles) {
542 ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
543 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
544 // Insert safe browsing at the front of the list, so it gets to decide on
545 // policies first.
546 if (io_data->safe_browsing_enabled()->GetValue()
547 #if defined(OS_ANDROID)
548 || io_data->IsDataReductionProxyEnabled()
549 #endif
551 content::ResourceThrottle* throttle =
552 SafeBrowsingResourceThrottleFactory::Create(request,
553 resource_context,
554 resource_type,
555 safe_browsing_.get());
556 if (throttle)
557 throttles->push_back(throttle);
559 #endif
561 #if defined(ENABLE_DATA_REDUCTION_PROXY_DEBUGGING)
562 scoped_ptr<content::ResourceThrottle> data_reduction_proxy_throttle =
563 data_reduction_proxy::DataReductionProxyDebugResourceThrottle::
564 MaybeCreate(
565 request, resource_type, io_data->data_reduction_proxy_io_data());
566 if (data_reduction_proxy_throttle)
567 throttles->push_back(data_reduction_proxy_throttle.release());
568 #endif
570 #if defined(ENABLE_SUPERVISED_USERS)
571 bool is_subresource_request =
572 resource_type != content::RESOURCE_TYPE_MAIN_FRAME;
573 throttles->push_back(new SupervisedUserResourceThrottle(
574 request, !is_subresource_request,
575 io_data->supervised_user_url_filter()));
576 #endif
578 #if defined(ENABLE_EXTENSIONS)
579 content::ResourceThrottle* throttle =
580 user_script_listener_->CreateResourceThrottle(request->url(),
581 resource_type);
582 if (throttle)
583 throttles->push_back(throttle);
584 #endif
586 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
587 if (info->GetVisibilityState() == blink::WebPageVisibilityStatePrerender) {
588 throttles->push_back(new prerender::PrerenderResourceThrottle(request));
592 bool ChromeResourceDispatcherHostDelegate::ShouldForceDownloadResource(
593 const GURL& url, const std::string& mime_type) {
594 #if defined(ENABLE_EXTENSIONS)
595 // Special-case user scripts to get downloaded instead of viewed.
596 return extensions::UserScript::IsURLUserScript(url, mime_type);
597 #else
598 return false;
599 #endif
602 bool ChromeResourceDispatcherHostDelegate::ShouldInterceptResourceAsStream(
603 net::URLRequest* request,
604 const std::string& mime_type,
605 GURL* origin,
606 std::string* payload) {
607 #if defined(ENABLE_EXTENSIONS)
608 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
609 ProfileIOData* io_data =
610 ProfileIOData::FromResourceContext(info->GetContext());
611 bool profile_is_off_the_record = io_data->IsOffTheRecord();
612 const scoped_refptr<const extensions::InfoMap> extension_info_map(
613 io_data->GetExtensionInfoMap());
614 std::vector<std::string> whitelist = MimeTypesHandler::GetMIMETypeWhitelist();
615 // Go through the white-listed extensions and try to use them to intercept
616 // the URL request.
617 for (const std::string& extension_id : whitelist) {
618 const Extension* extension =
619 extension_info_map->extensions().GetByID(extension_id);
620 // The white-listed extension may not be installed, so we have to NULL check
621 // |extension|.
622 if (!extension ||
623 (profile_is_off_the_record &&
624 !extension_info_map->IsIncognitoEnabled(extension_id))) {
625 continue;
628 MimeTypesHandler* handler = MimeTypesHandler::GetHandler(extension);
629 if (handler && handler->CanHandleMIMEType(mime_type)) {
630 StreamTargetInfo target_info;
631 *origin = Extension::GetBaseURLFromExtensionId(extension_id);
632 target_info.extension_id = extension_id;
633 if (!handler->handler_url().empty()) {
634 // This is reached in the case of MimeHandlerViews. If the
635 // MimeHandlerView plugin is disabled, then we shouldn't intercept the
636 // stream.
637 if (!IsPluginEnabledForExtension(extension, info, mime_type,
638 request->url())) {
639 continue;
641 target_info.view_id = base::GenerateGUID();
642 *payload = target_info.view_id;
644 stream_target_info_[request] = target_info;
645 return true;
648 #endif
649 return false;
652 void ChromeResourceDispatcherHostDelegate::OnStreamCreated(
653 net::URLRequest* request,
654 scoped_ptr<content::StreamInfo> stream) {
655 #if defined(ENABLE_EXTENSIONS)
656 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
657 std::map<net::URLRequest*, StreamTargetInfo>::iterator ix =
658 stream_target_info_.find(request);
659 CHECK(ix != stream_target_info_.end());
660 bool embedded = info->GetResourceType() != content::RESOURCE_TYPE_MAIN_FRAME;
661 content::BrowserThread::PostTask(
662 content::BrowserThread::UI, FROM_HERE,
663 base::Bind(&SendExecuteMimeTypeHandlerEvent, base::Passed(&stream),
664 request->GetExpectedContentSize(), info->GetChildID(),
665 info->GetRenderFrameID(), ix->second.extension_id,
666 ix->second.view_id, embedded));
667 stream_target_info_.erase(request);
668 #endif
671 void ChromeResourceDispatcherHostDelegate::OnResponseStarted(
672 net::URLRequest* request,
673 content::ResourceContext* resource_context,
674 content::ResourceResponse* response,
675 IPC::Sender* sender) {
676 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
677 ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
679 // See if the response contains the X-Chrome-Manage-Accounts header. If so
680 // show the profile avatar bubble so that user can complete signin/out action
681 // the native UI.
682 signin::ProcessMirrorResponseHeaderIfExists(request, io_data,
683 info->GetChildID(),
684 info->GetRouteID());
686 // Build in additional protection for the chrome web store origin.
687 #if defined(ENABLE_EXTENSIONS)
688 GURL webstore_url(extension_urls::GetWebstoreLaunchURL());
689 if (request->url().DomainIs(webstore_url.host().c_str())) {
690 net::HttpResponseHeaders* response_headers = request->response_headers();
691 if (!response_headers->HasHeaderValue("x-frame-options", "deny") &&
692 !response_headers->HasHeaderValue("x-frame-options", "sameorigin")) {
693 response_headers->RemoveHeader("x-frame-options");
694 response_headers->AddHeader("x-frame-options: sameorigin");
697 #endif
699 if (io_data->resource_prefetch_predictor_observer())
700 io_data->resource_prefetch_predictor_observer()->OnResponseStarted(request);
702 // Ignores x-frame-options for the chrome signin UI.
703 const std::string request_spec(
704 request->first_party_for_cookies().GetOrigin().spec());
705 #if defined(OS_CHROMEOS)
706 if (request_spec == chrome::kChromeUIOobeURL ||
707 request_spec == chrome::kChromeUIChromeSigninURL) {
708 #else
709 if (request_spec == chrome::kChromeUIChromeSigninURL) {
710 #endif
711 net::HttpResponseHeaders* response_headers = request->response_headers();
712 if (response_headers && response_headers->HasHeader("x-frame-options"))
713 response_headers->RemoveHeader("x-frame-options");
716 prerender::URLRequestResponseStarted(request);
719 void ChromeResourceDispatcherHostDelegate::OnRequestRedirected(
720 const GURL& redirect_url,
721 net::URLRequest* request,
722 content::ResourceContext* resource_context,
723 content::ResourceResponse* response) {
724 ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
726 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
728 // In the Mirror world, Chrome should append a X-Chrome-Connected header to
729 // all Gaia requests from a connected profile so Gaia could return a 204
730 // response and let Chrome handle the action with native UI. The only
731 // exception is requests from gaia webview, since the native profile
732 // management UI is built on top of it.
733 signin::AppendMirrorRequestHeaderIfPossible(request, redirect_url, io_data,
734 info->GetChildID(), info->GetRouteID());
736 if (io_data->resource_prefetch_predictor_observer()) {
737 io_data->resource_prefetch_predictor_observer()->OnRequestRedirected(
738 redirect_url, request);
741 #if defined(ENABLE_CONFIGURATION_POLICY)
742 if (io_data->policy_header_helper())
743 io_data->policy_header_helper()->AddPolicyHeaders(redirect_url, request);
744 #endif
747 // Notification that a request has completed.
748 void ChromeResourceDispatcherHostDelegate::RequestComplete(
749 net::URLRequest* url_request) {
750 // Jump on the UI thread and inform the prerender about the bytes.
751 const ResourceRequestInfo* info =
752 ResourceRequestInfo::ForRequest(url_request);
753 if (url_request && !url_request->was_cached()) {
754 BrowserThread::PostTask(BrowserThread::UI,
755 FROM_HERE,
756 base::Bind(&UpdatePrerenderNetworkBytesCallback,
757 info->GetChildID(),
758 info->GetRouteID(),
759 url_request->GetTotalReceivedBytes()));
763 // static
764 void ChromeResourceDispatcherHostDelegate::
765 SetExternalProtocolHandlerDelegateForTesting(
766 ExternalProtocolHandler::Delegate* delegate) {
767 g_external_protocol_handler_delegate = delegate;