[Cronet] Delay StartNetLog and StopNetLog until native request context is initialized
[chromium-blink-merge.git] / chrome / browser / renderer_host / chrome_resource_dispatcher_host_delegate.cc
blobfdb8ca196ccdd19524ff13ceb32ebe95776a19fc
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 (resource_type == content::RESOURCE_TYPE_MAIN_FRAME && !is_prerendering) {
371 throttles->push_back(
372 InterceptNavigationDelegate::CreateThrottleFor(request));
374 #else
375 if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME) {
376 // Redirect some navigations to apps that have registered matching URL
377 // handlers ('url_handlers' in the manifest).
378 content::ResourceThrottle* url_to_app_throttle =
379 AppUrlRedirector::MaybeCreateThrottleFor(request, io_data);
380 if (url_to_app_throttle)
381 throttles->push_back(url_to_app_throttle);
383 if (!is_prerendering) {
384 // Experimental: Launch ephemeral apps from search results.
385 content::ResourceThrottle* ephemeral_app_throttle =
386 EphemeralAppThrottle::MaybeCreateThrottleForLaunch(
387 request, io_data);
388 if (ephemeral_app_throttle)
389 throttles->push_back(ephemeral_app_throttle);
392 #endif
394 #if defined(OS_CHROMEOS)
395 // Check if we need to add offline throttle. This should be done only
396 // for main frames.
397 // We will fall back to the old ChromeOS offline error page if the
398 // --disable-new-offline-error-page command-line switch is defined.
399 bool new_error_page_enabled = switches::NewOfflineErrorPageEnabled();
400 if (!new_error_page_enabled &&
401 resource_type == content::RESOURCE_TYPE_MAIN_FRAME) {
402 // We check offline first, then check safe browsing so that we still can
403 // block unsafe site after we remove offline page.
404 throttles->push_back(new OfflineResourceThrottle(request,
405 appcache_service));
408 // Check if we need to add merge session throttle. This throttle will postpone
409 // loading of main frames and XHR request.
410 if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME ||
411 resource_type == content::RESOURCE_TYPE_XHR) {
412 // Add interstitial page while merge session process (cookie
413 // reconstruction from OAuth2 refresh token in ChromeOS login) is still in
414 // progress while we are attempting to load a google property.
415 if (!MergeSessionThrottle::AreAllSessionMergedAlready() &&
416 request->url().SchemeIsHTTPOrHTTPS()) {
417 throttles->push_back(new MergeSessionThrottle(request, resource_type));
420 #endif
422 // Don't attempt to append headers to requests that have already started.
423 // TODO(stevet): Remove this once the request ordering issues are resolved
424 // in crbug.com/128048.
425 if (!request->is_pending()) {
426 net::HttpRequestHeaders headers;
427 headers.CopyFrom(request->extra_request_headers());
428 bool is_off_the_record = io_data->IsOffTheRecord();
429 variations::VariationsHttpHeaderProvider::GetInstance()->
430 AppendHeaders(request->url(),
431 is_off_the_record,
432 !is_off_the_record &&
433 io_data->GetMetricsEnabledStateOnIOThread(),
434 &headers);
435 request->SetExtraRequestHeaders(headers);
438 #if defined(ENABLE_CONFIGURATION_POLICY)
439 if (io_data->policy_header_helper())
440 io_data->policy_header_helper()->AddPolicyHeaders(request->url(), request);
441 #endif
443 signin::AppendMirrorRequestHeaderIfPossible(
444 request, GURL() /* redirect_url */, io_data,
445 info->GetChildID(), info->GetRouteID());
447 AppendStandardResourceThrottles(request,
448 resource_context,
449 resource_type,
450 throttles);
451 #if !defined(DISABLE_NACL)
452 if (!is_prerendering) {
453 AppendComponentUpdaterThrottles(request,
454 resource_context,
455 resource_type,
456 throttles);
458 #endif
460 if (io_data->resource_prefetch_predictor_observer()) {
461 io_data->resource_prefetch_predictor_observer()->OnRequestStarted(
462 request, resource_type, info->GetChildID(), info->GetRenderFrameID());
466 void ChromeResourceDispatcherHostDelegate::DownloadStarting(
467 net::URLRequest* request,
468 content::ResourceContext* resource_context,
469 int child_id,
470 int route_id,
471 int request_id,
472 bool is_content_initiated,
473 bool must_download,
474 ScopedVector<content::ResourceThrottle>* throttles) {
475 BrowserThread::PostTask(
476 BrowserThread::UI, FROM_HERE,
477 base::Bind(&NotifyDownloadInitiatedOnUI, child_id, route_id));
479 // If it's from the web, we don't trust it, so we push the throttle on.
480 if (is_content_initiated) {
481 throttles->push_back(
482 new DownloadResourceThrottle(download_request_limiter_.get(),
483 child_id,
484 route_id,
485 request->url(),
486 request->method()));
487 #if defined(OS_ANDROID)
488 throttles->push_back(
489 new chrome::InterceptDownloadResourceThrottle(
490 request, child_id, route_id, request_id));
491 #endif
494 // If this isn't a new request, we've seen this before and added the standard
495 // resource throttles already so no need to add it again.
496 if (!request->is_pending()) {
497 AppendStandardResourceThrottles(request,
498 resource_context,
499 content::RESOURCE_TYPE_MAIN_FRAME,
500 throttles);
504 ResourceDispatcherHostLoginDelegate*
505 ChromeResourceDispatcherHostDelegate::CreateLoginDelegate(
506 net::AuthChallengeInfo* auth_info, net::URLRequest* request) {
507 return CreateLoginPrompt(auth_info, request);
510 bool ChromeResourceDispatcherHostDelegate::HandleExternalProtocol(
511 const GURL& url,
512 int child_id,
513 int route_id) {
514 #if defined(OS_ANDROID)
515 // Android use a resource throttle to handle external as well as internal
516 // protocols.
517 return false;
518 #else
520 #if defined(ENABLE_EXTENSIONS)
521 if (extensions::WebViewRendererState::GetInstance()->IsGuest(child_id))
522 return false;
524 #endif // defined(ENABLE_EXTENSIONS)
526 BrowserThread::PostTask(BrowserThread::UI,
527 FROM_HERE,
528 base::Bind(&LaunchURL, url, child_id, route_id));
529 return true;
530 #endif
533 void ChromeResourceDispatcherHostDelegate::AppendStandardResourceThrottles(
534 net::URLRequest* request,
535 content::ResourceContext* resource_context,
536 ResourceType resource_type,
537 ScopedVector<content::ResourceThrottle>* throttles) {
538 ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
539 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
540 // Insert safe browsing at the front of the list, so it gets to decide on
541 // policies first.
542 if (io_data->safe_browsing_enabled()->GetValue()
543 #if defined(OS_ANDROID)
544 || io_data->IsDataReductionProxyEnabled()
545 #endif
547 content::ResourceThrottle* throttle =
548 SafeBrowsingResourceThrottleFactory::Create(request,
549 resource_context,
550 resource_type,
551 safe_browsing_.get());
552 if (throttle)
553 throttles->push_back(throttle);
555 #endif
557 #if defined(ENABLE_DATA_REDUCTION_PROXY_DEBUGGING)
558 scoped_ptr<content::ResourceThrottle> data_reduction_proxy_throttle =
559 data_reduction_proxy::DataReductionProxyDebugResourceThrottle::
560 MaybeCreate(
561 request, resource_type, io_data->data_reduction_proxy_io_data());
562 if (data_reduction_proxy_throttle)
563 throttles->push_back(data_reduction_proxy_throttle.release());
564 #endif
566 #if defined(ENABLE_SUPERVISED_USERS)
567 bool is_subresource_request =
568 resource_type != content::RESOURCE_TYPE_MAIN_FRAME;
569 throttles->push_back(new SupervisedUserResourceThrottle(
570 request, !is_subresource_request,
571 io_data->supervised_user_url_filter()));
572 #endif
574 #if defined(ENABLE_EXTENSIONS)
575 content::ResourceThrottle* throttle =
576 user_script_listener_->CreateResourceThrottle(request->url(),
577 resource_type);
578 if (throttle)
579 throttles->push_back(throttle);
580 #endif
582 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
583 if (info->GetVisibilityState() == blink::WebPageVisibilityStatePrerender) {
584 throttles->push_back(new prerender::PrerenderResourceThrottle(request));
588 bool ChromeResourceDispatcherHostDelegate::ShouldForceDownloadResource(
589 const GURL& url, const std::string& mime_type) {
590 #if defined(ENABLE_EXTENSIONS)
591 // Special-case user scripts to get downloaded instead of viewed.
592 return extensions::UserScript::IsURLUserScript(url, mime_type);
593 #else
594 return false;
595 #endif
598 bool ChromeResourceDispatcherHostDelegate::ShouldInterceptResourceAsStream(
599 net::URLRequest* request,
600 const std::string& mime_type,
601 GURL* origin,
602 std::string* payload) {
603 #if defined(ENABLE_EXTENSIONS)
604 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
605 ProfileIOData* io_data =
606 ProfileIOData::FromResourceContext(info->GetContext());
607 bool profile_is_off_the_record = io_data->IsOffTheRecord();
608 const scoped_refptr<const extensions::InfoMap> extension_info_map(
609 io_data->GetExtensionInfoMap());
610 std::vector<std::string> whitelist = MimeTypesHandler::GetMIMETypeWhitelist();
611 // Go through the white-listed extensions and try to use them to intercept
612 // the URL request.
613 for (const std::string& extension_id : whitelist) {
614 const Extension* extension =
615 extension_info_map->extensions().GetByID(extension_id);
616 // The white-listed extension may not be installed, so we have to NULL check
617 // |extension|.
618 if (!extension ||
619 (profile_is_off_the_record &&
620 !extension_info_map->IsIncognitoEnabled(extension_id))) {
621 continue;
624 MimeTypesHandler* handler = MimeTypesHandler::GetHandler(extension);
625 if (handler && handler->CanHandleMIMEType(mime_type)) {
626 StreamTargetInfo target_info;
627 *origin = Extension::GetBaseURLFromExtensionId(extension_id);
628 target_info.extension_id = extension_id;
629 if (!handler->handler_url().empty()) {
630 // This is reached in the case of MimeHandlerViews. If the
631 // MimeHandlerView plugin is disabled, then we shouldn't intercept the
632 // stream.
633 if (!IsPluginEnabledForExtension(extension, info, mime_type,
634 request->url())) {
635 continue;
637 target_info.view_id = base::GenerateGUID();
638 *payload = target_info.view_id;
640 stream_target_info_[request] = target_info;
641 return true;
644 #endif
645 return false;
648 void ChromeResourceDispatcherHostDelegate::OnStreamCreated(
649 net::URLRequest* request,
650 scoped_ptr<content::StreamInfo> stream) {
651 #if defined(ENABLE_EXTENSIONS)
652 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
653 std::map<net::URLRequest*, StreamTargetInfo>::iterator ix =
654 stream_target_info_.find(request);
655 CHECK(ix != stream_target_info_.end());
656 bool embedded = info->GetResourceType() != content::RESOURCE_TYPE_MAIN_FRAME;
657 content::BrowserThread::PostTask(
658 content::BrowserThread::UI, FROM_HERE,
659 base::Bind(&SendExecuteMimeTypeHandlerEvent, base::Passed(&stream),
660 request->GetExpectedContentSize(), info->GetChildID(),
661 info->GetRenderFrameID(), ix->second.extension_id,
662 ix->second.view_id, embedded));
663 stream_target_info_.erase(request);
664 #endif
667 void ChromeResourceDispatcherHostDelegate::OnResponseStarted(
668 net::URLRequest* request,
669 content::ResourceContext* resource_context,
670 content::ResourceResponse* response,
671 IPC::Sender* sender) {
672 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
673 ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
675 // See if the response contains the X-Chrome-Manage-Accounts header. If so
676 // show the profile avatar bubble so that user can complete signin/out action
677 // the native UI.
678 signin::ProcessMirrorResponseHeaderIfExists(request, io_data,
679 info->GetChildID(),
680 info->GetRouteID());
682 // Build in additional protection for the chrome web store origin.
683 #if defined(ENABLE_EXTENSIONS)
684 GURL webstore_url(extension_urls::GetWebstoreLaunchURL());
685 if (request->url().DomainIs(webstore_url.host().c_str())) {
686 net::HttpResponseHeaders* response_headers = request->response_headers();
687 if (!response_headers->HasHeaderValue("x-frame-options", "deny") &&
688 !response_headers->HasHeaderValue("x-frame-options", "sameorigin")) {
689 response_headers->RemoveHeader("x-frame-options");
690 response_headers->AddHeader("x-frame-options: sameorigin");
693 #endif
695 if (io_data->resource_prefetch_predictor_observer())
696 io_data->resource_prefetch_predictor_observer()->OnResponseStarted(request);
698 // Ignores x-frame-options for the chrome signin UI.
699 const std::string request_spec(
700 request->first_party_for_cookies().GetOrigin().spec());
701 #if defined(OS_CHROMEOS)
702 if (request_spec == chrome::kChromeUIOobeURL ||
703 request_spec == chrome::kChromeUIChromeSigninURL) {
704 #else
705 if (request_spec == chrome::kChromeUIChromeSigninURL) {
706 #endif
707 net::HttpResponseHeaders* response_headers = request->response_headers();
708 if (response_headers && response_headers->HasHeader("x-frame-options"))
709 response_headers->RemoveHeader("x-frame-options");
712 prerender::URLRequestResponseStarted(request);
715 void ChromeResourceDispatcherHostDelegate::OnRequestRedirected(
716 const GURL& redirect_url,
717 net::URLRequest* request,
718 content::ResourceContext* resource_context,
719 content::ResourceResponse* response) {
720 ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
722 const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
724 // In the Mirror world, Chrome should append a X-Chrome-Connected header to
725 // all Gaia requests from a connected profile so Gaia could return a 204
726 // response and let Chrome handle the action with native UI. The only
727 // exception is requests from gaia webview, since the native profile
728 // management UI is built on top of it.
729 signin::AppendMirrorRequestHeaderIfPossible(request, redirect_url, io_data,
730 info->GetChildID(), info->GetRouteID());
732 if (io_data->resource_prefetch_predictor_observer()) {
733 io_data->resource_prefetch_predictor_observer()->OnRequestRedirected(
734 redirect_url, request);
737 #if defined(ENABLE_CONFIGURATION_POLICY)
738 if (io_data->policy_header_helper())
739 io_data->policy_header_helper()->AddPolicyHeaders(redirect_url, request);
740 #endif
743 // Notification that a request has completed.
744 void ChromeResourceDispatcherHostDelegate::RequestComplete(
745 net::URLRequest* url_request) {
746 // Jump on the UI thread and inform the prerender about the bytes.
747 const ResourceRequestInfo* info =
748 ResourceRequestInfo::ForRequest(url_request);
749 if (url_request && !url_request->was_cached()) {
750 BrowserThread::PostTask(BrowserThread::UI,
751 FROM_HERE,
752 base::Bind(&UpdatePrerenderNetworkBytesCallback,
753 info->GetChildID(),
754 info->GetRouteID(),
755 url_request->GetTotalReceivedBytes()));
759 // static
760 void ChromeResourceDispatcherHostDelegate::
761 SetExternalProtocolHandlerDelegateForTesting(
762 ExternalProtocolHandler::Delegate* delegate) {
763 g_external_protocol_handler_delegate = delegate;