a46608e49f95cf9e54bc3066b31475b9bc220780
[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                bool user_gesture) {
195   // If there is no longer a WebContents, the request may have raced with tab
196   // closing. Don't fire the external request. (It may have been a prerender.)
197   content::WebContents* web_contents =
198       tab_util::GetWebContentsByID(render_process_id, render_view_id);
199   if (!web_contents)
200     return;
201
202   // Do not launch external requests attached to unswapped prerenders.
203   prerender::PrerenderContents* prerender_contents =
204       prerender::PrerenderContents::FromWebContents(web_contents);
205   if (prerender_contents) {
206     prerender_contents->Destroy(prerender::FINAL_STATUS_UNSUPPORTED_SCHEME);
207     prerender::ReportPrerenderExternalURL();
208     return;
209   }
210
211   ExternalProtocolHandler::LaunchUrlWithDelegate(
212       url, render_process_id, render_view_id,
213       g_external_protocol_handler_delegate,
214       user_gesture);
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     bool initiated_by_user_gesture) {
450 #if defined(OS_ANDROID)
451   // Android use a resource throttle to handle external as well as internal
452   // protocols.
453   return false;
454 #else
455
456   ExtensionRendererState::WebViewInfo info;
457   if (ExtensionRendererState::GetInstance()->GetWebViewInfo(child_id,
458                                                             route_id,
459                                                             &info)) {
460     return false;
461   }
462
463   BrowserThread::PostTask(
464       BrowserThread::UI, FROM_HERE,
465       base::Bind(&LaunchURL, url, child_id, route_id,
466                  initiated_by_user_gesture));
467   return true;
468 #endif
469 }
470
471 void ChromeResourceDispatcherHostDelegate::AppendStandardResourceThrottles(
472     net::URLRequest* request,
473     content::ResourceContext* resource_context,
474     ResourceType::Type resource_type,
475     ScopedVector<content::ResourceThrottle>* throttles) {
476   ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
477 #if defined(FULL_SAFE_BROWSING) || defined(MOBILE_SAFE_BROWSING)
478   // Insert safe browsing at the front of the list, so it gets to decide on
479   // policies first.
480   if (io_data->safe_browsing_enabled()->GetValue()
481 #if defined(OS_ANDROID)
482       || io_data->data_reduction_proxy_enabled()->GetValue()
483 #endif
484   ) {
485     bool is_subresource_request = resource_type != ResourceType::MAIN_FRAME;
486     content::ResourceThrottle* throttle =
487         SafeBrowsingResourceThrottleFactory::Create(request,
488                                                     resource_context,
489                                                     is_subresource_request,
490                                                     safe_browsing_.get());
491     if (throttle)
492       throttles->push_back(throttle);
493   }
494 #endif
495
496 #if defined(ENABLE_MANAGED_USERS)
497   bool is_subresource_request = resource_type != ResourceType::MAIN_FRAME;
498   throttles->push_back(new SupervisedUserResourceThrottle(
499         request, !is_subresource_request,
500         io_data->supervised_user_url_filter()));
501 #endif
502
503   content::ResourceThrottle* throttle =
504       user_script_listener_->CreateResourceThrottle(request->url(),
505                                                     resource_type);
506   if (throttle)
507     throttles->push_back(throttle);
508
509   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
510   if (info->GetVisibilityState() == blink::WebPageVisibilityStatePrerender) {
511     throttles->push_back(new prerender::PrerenderResourceThrottle(request));
512   }
513   if (prerender_tracker_->IsPendingSwapRequestOnIOThread(
514           info->GetChildID(), info->GetRenderFrameID(), request->url())) {
515     throttles->push_back(new prerender::PrerenderPendingSwapThrottle(
516         request, prerender_tracker_));
517   }
518 }
519
520 #if defined(ENABLE_ONE_CLICK_SIGNIN)
521 void ChromeResourceDispatcherHostDelegate::AppendChromeSyncGaiaHeader(
522     net::URLRequest* request,
523     content::ResourceContext* resource_context) {
524   static const char kAllowChromeSignIn[] = "Allow-Chrome-SignIn";
525
526   ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
527   OneClickSigninHelper::Offer offer =
528       OneClickSigninHelper::CanOfferOnIOThread(request, io_data);
529   switch (offer) {
530     case OneClickSigninHelper::CAN_OFFER:
531       request->SetExtraRequestHeaderByName(kAllowChromeSignIn, "1", false);
532       break;
533     case OneClickSigninHelper::DONT_OFFER:
534       request->RemoveRequestHeaderByName(kAllowChromeSignIn);
535       break;
536     case OneClickSigninHelper::IGNORE_REQUEST:
537       break;
538   }
539 }
540 #endif
541
542 bool ChromeResourceDispatcherHostDelegate::ShouldForceDownloadResource(
543     const GURL& url, const std::string& mime_type) {
544   // Special-case user scripts to get downloaded instead of viewed.
545   return extensions::UserScript::IsURLUserScript(url, mime_type);
546 }
547
548 bool ChromeResourceDispatcherHostDelegate::ShouldInterceptResourceAsStream(
549     net::URLRequest* request,
550     const std::string& mime_type,
551     GURL* origin,
552     std::string* payload) {
553 #if !defined(OS_ANDROID)
554   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
555   ProfileIOData* io_data =
556       ProfileIOData::FromResourceContext(info->GetContext());
557   bool profile_is_off_the_record = io_data->IsOffTheRecord();
558   const scoped_refptr<const extensions::InfoMap> extension_info_map(
559       io_data->GetExtensionInfoMap());
560   std::vector<std::string> whitelist = MimeTypesHandler::GetMIMETypeWhitelist();
561   // Go through the white-listed extensions and try to use them to intercept
562   // the URL request.
563   for (size_t i = 0; i < whitelist.size(); ++i) {
564     const char* extension_id = whitelist[i].c_str();
565     const Extension* extension =
566         extension_info_map->extensions().GetByID(extension_id);
567     // The white-listed extension may not be installed, so we have to NULL check
568     // |extension|.
569     if (!extension ||
570         (profile_is_off_the_record &&
571          !extension_info_map->IsIncognitoEnabled(extension_id))) {
572       continue;
573     }
574
575     MimeTypesHandler* handler = MimeTypesHandler::GetHandler(extension);
576     if (handler && handler->CanHandleMIMEType(mime_type)) {
577       StreamTargetInfo target_info;
578       *origin = Extension::GetBaseURLFromExtensionId(extension_id);
579       target_info.extension_id = extension_id;
580       if (!handler->handler_url().empty()) {
581         target_info.view_id = base::GenerateGUID();
582         *payload = origin->spec() + handler->handler_url() +
583             "?id=" + target_info.view_id;
584       }
585       stream_target_info_[request] = target_info;
586       return true;
587     }
588   }
589 #endif
590   return false;
591 }
592
593 void ChromeResourceDispatcherHostDelegate::OnStreamCreated(
594     net::URLRequest* request,
595     scoped_ptr<content::StreamHandle> stream) {
596 #if !defined(OS_ANDROID)
597   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
598   std::map<net::URLRequest*, StreamTargetInfo>::iterator ix =
599       stream_target_info_.find(request);
600   CHECK(ix != stream_target_info_.end());
601   content::BrowserThread::PostTask(
602       content::BrowserThread::UI, FROM_HERE,
603       base::Bind(&SendExecuteMimeTypeHandlerEvent, base::Passed(&stream),
604                  request->GetExpectedContentSize(),
605                  info->GetChildID(), info->GetRouteID(),
606                  ix->second.extension_id, ix->second.view_id));
607   stream_target_info_.erase(request);
608 #endif
609 }
610
611 void ChromeResourceDispatcherHostDelegate::OnResponseStarted(
612     net::URLRequest* request,
613     content::ResourceContext* resource_context,
614     content::ResourceResponse* response,
615     IPC::Sender* sender) {
616   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
617
618 #if defined(OS_ANDROID)
619   // See if the response contains the X-Auto-Login header.  If so, this was
620   // a request for a login page, and the server is allowing the browser to
621   // suggest auto-login, if available.
622   AutoLoginPrompter::ShowInfoBarIfPossible(request, info->GetChildID(),
623                                            info->GetRouteID());
624 #endif
625
626   ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
627
628 #if defined(ENABLE_ONE_CLICK_SIGNIN)
629   // See if the response contains the Google-Accounts-SignIn header.  If so,
630   // then the user has just finished signing in, and the server is allowing the
631   // browser to suggest connecting the user's profile to the account.
632   OneClickSigninHelper::ShowInfoBarIfPossible(request, io_data,
633                                               info->GetChildID(),
634                                               info->GetRouteID());
635 #endif
636
637   // See if the response contains the X-Chrome-Manage-Accounts header. If so
638   // show the profile avatar bubble so that user can complete signin/out action
639   // the native UI.
640   signin::ProcessMirrorResponseHeaderIfExists(request, io_data,
641                                               info->GetChildID(),
642                                               info->GetRouteID());
643
644   // Build in additional protection for the chrome web store origin.
645   GURL webstore_url(extension_urls::GetWebstoreLaunchURL());
646   if (request->url().DomainIs(webstore_url.host().c_str())) {
647     net::HttpResponseHeaders* response_headers = request->response_headers();
648     if (!response_headers->HasHeaderValue("x-frame-options", "deny") &&
649         !response_headers->HasHeaderValue("x-frame-options", "sameorigin")) {
650       response_headers->RemoveHeader("x-frame-options");
651       response_headers->AddHeader("x-frame-options: sameorigin");
652     }
653   }
654
655   // Ignores x-frame-options for the chrome signin UI.
656   const std::string request_spec(
657       request->first_party_for_cookies().GetOrigin().spec());
658 #if defined(OS_CHROMEOS)
659   if (request_spec == chrome::kChromeUIOobeURL ||
660       request_spec == chrome::kChromeUIChromeSigninURL) {
661 #else
662   if (request_spec == chrome::kChromeUIChromeSigninURL) {
663 #endif
664     net::HttpResponseHeaders* response_headers = request->response_headers();
665     if (response_headers && response_headers->HasHeader("x-frame-options"))
666       response_headers->RemoveHeader("x-frame-options");
667   }
668
669   prerender::URLRequestResponseStarted(request);
670 }
671
672 void ChromeResourceDispatcherHostDelegate::OnRequestRedirected(
673     const GURL& redirect_url,
674     net::URLRequest* request,
675     content::ResourceContext* resource_context,
676     content::ResourceResponse* response) {
677   ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
678   const ResourceRequestInfo* info = ResourceRequestInfo::ForRequest(request);
679
680 #if defined(ENABLE_ONE_CLICK_SIGNIN)
681   // See if the response contains the Google-Accounts-SignIn header.  If so,
682   // then the user has just finished signing in, and the server is allowing the
683   // browser to suggest connecting the user's profile to the account.
684   OneClickSigninHelper::ShowInfoBarIfPossible(request, io_data,
685                                               info->GetChildID(),
686                                               info->GetRouteID());
687   AppendChromeSyncGaiaHeader(request, resource_context);
688 #endif
689
690   // In the Mirror world, Chrome should append a X-Chrome-Connected header to
691   // all Gaia requests from a connected profile so Gaia could return a 204
692   // response and let Chrome handle the action with native UI. The only
693   // exception is requests from gaia webview, since the native profile
694   // management UI is built on top of it.
695   signin::AppendMirrorRequestHeaderIfPossible(request, redirect_url, io_data,
696       info->GetChildID(), info->GetRouteID());
697
698 #if defined(ENABLE_CONFIGURATION_POLICY)
699   if (io_data->policy_header_helper())
700     io_data->policy_header_helper()->AddPolicyHeaders(redirect_url, request);
701 #endif
702 }
703
704 // Notification that a request has completed.
705 void ChromeResourceDispatcherHostDelegate::RequestComplete(
706     net::URLRequest* url_request) {
707   // Jump on the UI thread and inform the prerender about the bytes.
708   const ResourceRequestInfo* info =
709       ResourceRequestInfo::ForRequest(url_request);
710   if (url_request && !url_request->was_cached()) {
711     BrowserThread::PostTask(BrowserThread::UI,
712                             FROM_HERE,
713                             base::Bind(&UpdatePrerenderNetworkBytesCallback,
714                                        info->GetChildID(),
715                                        info->GetRouteID(),
716                                        url_request->GetTotalReceivedBytes()));
717   }
718 }
719
720 // static
721 void ChromeResourceDispatcherHostDelegate::
722     SetExternalProtocolHandlerDelegateForTesting(
723     ExternalProtocolHandler::Delegate* delegate) {
724   g_external_protocol_handler_delegate = delegate;
725 }