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