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