chrome_content_browser_client.cc revision a36e5920737c6adbddd3e43b760e5de8431db6e0
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/chrome_content_browser_client.h"
6
7#include <set>
8#include <utility>
9#include <vector>
10
11#include "base/bind.h"
12#include "base/command_line.h"
13#include "base/lazy_instance.h"
14#include "base/path_service.h"
15#include "base/prefs/pref_service.h"
16#include "base/strings/string_number_conversions.h"
17#include "base/strings/utf_string_conversions.h"
18#include "base/threading/sequenced_worker_pool.h"
19#include "chrome/app/breakpad_mac.h"
20#include "chrome/browser/app_mode/app_mode_utils.h"
21#include "chrome/browser/browser_about_handler.h"
22#include "chrome/browser/browser_process.h"
23#include "chrome/browser/browser_shutdown.h"
24#include "chrome/browser/browsing_data/browsing_data_helper.h"
25#include "chrome/browser/browsing_data/browsing_data_remover.h"
26#include "chrome/browser/character_encoding.h"
27#include "chrome/browser/chrome_net_benchmarking_message_filter.h"
28#include "chrome/browser/chrome_quota_permission_context.h"
29#include "chrome/browser/content_settings/content_settings_utils.h"
30#include "chrome/browser/content_settings/cookie_settings.h"
31#include "chrome/browser/content_settings/host_content_settings_map.h"
32#include "chrome/browser/content_settings/tab_specific_content_settings.h"
33#include "chrome/browser/defaults.h"
34#include "chrome/browser/download/download_util.h"
35#include "chrome/browser/extensions/activity_log/activity_log.h"
36#include "chrome/browser/extensions/api/web_request/web_request_api.h"
37#include "chrome/browser/extensions/browser_permissions_policy_delegate.h"
38#include "chrome/browser/extensions/extension_host.h"
39#include "chrome/browser/extensions/extension_info_map.h"
40#include "chrome/browser/extensions/extension_process_manager.h"
41#include "chrome/browser/extensions/extension_service.h"
42#include "chrome/browser/extensions/extension_system.h"
43#include "chrome/browser/extensions/extension_web_ui.h"
44#include "chrome/browser/extensions/extension_webkit_preferences.h"
45#include "chrome/browser/extensions/suggest_permission_util.h"
46#include "chrome/browser/geolocation/chrome_access_token_store.h"
47#include "chrome/browser/google/google_util.h"
48#include "chrome/browser/guestview/adview/adview_guest.h"
49#include "chrome/browser/guestview/guestview_constants.h"
50#include "chrome/browser/guestview/webview/webview_guest.h"
51#include "chrome/browser/media/media_capture_devices_dispatcher.h"
52#include "chrome/browser/metrics/chrome_browser_main_extra_parts_metrics.h"
53#include "chrome/browser/nacl_host/nacl_host_message_filter.h"
54#include "chrome/browser/nacl_host/nacl_process_host.h"
55#include "chrome/browser/net/chrome_net_log.h"
56#include "chrome/browser/notifications/desktop_notification_service.h"
57#include "chrome/browser/notifications/desktop_notification_service_factory.h"
58#include "chrome/browser/platform_util.h"
59#include "chrome/browser/plugins/plugin_info_message_filter.h"
60#include "chrome/browser/prefs/scoped_user_pref_update.h"
61#include "chrome/browser/prerender/prerender_final_status.h"
62#include "chrome/browser/prerender/prerender_manager.h"
63#include "chrome/browser/prerender/prerender_manager_factory.h"
64#include "chrome/browser/prerender/prerender_message_filter.h"
65#include "chrome/browser/prerender/prerender_tracker.h"
66#include "chrome/browser/printing/printing_message_filter.h"
67#include "chrome/browser/profiles/chrome_browser_main_extra_parts_profiles.h"
68#include "chrome/browser/profiles/profile.h"
69#include "chrome/browser/profiles/profile_io_data.h"
70#include "chrome/browser/profiles/profile_manager.h"
71#include "chrome/browser/renderer_host/chrome_render_message_filter.h"
72#include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
73#include "chrome/browser/search/instant_service.h"
74#include "chrome/browser/search/instant_service_factory.h"
75#include "chrome/browser/search/search.h"
76#include "chrome/browser/search_engines/search_provider_install_state_message_filter.h"
77#include "chrome/browser/speech/chrome_speech_recognition_manager_delegate.h"
78#include "chrome/browser/speech/tts_message_filter.h"
79#include "chrome/browser/ssl/ssl_add_certificate.h"
80#include "chrome/browser/ssl/ssl_blocking_page.h"
81#include "chrome/browser/ssl/ssl_tab_helper.h"
82#include "chrome/browser/tab_contents/tab_util.h"
83#include "chrome/browser/ui/chrome_select_file_policy.h"
84#include "chrome/browser/ui/sync/sync_promo_ui.h"
85#include "chrome/browser/ui/tab_contents/chrome_web_contents_view_delegate.h"
86#include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
87#include "chrome/browser/user_style_sheet_watcher.h"
88#include "chrome/browser/user_style_sheet_watcher_factory.h"
89#include "chrome/browser/validation_message_message_filter.h"
90#include "chrome/common/child_process_logging.h"
91#include "chrome/common/chrome_constants.h"
92#include "chrome/common/chrome_paths.h"
93#include "chrome/common/chrome_switches.h"
94#include "chrome/common/extensions/background_info.h"
95#include "chrome/common/extensions/extension.h"
96#include "chrome/common/extensions/extension_process_policy.h"
97#include "chrome/common/extensions/extension_set.h"
98#include "chrome/common/extensions/manifest_handlers/app_isolation_info.h"
99#include "chrome/common/extensions/manifest_handlers/shared_module_info.h"
100#include "chrome/common/extensions/permissions/permissions_data.h"
101#include "chrome/common/extensions/permissions/socket_permission.h"
102#include "chrome/common/logging_chrome.h"
103#include "chrome/common/pepper_permission_util.h"
104#include "chrome/common/pref_names.h"
105#include "chrome/common/render_messages.h"
106#include "chrome/common/url_constants.h"
107#include "chromeos/chromeos_constants.h"
108#include "components/nacl/common/nacl_process_type.h"
109#include "components/user_prefs/pref_registry_syncable.h"
110#include "content/public/browser/browser_child_process_host.h"
111#include "content/public/browser/browser_main_parts.h"
112#include "content/public/browser/browser_ppapi_host.h"
113#include "content/public/browser/browser_thread.h"
114#include "content/public/browser/browser_url_handler.h"
115#include "content/public/browser/child_process_data.h"
116#include "content/public/browser/child_process_security_policy.h"
117#include "content/public/browser/compositor_util.h"
118#include "content/public/browser/render_process_host.h"
119#include "content/public/browser/render_view_host.h"
120#include "content/public/browser/resource_context.h"
121#include "content/public/browser/site_instance.h"
122#include "content/public/browser/web_contents.h"
123#include "content/public/browser/web_contents_view.h"
124#include "content/public/common/child_process_host.h"
125#include "content/public/common/content_descriptors.h"
126#include "extensions/browser/view_type_utils.h"
127#include "extensions/common/constants.h"
128#include "extensions/common/switches.h"
129#include "grit/generated_resources.h"
130#include "grit/ui_resources.h"
131#include "net/base/escape.h"
132#include "net/base/mime_util.h"
133#include "net/cookies/canonical_cookie.h"
134#include "net/cookies/cookie_options.h"
135#include "net/ssl/ssl_cert_request_info.h"
136#include "ppapi/host/ppapi_host.h"
137#include "ui/base/l10n/l10n_util.h"
138#include "ui/base/resource/resource_bundle.h"
139#include "ui/message_center/message_center_util.h"
140#include "webkit/browser/fileapi/external_mount_points.h"
141#include "webkit/browser/fileapi/syncable/sync_file_system_backend.h"
142#include "webkit/common/webpreferences.h"
143#include "webkit/plugins/plugin_switches.h"
144
145#if defined(OS_WIN)
146#include "chrome/browser/chrome_browser_main_win.h"
147#include "sandbox/win/src/sandbox_policy.h"
148#elif defined(OS_MACOSX)
149#include "chrome/browser/chrome_browser_main_mac.h"
150#include "chrome/browser/spellchecker/spellcheck_message_filter_mac.h"
151#elif defined(OS_CHROMEOS)
152#include "chrome/browser/chromeos/chrome_browser_main_chromeos.h"
153#include "chrome/browser/chromeos/drive/file_system_backend_delegate.h"
154#include "chrome/browser/chromeos/fileapi/file_system_backend.h"
155#include "chrome/browser/chromeos/login/startup_utils.h"
156#include "chrome/browser/chromeos/login/user_manager.h"
157#include "chrome/browser/chromeos/system/input_device_settings.h"
158#include "chromeos/chromeos_switches.h"
159#elif defined(OS_LINUX)
160#include "chrome/browser/chrome_browser_main_linux.h"
161#elif defined(OS_ANDROID)
162#include "chrome/browser/android/crash_dump_manager.h"
163#include "chrome/browser/chrome_browser_main_android.h"
164#include "chrome/common/descriptors_android.h"
165#elif defined(OS_POSIX)
166#include "chrome/browser/chrome_browser_main_posix.h"
167#endif
168
169#if defined(OS_LINUX) || defined(OS_OPENBSD) || defined(OS_ANDROID)
170#include "base/linux_util.h"
171#include "chrome/browser/crash_handler_host_linux.h"
172#endif
173
174#if !defined(OS_ANDROID)
175#include "chrome/browser/ui/blocked_content/popup_blocker_tab_helper.h"
176#endif
177
178#if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
179#include "chrome/browser/captive_portal/captive_portal_tab_helper.h"
180#endif
181
182#if defined(OS_ANDROID)
183#include "ui/base/ui_base_paths.h"
184#endif
185
186#if defined(USE_NSS)
187#include "chrome/browser/ui/crypto_module_password_dialog.h"
188#endif
189
190#if !defined(OS_CHROMEOS)
191#include "chrome/browser/signin/signin_manager.h"
192#include "chrome/browser/signin/signin_manager_factory.h"
193#endif
194
195#if !defined(OS_ANDROID)
196#include "chrome/browser/media_galleries/fileapi/media_file_system_backend.h"
197#endif
198
199#if defined(ENABLE_WEBRTC)
200#include "chrome/browser/media/webrtc_logging_handler_host.h"
201#endif
202
203#if defined(ENABLE_INPUT_SPEECH)
204#include "chrome/browser/speech/chrome_speech_recognition_manager_delegate_bubble_ui.h"
205#endif
206
207#if defined(FILE_MANAGER_EXTENSION)
208#include "chrome/browser/chromeos/extensions/file_manager/file_manager_util.h"
209#endif
210
211#if defined(TOOLKIT_GTK)
212#include "chrome/browser/ui/gtk/chrome_browser_main_extra_parts_gtk.h"
213#endif
214
215#if defined(TOOLKIT_VIEWS)
216#include "chrome/browser/ui/views/chrome_browser_main_extra_parts_views.h"
217#endif
218
219#if defined(USE_ASH)
220#include "chrome/browser/ui/views/ash/chrome_browser_main_extra_parts_ash.h"
221#endif
222
223#if defined(USE_AURA)
224#include "chrome/browser/ui/aura/chrome_browser_main_extra_parts_aura.h"
225#endif
226
227#if defined(USE_X11)
228#include "chrome/browser/chrome_browser_main_extra_parts_x11.h"
229#endif
230
231#if defined(ENABLE_SPELLCHECK)
232#include "chrome/browser/spellchecker/spellcheck_message_filter.h"
233#endif
234
235using WebKit::WebWindowFeatures;
236using base::FileDescriptor;
237using content::AccessTokenStore;
238using content::BrowserChildProcessHostIterator;
239using content::BrowserThread;
240using content::BrowserURLHandler;
241using content::ChildProcessSecurityPolicy;
242using content::FileDescriptorInfo;
243using content::QuotaPermissionContext;
244using content::RenderViewHost;
245using content::SiteInstance;
246using content::WebContents;
247using extensions::APIPermission;
248using extensions::Extension;
249using extensions::Manifest;
250using message_center::NotifierId;
251
252namespace {
253
254// Cached version of the locale so we can return the locale on the I/O
255// thread.
256base::LazyInstance<std::string> g_io_thread_application_locale;
257
258#if defined(ENABLE_PLUGINS)
259const char* kPredefinedAllowedSocketOrigins[] = {
260  "okddffdblfhhnmhodogpojmfkjmhinfp",  // Test SSH Client
261  "pnhechapfaindjhompbnflcldabbghjo",  // HTerm App (SSH Client)
262  "bglhmjfplikpjnfoegeomebmfnkjomhe",  // see crbug.com/122126
263  "gbchcmhmhahfdphkhkmpfmihenigjmpp",  // Chrome Remote Desktop
264  "kgngmbheleoaphbjbaiobfdepmghbfah",  // Pre-release Chrome Remote Desktop
265  "odkaodonbgfohohmklejpjiejmcipmib",  // Dogfood Chrome Remote Desktop
266  "ojoimpklfciegopdfgeenehpalipignm",  // Chromoting canary
267  "cbkkbcmdlboombapidmoeolnmdacpkch",  // see crbug.com/129089
268  "hhnbmknkdabfoieppbbljkhkfjcmcbjh",  // see crbug.com/134099
269  "mablfbjkhmhkmefkjjacnbaikjkipphg",  // see crbug.com/134099
270  "pdeelgamlgannhelgoegilelnnojegoh",  // see crbug.com/134099
271  "cabapfdbkniadpollkckdnedaanlciaj",  // see crbug.com/134099
272  "mapljbgnjledlpdmlchihnmeclmefbba",  // see crbug.com/134099
273  "ghbfeebgmiidnnmeobbbaiamklmpbpii",  // see crbug.com/134099
274  "jdfhpkjeckflbbleddjlpimecpbjdeep",  // see crbug.com/142514
275  "iabmpiboiopbgfabjmgeedhcmjenhbla",  // see crbug.com/165080
276  "B7CF8A292249681AF81771650BA4CEEAF19A4560", // see crbug.com/165080
277  "6EAED1924DB611B6EEF2A664BD077BE7EAD33B8F", // see crbug.com/234789
278  "7525AF4F66763A70A883C4700529F647B470E4D2", // see crbug.com/238084
279  "0B549507088E1564D672F7942EB87CA4DAD73972", // see crbug.com/238084
280  "864288364E239573E777D3E0E36864E590E95C74"  // see crbug.com/238084
281};
282#endif
283
284// Returns a copy of the given url with its host set to given host and path set
285// to given path. Other parts of the url will be the same.
286GURL ReplaceURLHostAndPath(const GURL& url,
287                           const std::string& host,
288                           const std::string& path) {
289  url_canon::Replacements<char> replacements;
290  replacements.SetHost(host.c_str(),
291                       url_parse::Component(0, host.length()));
292  replacements.SetPath(path.c_str(),
293                       url_parse::Component(0, path.length()));
294  return url.ReplaceComponents(replacements);
295}
296
297// Maps "foo://bar/baz/" to "foo://chrome/bar/baz/".
298GURL AddUberHost(const GURL& url) {
299  const std::string uber_host = chrome::kChromeUIUberHost;
300  const std::string new_path = url.host() + url.path();
301
302  return ReplaceURLHostAndPath(url, uber_host, new_path);
303}
304
305// If url->host() is "chrome" and url->path() has characters other than the
306// first slash, changes the url from "foo://chrome/bar/" to "foo://bar/" and
307// returns true. Otherwise returns false.
308bool RemoveUberHost(GURL* url) {
309  if (url->host() != chrome::kChromeUIUberHost)
310    return false;
311
312  if (url->path().empty() || url->path() == "/")
313    return false;
314
315  const std::string old_path = url->path();
316
317  const std::string::size_type separator = old_path.find('/', 1);
318  std::string new_host;
319  std::string new_path;
320  if (separator == std::string::npos) {
321    new_host = old_path.substr(1);
322  } else {
323    new_host = old_path.substr(1, separator - 1);
324    new_path = old_path.substr(separator);
325  }
326
327  // Do not allow URLs with paths empty before the first slash since we can't
328  // have an empty host. (e.g "foo://chrome//")
329  if (new_host.empty())
330    return false;
331
332  *url = ReplaceURLHostAndPath(*url, new_host, new_path);
333
334  DCHECK(url->is_valid());
335
336  return true;
337}
338
339// Handles rewriting Web UI URLs.
340bool HandleWebUI(GURL* url, content::BrowserContext* browser_context) {
341  // Do not handle special URLs such as "about:foo"
342  if (!url->host().empty()) {
343    const GURL chrome_url = AddUberHost(*url);
344
345    // Handle valid "chrome://chrome/foo" URLs so the reverse handler will
346    // be called.
347    if (ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
348            browser_context, chrome_url))
349      return true;
350  }
351
352  if (!ChromeWebUIControllerFactory::GetInstance()->UseWebUIForURL(
353          browser_context, *url))
354    return false;
355
356#if defined(OS_CHROMEOS)
357  // Special case : in ChromeOS in Guest mode bookmarks and history are
358  // disabled for security reasons. New tab page explains the reasons, so
359  // we redirect user to new tab page.
360  if (chromeos::UserManager::Get()->IsLoggedInAsGuest()) {
361    if (url->SchemeIs(chrome::kChromeUIScheme) &&
362        (url->DomainIs(chrome::kChromeUIBookmarksHost) ||
363         url->DomainIs(chrome::kChromeUIHistoryHost))) {
364      // Rewrite with new tab URL
365      *url = GURL(chrome::kChromeUINewTabURL);
366    }
367  }
368#endif
369
370  // Special case the new tab page. In older versions of Chrome, the new tab
371  // page was hosted at chrome-internal:<blah>. This might be in people's saved
372  // sessions or bookmarks, so we say any URL with that scheme triggers the new
373  // tab page.
374  if (url->SchemeIs(chrome::kChromeInternalScheme)) {
375    // Rewrite it with the proper new tab URL.
376    *url = GURL(chrome::kChromeUINewTabURL);
377  }
378
379  return true;
380}
381
382// Reverse URL handler for Web UI. Maps "chrome://chrome/foo/" to
383// "chrome://foo/".
384bool HandleWebUIReverse(GURL* url, content::BrowserContext* browser_context) {
385  if (!url->is_valid() || !url->SchemeIs(chrome::kChromeUIScheme))
386    return false;
387
388  return RemoveUberHost(url);
389}
390
391// Used by the GetPrivilegeRequiredByUrl() and GetProcessPrivilege() functions
392// below.  Extension, and isolated apps require different privileges to be
393// granted to their RenderProcessHosts.  This classification allows us to make
394// sure URLs are served by hosts with the right set of privileges.
395enum RenderProcessHostPrivilege {
396  PRIV_NORMAL,
397  PRIV_HOSTED,
398  PRIV_ISOLATED,
399  PRIV_EXTENSION,
400};
401
402RenderProcessHostPrivilege GetPrivilegeRequiredByUrl(
403    const GURL& url,
404    ExtensionService* service) {
405  // Default to a normal renderer cause it is lower privileged. This should only
406  // occur if the URL on a site instance is either malformed, or uninitialized.
407  // If it is malformed, then there is no need for better privileges anyways.
408  // If it is uninitialized, but eventually settles on being an a scheme other
409  // than normal webrenderer, the navigation logic will correct us out of band
410  // anyways.
411  if (!url.is_valid())
412    return PRIV_NORMAL;
413
414  if (url.SchemeIs(extensions::kExtensionScheme)) {
415    const Extension* extension =
416        service->extensions()->GetByID(url.host());
417    if (extension &&
418        extensions::AppIsolationInfo::HasIsolatedStorage(extension))
419      return PRIV_ISOLATED;
420    if (extension && extension->is_hosted_app())
421      return PRIV_HOSTED;
422
423    return PRIV_EXTENSION;
424  }
425
426  return PRIV_NORMAL;
427}
428
429RenderProcessHostPrivilege GetProcessPrivilege(
430    content::RenderProcessHost* process_host,
431    extensions::ProcessMap* process_map,
432    ExtensionService* service) {
433  std::set<std::string> extension_ids =
434      process_map->GetExtensionsInProcess(process_host->GetID());
435  if (extension_ids.empty())
436    return PRIV_NORMAL;
437
438  for (std::set<std::string>::iterator iter = extension_ids.begin();
439       iter != extension_ids.end(); ++iter) {
440    const Extension* extension = service->GetExtensionById(*iter, false);
441    if (extension &&
442        extensions::AppIsolationInfo::HasIsolatedStorage(extension))
443      return PRIV_ISOLATED;
444    if (extension && extension->is_hosted_app())
445      return PRIV_HOSTED;
446  }
447
448  return PRIV_EXTENSION;
449}
450
451bool CertMatchesFilter(const net::X509Certificate& cert,
452                       const base::DictionaryValue& filter) {
453  // TODO(markusheintz): This is the minimal required filter implementation.
454  // Implement a better matcher.
455
456  // An empty filter matches any client certificate since no requirements are
457  // specified at all.
458  if (filter.empty())
459    return true;
460
461  std::string common_name;
462  if (filter.GetString("ISSUER.CN", &common_name) &&
463      (cert.issuer().common_name == common_name)) {
464    return true;
465  }
466  return false;
467}
468
469// Fills |map| with the per-script font prefs under path |map_name|.
470void FillFontFamilyMap(const PrefService* prefs,
471                       const char* map_name,
472                       webkit_glue::ScriptFontFamilyMap* map) {
473  for (size_t i = 0; i < prefs::kWebKitScriptsForFontFamilyMapsLength; ++i) {
474    const char* script = prefs::kWebKitScriptsForFontFamilyMaps[i];
475    std::string pref_name = base::StringPrintf("%s.%s", map_name, script);
476    std::string font_family = prefs->GetString(pref_name.c_str());
477    if (!font_family.empty())
478      (*map)[script] = UTF8ToUTF16(font_family);
479  }
480}
481
482#if defined(OS_POSIX) && !defined(OS_MACOSX)
483int GetCrashSignalFD(const CommandLine& command_line) {
484  if (command_line.HasSwitch(switches::kExtensionProcess)) {
485    ExtensionCrashHandlerHostLinux* crash_handler =
486        ExtensionCrashHandlerHostLinux::GetInstance();
487    return crash_handler->GetDeathSignalSocket();
488  }
489
490  std::string process_type =
491      command_line.GetSwitchValueASCII(switches::kProcessType);
492
493  if (process_type == switches::kRendererProcess)
494    return RendererCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket();
495
496  if (process_type == switches::kPluginProcess)
497    return PluginCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket();
498
499  if (process_type == switches::kPpapiPluginProcess)
500    return PpapiCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket();
501
502  if (process_type == switches::kGpuProcess)
503    return GpuCrashHandlerHostLinux::GetInstance()->GetDeathSignalSocket();
504
505  return -1;
506}
507#endif  // defined(OS_POSIX) && !defined(OS_MACOSX)
508
509#if !defined(OS_CHROMEOS)
510GURL GetEffectiveURLForSignin(const GURL& url) {
511  CHECK(SigninManager::IsWebBasedSigninFlowURL(url));
512
513  GURL effective_url(SigninManager::kChromeSigninEffectiveSite);
514  // Copy the path because the argument to SetPathStr must outlive
515  // the Replacements object.
516  const std::string path_copy(url.path());
517  GURL::Replacements replacements;
518  replacements.SetPathStr(path_copy);
519  effective_url = effective_url.ReplaceComponents(replacements);
520  return effective_url;
521}
522#endif
523
524void SetApplicationLocaleOnIOThread(const std::string& locale) {
525  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
526  g_io_thread_application_locale.Get() = locale;
527}
528
529#if !defined(OS_ANDROID)
530struct BlockedPopupParams {
531  BlockedPopupParams(const GURL& target_url,
532                     const content::Referrer& referrer,
533                     WindowOpenDisposition disposition,
534                     const WebWindowFeatures& features,
535                     bool user_gesture,
536                     bool opener_suppressed,
537                     int render_process_id,
538                     int opener_id)
539      : target_url(target_url),
540        referrer(referrer),
541        disposition(disposition),
542        features(features),
543        user_gesture(user_gesture),
544        opener_suppressed(opener_suppressed),
545        render_process_id(render_process_id),
546        opener_id(opener_id)
547        {}
548
549  GURL target_url;
550  content::Referrer referrer;
551  WindowOpenDisposition disposition;
552  WebWindowFeatures features;
553  bool user_gesture;
554  bool opener_suppressed;
555  int render_process_id;
556  int opener_id;
557};
558
559void HandleBlockedPopupOnUIThread(const BlockedPopupParams& params) {
560  WebContents* tab =
561      tab_util::GetWebContentsByID(params.render_process_id, params.opener_id);
562  if (!tab)
563    return;
564
565  prerender::PrerenderManager* prerender_manager =
566      prerender::PrerenderManagerFactory::GetForProfile(
567          Profile::FromBrowserContext(tab->GetBrowserContext()));
568  if (prerender_manager) {
569    prerender_manager->DestroyPrerenderForRenderView(
570        params.render_process_id,
571        params.opener_id,
572        prerender::FINAL_STATUS_CREATE_NEW_WINDOW);
573  }
574
575  PopupBlockerTabHelper* popup_helper =
576      PopupBlockerTabHelper::FromWebContents(tab);
577  if (!popup_helper)
578    return;
579  popup_helper->AddBlockedPopup(params.target_url,
580                                params.referrer,
581                                params.disposition,
582                                params.features,
583                                params.user_gesture,
584                                params.opener_suppressed);
585}
586#endif
587
588}  // namespace
589
590namespace chrome {
591
592ChromeContentBrowserClient::ChromeContentBrowserClient() {
593#if defined(ENABLE_PLUGINS)
594  for (size_t i = 0; i < arraysize(kPredefinedAllowedSocketOrigins); ++i)
595    allowed_socket_origins_.insert(kPredefinedAllowedSocketOrigins[i]);
596#endif
597
598  permissions_policy_delegate_.reset(
599      new extensions::BrowserPermissionsPolicyDelegate());
600}
601
602ChromeContentBrowserClient::~ChromeContentBrowserClient() {
603}
604
605// static
606void ChromeContentBrowserClient::RegisterProfilePrefs(
607    user_prefs::PrefRegistrySyncable* registry) {
608  registry->RegisterBooleanPref(
609      prefs::kDisable3DAPIs,
610      false,
611      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
612  registry->RegisterBooleanPref(
613      prefs::kEnableHyperlinkAuditing,
614      true,
615      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
616  registry->RegisterBooleanPref(
617      prefs::kEnableMemoryInfo,
618      false,
619      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
620}
621
622// static
623void ChromeContentBrowserClient::SetApplicationLocale(
624    const std::string& locale) {
625  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
626
627  // This object is guaranteed to outlive all threads so we don't have to
628  // worry about the lack of refcounting and can just post as Unretained.
629  //
630  // The common case is that this function is called early in Chrome startup
631  // before any threads are created (it will also be called later if the user
632  // changes the pref). In this case, there will be no threads created and
633  // posting will fail. When there are no threads, we can just set the string
634  // without worrying about threadsafety.
635  if (!BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
636          base::Bind(&SetApplicationLocaleOnIOThread, locale))) {
637    g_io_thread_application_locale.Get() = locale;
638  }
639}
640
641content::BrowserMainParts* ChromeContentBrowserClient::CreateBrowserMainParts(
642    const content::MainFunctionParams& parameters) {
643  ChromeBrowserMainParts* main_parts;
644  // Construct the Main browser parts based on the OS type.
645#if defined(OS_WIN)
646  main_parts = new ChromeBrowserMainPartsWin(parameters);
647#elif defined(OS_MACOSX)
648  main_parts = new ChromeBrowserMainPartsMac(parameters);
649#elif defined(OS_CHROMEOS)
650  main_parts = new chromeos::ChromeBrowserMainPartsChromeos(parameters);
651#elif defined(OS_LINUX)
652  main_parts = new ChromeBrowserMainPartsLinux(parameters);
653#elif defined(OS_ANDROID)
654  main_parts = new ChromeBrowserMainPartsAndroid(parameters);
655#elif defined(OS_POSIX)
656  main_parts = new ChromeBrowserMainPartsPosix(parameters);
657#else
658  NOTREACHED();
659  main_parts = new ChromeBrowserMainParts(parameters);
660#endif
661
662  chrome::AddProfilesExtraParts(main_parts);
663
664  // Construct additional browser parts. Stages are called in the order in
665  // which they are added.
666#if defined(TOOLKIT_GTK)
667  main_parts->AddParts(new ChromeBrowserMainExtraPartsGtk());
668#endif
669
670#if defined(TOOLKIT_VIEWS)
671  main_parts->AddParts(new ChromeBrowserMainExtraPartsViews());
672#endif
673
674#if defined(USE_ASH)
675  main_parts->AddParts(new ChromeBrowserMainExtraPartsAsh());
676#endif
677
678#if defined(USE_AURA)
679  main_parts->AddParts(new ChromeBrowserMainExtraPartsAura());
680#endif
681
682#if defined(USE_X11)
683  main_parts->AddParts(new ChromeBrowserMainExtraPartsX11());
684#endif
685
686  chrome::AddMetricsExtraParts(main_parts);
687
688  return main_parts;
689}
690
691std::string ChromeContentBrowserClient::GetStoragePartitionIdForSite(
692    content::BrowserContext* browser_context,
693    const GURL& site) {
694  std::string partition_id;
695
696  // The partition ID for webview guest processes is the string value of its
697  // SiteInstance URL - "chrome-guest://app_id/persist?partition".
698  if (site.SchemeIs(chrome::kGuestScheme))
699    partition_id = site.spec();
700
701  DCHECK(IsValidStoragePartitionId(browser_context, partition_id));
702  return partition_id;
703}
704
705bool ChromeContentBrowserClient::IsValidStoragePartitionId(
706    content::BrowserContext* browser_context,
707    const std::string& partition_id) {
708  // The default ID is empty and is always valid.
709  if (partition_id.empty())
710    return true;
711
712  return GURL(partition_id).is_valid();
713}
714
715void ChromeContentBrowserClient::GetStoragePartitionConfigForSite(
716    content::BrowserContext* browser_context,
717    const GURL& site,
718    bool can_be_default,
719    std::string* partition_domain,
720    std::string* partition_name,
721    bool* in_memory) {
722  // Default to the browser-wide storage partition and override based on |site|
723  // below.
724  partition_domain->clear();
725  partition_name->clear();
726  *in_memory = false;
727
728  // For the webview tag, we create special guest processes, which host the
729  // tag content separately from the main application that embeds the tag.
730  // A webview tag can specify both the partition name and whether the storage
731  // for that partition should be persisted. Each tag gets a SiteInstance with
732  // a specially formatted URL, based on the application it is hosted by and
733  // the partition requested by it. The format for that URL is:
734  // chrome-guest://partition_domain/persist?partition_name
735  if (site.SchemeIs(chrome::kGuestScheme)) {
736    // Since guest URLs are only used for packaged apps, there must be an app
737    // id in the URL.
738    CHECK(site.has_host());
739    *partition_domain = site.host();
740    // Since persistence is optional, the path must either be empty or the
741    // literal string.
742    *in_memory = (site.path() != "/persist");
743    // The partition name is user supplied value, which we have encoded when the
744    // URL was created, so it needs to be decoded.
745    *partition_name = net::UnescapeURLComponent(site.query(),
746                                                net::UnescapeRule::NORMAL);
747  } else if (site.SchemeIs(extensions::kExtensionScheme)) {
748    // If |can_be_default| is false, the caller is stating that the |site|
749    // should be parsed as if it had isolated storage. In particular it is
750    // important to NOT check ExtensionService for the is_storage_isolated()
751    // attribute because this code path is run during Extension uninstall
752    // to do cleanup after the Extension has already been unloaded from the
753    // ExtensionService.
754    bool is_isolated = !can_be_default;
755    if (can_be_default) {
756      const Extension* extension = NULL;
757      Profile* profile = Profile::FromBrowserContext(browser_context);
758      ExtensionService* extension_service =
759          extensions::ExtensionSystem::Get(profile)->extension_service();
760      if (extension_service) {
761        extension =
762            extension_service->extensions()->GetExtensionOrAppByURL(site);
763        if (extension &&
764            extensions::AppIsolationInfo::HasIsolatedStorage(extension)) {
765          is_isolated = true;
766        }
767      }
768    }
769
770    if (is_isolated) {
771      CHECK(site.has_host());
772      // For extensions with isolated storage, the the host of the |site| is
773      // the |partition_domain|. The |in_memory| and |partition_name| are only
774      // used in guest schemes so they are cleared here.
775      *partition_domain = site.host();
776      *in_memory = false;
777      partition_name->clear();
778    }
779  }
780
781  // Assert that if |can_be_default| is false, the code above must have found a
782  // non-default partition.  If this fails, the caller has a serious logic
783  // error about which StoragePartition they expect to be in and it is not
784  // safe to continue.
785  CHECK(can_be_default || !partition_domain->empty());
786}
787
788content::WebContentsViewDelegate*
789    ChromeContentBrowserClient::GetWebContentsViewDelegate(
790        content::WebContents* web_contents) {
791  return chrome::CreateWebContentsViewDelegate(web_contents);
792}
793
794// Check if the extension activity log is enabled for the profile.
795static bool IsExtensionActivityLogEnabledForProfile(Profile* profile) {
796  // crbug.com/247908 - This should be IsLogEnabled except for an issue
797  // in chrome_frame_net_tests
798  return extensions::ActivityLog::IsLogEnabledOnAnyProfile();
799}
800
801void ChromeContentBrowserClient::GuestWebContentsCreated(
802    WebContents* guest_web_contents,
803    WebContents* opener_web_contents,
804    content::BrowserPluginGuestDelegate** guest_delegate,
805    scoped_ptr<base::DictionaryValue> extra_params) {
806  if (opener_web_contents) {
807    GuestView* guest = GuestView::FromWebContents(opener_web_contents);
808    if (!guest) {
809      NOTREACHED();
810      return;
811    }
812
813    switch (guest->GetViewType()) {
814      case GuestView::WEBVIEW: {
815        *guest_delegate = new WebViewGuest(guest_web_contents);
816        break;
817      }
818      case GuestView::ADVIEW: {
819        *guest_delegate = new AdViewGuest(guest_web_contents);
820        break;
821      }
822      default:
823        NOTREACHED();
824        break;
825    }
826    return;
827  }
828
829  if (!extra_params) {
830    NOTREACHED();
831    return;
832  }
833  std::string api_type;
834  extra_params->GetString(guestview::kAttributeApi, &api_type);
835
836  if (api_type == "adview") {
837    *guest_delegate  = new AdViewGuest(guest_web_contents);
838  } else if (api_type == "webview") {
839    *guest_delegate = new WebViewGuest(guest_web_contents);
840  } else {
841    NOTREACHED();
842  }
843}
844
845void ChromeContentBrowserClient::GuestWebContentsAttached(
846    WebContents* guest_web_contents,
847    WebContents* embedder_web_contents,
848    int browser_plugin_instance_id,
849    const base::DictionaryValue& extra_params) {
850  Profile* profile = Profile::FromBrowserContext(
851      embedder_web_contents->GetBrowserContext());
852  ExtensionService* service =
853      extensions::ExtensionSystem::Get(profile)->extension_service();
854  if (!service) {
855    NOTREACHED();
856    return;
857  }
858  const GURL& url = embedder_web_contents->GetSiteInstance()->GetSiteURL();
859  const Extension* extension =
860      service->extensions()->GetExtensionOrAppByURL(url);
861  if (!extension) {
862    // It's ok to return here, since we could be running a browser plugin
863    // outside an extension, and don't need to attach a
864    // BrowserPluginGuestDelegate in that case;
865    // e.g. running with flag --enable-browser-plugin-for-all-view-types.
866    return;
867  }
868
869  GuestView* guest = GuestView::FromWebContents(guest_web_contents);
870  if (!guest) {
871    NOTREACHED();
872    return;
873  }
874  guest->Attach(embedder_web_contents,
875                extension->id(),
876                browser_plugin_instance_id,
877                extra_params);
878}
879
880void ChromeContentBrowserClient::RenderProcessHostCreated(
881    content::RenderProcessHost* host) {
882  int id = host->GetID();
883  Profile* profile = Profile::FromBrowserContext(host->GetBrowserContext());
884  net::URLRequestContextGetter* context =
885      profile->GetRequestContextForRenderProcess(id);
886
887  host->GetChannel()->AddFilter(new ChromeRenderMessageFilter(
888      id, profile, context));
889#if defined(ENABLE_PLUGINS)
890  host->GetChannel()->AddFilter(new PluginInfoMessageFilter(id, profile));
891#endif
892#if defined(ENABLE_PRINTING)
893  host->GetChannel()->AddFilter(new PrintingMessageFilter(id, profile));
894#endif
895  host->GetChannel()->AddFilter(
896      new SearchProviderInstallStateMessageFilter(id, profile));
897#if defined(ENABLE_SPELLCHECK)
898  host->GetChannel()->AddFilter(new SpellCheckMessageFilter(id));
899#endif
900#if defined(OS_MACOSX)
901  host->GetChannel()->AddFilter(new SpellCheckMessageFilterMac(id));
902#endif
903  host->GetChannel()->AddFilter(new ChromeNetBenchmarkingMessageFilter(
904      id, profile, context));
905  host->GetChannel()->AddFilter(
906      new prerender::PrerenderMessageFilter(id, profile));
907  host->GetChannel()->AddFilter(new ValidationMessageMessageFilter(id));
908  host->GetChannel()->AddFilter(new TtsMessageFilter(id, profile));
909#if defined(ENABLE_WEBRTC)
910  host->GetChannel()->AddFilter(new WebRtcLoggingHandlerHost());
911#endif
912#if !defined(DISABLE_NACL)
913  ExtensionInfoMap* extension_info_map =
914      extensions::ExtensionSystem::Get(profile)->info_map();
915  host->GetChannel()->AddFilter(new NaClHostMessageFilter(
916      id, profile->IsOffTheRecord(),
917      profile->GetPath(), extension_info_map,
918      context));
919#endif
920
921  host->Send(new ChromeViewMsg_SetIsIncognitoProcess(
922      profile->IsOffTheRecord()));
923
924  host->Send(new ChromeViewMsg_SetExtensionActivityLogEnabled(
925      IsExtensionActivityLogEnabledForProfile(profile)));
926
927  SendExtensionWebRequestStatusToHost(host);
928
929  RendererContentSettingRules rules;
930  GetRendererContentSettingRules(profile->GetHostContentSettingsMap(), &rules);
931  host->Send(new ChromeViewMsg_SetContentSettingRules(rules));
932}
933
934GURL ChromeContentBrowserClient::GetEffectiveURL(
935    content::BrowserContext* browser_context, const GURL& url) {
936  Profile* profile = Profile::FromBrowserContext(browser_context);
937  if (!profile)
938    return url;
939
940  // If the input |url| should be assigned to the Instant renderer, make its
941  // effective URL distinct from other URLs on the search provider's domain.
942  if (chrome::ShouldAssignURLToInstantRenderer(url, profile))
943    return chrome::GetEffectiveURLForInstant(url, profile);
944
945#if !defined(OS_CHROMEOS)
946  // If the input |url| should be assigned to the Signin renderer, make its
947  // effective URL distinct from other URLs on the signin service's domain.
948  // Note that the signin renderer will be allowed to sign the user in to
949  // Chrome.
950  if (SigninManager::IsWebBasedSigninFlowURL(url))
951    return GetEffectiveURLForSignin(url);
952#endif
953
954  // If the input |url| is part of an installed app, the effective URL is an
955  // extension URL with the ID of that extension as the host. This has the
956  // effect of grouping apps together in a common SiteInstance.
957  ExtensionService* extension_service =
958      extensions::ExtensionSystem::Get(profile)->extension_service();
959  if (!extension_service)
960    return url;
961
962  const Extension* extension = extension_service->extensions()->
963      GetHostedAppByURL(url);
964  if (!extension)
965    return url;
966
967  // Bookmark apps do not use the hosted app process model, and should be
968  // treated as normal URLs.
969  if (extension->from_bookmark())
970    return url;
971
972  // If the URL is part of an extension's web extent, convert it to an
973  // extension URL.
974  return extension->GetResourceURL(url.path());
975}
976
977bool ChromeContentBrowserClient::ShouldUseProcessPerSite(
978    content::BrowserContext* browser_context, const GURL& effective_url) {
979  // Non-extension, non-Instant URLs should generally use
980  // process-per-site-instance.  Because we expect to use the effective URL,
981  // URLs for hosted apps (apart from bookmark apps) should have an extension
982  // scheme by now.
983
984  Profile* profile = Profile::FromBrowserContext(browser_context);
985  if (!profile)
986    return false;
987
988  if (chrome::ShouldUseProcessPerSiteForInstantURL(effective_url, profile))
989    return true;
990
991#if !defined(OS_CHROMEOS)
992  if (SigninManager::IsWebBasedSigninFlowURL(effective_url))
993    return true;
994#endif
995
996  if (!effective_url.SchemeIs(extensions::kExtensionScheme))
997    return false;
998
999  ExtensionService* extension_service =
1000      extensions::ExtensionSystem::Get(profile)->extension_service();
1001  if (!extension_service)
1002    return false;
1003
1004  const Extension* extension =
1005      extension_service->extensions()->GetExtensionOrAppByURL(effective_url);
1006  if (!extension)
1007    return false;
1008
1009  // If the URL is part of a hosted app that does not have the background
1010  // permission, or that does not allow JavaScript access to the background
1011  // page, we want to give each instance its own process to improve
1012  // responsiveness.
1013  if (extension->GetType() == Manifest::TYPE_HOSTED_APP) {
1014    if (!extension->HasAPIPermission(APIPermission::kBackground) ||
1015        !extensions::BackgroundInfo::AllowJSAccess(extension)) {
1016      return false;
1017    }
1018  }
1019
1020  // Hosted apps that have script access to their background page must use
1021  // process per site, since all instances can make synchronous calls to the
1022  // background window.  Other extensions should use process per site as well.
1023  return true;
1024}
1025
1026// These are treated as WebUI schemes but do not get WebUI bindings.
1027void ChromeContentBrowserClient::GetAdditionalWebUISchemes(
1028    std::vector<std::string>* additional_schemes) {
1029  additional_schemes->push_back(chrome::kChromeSearchScheme);
1030}
1031
1032net::URLRequestContextGetter*
1033ChromeContentBrowserClient::CreateRequestContext(
1034    content::BrowserContext* browser_context,
1035    content::ProtocolHandlerMap* protocol_handlers) {
1036  Profile* profile = Profile::FromBrowserContext(browser_context);
1037  return profile->CreateRequestContext(protocol_handlers);
1038}
1039
1040net::URLRequestContextGetter*
1041ChromeContentBrowserClient::CreateRequestContextForStoragePartition(
1042    content::BrowserContext* browser_context,
1043    const base::FilePath& partition_path,
1044    bool in_memory,
1045    content::ProtocolHandlerMap* protocol_handlers) {
1046  Profile* profile = Profile::FromBrowserContext(browser_context);
1047  return profile->CreateRequestContextForStoragePartition(
1048      partition_path, in_memory, protocol_handlers);
1049}
1050
1051bool ChromeContentBrowserClient::IsHandledURL(const GURL& url) {
1052  return ProfileIOData::IsHandledURL(url);
1053}
1054
1055bool ChromeContentBrowserClient::CanCommitURL(
1056    content::RenderProcessHost* process_host,
1057    const GURL& url) {
1058  // We need to let most extension URLs commit in any process, since this can
1059  // be allowed due to web_accessible_resources.  Most hosted app URLs may also
1060  // load in any process (e.g., in an iframe).  However, the Chrome Web Store
1061  // cannot be loaded in iframes and should never be requested outside its
1062  // process.
1063  Profile* profile =
1064      Profile::FromBrowserContext(process_host->GetBrowserContext());
1065  ExtensionService* service =
1066      extensions::ExtensionSystem::Get(profile)->extension_service();
1067  if (!service)
1068    return true;
1069  const Extension* new_extension =
1070      service->extensions()->GetExtensionOrAppByURL(url);
1071  if (new_extension &&
1072      new_extension->is_hosted_app() &&
1073      new_extension->id() == extension_misc::kWebStoreAppId &&
1074      !service->process_map()->Contains(new_extension->id(),
1075                                        process_host->GetID())) {
1076    return false;
1077  }
1078
1079  return true;
1080}
1081
1082bool ChromeContentBrowserClient::IsSuitableHost(
1083    content::RenderProcessHost* process_host,
1084    const GURL& site_url) {
1085  Profile* profile =
1086      Profile::FromBrowserContext(process_host->GetBrowserContext());
1087  // This may be NULL during tests. In that case, just assume any site can
1088  // share any host.
1089  if (!profile)
1090    return true;
1091
1092  // Instant URLs should only be in the instant process and instant process
1093  // should only have Instant URLs.
1094  InstantService* instant_service =
1095      InstantServiceFactory::GetForProfile(profile);
1096  if (instant_service) {
1097    bool is_instant_process = instant_service->IsInstantProcess(
1098        process_host->GetID());
1099    bool should_be_in_instant_process =
1100        chrome::ShouldAssignURLToInstantRenderer(site_url, profile);
1101    if (is_instant_process || should_be_in_instant_process)
1102      return is_instant_process && should_be_in_instant_process;
1103  }
1104
1105#if !defined(OS_CHROMEOS)
1106  SigninManager* signin_manager = SigninManagerFactory::GetForProfile(profile);
1107  if (signin_manager && signin_manager->IsSigninProcess(process_host->GetID()))
1108    return SigninManager::IsWebBasedSigninFlowURL(site_url);
1109#endif
1110
1111  ExtensionService* service =
1112      extensions::ExtensionSystem::Get(profile)->extension_service();
1113  extensions::ProcessMap* process_map = service->process_map();
1114
1115  // Don't allow the Task Manager to share a process with anything else.
1116  // Otherwise it can affect the renderers it is observing.
1117  // Note: we could create another RenderProcessHostPrivilege bucket for
1118  // this to allow multiple chrome://tasks instances to share, but that's
1119  // a very unlikely case without serious consequences.
1120  if (site_url.GetOrigin() == GURL(chrome::kChromeUITaskManagerURL).GetOrigin())
1121    return false;
1122
1123  // These may be NULL during tests. In that case, just assume any site can
1124  // share any host.
1125  if (!service || !process_map)
1126    return true;
1127
1128  // Otherwise, just make sure the process privilege matches the privilege
1129  // required by the site.
1130  RenderProcessHostPrivilege privilege_required =
1131      GetPrivilegeRequiredByUrl(site_url, service);
1132  return GetProcessPrivilege(process_host, process_map, service) ==
1133      privilege_required;
1134}
1135
1136// This function is trying to limit the amount of processes used by extensions
1137// with background pages. It uses a globally set percentage of processes to
1138// run such extensions and if the limit is exceeded, it returns true, to
1139// indicate to the content module to group extensions together.
1140bool ChromeContentBrowserClient::ShouldTryToUseExistingProcessHost(
1141    content::BrowserContext* browser_context, const GURL& url) {
1142  // It has to be a valid URL for us to check for an extension.
1143  if (!url.is_valid())
1144    return false;
1145
1146  Profile* profile = Profile::FromBrowserContext(browser_context);
1147  ExtensionService* service = !profile ? NULL :
1148      extensions::ExtensionSystem::Get(profile)->extension_service();
1149  if (!service)
1150    return false;
1151
1152  // We have to have a valid extension with background page to proceed.
1153  const Extension* extension =
1154      service->extensions()->GetExtensionOrAppByURL(url);
1155  if (!extension)
1156    return false;
1157  if (!extensions::BackgroundInfo::HasBackgroundPage(extension))
1158    return false;
1159
1160  std::set<int> process_ids;
1161  size_t max_process_count =
1162      content::RenderProcessHost::GetMaxRendererProcessCount();
1163
1164  // Go through all profiles to ensure we have total count of extension
1165  // processes containing background pages, otherwise one profile can
1166  // starve the other.
1167  std::vector<Profile*> profiles = g_browser_process->profile_manager()->
1168      GetLoadedProfiles();
1169  for (size_t i = 0; i < profiles.size(); ++i) {
1170    ExtensionProcessManager* epm =
1171        extensions::ExtensionSystem::Get(profiles[i])->process_manager();
1172    for (ExtensionProcessManager::const_iterator iter =
1173             epm->background_hosts().begin();
1174         iter != epm->background_hosts().end(); ++iter) {
1175      const extensions::ExtensionHost* host = *iter;
1176      process_ids.insert(host->render_process_host()->GetID());
1177    }
1178  }
1179
1180  if (process_ids.size() >
1181      (max_process_count * chrome::kMaxShareOfExtensionProcesses)) {
1182    return true;
1183  }
1184
1185  return false;
1186}
1187
1188void ChromeContentBrowserClient::SiteInstanceGotProcess(
1189    SiteInstance* site_instance) {
1190  CHECK(site_instance->HasProcess());
1191
1192  Profile* profile = Profile::FromBrowserContext(
1193      site_instance->GetBrowserContext());
1194  if (!profile)
1195    return;
1196
1197  // Remember the ID of the Instant process to signal the renderer process
1198  // on startup in |AppendExtraCommandLineSwitches| below.
1199  if (chrome::ShouldAssignURLToInstantRenderer(
1200          site_instance->GetSiteURL(), profile)) {
1201    InstantService* instant_service =
1202        InstantServiceFactory::GetForProfile(profile);
1203    if (instant_service)
1204      instant_service->AddInstantProcess(site_instance->GetProcess()->GetID());
1205  }
1206
1207#if !defined(OS_CHROMEOS)
1208  // We only expect there to be one signin process as we use process-per-site
1209  // for signin URLs. The signin process will be cleared from SigninManager
1210  // when the renderer is destroyed.
1211  if (SigninManager::IsWebBasedSigninFlowURL(site_instance->GetSiteURL())) {
1212    SigninManager* signin_manager =
1213        SigninManagerFactory::GetForProfile(profile);
1214    if (signin_manager)
1215      signin_manager->SetSigninProcess(site_instance->GetProcess()->GetID());
1216    BrowserThread::PostTask(
1217        BrowserThread::IO, FROM_HERE,
1218        base::Bind(&ExtensionInfoMap::SetSigninProcess,
1219                   extensions::ExtensionSystem::Get(profile)->info_map(),
1220                   site_instance->GetProcess()->GetID()));
1221  }
1222#endif
1223
1224  ExtensionService* service =
1225      extensions::ExtensionSystem::Get(profile)->extension_service();
1226  if (!service)
1227    return;
1228
1229  const Extension* extension = service->extensions()->GetExtensionOrAppByURL(
1230      site_instance->GetSiteURL());
1231  if (!extension)
1232    return;
1233
1234  service->process_map()->Insert(extension->id(),
1235                                 site_instance->GetProcess()->GetID(),
1236                                 site_instance->GetId());
1237  BrowserThread::PostTask(
1238      BrowserThread::IO, FROM_HERE,
1239      base::Bind(&ExtensionInfoMap::RegisterExtensionProcess,
1240                 extensions::ExtensionSystem::Get(profile)->info_map(),
1241                 extension->id(),
1242                 site_instance->GetProcess()->GetID(),
1243                 site_instance->GetId()));
1244}
1245
1246void ChromeContentBrowserClient::SiteInstanceDeleting(
1247    SiteInstance* site_instance) {
1248  if (!site_instance->HasProcess())
1249    return;
1250
1251  Profile* profile = Profile::FromBrowserContext(
1252      site_instance->GetBrowserContext());
1253  ExtensionService* service =
1254      extensions::ExtensionSystem::Get(profile)->extension_service();
1255  if (!service)
1256    return;
1257
1258  const Extension* extension = service->extensions()->GetExtensionOrAppByURL(
1259      site_instance->GetSiteURL());
1260  if (!extension)
1261    return;
1262
1263  service->process_map()->Remove(extension->id(),
1264                                 site_instance->GetProcess()->GetID(),
1265                                 site_instance->GetId());
1266  BrowserThread::PostTask(
1267      BrowserThread::IO, FROM_HERE,
1268      base::Bind(&ExtensionInfoMap::UnregisterExtensionProcess,
1269                 extensions::ExtensionSystem::Get(profile)->info_map(),
1270                 extension->id(),
1271                 site_instance->GetProcess()->GetID(),
1272                 site_instance->GetId()));
1273}
1274
1275bool ChromeContentBrowserClient::ShouldSwapProcessesForNavigation(
1276    SiteInstance* site_instance,
1277    const GURL& current_url,
1278    const GURL& new_url) {
1279  if (current_url.is_empty()) {
1280    // Always choose a new process when navigating to extension URLs. The
1281    // process grouping logic will combine all of a given extension's pages
1282    // into the same process.
1283    if (new_url.SchemeIs(extensions::kExtensionScheme))
1284      return true;
1285
1286    return false;
1287  }
1288
1289  // Also, we must switch if one is an extension and the other is not the exact
1290  // same extension.
1291  if (current_url.SchemeIs(extensions::kExtensionScheme) ||
1292      new_url.SchemeIs(extensions::kExtensionScheme)) {
1293    if (current_url.GetOrigin() != new_url.GetOrigin())
1294      return true;
1295  }
1296
1297  // The checks below only matter if we can retrieve which extensions are
1298  // installed.
1299  Profile* profile =
1300      Profile::FromBrowserContext(site_instance->GetBrowserContext());
1301  ExtensionService* service =
1302      extensions::ExtensionSystem::Get(profile)->extension_service();
1303  if (!service)
1304    return false;
1305
1306  // We must swap if the URL is for an extension and we are not using an
1307  // extension process.
1308  const Extension* new_extension =
1309      service->extensions()->GetExtensionOrAppByURL(new_url);
1310  // Ignore all hosted apps except the Chrome Web Store, since they do not
1311  // require their own BrowsingInstance (e.g., postMessage is ok).
1312  if (new_extension &&
1313      new_extension->is_hosted_app() &&
1314      new_extension->id() != extension_misc::kWebStoreAppId)
1315    new_extension = NULL;
1316  if (new_extension &&
1317      site_instance->HasProcess() &&
1318      !service->process_map()->Contains(new_extension->id(),
1319                                        site_instance->GetProcess()->GetID()))
1320    return true;
1321
1322  return false;
1323}
1324
1325bool ChromeContentBrowserClient::ShouldSwapProcessesForRedirect(
1326    content::ResourceContext* resource_context, const GURL& current_url,
1327    const GURL& new_url) {
1328  ProfileIOData* io_data = ProfileIOData::FromResourceContext(resource_context);
1329  return extensions::CrossesExtensionProcessBoundary(
1330      io_data->GetExtensionInfoMap()->extensions(),
1331      current_url, new_url, false);
1332}
1333
1334bool ChromeContentBrowserClient::ShouldAssignSiteForURL(const GURL& url) {
1335  return !url.SchemeIs(chrome::kChromeNativeScheme);
1336}
1337
1338std::string ChromeContentBrowserClient::GetCanonicalEncodingNameByAliasName(
1339    const std::string& alias_name) {
1340  return CharacterEncoding::GetCanonicalEncodingNameByAliasName(alias_name);
1341}
1342
1343void ChromeContentBrowserClient::AppendExtraCommandLineSwitches(
1344    CommandLine* command_line, int child_process_id) {
1345#if defined(OS_MACOSX)
1346  if (IsCrashReporterEnabled()) {
1347    command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1348                                    child_process_logging::GetClientId());
1349  }
1350#elif defined(OS_POSIX)
1351  if (IsCrashReporterEnabled()) {
1352    command_line->AppendSwitchASCII(switches::kEnableCrashReporter,
1353        child_process_logging::GetClientId() + "," + base::GetLinuxDistro());
1354  }
1355
1356#endif  // OS_MACOSX
1357
1358  if (logging::DialogsAreSuppressed())
1359    command_line->AppendSwitch(switches::kNoErrorDialogs);
1360
1361  std::string process_type =
1362      command_line->GetSwitchValueASCII(switches::kProcessType);
1363  const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
1364
1365  if (browser_command_line.HasSwitch(switches::kChromeFrame))
1366    command_line->AppendSwitch(switches::kChromeFrame);
1367
1368  if (process_type == switches::kRendererProcess) {
1369    base::FilePath user_data_dir =
1370        browser_command_line.GetSwitchValuePath(switches::kUserDataDir);
1371    if (!user_data_dir.empty())
1372      command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
1373#if defined(OS_CHROMEOS)
1374    const std::string& login_profile =
1375        browser_command_line.GetSwitchValueASCII(
1376            chromeos::switches::kLoginProfile);
1377    if (!login_profile.empty())
1378      command_line->AppendSwitchASCII(
1379          chromeos::switches::kLoginProfile, login_profile);
1380#endif
1381
1382    content::RenderProcessHost* process =
1383        content::RenderProcessHost::FromID(child_process_id);
1384    if (process) {
1385      Profile* profile = Profile::FromBrowserContext(
1386          process->GetBrowserContext());
1387      ExtensionService* extension_service =
1388          extensions::ExtensionSystem::Get(profile)->extension_service();
1389      if (extension_service) {
1390        extensions::ProcessMap* process_map = extension_service->process_map();
1391        if (process_map && process_map->Contains(process->GetID()))
1392          command_line->AppendSwitch(switches::kExtensionProcess);
1393      }
1394
1395      PrefService* prefs = profile->GetPrefs();
1396      // Currently this pref is only registered if applied via a policy.
1397      if (prefs->HasPrefPath(prefs::kDisable3DAPIs) &&
1398          prefs->GetBoolean(prefs::kDisable3DAPIs)) {
1399        // Turn this policy into a command line switch.
1400        command_line->AppendSwitch(switches::kDisable3DAPIs);
1401      }
1402
1403      // Disable client-side phishing detection in the renderer if it is
1404      // disabled in the Profile preferences or the browser process.
1405      if (!prefs->GetBoolean(prefs::kSafeBrowsingEnabled) ||
1406          !g_browser_process->safe_browsing_detection_service()) {
1407        command_line->AppendSwitch(
1408            switches::kDisableClientSidePhishingDetection);
1409      }
1410
1411      if (!prefs->GetBoolean(prefs::kPrintPreviewDisabled))
1412        command_line->AppendSwitch(switches::kRendererPrintPreview);
1413
1414      InstantService* instant_service =
1415          InstantServiceFactory::GetForProfile(profile);
1416      if (instant_service &&
1417          instant_service->IsInstantProcess(process->GetID()))
1418        command_line->AppendSwitch(switches::kInstantProcess);
1419
1420#if !defined(OS_CHROMEOS)
1421      SigninManager* signin_manager =
1422          SigninManagerFactory::GetForProfile(profile);
1423      if (signin_manager && signin_manager->IsSigninProcess(process->GetID()))
1424        command_line->AppendSwitch(switches::kSigninProcess);
1425#endif
1426    }
1427
1428    if (content::IsThreadedCompositingEnabled())
1429      command_line->AppendSwitch(switches::kEnableThreadedCompositing);
1430
1431    if (message_center::IsRichNotificationEnabled())
1432      command_line->AppendSwitch(switches::kDisableHTMLNotifications);
1433
1434    // Please keep this in alphabetical order.
1435    static const char* const kSwitchNames[] = {
1436      autofill::switches::kDisableInteractiveAutocomplete,
1437      autofill::switches::kEnableExperimentalFormFilling,
1438      autofill::switches::kEnableInteractiveAutocomplete,
1439      extensions::switches::kAllowLegacyExtensionManifests,
1440      extensions::switches::kAllowScriptingGallery,
1441      extensions::switches::kEnableExperimentalExtensionApis,
1442      extensions::switches::kExtensionsOnChromeURLs,
1443      switches::kAllowHTTPBackgroundPage,
1444      // TODO(victorhsieh): remove the following flag once we move PPAPI FileIO
1445      // to browser.
1446      switches::kAllowNaClFileHandleAPI,
1447      switches::kAppsCheckoutURL,
1448      switches::kAppsGalleryURL,
1449      switches::kCloudPrintServiceURL,
1450      switches::kDebugPrint,
1451      switches::kDisableBundledPpapiFlash,
1452      switches::kDisableExtensionsResourceWhitelist,
1453      switches::kDisablePnacl,
1454      switches::kDisableScriptedPrintThrottling,
1455      switches::kEnableAdview,
1456      switches::kEnableAdviewSrcAttribute,
1457      switches::kEnableAppWindowControls,
1458      switches::kEnableBenchmarking,
1459      switches::kEnableIPCFuzzing,
1460      switches::kEnableNaCl,
1461      switches::kEnableNetBenchmarking,
1462      switches::kEnablePasswordGeneration,
1463      switches::kEnableWatchdog,
1464      switches::kMemoryProfiling,
1465      switches::kMessageLoopHistogrammer,
1466      switches::kNoJsRandomness,
1467      switches::kPlaybackMode,
1468      switches::kPpapiFlashArgs,
1469      switches::kPpapiFlashInProcess,
1470      switches::kPpapiFlashPath,
1471      switches::kPpapiFlashVersion,
1472      switches::kProfilingAtStart,
1473      switches::kProfilingFile,
1474      switches::kProfilingFlush,
1475      switches::kRecordMode,
1476      switches::kSilentDumpOnDCHECK,
1477      switches::kSpdyProxyAuthOrigin,
1478      switches::kWhitelistedExtensionID,
1479    };
1480
1481    command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1482                                   arraysize(kSwitchNames));
1483  } else if (process_type == switches::kUtilityProcess) {
1484    static const char* const kSwitchNames[] = {
1485      extensions::switches::kEnableExperimentalExtensionApis,
1486      extensions::switches::kExtensionsOnChromeURLs,
1487      switches::kAllowHTTPBackgroundPage,
1488      switches::kWhitelistedExtensionID,
1489    };
1490
1491    command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1492                                   arraysize(kSwitchNames));
1493  } else if (process_type == switches::kPluginProcess) {
1494    static const char* const kSwitchNames[] = {
1495#if defined(OS_CHROMEOS)
1496      chromeos::switches::kLoginProfile,
1497#endif
1498      switches::kMemoryProfiling,
1499      switches::kSilentDumpOnDCHECK,
1500      switches::kUserDataDir,
1501    };
1502
1503    command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1504                                   arraysize(kSwitchNames));
1505  } else if (process_type == switches::kZygoteProcess) {
1506    static const char* const kSwitchNames[] = {
1507      switches::kUserDataDir,  // Make logs go to the right file.
1508      // Load (in-process) Pepper plugins in-process in the zygote pre-sandbox.
1509      switches::kDisableBundledPpapiFlash,
1510      switches::kPpapiFlashInProcess,
1511      switches::kPpapiFlashPath,
1512      switches::kPpapiFlashVersion,
1513    };
1514
1515    command_line->CopySwitchesFrom(browser_command_line, kSwitchNames,
1516                                   arraysize(kSwitchNames));
1517  } else if (process_type == switches::kGpuProcess) {
1518    base::FilePath user_data_dir =
1519        browser_command_line.GetSwitchValuePath(switches::kUserDataDir);
1520    if (!user_data_dir.empty())
1521      command_line->AppendSwitchPath(switches::kUserDataDir, user_data_dir);
1522    // If --ignore-gpu-blacklist is passed in, don't send in crash reports
1523    // because GPU is expected to be unreliable.
1524    if (browser_command_line.HasSwitch(switches::kIgnoreGpuBlacklist) &&
1525        !command_line->HasSwitch(switches::kDisableBreakpad))
1526      command_line->AppendSwitch(switches::kDisableBreakpad);
1527  }
1528
1529  // The command line switch kEnableBenchmarking needs to be specified along
1530  // with the kEnableStatsTable switch to ensure that the stats table global
1531  // is initialized correctly.
1532  if (command_line->HasSwitch(switches::kEnableBenchmarking))
1533    DCHECK(command_line->HasSwitch(switches::kEnableStatsTable));
1534}
1535
1536std::string ChromeContentBrowserClient::GetApplicationLocale() {
1537  if (BrowserThread::CurrentlyOn(BrowserThread::IO))
1538    return g_io_thread_application_locale.Get();
1539  return g_browser_process->GetApplicationLocale();
1540}
1541
1542std::string ChromeContentBrowserClient::GetAcceptLangs(
1543    content::BrowserContext* context) {
1544  Profile* profile = Profile::FromBrowserContext(context);
1545  return profile->GetPrefs()->GetString(prefs::kAcceptLanguages);
1546}
1547
1548gfx::ImageSkia* ChromeContentBrowserClient::GetDefaultFavicon() {
1549  ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1550  return rb.GetImageSkiaNamed(IDR_DEFAULT_FAVICON);
1551}
1552
1553bool ChromeContentBrowserClient::AllowAppCache(
1554    const GURL& manifest_url,
1555    const GURL& first_party,
1556    content::ResourceContext* context) {
1557  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1558  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1559  return io_data->GetCookieSettings()->
1560      IsSettingCookieAllowed(manifest_url, first_party);
1561}
1562
1563bool ChromeContentBrowserClient::AllowGetCookie(
1564    const GURL& url,
1565    const GURL& first_party,
1566    const net::CookieList& cookie_list,
1567    content::ResourceContext* context,
1568    int render_process_id,
1569    int render_view_id) {
1570  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1571  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1572  bool allow = io_data->GetCookieSettings()->
1573      IsReadingCookieAllowed(url, first_party);
1574
1575  BrowserThread::PostTask(
1576      BrowserThread::UI, FROM_HERE,
1577      base::Bind(&TabSpecificContentSettings::CookiesRead, render_process_id,
1578                 render_view_id, url, first_party, cookie_list, !allow));
1579  return allow;
1580}
1581
1582bool ChromeContentBrowserClient::AllowSetCookie(
1583    const GURL& url,
1584    const GURL& first_party,
1585    const std::string& cookie_line,
1586    content::ResourceContext* context,
1587    int render_process_id,
1588    int render_view_id,
1589    net::CookieOptions* options) {
1590  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1591  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1592  CookieSettings* cookie_settings = io_data->GetCookieSettings();
1593  bool allow = cookie_settings->IsSettingCookieAllowed(url, first_party);
1594
1595  BrowserThread::PostTask(
1596      BrowserThread::UI, FROM_HERE,
1597      base::Bind(&TabSpecificContentSettings::CookieChanged, render_process_id,
1598                 render_view_id, url, first_party, cookie_line, *options,
1599                 !allow));
1600  return allow;
1601}
1602
1603bool ChromeContentBrowserClient::AllowSaveLocalState(
1604    content::ResourceContext* context) {
1605  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1606  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1607  CookieSettings* cookie_settings = io_data->GetCookieSettings();
1608  ContentSetting setting = cookie_settings->GetDefaultCookieSetting(NULL);
1609
1610  // TODO(bauerb): Should we also disallow local state if the default is BLOCK?
1611  // Could we even support per-origin settings?
1612  return setting != CONTENT_SETTING_SESSION_ONLY;
1613}
1614
1615bool ChromeContentBrowserClient::AllowWorkerDatabase(
1616    const GURL& url,
1617    const string16& name,
1618    const string16& display_name,
1619    unsigned long estimated_size,
1620    content::ResourceContext* context,
1621    const std::vector<std::pair<int, int> >& render_views) {
1622  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1623  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1624  CookieSettings* cookie_settings = io_data->GetCookieSettings();
1625  bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1626
1627  // Record access to database for potential display in UI.
1628  std::vector<std::pair<int, int> >::const_iterator i;
1629  for (i = render_views.begin(); i != render_views.end(); ++i) {
1630    BrowserThread::PostTask(
1631        BrowserThread::UI, FROM_HERE,
1632        base::Bind(&TabSpecificContentSettings::WebDatabaseAccessed,
1633                   i->first, i->second, url, name, display_name, !allow));
1634  }
1635
1636  return allow;
1637}
1638
1639bool ChromeContentBrowserClient::AllowWorkerFileSystem(
1640    const GURL& url,
1641    content::ResourceContext* context,
1642    const std::vector<std::pair<int, int> >& render_views) {
1643  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1644  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1645  CookieSettings* cookie_settings = io_data->GetCookieSettings();
1646  bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1647
1648  // Record access to file system for potential display in UI.
1649  std::vector<std::pair<int, int> >::const_iterator i;
1650  for (i = render_views.begin(); i != render_views.end(); ++i) {
1651    BrowserThread::PostTask(
1652        BrowserThread::UI, FROM_HERE,
1653        base::Bind(&TabSpecificContentSettings::FileSystemAccessed,
1654                   i->first, i->second, url, !allow));
1655  }
1656
1657  return allow;
1658}
1659
1660bool ChromeContentBrowserClient::AllowWorkerIndexedDB(
1661    const GURL& url,
1662    const string16& name,
1663    content::ResourceContext* context,
1664    const std::vector<std::pair<int, int> >& render_views) {
1665  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1666  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1667  CookieSettings* cookie_settings = io_data->GetCookieSettings();
1668  bool allow = cookie_settings->IsSettingCookieAllowed(url, url);
1669
1670  // Record access to IndexedDB for potential display in UI.
1671  std::vector<std::pair<int, int> >::const_iterator i;
1672  for (i = render_views.begin(); i != render_views.end(); ++i) {
1673    BrowserThread::PostTask(
1674        BrowserThread::UI, FROM_HERE,
1675        base::Bind(&TabSpecificContentSettings::IndexedDBAccessed,
1676                   i->first, i->second, url, name, !allow));
1677  }
1678
1679  return allow;
1680}
1681
1682net::URLRequestContext*
1683ChromeContentBrowserClient::OverrideRequestContextForURL(
1684    const GURL& url, content::ResourceContext* context) {
1685  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1686  if (url.SchemeIs(extensions::kExtensionScheme)) {
1687    ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1688    return io_data->extensions_request_context();
1689  }
1690
1691  return NULL;
1692}
1693
1694QuotaPermissionContext*
1695ChromeContentBrowserClient::CreateQuotaPermissionContext() {
1696  return new ChromeQuotaPermissionContext();
1697}
1698
1699void ChromeContentBrowserClient::AllowCertificateError(
1700    int render_process_id,
1701    int render_view_id,
1702    int cert_error,
1703    const net::SSLInfo& ssl_info,
1704    const GURL& request_url,
1705    ResourceType::Type resource_type,
1706    bool overridable,
1707    bool strict_enforcement,
1708    const base::Callback<void(bool)>& callback,
1709    content::CertificateRequestResultType* result) {
1710  if (resource_type != ResourceType::MAIN_FRAME) {
1711    // A sub-resource has a certificate error.  The user doesn't really
1712    // have a context for making the right decision, so block the
1713    // request hard, without an info bar to allow showing the insecure
1714    // content.
1715    *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_DENY;
1716    return;
1717  }
1718
1719  // If the tab is being prerendered, cancel the prerender and the request.
1720  WebContents* tab = tab_util::GetWebContentsByID(
1721      render_process_id, render_view_id);
1722  if (!tab) {
1723    NOTREACHED();
1724    return;
1725  }
1726  prerender::PrerenderManager* prerender_manager =
1727      prerender::PrerenderManagerFactory::GetForProfile(
1728          Profile::FromBrowserContext(tab->GetBrowserContext()));
1729  if (prerender_manager && prerender_manager->IsWebContentsPrerendering(tab,
1730                                                                        NULL)) {
1731    if (prerender_manager->prerender_tracker()->TryCancel(
1732            render_process_id, render_view_id,
1733            prerender::FINAL_STATUS_SSL_ERROR)) {
1734      *result = content::CERTIFICATE_REQUEST_RESULT_TYPE_CANCEL;
1735      return;
1736    }
1737  }
1738
1739#if defined(ENABLE_CAPTIVE_PORTAL_DETECTION)
1740  captive_portal::CaptivePortalTabHelper* captive_portal_tab_helper =
1741      captive_portal::CaptivePortalTabHelper::FromWebContents(tab);
1742  if (captive_portal_tab_helper)
1743    captive_portal_tab_helper->OnSSLCertError(ssl_info);
1744#endif
1745
1746  // Otherwise, display an SSL blocking page.
1747  new SSLBlockingPage(tab, cert_error, ssl_info, request_url, overridable,
1748                      strict_enforcement, callback);
1749}
1750
1751void ChromeContentBrowserClient::SelectClientCertificate(
1752    int render_process_id,
1753    int render_view_id,
1754    const net::HttpNetworkSession* network_session,
1755    net::SSLCertRequestInfo* cert_request_info,
1756    const base::Callback<void(net::X509Certificate*)>& callback) {
1757  WebContents* tab = tab_util::GetWebContentsByID(
1758      render_process_id, render_view_id);
1759  if (!tab) {
1760    NOTREACHED();
1761    return;
1762  }
1763
1764  GURL requesting_url("https://" + cert_request_info->host_and_port);
1765  DCHECK(requesting_url.is_valid()) << "Invalid URL string: https://"
1766                                    << cert_request_info->host_and_port;
1767
1768  Profile* profile = Profile::FromBrowserContext(tab->GetBrowserContext());
1769  scoped_ptr<Value> filter(
1770      profile->GetHostContentSettingsMap()->GetWebsiteSetting(
1771          requesting_url,
1772          requesting_url,
1773          CONTENT_SETTINGS_TYPE_AUTO_SELECT_CERTIFICATE,
1774          std::string(), NULL));
1775
1776  if (filter.get()) {
1777    // Try to automatically select a client certificate.
1778    if (filter->IsType(Value::TYPE_DICTIONARY)) {
1779      DictionaryValue* filter_dict =
1780          static_cast<DictionaryValue*>(filter.get());
1781
1782      const std::vector<scoped_refptr<net::X509Certificate> >&
1783          all_client_certs = cert_request_info->client_certs;
1784      for (size_t i = 0; i < all_client_certs.size(); ++i) {
1785        if (CertMatchesFilter(*all_client_certs[i].get(), *filter_dict)) {
1786          // Use the first certificate that is matched by the filter.
1787          callback.Run(all_client_certs[i].get());
1788          return;
1789        }
1790      }
1791    } else {
1792      NOTREACHED();
1793    }
1794  }
1795
1796  SSLTabHelper* ssl_tab_helper = SSLTabHelper::FromWebContents(tab);
1797  if (!ssl_tab_helper) {
1798    // If there is no SSLTabHelper for the given WebContents then we can't
1799    // show the user a dialog to select a client certificate. So we simply
1800    // proceed with no client certificate.
1801    callback.Run(NULL);
1802    return;
1803  }
1804  ssl_tab_helper->ShowClientCertificateRequestDialog(
1805      network_session, cert_request_info, callback);
1806}
1807
1808void ChromeContentBrowserClient::AddCertificate(
1809    net::URLRequest* request,
1810    net::CertificateMimeType cert_type,
1811    const void* cert_data,
1812    size_t cert_size,
1813    int render_process_id,
1814    int render_view_id) {
1815  chrome::SSLAddCertificate(request, cert_type, cert_data, cert_size,
1816      render_process_id, render_view_id);
1817}
1818
1819content::MediaObserver* ChromeContentBrowserClient::GetMediaObserver() {
1820  return MediaCaptureDevicesDispatcher::GetInstance();
1821}
1822
1823void ChromeContentBrowserClient::RequestDesktopNotificationPermission(
1824    const GURL& source_origin,
1825    int callback_context,
1826    int render_process_id,
1827    int render_view_id) {
1828#if defined(ENABLE_NOTIFICATIONS)
1829  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
1830  WebContents* contents =
1831      tab_util::GetWebContentsByID(render_process_id, render_view_id);
1832  if (!contents) {
1833    NOTREACHED();
1834    return;
1835  }
1836
1837  // Skip showing the infobar if the request comes from an extension, and that
1838  // extension has the 'notify' permission. (If the extension does not have the
1839  // permission, the user will still be prompted.)
1840  Profile* profile = Profile::FromBrowserContext(contents->GetBrowserContext());
1841  ExtensionInfoMap* extension_info_map =
1842      extensions::ExtensionSystem::Get(profile)->info_map();
1843  DesktopNotificationService* notification_service =
1844      DesktopNotificationServiceFactory::GetForProfile(profile);
1845  const Extension* extension = NULL;
1846  if (extension_info_map) {
1847    ExtensionSet extensions;
1848    extension_info_map->GetExtensionsWithAPIPermissionForSecurityOrigin(
1849        source_origin, render_process_id,
1850        extensions::APIPermission::kNotification, &extensions);
1851    for (ExtensionSet::const_iterator iter = extensions.begin();
1852         iter != extensions.end(); ++iter) {
1853      if (notification_service->IsNotifierEnabled(NotifierId(
1854              NotifierId::APPLICATION, (*iter)->id()))) {
1855        extension = iter->get();
1856        break;
1857      }
1858    }
1859  }
1860  RenderViewHost* rvh =
1861      RenderViewHost::FromID(render_process_id, render_view_id);
1862  if (IsExtensionWithPermissionOrSuggestInConsole(
1863      APIPermission::kNotification, extension, rvh)) {
1864    if (rvh)
1865      rvh->DesktopNotificationPermissionRequestDone(callback_context);
1866    return;
1867  }
1868
1869  notification_service->RequestPermission(source_origin, render_process_id,
1870      render_view_id, callback_context, contents);
1871#else
1872  NOTIMPLEMENTED();
1873#endif
1874}
1875
1876WebKit::WebNotificationPresenter::Permission
1877    ChromeContentBrowserClient::CheckDesktopNotificationPermission(
1878        const GURL& source_origin,
1879        content::ResourceContext* context,
1880        int render_process_id) {
1881#if defined(ENABLE_NOTIFICATIONS)
1882  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1883  // Sometimes a notification may be invoked during the shutdown.
1884  // See http://crbug.com/256638
1885  if (browser_shutdown::IsTryingToQuit())
1886    return WebKit::WebNotificationPresenter::PermissionNotAllowed;
1887
1888  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1889
1890  DesktopNotificationService* notification_service =
1891      io_data->GetNotificationService();
1892  if (notification_service) {
1893    ExtensionInfoMap* extension_info_map = io_data->GetExtensionInfoMap();
1894    ExtensionSet extensions;
1895    extension_info_map->GetExtensionsWithAPIPermissionForSecurityOrigin(
1896        source_origin, render_process_id,
1897        extensions::APIPermission::kNotification, &extensions);
1898    for (ExtensionSet::const_iterator iter = extensions.begin();
1899         iter != extensions.end(); ++iter) {
1900      NotifierId notifier_id(NotifierId::APPLICATION, (*iter)->id());
1901      if (notification_service->IsNotifierEnabled(notifier_id))
1902        return WebKit::WebNotificationPresenter::PermissionAllowed;
1903    }
1904
1905    return notification_service->HasPermission(source_origin);
1906  }
1907
1908  return WebKit::WebNotificationPresenter::PermissionNotAllowed;
1909#else
1910  return WebKit::WebNotificationPresenter::PermissionAllowed;
1911#endif
1912}
1913
1914void ChromeContentBrowserClient::ShowDesktopNotification(
1915    const content::ShowDesktopNotificationHostMsgParams& params,
1916    int render_process_id,
1917    int render_view_id,
1918    bool worker) {
1919#if defined(ENABLE_NOTIFICATIONS)
1920  RenderViewHost* rvh = RenderViewHost::FromID(
1921      render_process_id, render_view_id);
1922  if (!rvh) {
1923    NOTREACHED();
1924    return;
1925  }
1926
1927  content::RenderProcessHost* process = rvh->GetProcess();
1928  Profile* profile = Profile::FromBrowserContext(process->GetBrowserContext());
1929  DesktopNotificationService* service =
1930      DesktopNotificationServiceFactory::GetForProfile(profile);
1931  service->ShowDesktopNotification(
1932    params, render_process_id, render_view_id,
1933    worker ? DesktopNotificationService::WorkerNotification :
1934        DesktopNotificationService::PageNotification);
1935#else
1936  NOTIMPLEMENTED();
1937#endif
1938}
1939
1940void ChromeContentBrowserClient::CancelDesktopNotification(
1941    int render_process_id,
1942    int render_view_id,
1943    int notification_id) {
1944#if defined(ENABLE_NOTIFICATIONS)
1945  RenderViewHost* rvh = RenderViewHost::FromID(
1946      render_process_id, render_view_id);
1947  if (!rvh) {
1948    NOTREACHED();
1949    return;
1950  }
1951
1952  content::RenderProcessHost* process = rvh->GetProcess();
1953  Profile* profile = Profile::FromBrowserContext(process->GetBrowserContext());
1954  DesktopNotificationService* service =
1955      DesktopNotificationServiceFactory::GetForProfile(profile);
1956  service->CancelDesktopNotification(
1957      render_process_id, render_view_id, notification_id);
1958#else
1959  NOTIMPLEMENTED();
1960#endif
1961}
1962
1963bool ChromeContentBrowserClient::CanCreateWindow(
1964    const GURL& opener_url,
1965    const GURL& source_origin,
1966    WindowContainerType container_type,
1967    const GURL& target_url,
1968    const content::Referrer& referrer,
1969    WindowOpenDisposition disposition,
1970    const WebWindowFeatures& features,
1971    bool user_gesture,
1972    bool opener_suppressed,
1973    content::ResourceContext* context,
1974    int render_process_id,
1975    bool is_guest,
1976    int opener_id,
1977    bool* no_javascript_access) {
1978  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
1979
1980  *no_javascript_access = false;
1981
1982  // If the opener is trying to create a background window but doesn't have
1983  // the appropriate permission, fail the attempt.
1984  if (container_type == WINDOW_CONTAINER_TYPE_BACKGROUND) {
1985    ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
1986    ExtensionInfoMap* map = io_data->GetExtensionInfoMap();
1987
1988    if (!map->SecurityOriginHasAPIPermission(
1989            source_origin,
1990            render_process_id,
1991            APIPermission::kBackground)) {
1992      return false;
1993    }
1994
1995    // Note: this use of GetExtensionOrAppByURL is safe but imperfect.  It may
1996    // return a recently installed Extension even if this CanCreateWindow call
1997    // was made by an old copy of the page in a normal web process.  That's ok,
1998    // because the permission check above would have caused an early return
1999    // already. We must use the full URL to find hosted apps, though, and not
2000    // just the origin.
2001    const Extension* extension =
2002        map->extensions().GetExtensionOrAppByURL(opener_url);
2003    if (extension && !extensions::BackgroundInfo::AllowJSAccess(extension))
2004      *no_javascript_access = true;
2005
2006    return true;
2007  }
2008
2009  // No new browser window (popup or tab) in app mode.
2010  if (container_type == WINDOW_CONTAINER_TYPE_NORMAL &&
2011      chrome::IsRunningInForcedAppMode()) {
2012    return false;
2013  }
2014
2015#if !defined(OS_ANDROID)
2016  if (CommandLine::ForCurrentProcess()->HasSwitch(
2017          switches::kDisableBetterPopupBlocking)) {
2018    return true;
2019  }
2020
2021  if (is_guest)
2022    return true;
2023
2024  HostContentSettingsMap* content_settings =
2025      ProfileIOData::FromResourceContext(context)->GetHostContentSettingsMap();
2026
2027  if ((disposition == NEW_POPUP || disposition == NEW_FOREGROUND_TAB ||
2028       disposition == NEW_BACKGROUND_TAB) && !user_gesture &&
2029      !CommandLine::ForCurrentProcess()->HasSwitch(
2030          switches::kDisablePopupBlocking)) {
2031    if (content_settings->GetContentSetting(opener_url,
2032                                            opener_url,
2033                                            CONTENT_SETTINGS_TYPE_POPUPS,
2034                                            std::string()) ==
2035        CONTENT_SETTING_ALLOW) {
2036      return true;
2037    }
2038
2039    BrowserThread::PostTask(BrowserThread::UI,
2040                            FROM_HERE,
2041                            base::Bind(&HandleBlockedPopupOnUIThread,
2042                                       BlockedPopupParams(target_url,
2043                                                          referrer,
2044                                                          disposition,
2045                                                          features,
2046                                                          user_gesture,
2047                                                          opener_suppressed,
2048                                                          render_process_id,
2049                                                          opener_id)));
2050    return false;
2051  }
2052#endif
2053
2054  return true;
2055}
2056
2057std::string ChromeContentBrowserClient::GetWorkerProcessTitle(
2058    const GURL& url, content::ResourceContext* context) {
2059  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
2060  // Check if it's an extension-created worker, in which case we want to use
2061  // the name of the extension.
2062  ProfileIOData* io_data = ProfileIOData::FromResourceContext(context);
2063  const Extension* extension =
2064      io_data->GetExtensionInfoMap()->extensions().GetByID(url.host());
2065  return extension ? extension->name() : std::string();
2066}
2067
2068void ChromeContentBrowserClient::ResourceDispatcherHostCreated() {
2069  return g_browser_process->ResourceDispatcherHostCreated();
2070}
2071
2072// TODO(tommi): Rename from Get to Create.
2073content::SpeechRecognitionManagerDelegate*
2074    ChromeContentBrowserClient::GetSpeechRecognitionManagerDelegate() {
2075#if defined(ENABLE_INPUT_SPEECH)
2076  return new speech::ChromeSpeechRecognitionManagerDelegateBubbleUI();
2077#else
2078  // Platforms who don't implement x-webkit-speech (a.k.a INPUT_SPEECH) just
2079  // need the base delegate without the bubble UI.
2080  return new speech::ChromeSpeechRecognitionManagerDelegate();
2081#endif
2082}
2083
2084net::NetLog* ChromeContentBrowserClient::GetNetLog() {
2085  return g_browser_process->net_log();
2086}
2087
2088AccessTokenStore* ChromeContentBrowserClient::CreateAccessTokenStore() {
2089  return new ChromeAccessTokenStore();
2090}
2091
2092bool ChromeContentBrowserClient::IsFastShutdownPossible() {
2093  return true;
2094}
2095
2096void ChromeContentBrowserClient::OverrideWebkitPrefs(
2097    RenderViewHost* rvh, const GURL& url, WebPreferences* web_prefs) {
2098  Profile* profile = Profile::FromBrowserContext(
2099      rvh->GetProcess()->GetBrowserContext());
2100  PrefService* prefs = profile->GetPrefs();
2101
2102  FillFontFamilyMap(prefs, prefs::kWebKitStandardFontFamilyMap,
2103                    &web_prefs->standard_font_family_map);
2104  FillFontFamilyMap(prefs, prefs::kWebKitFixedFontFamilyMap,
2105                    &web_prefs->fixed_font_family_map);
2106  FillFontFamilyMap(prefs, prefs::kWebKitSerifFontFamilyMap,
2107                    &web_prefs->serif_font_family_map);
2108  FillFontFamilyMap(prefs, prefs::kWebKitSansSerifFontFamilyMap,
2109                    &web_prefs->sans_serif_font_family_map);
2110  FillFontFamilyMap(prefs, prefs::kWebKitCursiveFontFamilyMap,
2111                    &web_prefs->cursive_font_family_map);
2112  FillFontFamilyMap(prefs, prefs::kWebKitFantasyFontFamilyMap,
2113                    &web_prefs->fantasy_font_family_map);
2114  FillFontFamilyMap(prefs, prefs::kWebKitPictographFontFamilyMap,
2115                    &web_prefs->pictograph_font_family_map);
2116
2117  web_prefs->default_font_size =
2118      prefs->GetInteger(prefs::kWebKitDefaultFontSize);
2119  web_prefs->default_fixed_font_size =
2120      prefs->GetInteger(prefs::kWebKitDefaultFixedFontSize);
2121  web_prefs->minimum_font_size =
2122      prefs->GetInteger(prefs::kWebKitMinimumFontSize);
2123  web_prefs->minimum_logical_font_size =
2124      prefs->GetInteger(prefs::kWebKitMinimumLogicalFontSize);
2125
2126  web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2127
2128  web_prefs->javascript_can_open_windows_automatically =
2129      prefs->GetBoolean(prefs::kWebKitJavascriptCanOpenWindowsAutomatically);
2130  web_prefs->dom_paste_enabled =
2131      prefs->GetBoolean(prefs::kWebKitDomPasteEnabled);
2132  web_prefs->shrinks_standalone_images_to_fit =
2133      prefs->GetBoolean(prefs::kWebKitShrinksStandaloneImagesToFit);
2134  const DictionaryValue* inspector_settings =
2135      prefs->GetDictionary(prefs::kWebKitInspectorSettings);
2136  if (inspector_settings) {
2137    for (DictionaryValue::Iterator iter(*inspector_settings); !iter.IsAtEnd();
2138         iter.Advance()) {
2139      std::string value;
2140      if (iter.value().GetAsString(&value)) {
2141          web_prefs->inspector_settings.push_back(
2142              std::make_pair(iter.key(), value));
2143      }
2144    }
2145  }
2146  web_prefs->tabs_to_links = prefs->GetBoolean(prefs::kWebkitTabsToLinks);
2147
2148  if (!prefs->GetBoolean(prefs::kWebKitJavascriptEnabled))
2149    web_prefs->javascript_enabled = false;
2150  if (!prefs->GetBoolean(prefs::kWebKitWebSecurityEnabled))
2151    web_prefs->web_security_enabled = false;
2152  if (!prefs->GetBoolean(prefs::kWebKitPluginsEnabled))
2153    web_prefs->plugins_enabled = false;
2154  if (!prefs->GetBoolean(prefs::kWebKitJavaEnabled))
2155    web_prefs->java_enabled = false;
2156  web_prefs->loads_images_automatically =
2157      prefs->GetBoolean(prefs::kWebKitLoadsImagesAutomatically);
2158
2159  if (prefs->GetBoolean(prefs::kDisable3DAPIs))
2160    web_prefs->experimental_webgl_enabled = false;
2161
2162  web_prefs->memory_info_enabled =
2163      prefs->GetBoolean(prefs::kEnableMemoryInfo);
2164  web_prefs->allow_displaying_insecure_content =
2165      prefs->GetBoolean(prefs::kWebKitAllowDisplayingInsecureContent);
2166  web_prefs->allow_running_insecure_content =
2167      prefs->GetBoolean(prefs::kWebKitAllowRunningInsecureContent);
2168#if defined(OS_ANDROID)
2169  web_prefs->font_scale_factor =
2170      static_cast<float>(prefs->GetDouble(prefs::kWebKitFontScaleFactor));
2171  web_prefs->force_enable_zoom =
2172      prefs->GetBoolean(prefs::kWebKitForceEnableZoom);
2173#endif
2174
2175#if defined(OS_ANDROID)
2176  web_prefs->password_echo_enabled =
2177      prefs->GetBoolean(prefs::kWebKitPasswordEchoEnabled);
2178#else
2179  web_prefs->password_echo_enabled = browser_defaults::kPasswordEchoEnabled;
2180#endif
2181
2182#if defined(OS_CHROMEOS)
2183  // Enable password echo during OOBE when keyboard driven flag is set.
2184  if (chromeos::UserManager::IsInitialized() &&
2185      !chromeos::UserManager::Get()->IsUserLoggedIn() &&
2186      !chromeos::StartupUtils::IsOobeCompleted() &&
2187      chromeos::system::keyboard_settings::ForceKeyboardDrivenUINavigation()) {
2188    web_prefs->password_echo_enabled = true;
2189  }
2190#endif
2191
2192#if defined(OS_ANDROID)
2193  web_prefs->user_style_sheet_enabled = false;
2194#else
2195  // The user stylesheet watcher may not exist in a testing profile.
2196  UserStyleSheetWatcher* user_style_sheet_watcher =
2197      UserStyleSheetWatcherFactory::GetForProfile(profile).get();
2198  if (user_style_sheet_watcher) {
2199    web_prefs->user_style_sheet_enabled = true;
2200    web_prefs->user_style_sheet_location =
2201        user_style_sheet_watcher->user_style_sheet();
2202  } else {
2203    web_prefs->user_style_sheet_enabled = false;
2204  }
2205#endif
2206
2207  web_prefs->asynchronous_spell_checking_enabled = true;
2208  web_prefs->unified_textchecker_enabled = true;
2209
2210  web_prefs->uses_universal_detector =
2211      prefs->GetBoolean(prefs::kWebKitUsesUniversalDetector);
2212  web_prefs->text_areas_are_resizable =
2213      prefs->GetBoolean(prefs::kWebKitTextAreasAreResizable);
2214  web_prefs->hyperlink_auditing_enabled =
2215      prefs->GetBoolean(prefs::kEnableHyperlinkAuditing);
2216
2217  // Make sure we will set the default_encoding with canonical encoding name.
2218  web_prefs->default_encoding =
2219      CharacterEncoding::GetCanonicalEncodingNameByAliasName(
2220          web_prefs->default_encoding);
2221  if (web_prefs->default_encoding.empty()) {
2222    prefs->ClearPref(prefs::kDefaultCharset);
2223    web_prefs->default_encoding = prefs->GetString(prefs::kDefaultCharset);
2224  }
2225  DCHECK(!web_prefs->default_encoding.empty());
2226
2227  if (content::IsForceCompositingModeEnabled())
2228    web_prefs->force_compositing_mode = true;
2229
2230  WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
2231  extensions::ViewType view_type = extensions::GetViewType(web_contents);
2232  ExtensionService* service =
2233      extensions::ExtensionSystem::Get(profile)->extension_service();
2234  if (service) {
2235    const GURL& url = rvh->GetSiteInstance()->GetSiteURL();
2236    const Extension* extension = service->extensions()->GetByID(url.host());
2237    // Ensure that we are only granting extension preferences to URLs with
2238    // the correct scheme. Without this check, chrome-guest:// schemes used by
2239    // webview tags as well as hosts that happen to match the id of an
2240    // installed extension would get the wrong preferences.
2241    if (url.SchemeIs(extensions::kExtensionScheme)) {
2242      extension_webkit_preferences::SetPreferences(
2243          extension, view_type, web_prefs);
2244    }
2245  }
2246
2247  if (view_type == extensions::VIEW_TYPE_NOTIFICATION) {
2248    web_prefs->allow_scripts_to_close_windows = true;
2249  } else if (view_type == extensions::VIEW_TYPE_BACKGROUND_CONTENTS) {
2250    // Disable all kinds of acceleration for background pages.
2251    // See http://crbug.com/96005 and http://crbug.com/96006
2252    web_prefs->force_compositing_mode = false;
2253    web_prefs->accelerated_compositing_enabled = false;
2254  }
2255
2256#if defined(FILE_MANAGER_EXTENSION)
2257  // Override the default of suppressing HW compositing for WebUI pages for the
2258  // file manager, which is implemented using WebUI but wants HW acceleration
2259  // for video decode & render.
2260  if (url.SchemeIs(extensions::kExtensionScheme) &&
2261      url.host() == kFileBrowserDomain) {
2262    web_prefs->accelerated_compositing_enabled = true;
2263    web_prefs->accelerated_2d_canvas_enabled = true;
2264  }
2265#endif
2266}
2267
2268void ChromeContentBrowserClient::UpdateInspectorSetting(
2269    RenderViewHost* rvh, const std::string& key, const std::string& value) {
2270  content::BrowserContext* browser_context =
2271      rvh->GetProcess()->GetBrowserContext();
2272  DictionaryPrefUpdate update(
2273      Profile::FromBrowserContext(browser_context)->GetPrefs(),
2274      prefs::kWebKitInspectorSettings);
2275  DictionaryValue* inspector_settings = update.Get();
2276  inspector_settings->SetWithoutPathExpansion(key,
2277                                              Value::CreateStringValue(value));
2278}
2279
2280void ChromeContentBrowserClient::BrowserURLHandlerCreated(
2281    BrowserURLHandler* handler) {
2282  // Add the default URL handlers.
2283  handler->AddHandlerPair(&ExtensionWebUI::HandleChromeURLOverride,
2284                          BrowserURLHandler::null_handler());
2285  handler->AddHandlerPair(BrowserURLHandler::null_handler(),
2286                          &ExtensionWebUI::HandleChromeURLOverrideReverse);
2287
2288  // about: handler. Must come before chrome: handler, since it will
2289  // rewrite about: urls to chrome: URLs and then expect chrome: to
2290  // actually handle them.
2291  handler->AddHandlerPair(&WillHandleBrowserAboutURL,
2292                          BrowserURLHandler::null_handler());
2293
2294  // Handler to rewrite chrome://newtab for InstantExtended.
2295  handler->AddHandlerPair(&chrome::HandleNewTabURLRewrite,
2296                          &chrome::HandleNewTabURLReverseRewrite);
2297
2298  // chrome: & friends.
2299  handler->AddHandlerPair(&HandleWebUI, &HandleWebUIReverse);
2300}
2301
2302void ChromeContentBrowserClient::ClearCache(RenderViewHost* rvh) {
2303  Profile* profile = Profile::FromBrowserContext(
2304      rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2305  BrowsingDataRemover* remover =
2306      BrowsingDataRemover::CreateForUnboundedRange(profile);
2307  remover->Remove(BrowsingDataRemover::REMOVE_CACHE,
2308                  BrowsingDataHelper::UNPROTECTED_WEB);
2309  // BrowsingDataRemover takes care of deleting itself when done.
2310}
2311
2312void ChromeContentBrowserClient::ClearCookies(RenderViewHost* rvh) {
2313  Profile* profile = Profile::FromBrowserContext(
2314      rvh->GetSiteInstance()->GetProcess()->GetBrowserContext());
2315  BrowsingDataRemover* remover =
2316      BrowsingDataRemover::CreateForUnboundedRange(profile);
2317  int remove_mask = BrowsingDataRemover::REMOVE_SITE_DATA;
2318  remover->Remove(remove_mask, BrowsingDataHelper::UNPROTECTED_WEB);
2319  // BrowsingDataRemover takes care of deleting itself when done.
2320}
2321
2322base::FilePath ChromeContentBrowserClient::GetDefaultDownloadDirectory() {
2323  return download_util::GetDefaultDownloadDirectory();
2324}
2325
2326std::string ChromeContentBrowserClient::GetDefaultDownloadName() {
2327  return l10n_util::GetStringUTF8(IDS_DEFAULT_DOWNLOAD_FILENAME);
2328}
2329
2330void ChromeContentBrowserClient::DidCreatePpapiPlugin(
2331    content::BrowserPpapiHost* browser_host) {
2332#if defined(ENABLE_PLUGINS)
2333  browser_host->GetPpapiHost()->AddHostFactoryFilter(
2334      scoped_ptr<ppapi::host::HostFactory>(
2335          new ChromeBrowserPepperHostFactory(browser_host)));
2336#endif
2337}
2338
2339content::BrowserPpapiHost*
2340    ChromeContentBrowserClient::GetExternalBrowserPpapiHost(
2341        int plugin_process_id) {
2342  BrowserChildProcessHostIterator iter(PROCESS_TYPE_NACL_LOADER);
2343  while (!iter.Done()) {
2344    NaClProcessHost* host = static_cast<NaClProcessHost*>(iter.GetDelegate());
2345    if (host->process() &&
2346        host->process()->GetData().id == plugin_process_id) {
2347      // Found the plugin.
2348      return host->browser_ppapi_host();
2349    }
2350    ++iter;
2351  }
2352  return NULL;
2353}
2354
2355bool ChromeContentBrowserClient::SupportsBrowserPlugin(
2356    content::BrowserContext* browser_context, const GURL& site_url) {
2357  if (CommandLine::ForCurrentProcess()->HasSwitch(
2358          switches::kEnableBrowserPluginForAllViewTypes))
2359    return true;
2360
2361  Profile* profile = Profile::FromBrowserContext(browser_context);
2362  ExtensionService* service =
2363      extensions::ExtensionSystem::Get(profile)->extension_service();
2364  if (!service)
2365    return false;
2366
2367  const Extension* extension =
2368      service->extensions()->GetExtensionOrAppByURL(site_url);
2369  if (!extension)
2370    return false;
2371
2372  return extension->HasAPIPermission(APIPermission::kWebView) ||
2373         extension->HasAPIPermission(APIPermission::kAdView);
2374}
2375
2376bool ChromeContentBrowserClient::AllowPepperSocketAPI(
2377    content::BrowserContext* browser_context,
2378    const GURL& url,
2379    bool private_api,
2380    const content::SocketPermissionRequest& params) {
2381#if defined(ENABLE_PLUGINS)
2382  Profile* profile = Profile::FromBrowserContext(browser_context);
2383  const ExtensionSet* extension_set = NULL;
2384  if (profile) {
2385    extension_set = extensions::ExtensionSystem::Get(profile)->
2386        extension_service()->extensions();
2387  }
2388
2389  if (private_api) {
2390    // Access to private socket APIs is controlled by the whitelist.
2391    if (IsExtensionOrSharedModuleWhitelisted(url, extension_set,
2392                                             allowed_socket_origins_)) {
2393      return true;
2394    }
2395  } else {
2396    // Access to public socket APIs is controlled by extension permissions.
2397    if (url.is_valid() && url.SchemeIs(extensions::kExtensionScheme) &&
2398        extension_set) {
2399      const Extension* extension = extension_set->GetByID(url.host());
2400      if (extension) {
2401        extensions::SocketPermission::CheckParam check_params(
2402            params.type, params.host, params.port);
2403        if (extensions::PermissionsData::CheckAPIPermissionWithParam(
2404                extension, extensions::APIPermission::kSocket, &check_params)) {
2405          return true;
2406        }
2407      }
2408    }
2409  }
2410
2411  // Allow both public and private APIs if the command line says so.
2412  return IsHostAllowedByCommandLine(url, extension_set,
2413                                    switches::kAllowNaClSocketAPI);
2414#else
2415  return false;
2416#endif
2417}
2418
2419ui::SelectFilePolicy* ChromeContentBrowserClient::CreateSelectFilePolicy(
2420    WebContents* web_contents) {
2421  return new ChromeSelectFilePolicy(web_contents);
2422}
2423
2424void ChromeContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2425    std::vector<std::string>* additional_allowed_schemes) {
2426  ContentBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
2427      additional_allowed_schemes);
2428  additional_allowed_schemes->push_back(kChromeUIScheme);
2429  additional_allowed_schemes->push_back(extensions::kExtensionScheme);
2430}
2431
2432void ChromeContentBrowserClient::GetAdditionalFileSystemBackends(
2433    content::BrowserContext* browser_context,
2434    const base::FilePath& storage_partition_path,
2435    ScopedVector<fileapi::FileSystemBackend>* additional_backends) {
2436#if !defined(OS_ANDROID)
2437  base::SequencedWorkerPool* pool = content::BrowserThread::GetBlockingPool();
2438  additional_backends->push_back(new MediaFileSystemBackend(
2439      storage_partition_path,
2440      pool->GetSequencedTaskRunner(pool->GetNamedSequenceToken(
2441          MediaFileSystemBackend::kMediaTaskRunnerName)).get()));
2442#endif
2443#if defined(OS_CHROMEOS)
2444  fileapi::ExternalMountPoints* external_mount_points =
2445      content::BrowserContext::GetMountPoints(browser_context);
2446  DCHECK(external_mount_points);
2447  chromeos::FileSystemBackend* backend =
2448      new chromeos::FileSystemBackend(
2449          new drive::FileSystemBackendDelegate(browser_context),
2450          browser_context->GetSpecialStoragePolicy(),
2451          external_mount_points,
2452          fileapi::ExternalMountPoints::GetSystemInstance());
2453  backend->AddSystemMountPoints();
2454  DCHECK(backend->CanHandleType(fileapi::kFileSystemTypeExternal));
2455  additional_backends->push_back(backend);
2456#endif
2457
2458  additional_backends->push_back(new sync_file_system::SyncFileSystemBackend());
2459}
2460
2461#if defined(OS_POSIX) && !defined(OS_MACOSX)
2462void ChromeContentBrowserClient::GetAdditionalMappedFilesForChildProcess(
2463    const CommandLine& command_line,
2464    int child_process_id,
2465    std::vector<FileDescriptorInfo>* mappings) {
2466#if defined(OS_ANDROID)
2467  base::FilePath data_path;
2468  PathService::Get(ui::DIR_RESOURCE_PAKS_ANDROID, &data_path);
2469  DCHECK(!data_path.empty());
2470
2471  int flags = base::PLATFORM_FILE_OPEN | base::PLATFORM_FILE_READ;
2472  base::FilePath chrome_pak = data_path.AppendASCII("chrome.pak");
2473  base::PlatformFile f =
2474      base::CreatePlatformFile(chrome_pak, flags, NULL, NULL);
2475  DCHECK(f != base::kInvalidPlatformFileValue);
2476  mappings->push_back(FileDescriptorInfo(kAndroidChromePakDescriptor,
2477                                         FileDescriptor(f, true)));
2478
2479  base::FilePath chrome_resources_pak =
2480      data_path.AppendASCII("chrome_100_percent.pak");
2481  f = base::CreatePlatformFile(chrome_resources_pak, flags, NULL, NULL);
2482  DCHECK(f != base::kInvalidPlatformFileValue);
2483  mappings->push_back(FileDescriptorInfo(kAndroidChrome100PercentPakDescriptor,
2484                                         FileDescriptor(f, true)));
2485
2486  const std::string locale = GetApplicationLocale();
2487  base::FilePath locale_pak = ResourceBundle::GetSharedInstance().
2488      GetLocaleFilePath(locale, false);
2489  f = base::CreatePlatformFile(locale_pak, flags, NULL, NULL);
2490  DCHECK(f != base::kInvalidPlatformFileValue);
2491  mappings->push_back(FileDescriptorInfo(kAndroidLocalePakDescriptor,
2492                                         FileDescriptor(f, true)));
2493
2494  base::FilePath resources_pack_path;
2495  PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
2496  f = base::CreatePlatformFile(resources_pack_path, flags, NULL, NULL);
2497  DCHECK(f != base::kInvalidPlatformFileValue);
2498  mappings->push_back(FileDescriptorInfo(kAndroidUIResourcesPakDescriptor,
2499                                         FileDescriptor(f, true)));
2500
2501  if (IsCrashReporterEnabled()) {
2502    f = CrashDumpManager::GetInstance()->CreateMinidumpFile(child_process_id);
2503    if (f == base::kInvalidPlatformFileValue) {
2504      LOG(ERROR) << "Failed to create file for minidump, crash reporting will "
2505                 "be disabled for this process.";
2506    } else {
2507      mappings->push_back(FileDescriptorInfo(kAndroidMinidumpDescriptor,
2508                                             FileDescriptor(f, true)));
2509    }
2510  }
2511
2512#else
2513  int crash_signal_fd = GetCrashSignalFD(command_line);
2514  if (crash_signal_fd >= 0) {
2515    mappings->push_back(FileDescriptorInfo(kCrashDumpSignal,
2516                                           FileDescriptor(crash_signal_fd,
2517                                                          false)));
2518  }
2519#endif  // defined(OS_ANDROID)
2520}
2521#endif  // defined(OS_POSIX) && !defined(OS_MACOSX)
2522
2523#if defined(OS_WIN)
2524const wchar_t* ChromeContentBrowserClient::GetResourceDllName() {
2525  return chrome::kBrowserResourcesDll;
2526}
2527
2528void ChromeContentBrowserClient::PreSpawnRenderer(
2529    sandbox::TargetPolicy* policy,
2530    bool* success) {
2531  // This code is duplicated in nacl_exe_win_64.cc.
2532  // Allow the server side of a pipe restricted to the "chrome.nacl."
2533  // namespace so that it cannot impersonate other system or other chrome
2534  // service pipes.
2535  sandbox::ResultCode result = policy->AddRule(
2536      sandbox::TargetPolicy::SUBSYS_NAMED_PIPES,
2537      sandbox::TargetPolicy::NAMEDPIPES_ALLOW_ANY,
2538      L"\\\\.\\pipe\\chrome.nacl.*");
2539  if (result != sandbox::SBOX_ALL_OK) {
2540    *success = false;
2541    return;
2542  }
2543
2544  // Renderers need to send named pipe handles and shared memory
2545  // segment handles to NaCl loader processes.
2546  result = policy->AddRule(sandbox::TargetPolicy::SUBSYS_HANDLES,
2547                           sandbox::TargetPolicy::HANDLES_DUP_ANY,
2548                           L"File");
2549  if (result != sandbox::SBOX_ALL_OK) {
2550    *success = false;
2551    return;
2552  }
2553}
2554#endif
2555
2556#if defined(USE_NSS)
2557crypto::CryptoModuleBlockingPasswordDelegate*
2558    ChromeContentBrowserClient::GetCryptoPasswordDelegate(
2559        const GURL& url) {
2560  return chrome::NewCryptoModuleBlockingDialogDelegate(
2561      chrome::kCryptoModulePasswordKeygen, url.host());
2562}
2563#endif
2564
2565}  // namespace chrome
2566