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