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