Upstream version 11.39.250.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / profiles / profile_impl.cc
index 52acc0c..86ffa39 100644 (file)
@@ -4,14 +4,16 @@
 
 #include "chrome/browser/profiles/profile_impl.h"
 
+#include <vector>
+
 #include "base/bind.h"
 #include "base/callback.h"
 #include "base/command_line.h"
 #include "base/compiler_specific.h"
 #include "base/debug/trace_event.h"
 #include "base/environment.h"
-#include "base/file_util.h"
 #include "base/files/file_path.h"
+#include "base/files/file_util.h"
 #include "base/memory/scoped_ptr.h"
 #include "base/path_service.h"
 #include "base/prefs/json_pref_store.h"
 #include "base/threading/sequenced_worker_pool.h"
 #include "base/version.h"
 #include "chrome/browser/autocomplete/autocomplete_classifier.h"
+#include "chrome/browser/autocomplete/shortcuts_backend.h"
 #include "chrome/browser/background/background_contents_service_factory.h"
 #include "chrome/browser/background/background_mode_manager.h"
-#include "chrome/browser/bookmarks/bookmark_model.h"
 #include "chrome/browser/bookmarks/bookmark_model_factory.h"
 #include "chrome/browser/browser_process.h"
 #include "chrome/browser/chrome_notification_types.h"
 #include "chrome/browser/content_settings/cookie_settings.h"
 #include "chrome/browser/content_settings/host_content_settings_map.h"
+#include "chrome/browser/dom_distiller/profile_utils.h"
+#include "chrome/browser/domain_reliability/service_factory.h"
 #include "chrome/browser/download/chrome_download_manager_delegate.h"
 #include "chrome/browser/download/download_service.h"
 #include "chrome/browser/download/download_service_factory.h"
-#include "chrome/browser/extensions/extension_service.h"
-#include "chrome/browser/extensions/extension_special_storage_policy.h"
-#include "chrome/browser/geolocation/chrome_geolocation_permission_context.h"
-#include "chrome/browser/geolocation/chrome_geolocation_permission_context_factory.h"
-#include "chrome/browser/history/shortcuts_backend.h"
 #include "chrome/browser/history/top_sites.h"
-#include "chrome/browser/media/chrome_midi_permission_context.h"
-#include "chrome/browser/media/chrome_midi_permission_context_factory.h"
-#include "chrome/browser/metrics/metrics_service.h"
-#include "chrome/browser/net/chrome_url_request_context.h"
 #include "chrome/browser/net/net_pref_observer.h"
 #include "chrome/browser/net/predictor.h"
 #include "chrome/browser/net/pref_proxy_config_tracker.h"
 #include "chrome/browser/net/proxy_service_factory.h"
+#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_configurator.h"
+#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings.h"
+#include "chrome/browser/net/spdyproxy/data_reduction_proxy_chrome_settings_factory.h"
 #include "chrome/browser/net/ssl_config_service_manager.h"
 #include "chrome/browser/plugins/chrome_plugin_service_filter.h"
 #include "chrome/browser/plugins/plugin_prefs.h"
@@ -57,6 +55,7 @@
 #include "chrome/browser/prefs/browser_prefs.h"
 #include "chrome/browser/prefs/chrome_pref_service_factory.h"
 #include "chrome/browser/prefs/pref_service_syncable.h"
+#include "chrome/browser/prefs/tracked/tracked_preference_validation_delegate.h"
 #include "chrome/browser/prerender/prerender_manager_factory.h"
 #include "chrome/browser/profiles/bookmark_model_loaded_observer.h"
 #include "chrome/browser/profiles/chrome_version_service.h"
 #include "chrome/browser/profiles/profile_info_cache.h"
 #include "chrome/browser/profiles/profile_manager.h"
 #include "chrome/browser/profiles/profile_metrics.h"
-#include "chrome/browser/search_engines/template_url_fetcher.h"
+#include "chrome/browser/safe_browsing/safe_browsing_service.h"
+#include "chrome/browser/services/gcm/gcm_profile_service.h"
+#include "chrome/browser/services/gcm/gcm_profile_service_factory.h"
+#include "chrome/browser/services/gcm/push_messaging_service_impl.h"
 #include "chrome/browser/sessions/session_service_factory.h"
+#include "chrome/browser/signin/signin_ui_util.h"
+#include "chrome/browser/ssl/chrome_ssl_host_state_delegate.h"
+#include "chrome/browser/ssl/chrome_ssl_host_state_delegate_factory.h"
 #include "chrome/browser/ui/startup/startup_browser_creator.h"
-#include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
-#include "chrome/browser/webdata/web_data_service.h"
 #include "chrome/common/chrome_constants.h"
 #include "chrome/common/chrome_paths_internal.h"
 #include "chrome/common/chrome_switches.h"
 #include "chrome/common/chrome_version_info.h"
-#include "chrome/common/net/url_fixer_upper.h"
 #include "chrome/common/pref_names.h"
 #include "chrome/common/url_constants.h"
-#include "components/browser_context_keyed_service/browser_context_dependency_manager.h"
+#include "chrome/grit/chromium_strings.h"
+#include "components/bookmarks/browser/bookmark_model.h"
+#include "components/data_reduction_proxy/browser/data_reduction_proxy_params.h"
+#include "components/data_reduction_proxy/browser/data_reduction_proxy_settings.h"
+#include "components/data_reduction_proxy/browser/data_reduction_proxy_statistics_prefs.h"
+#include "components/domain_reliability/monitor.h"
+#include "components/domain_reliability/service.h"
+#include "components/keyed_service/content/browser_context_dependency_manager.h"
+#include "components/metrics/metrics_service.h"
+#include "components/pref_registry/pref_registry_syncable.h"
 #include "components/startup_metric_utils/startup_metric_utils.h"
