Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / renderer_host / chrome_resource_dispatcher_host_delegate.cc
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.
4
5 #include "chrome/browser/renderer_host/chrome_resource_dispatcher_host_delegate.h"
6
7 #include <string>
8 #include <vector>
9
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/prefetch/prefetch.h"
20 #include "chrome/browser/prerender/prerender_manager.h"
21 #include "chrome/browser/prerender/prerender_manager_factory.h"
22 #include "chrome/browser/prerender/prerender_pending_swap_throttle.h"
23 #include "chrome/browser/prerender/prerender_resource_throttle.h"
24 #include "chrome/browser/prerender/prerender_tracker.h"
25 #include "chrome/browser/prerender/prerender_util.h"
26 #include "chrome/browser/profiles/profile.h"
27 #include "chrome/browser/profiles/profile_io_data.h"
28 #include "chrome/browser/renderer_host/safe_browsing_resource_throttle_factory.h"
29 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
30 #include "chrome/browser/signin/signin_header_helper.h"
31 #include "chrome/browser/tab_contents/tab_util.h"
32 #include "chrome/browser/ui/login/login_prompt.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/render_process_host.h"
41 #include "content/public/browser/render_view_host.h"
42 #include "content/public/browser/resource_context.h"
43 #include "content/public/browser/resource_dispatcher_host.h"
44 #include "content/public/browser/resource_request_info.h"
45 #include "content/public/browser/service_worker_context.h"
46 #include "content/public/browser/stream_info.h"
47 #include "content/public/browser/web_contents.h"
48 #include "content/public/common/resource_response.h"
49 #include "net/base/load_flags.h"
50 #include "net/base/load_timing_info.h"
51 #include "net/base/request_priority.h"
52 #include "net/http/http_response_headers.h"
53 #include "net/url_request/url_request.h"
54
55 #if !defined(DISABLE_NACL)
56 #include "chrome/browser/component_updater/pnacl/pnacl_component_installer.h"
57 #endif
58
59 #if defined(ENABLE_CONFIGURATION_POLICY)
60 #include "components/policy/core/common/cloud/policy_header_io_helper.h"
61 #endif
62
63 #if defined(ENABLE_EXTENSIONS)
64 #include "chrome/browser/apps/app_url_redirector.h"
65 #include "chrome/browser/apps/ephemeral_app_throttle.h"
66 #include "chrome/browser/extensions/api/streams_private/streams_private_api.h"
67 #include "chrome/browser/extensions/user_script_listener.h"
68 #include "chrome/common/extensions/manifest_handlers/mime_types_handler.h"
69 #include "extensions/browser/guest_view/web_view/web_view_renderer_state.h"
70 #include "extensions/browser/info_map.h"
71 #include "extensions/common/constants.h"
72 #include "extensions/common/extension_urls.h"
73 #include "extensions/common/user_script.h"
74 #endif
75
76 #if defined(ENABLE_MANAGED_USERS)
77 #include "chrome/browser/supervised_user/supervised_user_resource_throttle.h"
78 #endif
79
80 #if defined(ENABLE_ONE_CLICK_SIGNIN)
81 #include "chrome/browser/ui/sync/one_click_signin_helper.h"
82 #endif
83
84 #if defined(USE_SYSTEM_PROTOBUF)
85 #include <google/protobuf/repeated_field.h>
86 #else
87 #include "third_party/protobuf/src/google/protobuf/repeated_field.h"
88 #endif
89
90 #if defined(OS_ANDROID)
91 #include "chrome/browser/android/intercept_download_resource_throttle.h"
92 #include "chrome/browser/ui/android/infobars/auto_login_prompter.h"
93 #include "components/navigation_interception/intercept_navigation_delegate.h"
94 #endif
95
96 #if defined(OS_CHROMEOS)
97 #include "chrome/browser/chromeos/login/signin/merge_session_throttle.h"
98 // TODO(oshima): Enable this for other platforms.
99 #include "chrome/browser/renderer_host/offline_resource_throttle.h"
100 #endif
101
102 using content::BrowserThread;
103 using content::RenderViewHost;
104 using content::ResourceDispatcherHostLoginDelegate;
105 using content::ResourceRequestInfo;
106 using content::ResourceType;
107
108 #if defined(ENABLE_EXTENSIONS)
109 using extensions::Extension;
110 using extensions::StreamsPrivateAPI;
111 #endif
112
113 #if defined(OS_ANDROID)
114 using navigation_interception::InterceptNavigationDelegate;
115 #endif
116
117 namespace {
118
119 ExternalProtocolHandler::Delegate* g_external_protocol_handler_delegate = NULL;
120
121 void NotifyDownloadInitiatedOnUI(int render_process_id, int render_view_id) {
122   RenderViewHost* rvh = RenderViewHost::FromID(render_process_id,
123                                                render_view_id);
124   if (!rvh)
125     return;
126
127   content::NotificationService::current()->Notify(
128       chrome::NOTIFICATION_DOWNLOAD_INITIATED,
129       content::Source<RenderViewHost>(rvh),
130       content::NotificationService::NoDetails());
131 }
132
133 prerender::PrerenderManager* GetPrerenderManager(int render_process_id,
134                                                  int render_view_id) {
135   DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
136
137   content::WebContents* web_contents =
138       tab_util::GetWebContentsByID(render_process_id, render_view_id);
139   if (!web_contents)
140     return NULL;
141
142   content::BrowserContext* browser_context = web_contents->GetBrowserContext();
143   if (!browser_context)
144     return NULL;
145
146   Profile* profile = Profile::FromBrowserContext(browser_context);
147   if (!profile)
148     return NULL;
149
150   return prerender::PrerenderManagerFactory::GetForProfile(profile);
151 }
152
153 void UpdatePrerenderNetworkBytesCallback(int render_process_id,
154                                          int render_view_id,
155                                          int64 bytes) {
156   DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
157
158   content::WebContents* web_contents =
159       tab_util::GetWebContentsByID(render_process_id, render_view_id);
160   // PrerenderContents::FromWebContents handles the NULL case.
161   prerender::PrerenderContents* prerender_contents =
162       prerender::PrerenderContents::FromWebContents(web_contents);
163
164   if (prerender_contents)
165     prerender_contents->AddNetworkBytes(bytes);
166
167   prerender::PrerenderManager* prerender_manager =
168       GetPrerenderManager(render_process_id, render_view_id);
169   if (prerender_manager)
170     prerender_manager->AddProfileNetworkBytesIfEnabled(bytes);
171 }
172
173 #if defined(ENABLE_EXTENSIONS)
174 void SendExecuteMimeTypeHandlerEvent(scoped_ptr<content::StreamInfo> stream,
175                                      int64 expected_content_size,
176                                      int render_process_id,
177                                      int render_view_id,
178                                      const std::string& extension_id,
179                                      const std::string& view_id) {
180   DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
181
182   content::WebContents* web_contents =
183       tab_util::GetWebContentsByID(render_process_id, render_view_id);
184   if (!web_contents)
185     return;
186
187   // If the request was for a prerender, abort the prerender and do not
188   // continue.
189   prerender::PrerenderContents* prerender_contents =
190       prerender::PrerenderContents::FromWebContents(web_contents);
191   if (prerender_contents) {
192     prerender_contents->Destroy(prerender::FINAL_STATUS_DOWNLOAD);
193     return;
194   }
195
196   Profile* profile =
197       Profile::FromBrowserContext(web_contents->GetBrowserContext());
198
199   StreamsPrivateAPI* streams_private = StreamsPrivateAPI::Get(profile);
200   if (!streams_private)
201     return;
202   streams_private->ExecuteMimeTypeHandler(
203       extension_id, web_contents, stream.Pass(), view_id,
204       expected_content_size);
205 }
206 #endif  // !defined(ENABLE_EXTENSIONS)
207
208 #if !defined(OS_ANDROID)
209 void LaunchURL(const GURL& url, int render_process_id, int render_view_id) {
210   // If there is no longer a WebContents, the request may have raced with tab
211   // closing. Don't fire the external request. (It may have been a prerender.)
212   content::WebContents* web_contents =
213       tab_util::GetWebContentsByID(render_process_id, render_view_id);
214   if (!web_contents)
215     return;
216
217   // Do not launch external requests attached to unswapped prerenders.
218   prerender::PrerenderContents* prerender_contents =
219       prerender::PrerenderContents::FromWebContents(web_contents);
220   if (prerender_contents) {
221     prerender_contents->Destroy(prerender::FINAL_STATUS_UNSUPPORTED_SCHEME);
222     prerender::ReportPrerenderExternalURL();
223     return;
224   }
225
226   ExternalProtocolHandler::LaunchUrlWithDelegate(
227       url,
228       render_process_id,
229       render_view_id,
230       g_external_protocol_handler_delegate);
231 }
232 #endif  // !defined(OS_ANDROID)
233
234 #if !defined(DISABLE_NACL)
235 void AppendComponentUpdaterThrottles(
236     net::URLRequest* request,
237     content::ResourceContext* resource_context,
238     ResourceType resource_type,
239     ScopedVector<content::ResourceThrottle>* throttles) {
240   const char* crx_id = NULL;
241   component_updater::ComponentUpdateService* cus =
242       g_browser_process->component_updater();
243   if (!cus)
244     return;
245   // Check for PNaCl pexe request.
246   if (resource_type == content::RESOURCE_TYPE_OBJECT) {
247     const net::HttpRequestHeaders& headers = request->extra_request_headers();
248     std::string accept_headers;
249     if (headers.GetHeader("Accept", &accept_headers)) {
250       if (accept_headers.find("application/x-pnacl") != std::string::npos &&
251           pnacl::NeedsOnDemandUpdate())
252         crx_id = "hnimpnehoodheedghdeeijklkeaacbdc";
253     }
254   }
255
256   if (crx_id) {
257     // We got a component we need to install, so throttle the resource
258     // until the component is installed.
259     throttles->push_back(
260         component_updater::GetOnDemandResourceThrottle(cus, crx_id));
261   }
262 }
263 #endif  // !defined(DISABLE_NACL)
264
265 }  // namespace
266
267 ChromeResourceDispatcherHostDelegate::ChromeResourceDispatcherHostDelegate(
268     prerender::PrerenderTracker* prerender_tracker)
269     : download_request_limiter_(g_browser_process->download_request_limiter()),
270       safe_browsing_(g_browser_process->safe_browsing_service()),
271 #if defined(ENABLE_EXTENSIONS)
272       user_script_listener_(new extensions::UserScriptListener()),
273 #endif
274       prerender_tracker_(prerender_tracker) {
275   BrowserThread::PostTask(
276       BrowserThread::IO,
277       FROM_HERE,
278       base::Bind(content::ServiceWorkerContext::AddExcludedHeadersForFetchEvent,
279                  variations::VariationsHttpHeaderProvider::GetInstance()
280                      ->GetVariationHeaderNames()));
281 }
282
283 ChromeResourceDispatcherHostDelegate::~ChromeResourceDispatcherHostDelegate() {
284 #if defined(ENABLE_EXTENSIONS)
285   CHECK(stream_target_info_.empty());
286 #endif
287 }
288
289 bool ChromeResourceDispatcherHostDelegate::ShouldBeginRequest(
290     const std::string& method,
291     const GURL& url,
292     ResourceType resource_type,
293     content::ResourceContext* resource_context) {
294   DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
295
296   // Handle a PREFETCH resource type. If prefetch is disabled, squelch the
297   // request.  Otherwise, do a normal request to warm the cache.
298   if (resource_type == content::RESOURCE_TYPE_PREFETCH) {
299     // All PREFETCH requests should be GETs, but be defensive about it.
300     if (method != "GET")
301       return false;
302
303     // If prefetch is disabled, kill the request.
304     if (!prefetch::IsPrefetchEnabled(resource_context))
305       return false;
306   }
307
308   return true;
309 }
310
311 void ChromeResourceDispatcherHostDelegate::RequestBeginning(
312     net::URLRequest* request,
313     content::ResourceContext* resource_context,
314     content::AppCacheService* appcache_service,
315     ResourceType resource_type,
316     ScopedVector<content::ResourceThrottle>* throttles) {
317   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
318   bool is_prerendering =
319       info->GetVisibilityState() == blink::WebPageVisibilityStatePrerender;
320   if (is_prerendering) {
321     // Requests with the IGNORE_LIMITS flag set (i.e., sync XHRs)
322     // should remain at MAXIMUM_PRIORITY.
323     if (request->load_flags() & net::LOAD_IGNORE_LIMITS) {
324       DCHECK_EQ(request->priority(), net::MAXIMUM_PRIORITY);
325     } else {
326       request->SetPriority(net::IDLE);
327     }
328   }
329
330   ProfileIOData* io_data = ProfileIOData::FromResourceContext(
331       resource_context);
332
333 #if defined(OS_ANDROID)
334   // TODO(davidben): This is insufficient to integrate with prerender properly.
335   // https://crbug.com/370595
336   if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME && !is_prerendering) {
337     throttles->push_back(
338         InterceptNavigationDelegate::CreateThrottleFor(request));
339   }
340 #else
341   if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME) {
342     // Redirect some navigations to apps that have registered matching URL
343     // handlers ('url_handlers' in the manifest).
344     content::ResourceThrottle* url_to_app_throttle =
345         AppUrlRedirector::MaybeCreateThrottleFor(request, io_data);
346     if (url_to_app_throttle)
347       throttles->push_back(url_to_app_throttle);
348
349     if (!is_prerendering) {
350       // Experimental: Launch ephemeral apps from search results.
351       content::ResourceThrottle* ephemeral_app_throttle =
352           EphemeralAppThrottle::MaybeCreateThrottleForLaunch(
353               request, io_data);
354       if (ephemeral_app_throttle)
355         throttles->push_back(ephemeral_app_throttle);
356     }
357   }
358 #endif
359
360 #if defined(OS_CHROMEOS)
361   // Check if we need to add offline throttle. This should be done only
362   // for main frames.
363   if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME) {
364     // We check offline first, then check safe browsing so that we still can
365     // block unsafe site after we remove offline page.
366     throttles->push_back(new OfflineResourceThrottle(request,
367                                                      appcache_service));
368   }
369
370   // Check if we need to add merge session throttle. This throttle will postpone
371   // loading of main frames and XHR request.
372   if (resource_type == content::RESOURCE_TYPE_MAIN_FRAME ||
373       resource_type == content::RESOURCE_TYPE_XHR) {
374     // Add interstitial page while merge session process (cookie
375     // reconstruction from OAuth2 refresh token in ChromeOS login) is still in
376     // progress while we are attempting to load a google property.
377     if (!MergeSessionThrottle::AreAllSessionMergedAlready() &&
378         request->url().SchemeIsHTTPOrHTTPS()) {
379       throttles->push_back(new MergeSessionThrottle(request, resource_type));
380     }
381   }
382 #endif
383
384   // Don't attempt to append headers to requests that have already started.
385   // TODO(stevet): Remove this once the request ordering issues are resolved
386   // in crbug.com/128048.
387   if (!request->is_pending()) {
388     net::HttpRequestHeaders headers;
389     headers.CopyFrom(request->extra_request_headers());
390     bool is_off_the_record = io_data->IsOffTheRecord();
391     variations::VariationsHttpHeaderProvider::GetInstance()->
392         AppendHeaders(request->url(),
393                       is_off_the_record,
394                       !is_off_the_record &&
395                           io_data->GetMetricsEnabledStateOnIOThread(),
396                       &headers);
397     request->SetExtraRequestHeaders(headers);
398   }
399
400 #if defined(ENABLE_ONE_CLICK_SIGNIN)
401   AppendChromeSyncGaiaHeader(request, resource_context);
402 #endif
403
404 #if defined(ENABLE_CONFIGURATION_POLICY)
405   if (io_data->policy_header_helper())
406     io_data->policy_header_helper()->AddPolicyHeaders(request->url(), request);
407 #endif
408
409   signin::AppendMirrorRequestHeaderIfPossible(
410       request, GURL() /* redirect_url */, io_data);
411
412   AppendStandardResourceThrottles(request,
413                                   resource_context,
414                                   resource_type,
415                                   throttles);
416 #if !defined(DISABLE_NACL)
417   if (!is_prerendering) {
418     AppendComponentUpdaterThrottles(request,
419                                     resource_context,
420                                     resource_type,
421                                     throttles);
422   }
423 #endif
424
425   if (io_data->resource_prefetch_predictor_observer()) {
426     io_data->resource_prefetch_predictor_observer()->OnRequestStarted(
427         request, resource_type, info->GetChildID(), info->GetRenderFrameID());
428   }
429 }
430
431 void ChromeResourceDispatcherHostDelegate::DownloadStarting(
432     net::URLRequest* request,
433     content::ResourceContext* resource_context,
434     int child_id,
435     int route_id,
436     int request_id,
437     bool is_content_initiated,
438     bool must_download,
439     ScopedVector<content::ResourceThrottle>* throttles) {
440   BrowserThread::PostTask(
441       BrowserThread::UI, FROM_HERE,
442       base::Bind(&NotifyDownloadInitiatedOnUI, child_id, route_id));
443
444   // If it's from the web, we don't trust it, so we push the throttle on.
445   if (is_content_initiated) {
446     throttles->push_back(
447         new DownloadResourceThrottle(download_request_limiter_.get(),
448                                      child_id,
449                                      route_id,
450                                      request->url(),
451                                      request->method()));
452 #if defined(OS_ANDROID)
453     throttles->push_back(
454         new chrome::InterceptDownloadResourceThrottle(
455             request, child_id, route_id, request_id));
456 #endif
457   }
458
459   // If this isn't a new request, we've seen this before and added the standard
460   //  resource throttles already so no need to add it again.
461   if (!request->is_pending()) {
462     AppendStandardResourceThrottles(request,
463                                     resource_context,
464                                     content::RESOURCE_TYPE_MAIN_FRAME,
465                                     throttles);
466   }
467 }
468
469 ResourceDispatcherHostLoginDelegate*
470     ChromeResourceDispatcherHostDelegate::CreateLoginDelegate(
471         net::AuthChallengeInfo* auth_info, net::URLRequest* request) {
472   return CreateLoginPrompt(auth_info, request);
473 }
474
475 bool ChromeResourceDispatcherHostDelegate::HandleExternalProtocol(
476     const GURL& url,
477     int child_id,
478     int route_id) {
479 #if defined(OS_ANDROID)
480   // Android use a resource throttle to handle external as well as internal
481   // protocols.
482   return false;
483 #else
484
485 #if defined(ENABLE_EXTENSIONS)
486   if (extensions::WebViewRendererState::GetInstance()->IsGuest(child_id))
487     return false;
488
489 #endif  // defined(ENABLE_EXTENSIONS)
490
491   BrowserThread::PostTask(BrowserThread::UI,
492                           FROM_HERE,
493                           base::Bind(&LaunchURL, url, child_id, route_id));
494   return true;
495 #endif
496 }
497
498 void ChromeResourceDispatcherHostDelegate::AppendStandardResourceThrottles(
499     net::URLRequest* request,
500     content::ResourceContext* resource_context,
501     ResourceType resource_type,
502     ScopedVector<content::ResourceThrottle>* throttles) {
503   ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
504 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
505   // Insert safe browsing at the front of the list, so it gets to decide on
506   // policies first.
507   if (io_data->safe_browsing_enabled()->GetValue()
508 #if defined(OS_ANDROID)
509       || io_data->IsDataReductionProxyEnabled()
510 #endif
511   ) {
512     content::ResourceThrottle* throttle =
513         SafeBrowsingResourceThrottleFactory::Create(request,
514                                                     resource_context,
515                                                     resource_type,
516                                                     safe_browsing_.get());
517     if (throttle)
518       throttles->push_back(throttle);
519   }
520 #endif
521
522 #if defined(ENABLE_MANAGED_USERS)
523   bool is_subresource_request =
524       resource_type != content::RESOURCE_TYPE_MAIN_FRAME;
525   throttles->push_back(new SupervisedUserResourceThrottle(
526         request, !is_subresource_request,
527         io_data->supervised_user_url_filter()));
528 #endif
529
530 #if defined(ENABLE_EXTENSIONS)
531   content::ResourceThrottle* throttle =
532       user_script_listener_->CreateResourceThrottle(request->url(),
533                                                     resource_type);
534   if (throttle)
535     throttles->push_back(throttle);
536 #endif
537
538   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
539   if (info->GetVisibilityState() == blink::WebPageVisibilityStatePrerender) {
540     throttles->push_back(new prerender::PrerenderResourceThrottle(request));
541   }
542   if (prerender_tracker_->IsPendingSwapRequestOnIOThread(
543           info->GetChildID(), info->GetRenderFrameID(), request->url())) {
544     throttles->push_back(new prerender::PrerenderPendingSwapThrottle(
545         request, prerender_tracker_));
546   }
547 }
548
549 #if defined(ENABLE_ONE_CLICK_SIGNIN)
550 void ChromeResourceDispatcherHostDelegate::AppendChromeSyncGaiaHeader(
551     net::URLRequest* request,
552     content::ResourceContext* resource_context) {
553   static const char kAllowChromeSignIn[] = "Allow-Chrome-SignIn";
554
555   ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
556   OneClickSigninHelper::Offer offer =
557       OneClickSigninHelper::CanOfferOnIOThread(request, io_data);
558   switch (offer) {
559     case OneClickSigninHelper::CAN_OFFER:
560       request->SetExtraRequestHeaderByName(kAllowChromeSignIn, "1", false);
561       break;
562     case OneClickSigninHelper::DONT_OFFER:
563       request->RemoveRequestHeaderByName(kAllowChromeSignIn);
564       break;
565     case OneClickSigninHelper::IGNORE_REQUEST:
566       break;
567   }
568 }
569 #endif
570
571 bool ChromeResourceDispatcherHostDelegate::ShouldForceDownloadResource(
572     const GURL& url, const std::string& mime_type) {
573 #if defined(ENABLE_EXTENSIONS)
574   // Special-case user scripts to get downloaded instead of viewed.
575   return extensions::UserScript::IsURLUserScript(url, mime_type);
576 #else
577   return false;
578 #endif
579 }
580
581 bool ChromeResourceDispatcherHostDelegate::ShouldInterceptResourceAsStream(
582     net::URLRequest* request,
583     const std::string& mime_type,
584     GURL* origin,
585     std::string* payload) {
586 #if defined(ENABLE_EXTENSIONS)
587   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
588   ProfileIOData* io_data =
589       ProfileIOData::FromResourceContext(info->GetContext());
590   bool profile_is_off_the_record = io_data->IsOffTheRecord();
591   const scoped_refptr<const extensions::InfoMap> extension_info_map(
592       io_data->GetExtensionInfoMap());
593   std::vector<std::string> whitelist = MimeTypesHandler::GetMIMETypeWhitelist();
594   // Go through the white-listed extensions and try to use them to intercept
595   // the URL request.
596   for (size_t i = 0; i < whitelist.size(); ++i) {
597     const char* extension_id = whitelist[i].c_str();
598     const Extension* extension =
599         extension_info_map->extensions().GetByID(extension_id);
600     // The white-listed extension may not be installed, so we have to NULL check
601     // |extension|.
602     if (!extension ||
603         (profile_is_off_the_record &&
604          !extension_info_map->IsIncognitoEnabled(extension_id))) {
605       continue;
606     }
607
608     MimeTypesHandler* handler = MimeTypesHandler::GetHandler(extension);
609     if (handler && handler->CanHandleMIMEType(mime_type)) {
610       StreamTargetInfo target_info;
611       *origin = Extension::GetBaseURLFromExtensionId(extension_id);
612       target_info.extension_id = extension_id;
613       if (!handler->handler_url().empty()) {
614         target_info.view_id = base::GenerateGUID();
615         *payload = origin->spec() + handler->handler_url() +
616             "?id=" + target_info.view_id;
617       }
618       stream_target_info_[request] = target_info;
619       return true;
620     }
621   }
622 #endif
623   return false;
624 }
625
626 void ChromeResourceDispatcherHostDelegate::OnStreamCreated(
627     net::URLRequest* request,
628     scoped_ptr<content::StreamInfo> stream) {
629 #if defined(ENABLE_EXTENSIONS)
630   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
631   std::map<net::URLRequest*, StreamTargetInfo>::iterator ix =
632       stream_target_info_.find(request);
633   CHECK(ix != stream_target_info_.end());
634   content::BrowserThread::PostTask(
635       content::BrowserThread::UI, FROM_HERE,
636       base::Bind(&SendExecuteMimeTypeHandlerEvent, base::Passed(&stream),
637                  request->GetExpectedContentSize(),
638                  info->GetChildID(), info->GetRouteID(),
639                  ix->second.extension_id, ix->second.view_id));
640   stream_target_info_.erase(request);
641 #endif
642 }
643
644 void ChromeResourceDispatcherHostDelegate::OnResponseStarted(
645     net::URLRequest* request,
646     content::ResourceContext* resource_context,
647     content::ResourceResponse* response,
648     IPC::Sender* sender) {
649   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
650
651 #if defined(OS_ANDROID)
652   // See if the response contains the X-Auto-Login header.  If so, this was
653   // a request for a login page, and the server is allowing the browser to
654   // suggest auto-login, if available.
655   if (info->IsMainFrame()) {
656     AutoLoginPrompter::ShowInfoBarIfPossible(request, info->GetChildID(),
657                                              info->GetRouteID());
658   }
659 #endif
660
661   ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
662
663 #if defined(ENABLE_ONE_CLICK_SIGNIN)
664   // See if the response contains the Google-Accounts-SignIn header.  If so,
665   // then the user has just finished signing in, and the server is allowing the
666   // browser to suggest connecting the user's profile to the account.
667   OneClickSigninHelper::ShowInfoBarIfPossible(request, io_data,
668                                               info->GetChildID(),
669                                               info->GetRouteID());
670 #endif
671
672   // See if the response contains the X-Chrome-Manage-Accounts header. If so
673   // show the profile avatar bubble so that user can complete signin/out action
674   // the native UI.
675   signin::ProcessMirrorResponseHeaderIfExists(request, io_data,
676                                               info->GetChildID(),
677                                               info->GetRouteID());
678
679   // Build in additional protection for the chrome web store origin.
680 #if defined(ENABLE_EXTENSIONS)
681   GURL webstore_url(extension_urls::GetWebstoreLaunchURL());
682   if (request->url().DomainIs(webstore_url.host().c_str())) {
683     net::HttpResponseHeaders* response_headers = request->response_headers();
684     if (!response_headers->HasHeaderValue("x-frame-options", "deny") &&
685         !response_headers->HasHeaderValue("x-frame-options", "sameorigin")) {
686       response_headers->RemoveHeader("x-frame-options");
687       response_headers->AddHeader("x-frame-options: sameorigin");
688     }
689   }
690 #endif
691
692   if (io_data->resource_prefetch_predictor_observer())
693     io_data->resource_prefetch_predictor_observer()->OnResponseStarted(request);
694
695   // Ignores x-frame-options for the chrome signin UI.
696   const std::string request_spec(
697       request->first_party_for_cookies().GetOrigin().spec());
698 #if defined(OS_CHROMEOS)
699   if (request_spec == chrome::kChromeUIOobeURL ||
700       request_spec == chrome::kChromeUIChromeSigninURL) {
701 #else
702   if (request_spec == chrome::kChromeUIChromeSigninURL) {
703 #endif
704     net::HttpResponseHeaders* response_headers = request->response_headers();
705     if (response_headers && response_headers->HasHeader("x-frame-options"))
706       response_headers->RemoveHeader("x-frame-options");
707   }
708
709   prerender::URLRequestResponseStarted(request);
710 }
711
712 void ChromeResourceDispatcherHostDelegate::OnRequestRedirected(
713     const GURL& redirect_url,
714     net::URLRequest* request,
715     content::ResourceContext* resource_context,
716     content::ResourceResponse* response) {
717   ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
718
719 #if defined(ENABLE_ONE_CLICK_SIGNIN)
720   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
721
722   // See if the response contains the Google-Accounts-SignIn header.  If so,
723   // then the user has just finished signing in, and the server is allowing the
724   // browser to suggest connecting the user's profile to the account.
725   OneClickSigninHelper::ShowInfoBarIfPossible(request, io_data,
726                                               info->GetChildID(),
727                                               info->GetRouteID());
728   AppendChromeSyncGaiaHeader(request, resource_context);
729 #endif
730
731   // In the Mirror world, Chrome should append a X-Chrome-Connected header to
732   // all Gaia requests from a connected profile so Gaia could return a 204
733   // response and let Chrome handle the action with native UI. The only
734   // exception is requests from gaia webview, since the native profile
735   // management UI is built on top of it.
736   signin::AppendMirrorRequestHeaderIfPossible(request, redirect_url, io_data);
737
738   if (io_data->resource_prefetch_predictor_observer()) {
739     io_data->resource_prefetch_predictor_observer()->OnRequestRedirected(
740         redirect_url, request);
741   }
742
743 #if defined(ENABLE_CONFIGURATION_POLICY)
744   if (io_data->policy_header_helper())
745     io_data->policy_header_helper()->AddPolicyHeaders(redirect_url, request);
746 #endif
747 }
748
749 // Notification that a request has completed.
750 void ChromeResourceDispatcherHostDelegate::RequestComplete(
751     net::URLRequest* url_request) {
752   // Jump on the UI thread and inform the prerender about the bytes.
753   const ResourceRequestInfo* info =
754       ResourceRequestInfo::ForRequest(url_request);
755   if (url_request && !url_request->was_cached()) {
756     BrowserThread::PostTask(BrowserThread::UI,
757                             FROM_HERE,
758                             base::Bind(&UpdatePrerenderNetworkBytesCallback,
759                                        info->GetChildID(),
760                                        info->GetRouteID(),
761                                        url_request->GetTotalReceivedBytes()));
762   }
763 }
764
765 // static
766 void ChromeResourceDispatcherHostDelegate::
767     SetExternalProtocolHandlerDelegateForTesting(
768     ExternalProtocolHandler::Delegate* delegate) {
769   g_external_protocol_handler_delegate = delegate;
770 }