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