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