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