-#include "components/user_prefs/pref_registry_syncable.h"
+#include "components/url_fixer/url_fixer.h"
 #include "components/user_prefs/user_prefs.h"
 #include "content/public/browser/browser_thread.h"
 #include "content/public/browser/dom_storage_context.h"
 #include "content/public/browser/notification_service.h"
 #include "content/public/browser/render_process_host.h"
 #include "content/public/browser/storage_partition.h"
+#include "content/public/browser/url_data_source.h"
 #include "content/public/browser/user_metrics.h"
 #include "content/public/common/content_constants.h"
-#include "extensions/browser/extension_pref_store.h"
-#include "extensions/browser/extension_pref_value_map.h"
-#include "extensions/browser/extension_pref_value_map_factory.h"
-#include "extensions/browser/extension_system.h"
-#include "grit/chromium_strings.h"
-#include "grit/generated_resources.h"
+#include "content/public/common/page_zoom.h"
 #include "ui/base/l10n/l10n_util.h"
 
 #if defined(OS_ANDROID)
 #include "chrome/browser/media/protected_media_identifier_permission_context.h"
 #include "chrome/browser/media/protected_media_identifier_permission_context_factory.h"
-#endif  // defined(OS_ANDROID)
+#endif
+
+#if defined(OS_CHROMEOS)
+#include "chrome/browser/chromeos/locale_change_guard.h"
+#include "chrome/browser/chromeos/preferences.h"
+#include "chrome/browser/chromeos/profiles/profile_helper.h"
+#include "components/user_manager/user_manager.h"
+#endif
 
 #if defined(ENABLE_CONFIGURATION_POLICY)
 #include "chrome/browser/policy/schema_registry_service.h"
 #include "chrome/browser/policy/schema_registry_service_factory.h"
 #include "components/policy/core/browser/browser_policy_connector.h"
 #if defined(OS_CHROMEOS)
+#include "chrome/browser/chromeos/login/login_utils.h"
 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_factory_chromeos.h"
 #else
 #endif
 #endif
 
-#if defined(ENABLE_MANAGED_USERS)
-#include "chrome/browser/managed_mode/managed_user_settings_service.h"
-#include "chrome/browser/managed_mode/managed_user_settings_service_factory.h"
+#if defined(ENABLE_EXTENSIONS)
+#include "chrome/browser/extensions/extension_service.h"
+#include "chrome/browser/extensions/extension_special_storage_policy.h"
+#include "chrome/browser/ui/webui/extensions/extension_icon_source.h"
+#include "extensions/browser/extension_pref_store.h"
+#include "extensions/browser/extension_pref_value_map.h"
+#include "extensions/browser/extension_pref_value_map_factory.h"
+#include "extensions/browser/extension_system.h"
+#include "extensions/browser/guest_view/guest_view_manager.h"
 #endif
 
-#if defined(OS_CHROMEOS)
-#include "chrome/browser/chromeos/locale_change_guard.h"
-#include "chrome/browser/chromeos/login/user_manager.h"
-#include "chrome/browser/chromeos/preferences.h"
-#include "chrome/browser/chromeos/profiles/profile_helper.h"
+#if defined(ENABLE_MANAGED_USERS)
+#include "chrome/browser/supervised_user/supervised_user_settings_service.h"
+#include "chrome/browser/supervised_user/supervised_user_settings_service_factory.h"
 #endif
 
 using base::Time;
