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