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