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