@@ -136,39 +155,22 @@ using content::HostZoomMap;
 
 namespace {
 
-// Constrict us to a very specific platform and architecture to make sure
-// ifdefs don't cause problems with the check.
-#if defined(OS_LINUX) && defined(TOOLKIT_GTK) && defined(ARCH_CPU_X86_64) && \
-  !defined(_GLIBCXX_DEBUG)
-// Make sure that the ProfileImpl doesn't grow. We're currently trying to drive
-// the number of services that are included in ProfileImpl (instead of using
-// BrowserContextKeyedServiceFactory) to zero.
-//
-// If you don't know about this effort, please read:
-//   https://sites.google.com/a/chromium.org/dev/developers/design-documents/profile-architecture
-//
-// REVIEWERS: Do not let anyone increment this. We need to drive the number of
-// raw accessed services down to zero. DO NOT LET PEOPLE REGRESS THIS UNLESS
-// THE PATCH ITSELF IS MAKING PROGRESS ON PKSF REFACTORING.
-COMPILE_ASSERT(sizeof(ProfileImpl) <= 744u, profile_impl_size_unexpected);
-#endif
-
 #if defined(ENABLE_SESSION_SERVICE)
 // Delay, in milliseconds, before we explicitly create the SessionService.
-static const int kCreateSessionServiceDelayMS = 500;
+const int kCreateSessionServiceDelayMS = 500;
 #endif
 
 // Text content of README file created in each profile directory. Both %s
 // placeholders must contain the product name. This is not localizable and hence
 // not in resources.
-static const char kReadmeText[] =
+const char kReadmeText[] =
     "%s settings and storage represent user-selected preferences and "
     "information and MUST not be extracted, overwritten or modified except "
     "through %s defined APIs.";
 
 // Value written to prefs for EXIT_CRASHED and EXIT_SESSION_ENDED.
-const char* const kPrefExitTypeCrashed = "Crashed";
-const char* const kPrefExitTypeSessionEnded = "SessionEnded";
+const char kPrefExitTypeCrashed[] = "Crashed";
+const char kPrefExitTypeSessionEnded[] = "SessionEnded";
 
 // Helper method needed because PostTask cannot currently take a Callback
 // function with non-void return type.
@@ -217,8 +219,8 @@ void EnsureReadmeFile(const base::FilePath& base) {
   std::string product_name = l10n_util::GetStringUTF8(IDS_PRODUCT_NAME);
   std::string readme_text = base::StringPrintf(
       kReadmeText, product_name.c_str(), product_name.c_str());
-  if (file_util::WriteFile(
-          readme_path, readme_text.data(), readme_text.size()) == -1) {
+  if (base::WriteFile(readme_path, readme_text.data(), readme_text.size()) ==
+      -1) {
     LOG(ERROR) << "Could not create README file.";
   }
 }
@@ -246,13 +248,28 @@ std::string ExitTypeToSessionTypePrefValue(Profile::ExitType type) {
   return std::string();
 }
 
+PrefStore* CreateExtensionPrefStore(Profile* profile,
+                                    bool incognito_pref_store) {
+#if defined(ENABLE_EXTENSIONS)
+  return new ExtensionPrefStore(
+      ExtensionPrefValueMapFactory::GetForBrowserContext(profile),
+      incognito_pref_store);
+#else
+  return NULL;
+#endif
+}
+
 }  // namespace
 
 // static
 Profile* Profile::CreateProfile(const base::FilePath& path,
                                 Delegate* delegate,
                                 CreateMode create_mode) {
-  TRACE_EVENT0("browser", "Profile::CreateProfile")
+  TRACE_EVENT_BEGIN1("browser",
+                     "Profile::CreateProfile",
+                     "profile_path",
+                     path.value().c_str());
+
   // Get sequenced task runner for making sure that file operations of
   // this profile (defined by |path|) are executed in expected order
   // (what was previously assured by the FILE thread).
@@ -307,16 +324,28 @@ void ProfileImpl::RegisterProfilePrefs(
       prefs::kProfileAvatarIndex,
       -1,
       user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
-  registry->RegisterStringPref(prefs::kManagedUserId,
-                               std::string(),
-                               user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
-  registry->RegisterStringPref(prefs::kProfileName,
-                               std::string(),
-                               user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
+  // Whether a profile is using an avatar without having explicitely chosen it
+  // (i.e. was assigned by default by legacy profile creation).
   registry->RegisterBooleanPref(
-      prefs::kProfileIsManaged,
+      prefs::kProfileUsingDefaultAvatar,
+      true,
+      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
+  registry->RegisterBooleanPref(
+      prefs::kProfileUsingGAIAAvatar,
       false,
       user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
+  // Whether a profile is using a default avatar name (eg. Pickles or Person 1).
+  registry->RegisterBooleanPref(
+      prefs::kProfileUsingDefaultName,
+      true,
+      user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
+  registry->RegisterStringPref(
+      prefs::kSupervisedUserId,
+      std::string(),
+      user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
+  registry->RegisterStringPref(prefs::kProfileName,
+                               std::string(),
+                               user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
   registry->RegisterStringPref(prefs::kHomePage,
                                std::string(),
                                user_prefs::PrefRegistrySyncable::SYNCABLE_PREF);
@@ -328,11 +357,7 @@ void ProfileImpl::RegisterProfilePrefs(
 #endif
   registry->RegisterBooleanPref(
       prefs::kPrintPreviewDisabled,
-#if defined(GOOGLE_CHROME_BUILD)
       false,
-#else
-      true,
-#endif
       user_prefs::PrefRegistrySyncable::UNSYNCABLE_PREF);
   registry->RegisterBooleanPref(
       prefs::kForceEphemeralProfiles,
@@ -388,6 +413,7 @@ ProfileImpl::ProfileImpl(
   const CommandLine* command_line = CommandLine::ForCurrentProcess();
   predictor_ = chrome_browser_net::Predictor::CreatePredictor(
       !command_line->HasSwitch(switches::kDisablePreconnect),
+      !command_line->HasSwitch(switches::kDnsPrefetchDisable),
       g_browser_process->profile_manager() == NULL);
 
   // If we are creating the profile synchronously, then we should load the
@@ -431,14 +457,21 @@ ProfileImpl::ProfileImpl(
   BrowserContextDependencyManager::GetInstance()->
       RegisterProfilePrefsForServices(this, pref_registry_.get());
 
-  ManagedUserSettingsService* managed_user_settings = NULL;
+  SupervisedUserSettingsService* supervised_user_settings = NULL;
 #if defined(ENABLE_MANAGED_USERS)
-  managed_user_settings =
-      ManagedUserSettingsServiceFactory::GetForProfile(this);
-  managed_user_settings->Init(
+  supervised_user_settings =
+      SupervisedUserSettingsServiceFactory::GetForProfile(this);
+  supervised_user_settings->Init(
       path_, sequenced_task_runner, create_mode == CREATE_MODE_SYNCHRONOUS);
 #endif
 
+  scoped_refptr<SafeBrowsingService> safe_browsing_service(
+      g_browser_process->safe_browsing_service());
+  if (safe_browsing_service.get()) {
+    pref_validation_delegate_ =
+        safe_browsing_service->CreatePreferenceValidationDelegate(this).Pass();
+  }
+
   {
     // On startup, preference loading is always synchronous so a scoped timer
     // will work here.
@@ -447,10 +480,10 @@ ProfileImpl::ProfileImpl(
     prefs_ = chrome_prefs::CreateProfilePrefs(
         path_,
         sequenced_task_runner,
+        pref_validation_delegate_.get(),
         profile_policy_connector_->policy_service(),
-        managed_user_settings,
-        new ExtensionPrefStore(
-            ExtensionPrefValueMapFactory::GetForBrowserContext(this), false),
+        supervised_user_settings,
+        CreateExtensionPrefStore(this, false),
         pref_registry_,
         async_prefs).Pass();
     // Register on BrowserContext.
@@ -481,17 +514,38 @@ void ProfileImpl::DoFinalInit() {
       base::Bind(&ProfileImpl::UpdateProfileUserNameCache,
                  base::Unretained(this)));
   pref_change_registrar_.Add(
+      prefs::kSupervisedUserId,
+      base::Bind(&ProfileImpl::UpdateProfileSupervisedUserIdCache,
+                 base::Unretained(this)));
+  pref_change_registrar_.Add(
       prefs::kDefaultZoomLevel,
       base::Bind(&ProfileImpl::OnDefaultZoomLevelChanged,
                  base::Unretained(this)));
+
+  // Changes in the profile avatar.
   pref_change_registrar_.Add(
       prefs::kProfileAvatarIndex,
       base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
                  base::Unretained(this)));
   pref_change_registrar_.Add(
+      prefs::kProfileUsingDefaultAvatar,
+      base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
+                 base::Unretained(this)));
+  pref_change_registrar_.Add(
+      prefs::kProfileUsingGAIAAvatar,
+      base::Bind(&ProfileImpl::UpdateProfileAvatarCache,
+                 base::Unretained(this)));
+
+  // Changes in the profile name.
+  pref_change_registrar_.Add(
+      prefs::kProfileUsingDefaultName,
+      base::Bind(&ProfileImpl::UpdateProfileNameCache,
+                 base::Unretained(this)));
+  pref_change_registrar_.Add(
       prefs::kProfileName,
       base::Bind(&ProfileImpl::UpdateProfileNameCache,
                  base::Unretained(this)));
+
   pref_change_registrar_.Add(
       prefs::kForceEphemeralProfiles,
       base::Bind(&ProfileImpl::UpdateProfileIsEphemeralCache,
@@ -511,6 +565,7 @@ void ProfileImpl::DoFinalInit() {
   // kGoogleServicesUsername, initialize components that depend on it to reflect
   // the current value.
   UpdateProfileUserNameCache();
+  UpdateProfileSupervisedUserIdCache();
   UpdateProfileIsEphemeralCache();
   GAIAInfoUpdateServiceFactory::GetForProfile(this);
 
@@ -535,9 +590,8 @@ void ProfileImpl::DoFinalInit() {
 
   base::FilePath cookie_path = GetPath();
   cookie_path = cookie_path.Append(chrome::kCookieFilename);
-  base::FilePath server_bound_cert_path = GetPath();
-  server_bound_cert_path =
-      server_bound_cert_path.Append(chrome::kOBCertFilename);
+  base::FilePath channel_id_path = GetPath();
+  channel_id_path = channel_id_path.Append(chrome::kChannelIDFilename);
   base::FilePath cache_path = base_cache_path_;
   int cache_max_size;
   GetCacheParameters(false, &cache_path, &cache_max_size);
@@ -573,15 +627,68 @@ void ProfileImpl::DoFinalInit() {
 
   InitHostZoomMap();
 
+  base::Callback<void(bool)> data_reduction_proxy_unavailable;
+  scoped_ptr<data_reduction_proxy::DataReductionProxyParams>
+      data_reduction_proxy_params;
+  scoped_ptr<DataReductionProxyChromeConfigurator> chrome_configurator;
+  scoped_ptr<data_reduction_proxy::DataReductionProxyStatisticsPrefs>
+      data_reduction_proxy_statistics_prefs;
+  DataReductionProxyChromeSettings* data_reduction_proxy_chrome_settings =
+      DataReductionProxyChromeSettingsFactory::GetForBrowserContext(this);
+  data_reduction_proxy_params =
+      data_reduction_proxy_chrome_settings->params()->Clone();
+  data_reduction_proxy_unavailable =
+      base::Bind(
+          &data_reduction_proxy::DataReductionProxySettings::SetUnreachable,
+          base::Unretained(data_reduction_proxy_chrome_settings));
+  // The configurator is used by DataReductionProxyChromeSettings and
+  // ProfileIOData. Ownership is passed to the latter via ProfileIOData::Handle,
+  // which is only destroyed after BrowserContextKeyedServices,
+  // including DataReductionProxyChromeSettings.
+  chrome_configurator.reset(
+      new DataReductionProxyChromeConfigurator(
+          prefs_.get(),
+          BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
+  // Retain a raw pointer to use for initialization of data reduction proxy
+  // settings after ownership is passed.
+  DataReductionProxyChromeConfigurator*
+      data_reduction_proxy_chrome_configurator = chrome_configurator.get();
+#if defined(OS_ANDROID) || defined(OS_IOS)
+  // On mobile we write data reduction proxy prefs directly to the pref service.
+  // On desktop we store data reduction proxy prefs in memory, writing to disk
+  // every 60 minutes and on termination. Shutdown hooks must be added for
+  // Android and iOS in order for non-zero delays to be supported.
+  // (http://crbug.com/408264)
+  base::TimeDelta commit_delay = base::TimeDelta();
+#else
+  base::TimeDelta commit_delay = base::TimeDelta::FromMinutes(60);
+#endif
+  data_reduction_proxy_statistics_prefs =
+      scoped_ptr<data_reduction_proxy::DataReductionProxyStatisticsPrefs>(
+          new data_reduction_proxy::DataReductionProxyStatisticsPrefs(
+              g_browser_process->local_state(),
+              base::MessageLoopProxy::current(),
+              commit_delay));
+  data_reduction_proxy_chrome_settings->SetDataReductionProxyStatisticsPrefs(
+      data_reduction_proxy_statistics_prefs.get());
+
   // Make sure we initialize the ProfileIOData after everything else has been
   // initialized that we might be reading from the IO thread.
 
-  io_data_.Init(cookie_path, server_bound_cert_path, cache_path,
+  io_data_.Init(cookie_path, channel_id_path, cache_path,
                 cache_max_size, media_cache_path, media_cache_max_size,
                 extensions_cookie_path, GetPath(), infinite_cache_path,
-                predictor_,
-                session_cookie_mode,
-                GetSpecialStoragePolicy());
+                predictor_, session_cookie_mode, GetSpecialStoragePolicy(),
+                CreateDomainReliabilityMonitor(local_state),
+                data_reduction_proxy_unavailable,
+                chrome_configurator.Pass(),
+                data_reduction_proxy_params.Pass(),
+                data_reduction_proxy_statistics_prefs.Pass());
+  data_reduction_proxy_chrome_settings->InitDataReductionProxySettings(
+      data_reduction_proxy_chrome_configurator,
+      prefs_.get(),
+      g_browser_process->local_state(),
+      GetRequestContext());
 
 #if defined(ENABLE_PLUGINS)
   ChromePluginServiceFilter::GetInstance()->RegisterResourceContext(
@@ -595,14 +702,27 @@ void ProfileImpl::DoFinalInit() {
         base::Bind(&EnsureReadmeFile, GetPath()),
         base::TimeDelta::FromMilliseconds(create_readme_delay_ms));
 
-  if (!CommandLine::ForCurrentProcess()->HasSwitch(
-          switches::kDisableRestoreSessionState)) {
-    TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk")
-    content::BrowserContext::GetDefaultStoragePartition(this)->
-        GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
-  }
+  TRACE_EVENT0("browser", "ProfileImpl::SetSaveSessionStorageOnDisk");
+  content::BrowserContext::GetDefaultStoragePartition(this)->
+      GetDOMStorageContext()->SetSaveSessionStorageOnDisk();
+
+  // The DomDistillerViewerSource is not a normal WebUI so it must be registered
+  // as a URLDataSource early.
+  RegisterDomDistillerViewerSource(this);
 
   // Creation has been finished.
+  TRACE_EVENT_END1("browser",
+                   "Profile::CreateProfile",
+                   "profile_path",
+                   path_.value().c_str());
+
+#if defined(OS_CHROMEOS)
+  if (chromeos::LoginUtils::Get()->RestartToApplyPerSessionFlagsIfNeed(this,
+                                                                       true)) {
+    return;
+  }
+#endif
+
   if (delegate_) {
     TRACE_EVENT0("browser", "ProfileImpl::DoFileInit:DelegateOnProfileCreated")
     delegate_->OnProfileCreated(this, true, IsNewProfile());
@@ -619,10 +739,16 @@ void ProfileImpl::DoFinalInit() {
   BookmarkModel* model = BookmarkModelFactory::GetForProfile(this);
   model->AddObserver(new BookmarkModelLoadedObserver(this));
 #endif
+
+  gcm::PushMessagingServiceImpl::InitializeForProfile(this);
+
+#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS) && !defined(OS_IOS)
+  signin_ui_util::InitializePrefsForProfile(this);
+#endif
 }
 
 void ProfileImpl::InitHostZoomMap() {
-  HostZoomMap* host_zoom_map = HostZoomMap::GetForBrowserContext(this);
+  HostZoomMap* host_zoom_map = HostZoomMap::GetDefaultForBrowserContext(this);
   host_zoom_map->SetDefaultZoomLevel(
       prefs_->GetDouble(prefs::kDefaultZoomLevel));
 
@@ -630,6 +756,7 @@ void ProfileImpl::InitHostZoomMap() {
       prefs_->GetDictionary(prefs::kPerHostZoomLevels);
   // Careful: The returned value could be NULL if the pref has never been set.
   if (host_zoom_dictionary != NULL) {
+    std::vector<std::string> keys_to_remove;
     for (base::DictionaryValue::Iterator i(*host_zoom_dictionary); !i.IsAtEnd();
          i.Advance()) {
       const std::string& host(i.key());
@@ -637,8 +764,30 @@ void ProfileImpl::InitHostZoomMap() {
 
       bool success = i.value().GetAsDouble(&zoom_level);
       DCHECK(success);
+
+      // Filter out A) the empty host, B) zoom levels equal to the default; and
+      // remember them, so that we can later erase them from Prefs.
+      // Values of type A and B could have been stored due to crbug.com/364399.
+      // Values of type B could further have been stored before the default zoom
+      // level was set to its current value. In either case, SetZoomLevelForHost
+      // will ignore type B values, thus, to have consistency with HostZoomMap's
+      // internal state, these values must also be removed from Prefs.
+      if (host.empty() ||
+          content::ZoomValuesEqual(zoom_level,
+                                   host_zoom_map->GetDefaultZoomLevel())) {
+        keys_to_remove.push_back(host);
+        continue;
+      }
+
       host_zoom_map->SetZoomLevelForHost(host, zoom_level);
     }
+
+    DictionaryPrefUpdate update(prefs_.get(), prefs::kPerHostZoomLevels);
+    base::DictionaryValue* host_zoom_dictionary = update.Get();
+    for (std::vector<std::string>::const_iterator it = keys_to_remove.begin();
+         it != keys_to_remove.end(); ++it) {
+      host_zoom_dictionary->RemoveWithoutPathExpansion(*it, NULL);
+    }
   }
 
   zoom_subscription_ = host_zoom_map->AddZoomLevelChangedCallback(
@@ -676,8 +825,10 @@ ProfileImpl::~ProfileImpl() {
     ProfileDestroyer::DestroyOffTheRecordProfileNow(
         off_the_record_profile_.get());
   } else {
+#if defined(ENABLE_EXTENSIONS)
     ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
         ClearAllIncognitoSessionOnlyPreferences();
+#endif
   }
 
   BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
@@ -701,6 +852,10 @@ std::string ProfileImpl::GetProfileName() {
   return GetPrefs()->GetString(prefs::kGoogleServicesUsername);
 }
 
+Profile::ProfileType ProfileImpl::GetProfileType() const {
+  return REGULAR_PROFILE;
+}
+
 base::FilePath ProfileImpl::GetPath() const {
   return path_;
 }
@@ -729,8 +884,10 @@ Profile* ProfileImpl::GetOffTheRecordProfile() {
 
 void ProfileImpl::DestroyOffTheRecordProfile() {
   off_the_record_profile_.reset();
+#if defined(ENABLE_EXTENSIONS)
   ExtensionPrefValueMapFactory::GetForBrowserContext(this)->
       ClearAllIncognitoSessionOnlyPreferences();
+#endif
 }
 
 bool ProfileImpl::HasOffTheRecordProfile() {
@@ -741,22 +898,22 @@ Profile* ProfileImpl::GetOriginalProfile() {
   return this;
 }
 
-bool ProfileImpl::IsManaged() {
-  return !GetPrefs()->GetString(prefs::kManagedUserId).empty();
-}
-
-ExtensionService* ProfileImpl::GetExtensionService() {
-  return extensions::ExtensionSystem::Get(this)->extension_service();
+bool ProfileImpl::IsSupervised() {
+  return !GetPrefs()->GetString(prefs::kSupervisedUserId).empty();
 }
 
 ExtensionSpecialStoragePolicy*
     ProfileImpl::GetExtensionSpecialStoragePolicy() {
+#if defined(ENABLE_EXTENSIONS)
   if (!extension_special_storage_policy_.get()) {
     TRACE_EVENT0("browser", "ProfileImpl::GetExtensionSpecialStoragePolicy")
     extension_special_storage_policy_ = new ExtensionSpecialStoragePolicy(
         CookieSettings::Factory::GetForProfile(this).get());
   }
   return extension_special_storage_policy_.get();
+#else
+  return NULL;
+#endif
 }
 
 void ProfileImpl::OnPrefsLoaded(bool success) {
@@ -791,6 +948,13 @@ void ProfileImpl::OnPrefsLoaded(bool success) {
   // TODO(sky): remove this in a couple of releases (m28ish).
   prefs_->SetBoolean(prefs::kSessionExitedCleanly, true);
 
+#if defined(OS_ANDROID) && defined(FULL_SAFE_BROWSING)
+  // Clear safe browsing setting in the case we need to roll back
+  // for users enrolled in Finch trial before.
+  if (!SafeBrowsingService::IsEnabledByFieldTrial())
+    prefs_->ClearPref(prefs::kSafeBrowsingEnabled);
+#endif
+
   g_browser_process->profile_manager()->InitProfileUserPrefs(this);
 
   BrowserContextDependencyManager::GetInstance()->CreateBrowserContextServices(
@@ -799,10 +963,7 @@ void ProfileImpl::OnPrefsLoaded(bool success) {
   DCHECK(!net_pref_observer_);
   {
     TRACE_EVENT0("browser", "ProfileImpl::OnPrefsLoaded:NetPrefObserver")
-    net_pref_observer_.reset(new NetPrefObserver(
-        prefs_.get(),
-        prerender::PrerenderManagerFactory::GetForProfile(this),
-        predictor_));
+    net_pref_observer_.reset(new NetPrefObserver(prefs_.get()));
   }
 
   chrome_prefs::SchedulePrefsFilePathVerification(path_);
@@ -857,18 +1018,19 @@ PrefService* ProfileImpl::GetOffTheRecordPrefs() {
     // The new ExtensionPrefStore is ref_counted and the new PrefService
     // stores a reference so that we do not leak memory here.
     otr_prefs_.reset(prefs_->CreateIncognitoPrefService(
-        new ExtensionPrefStore(
-            ExtensionPrefValueMapFactory::GetForBrowserContext(this), true)));
+        CreateExtensionPrefStore(this, true)));
   }
   return otr_prefs_.get();
 }
 
 net::URLRequestContextGetter* ProfileImpl::CreateRequestContext(
-    content::ProtocolHandlerMap* protocol_handlers) {
-  return io_data_
-      .CreateMainRequestContextGetter(protocol_handlers,
-                                      g_browser_process->local_state(),
-                                      g_browser_process->io_thread()).get();
+    content::ProtocolHandlerMap* protocol_handlers,
+    content::URLRequestInterceptorScopedVector request_interceptors) {
+  return io_data_.CreateMainRequestContextGetter(
+      protocol_handlers,
+      request_interceptors.Pass(),
+      g_browser_process->local_state(),
+      g_browser_process->io_thread()).get();
 }
 
 net::URLRequestContextGetter* ProfileImpl::GetRequestContext() {
@@ -906,65 +1068,6 @@ ProfileImpl::GetMediaRequestContextForStoragePartition(
       .GetIsolatedMediaRequestContextGetter(partition_path, in_memory).get();
 }
 
-void ProfileImpl::RequestMidiSysExPermission(
-      int render_process_id,
-      int render_view_id,
-      int bridge_id,
-      const GURL& requesting_frame,
-      const MidiSysExPermissionCallback& callback) {
-  ChromeMidiPermissionContext* context =
-      ChromeMidiPermissionContextFactory::GetForProfile(this);
-  context->RequestMidiSysExPermission(render_process_id,
-                                      render_view_id,
-                                      bridge_id,
-                                      requesting_frame,
-                                      callback);
-}
-
-void ProfileImpl::CancelMidiSysExPermissionRequest(
-    int render_process_id,
-    int render_view_id,
-    int bridge_id,
-    const GURL& requesting_frame) {
-  ChromeMidiPermissionContext* context =
-      ChromeMidiPermissionContextFactory::GetForProfile(this);
-  context->CancelMidiSysExPermissionRequest(
-      render_process_id, render_view_id, bridge_id, requesting_frame);
-}
-
-void ProfileImpl::RequestProtectedMediaIdentifierPermission(
-    int render_process_id,
-    int render_view_id,
-    int bridge_id,
-    int group_id,
-    const GURL& requesting_frame,
-    const ProtectedMediaIdentifierPermissionCallback& callback) {
-#if defined(OS_ANDROID)
-  ProtectedMediaIdentifierPermissionContext* context =
-      ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(this);
-  context->RequestProtectedMediaIdentifierPermission(render_process_id,
-                                                     render_view_id,
-                                                     bridge_id,
-                                                     group_id,
-                                                     requesting_frame,
-                                                     callback);
-#else
-  NOTIMPLEMENTED();
-  callback.Run(false);
-#endif  // defined(OS_ANDROID)
-}
-
-void ProfileImpl::CancelProtectedMediaIdentifierPermissionRequests(
-    int group_id) {
-#if defined(OS_ANDROID)
-  ProtectedMediaIdentifierPermissionContext* context =
-      ProtectedMediaIdentifierPermissionContextFactory::GetForProfile(this);
-  context->CancelProtectedMediaIdentifierPermissionRequests(group_id);
-#else
-  NOTIMPLEMENTED();
-#endif  // defined(OS_ANDROID)
-}
-
 content::ResourceContext* ProfileImpl::GetResourceContext() {
   return io_data_.GetResourceContext();
 }
@@ -977,16 +1080,20 @@ net::URLRequestContextGetter*
 ProfileImpl::CreateRequestContextForStoragePartition(
     const base::FilePath& partition_path,
     bool in_memory,
-    content::ProtocolHandlerMap* protocol_handlers) {
+    content::ProtocolHandlerMap* protocol_handlers,
+    content::URLRequestInterceptorScopedVector request_interceptors) {
   return io_data_.CreateIsolatedAppRequestContextGetter(
-                      partition_path, in_memory, protocol_handlers).get();
+      partition_path,
+      in_memory,
+      protocol_handlers,
+      request_interceptors.Pass()).get();
 }
 
 net::SSLConfigService* ProfileImpl::GetSSLConfigService() {
   // If ssl_config_service_manager_ is null, this typically means that some
-  // BrowserContextKeyedService is trying to create a RequestContext at startup,
+  // KeyedService is trying to create a RequestContext at startup,
   // but SSLConfigServiceManager is not initialized until DoFinalInit() which is
-  // invoked after all BrowserContextKeyedServices have been initialized (see
+  // invoked after all KeyedServices have been initialized (see
   // http://crbug.com/171406).
   DCHECK(ssl_config_service_manager_) <<
       "SSLConfigServiceManager is not initialized yet";
@@ -1000,9 +1107,12 @@ HostContentSettingsMap* ProfileImpl::GetHostContentSettingsMap() {
   return host_content_settings_map_.get();
 }
 
-content::GeolocationPermissionContext*
-    ProfileImpl::GetGeolocationPermissionContext() {
-  return ChromeGeolocationPermissionContextFactory::GetForProfile(this);
+content::BrowserPluginGuestManager* ProfileImpl::GetGuestManager() {
+#if defined(ENABLE_EXTENSIONS)
+  return extensions::GuestViewManager::FromBrowserContext(this);
+#else
+  return NULL;
+#endif
 }
 
 DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
@@ -1010,8 +1120,21 @@ DownloadManagerDelegate* ProfileImpl::GetDownloadManagerDelegate() {
       GetDownloadManagerDelegate();
 }
 
-quota::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
+storage::SpecialStoragePolicy* ProfileImpl::GetSpecialStoragePolicy() {
+#if defined(ENABLE_EXTENSIONS)
   return GetExtensionSpecialStoragePolicy();
+#else
+  return NULL;
+#endif
+}
+
+content::PushMessagingService* ProfileImpl::GetPushMessagingService() {
+  return gcm::GCMProfileServiceFactory::GetForProfile(
+      this)->push_messaging_service();
+}
+
+content::SSLHostStateDelegate* ProfileImpl::GetSSLHostStateDelegate() {
+  return ChromeSSLHostStateDelegateFactory::GetForProfile(this);
 }
 
 bool ProfileImpl::IsSameProfile(Profile* profile) {
@@ -1038,7 +1161,7 @@ history::TopSites* ProfileImpl::GetTopSitesWithoutCreating() {
 }
 
 void ProfileImpl::OnDefaultZoomLevelChanged() {
-  HostZoomMap::GetForBrowserContext(this)->SetDefaultZoomLevel(
+  HostZoomMap::GetDefaultForBrowserContext(this)->SetDefaultZoomLevel(
       pref_change_registrar_.prefs()->GetDouble(prefs::kDefaultZoomLevel));
 }
 
@@ -1047,16 +1170,14 @@ void ProfileImpl::OnZoomLevelChanged(
 
   if (change.mode != HostZoomMap::ZOOM_CHANGED_FOR_HOST)
     return;
-  HostZoomMap* host_zoom_map = HostZoomMap::GetForBrowserContext(this);
+  HostZoomMap* host_zoom_map = HostZoomMap::GetDefaultForBrowserContext(this);
   double level = change.zoom_level;
   DictionaryPrefUpdate update(prefs_.get(), prefs::kPerHostZoomLevels);
   base::DictionaryValue* host_zoom_dictionary = update.Get();
-  if (level == host_zoom_map->GetDefaultZoomLevel()) {
+  if (content::ZoomValuesEqual(level, host_zoom_map->GetDefaultZoomLevel()))
     host_zoom_dictionary->RemoveWithoutPathExpansion(change.host, NULL);
-  } else {
-    host_zoom_dictionary->SetWithoutPathExpansion(
-        change.host, base::Value::CreateDoubleValue(level));
-  }
+  else
+    host_zoom_dictionary->SetDoubleWithoutPathExpansion(change.host, level);
 }
 
 #if defined(ENABLE_SESSION_SERVICE)
@@ -1096,7 +1217,8 @@ void ProfileImpl::ChangeAppLocale(
       // while user's profile determines his personal locale preference.
       break;
     }
-    case APP_LOCALE_CHANGED_VIA_LOGIN: {
+    case APP_LOCALE_CHANGED_VIA_LOGIN:
+    case APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN: {
       if (!pref_locale.empty()) {
         DCHECK(pref_locale == new_locale);
         std::string accepted_locale =
@@ -1141,10 +1263,11 @@ void ProfileImpl::ChangeAppLocale(
   }
   if (do_update_pref)
     GetPrefs()->SetString(prefs::kApplicationLocale, new_locale);
-  local_state->SetString(prefs::kApplicationLocale, new_locale);
+  if (via != APP_LOCALE_CHANGED_VIA_PUBLIC_SESSION_LOGIN)
+    local_state->SetString(prefs::kApplicationLocale, new_locale);
 
-  if (chromeos::UserManager::Get()->GetOwnerEmail() ==
-      chromeos::UserManager::Get()->GetUserByProfile(this)->email())
+  if (user_manager::UserManager::Get()->GetOwnerEmail() ==
+      chromeos::ProfileHelper::Get()->GetUserByProfile(this)->email())
     local_state->SetString(prefs::kOwnerLocale, new_locale);
 }
 
@@ -1157,8 +1280,7 @@ void ProfileImpl::OnLogin() {
 void ProfileImpl::InitChromeOSPreferences() {
   chromeos_preferences_.reset(new chromeos::Preferences());
   chromeos_preferences_->Init(
-      PrefServiceSyncable::FromProfile(this),
-      chromeos::UserManager::Get()->GetUserByProfile(this));
+      this, chromeos::ProfileHelper::Get()->GetUserByProfile(this));
 }
 
 #endif  // defined(OS_CHROMEOS)
@@ -1173,8 +1295,13 @@ chrome_browser_net::Predictor* ProfileImpl::GetNetworkPredictor() {
   return predictor_;
 }
 
-void ProfileImpl::ClearNetworkingHistorySince(base::Time time,
-                                              const base::Closure& completion) {
+DevToolsNetworkController* ProfileImpl::GetDevToolsNetworkController() {
+  return io_data_.GetDevToolsNetworkController();
+}
+
+void ProfileImpl::ClearNetworkingHistorySince(
+    base::Time time,
+    const base::Closure& completion) {
   io_data_.ClearNetworkingHistorySince(time, completion);
 }
 
@@ -1189,7 +1316,8 @@ GURL ProfileImpl::GetHomePage() {
 
     base::FilePath browser_directory;
     PathService::Get(base::DIR_CURRENT, &browser_directory);
-    GURL home_page(URLFixerUpper::FixupRelativeFile(browser_directory,
+    GURL home_page(url_fixer::FixupRelativeFile(
+        browser_directory,
         command_line.GetSwitchValuePath(switches::kHomePage)));
     if (home_page.is_valid())
       return home_page;
@@ -1197,9 +1325,8 @@ GURL ProfileImpl::GetHomePage() {
 
   if (GetPrefs()->GetBoolean(prefs::kHomePageIsNewTabPage))
     return GURL(chrome::kChromeUINewTabURL);
-  GURL home_page(URLFixerUpper::FixupURL(
-      GetPrefs()->GetString(prefs::kHomePage),
-      std::string()));
+  GURL home_page(url_fixer::FixupURL(GetPrefs()->GetString(prefs::kHomePage),
+                                     std::string()));
   if (!home_page.is_valid())
     return GURL(chrome::kChromeUINewTabURL);
   return home_page;
@@ -1217,6 +1344,18 @@ void ProfileImpl::UpdateProfileUserNameCache() {
   }
 }
 
+void ProfileImpl::UpdateProfileSupervisedUserIdCache() {
+  ProfileManager* profile_manager = g_browser_process->profile_manager();
+  ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
+  size_t index = cache.GetIndexOfProfileWithPath(GetPath());
+  if (index != std::string::npos) {
+    std::string supervised_user_id =
+        GetPrefs()->GetString(prefs::kSupervisedUserId);
+    cache.SetSupervisedUserIdOfProfileAtIndex(index, supervised_user_id);
+    ProfileMetrics::UpdateReportedProfilesStatistics(profile_manager);
+  }
+}
+
 void ProfileImpl::UpdateProfileNameCache() {
   ProfileManager* profile_manager = g_browser_process->profile_manager();
   ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
@@ -1225,6 +1364,9 @@ void ProfileImpl::UpdateProfileNameCache() {
     std::string profile_name =
         GetPrefs()->GetString(prefs::kProfileName);
     cache.SetNameOfProfileAtIndex(index, base::UTF8ToUTF16(profile_name));
+    bool default_name =
+        GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultName);
+    cache.SetProfileIsUsingDefaultNameAtIndex(index, default_name);
   }
 }
 
@@ -1236,6 +1378,12 @@ void ProfileImpl::UpdateProfileAvatarCache() {
     size_t avatar_index =
         GetPrefs()->GetInteger(prefs::kProfileAvatarIndex);
     cache.SetAvatarIconOfProfileAtIndex(index, avatar_index);
+    bool default_avatar =
+        GetPrefs()->GetBoolean(prefs::kProfileUsingDefaultAvatar);
+    cache.SetProfileIsUsingDefaultAvatarAtIndex(index, default_avatar);
+    bool gaia_avatar =
+        GetPrefs()->GetBoolean(prefs::kProfileUsingGAIAAvatar);
+    cache.SetIsUsingGAIAPictureOfProfileAtIndex(index, gaia_avatar);
   }
 }
 
@@ -1276,3 +1424,15 @@ PrefProxyConfigTracker* ProfileImpl::CreateProxyConfigTracker() {
   return ProxyServiceFactory::CreatePrefProxyConfigTrackerOfProfile(
       GetPrefs(), g_browser_process->local_state());
 }
+
+scoped_ptr<domain_reliability::DomainReliabilityMonitor>
+ProfileImpl::CreateDomainReliabilityMonitor(PrefService* local_state) {
+  domain_reliability::DomainReliabilityService* service =
+      domain_reliability::DomainReliabilityServiceFactory::GetInstance()->
+          GetForBrowserContext(this);
+  if (!service)
+    return scoped_ptr<domain_reliability::DomainReliabilityMonitor>();
+
+  return service->CreateMonitor(
+      BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
+}