atom_browser_context.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. // Copyright (c) 2013 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/browser/atom_browser_context.h"
  5. #include <utility>
  6. #include "base/command_line.h"
  7. #include "base/files/file_path.h"
  8. #include "base/path_service.h"
  9. #include "base/strings/string_util.h"
  10. #include "base/task/post_task.h"
  11. #include "base/threading/sequenced_task_runner_handle.h"
  12. #include "base/threading/thread_restrictions.h"
  13. #include "chrome/common/chrome_paths.h"
  14. #include "chrome/common/pref_names.h"
  15. #include "components/keyed_service/content/browser_context_dependency_manager.h"
  16. #include "components/prefs/json_pref_store.h"
  17. #include "components/prefs/pref_registry_simple.h"
  18. #include "components/prefs/pref_service.h"
  19. #include "components/prefs/pref_service_factory.h"
  20. #include "components/prefs/value_map_pref_store.h"
  21. #include "components/proxy_config/pref_proxy_config_tracker_impl.h"
  22. #include "components/proxy_config/proxy_config_pref_names.h"
  23. #include "content/browser/blob_storage/chrome_blob_storage_context.h" // nogncheck
  24. #include "content/public/browser/browser_thread.h"
  25. #include "content/public/browser/storage_partition.h"
  26. #include "mojo/public/cpp/bindings/self_owned_receiver.h"
  27. #include "net/base/escape.h"
  28. #include "services/network/public/cpp/features.h"
  29. #include "services/network/public/cpp/wrapper_shared_url_loader_factory.h"
  30. #include "services/network/public/mojom/network_context.mojom.h"
  31. #include "shell/browser/api/atom_api_url_loader.h"
  32. #include "shell/browser/atom_browser_client.h"
  33. #include "shell/browser/atom_browser_main_parts.h"
  34. #include "shell/browser/atom_download_manager_delegate.h"
  35. #include "shell/browser/atom_paths.h"
  36. #include "shell/browser/atom_permission_manager.h"
  37. #include "shell/browser/cookie_change_notifier.h"
  38. #include "shell/browser/net/resolve_proxy_helper.h"
  39. #include "shell/browser/pref_store_delegate.h"
  40. #include "shell/browser/special_storage_policy.h"
  41. #include "shell/browser/ui/inspectable_web_contents_impl.h"
  42. #include "shell/browser/web_view_manager.h"
  43. #include "shell/browser/zoom_level_delegate.h"
  44. #include "shell/common/application_info.h"
  45. #include "shell/common/options_switches.h"
  46. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  47. #include "components/pref_registry/pref_registry_syncable.h"
  48. #include "components/user_prefs/user_prefs.h"
  49. #include "extensions/browser/browser_context_keyed_service_factories.h"
  50. #include "extensions/browser/extension_pref_store.h"
  51. #include "extensions/browser/extension_pref_value_map_factory.h"
  52. #include "extensions/browser/extension_prefs.h"
  53. #include "extensions/browser/pref_names.h"
  54. #include "extensions/common/extension_api.h"
  55. #include "shell/browser/extensions/atom_browser_context_keyed_service_factories.h"
  56. #include "shell/browser/extensions/atom_extension_system.h"
  57. #include "shell/browser/extensions/atom_extension_system_factory.h"
  58. #include "shell/browser/extensions/atom_extensions_browser_client.h"
  59. #include "shell/common/extensions/atom_extensions_client.h"
  60. #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  61. using content::BrowserThread;
  62. namespace electron {
  63. namespace {
  64. // Convert string to lower case and escape it.
  65. std::string MakePartitionName(const std::string& input) {
  66. return net::EscapePath(base::ToLowerASCII(input));
  67. }
  68. } // namespace
  69. // static
  70. AtomBrowserContext::BrowserContextMap AtomBrowserContext::browser_context_map_;
  71. AtomBrowserContext::AtomBrowserContext(const std::string& partition,
  72. bool in_memory,
  73. const base::DictionaryValue& options)
  74. : base::RefCountedDeleteOnSequence<AtomBrowserContext>(
  75. base::ThreadTaskRunnerHandle::Get()),
  76. in_memory_pref_store_(nullptr),
  77. storage_policy_(new SpecialStoragePolicy),
  78. in_memory_(in_memory),
  79. weak_factory_(this) {
  80. user_agent_ = AtomBrowserClient::Get()->GetUserAgent();
  81. // Read options.
  82. base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
  83. use_cache_ = !command_line->HasSwitch(switches::kDisableHttpCache);
  84. options.GetBoolean("cache", &use_cache_);
  85. base::StringToInt(command_line->GetSwitchValueASCII(switches::kDiskCacheSize),
  86. &max_cache_size_);
  87. if (!base::PathService::Get(DIR_USER_DATA, &path_)) {
  88. base::PathService::Get(DIR_APP_DATA, &path_);
  89. path_ = path_.Append(base::FilePath::FromUTF8Unsafe(GetApplicationName()));
  90. base::PathService::Override(DIR_USER_DATA, path_);
  91. }
  92. if (!in_memory && !partition.empty())
  93. path_ = path_.Append(FILE_PATH_LITERAL("Partitions"))
  94. .Append(base::FilePath::FromUTF8Unsafe(
  95. MakePartitionName(partition)));
  96. content::BrowserContext::Initialize(this, path_);
  97. BrowserContextDependencyManager::GetInstance()->MarkBrowserContextLive(this);
  98. // Initialize Pref Registry.
  99. InitPrefs();
  100. cookie_change_notifier_ = std::make_unique<CookieChangeNotifier>(this);
  101. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  102. BrowserContextDependencyManager::GetInstance()->CreateBrowserContextServices(
  103. this);
  104. extension_system_ = static_cast<extensions::AtomExtensionSystem*>(
  105. extensions::ExtensionSystem::Get(this));
  106. extension_system_->InitForRegularProfile(true /* extensions_enabled */);
  107. extension_system_->FinishInitialization();
  108. #endif
  109. }
  110. AtomBrowserContext::~AtomBrowserContext() {
  111. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  112. NotifyWillBeDestroyed(this);
  113. ShutdownStoragePartitions();
  114. BrowserThread::DeleteSoon(BrowserThread::IO, FROM_HERE,
  115. std::move(resource_context_));
  116. // Notify any keyed services of browser context destruction.
  117. BrowserContextDependencyManager::GetInstance()->DestroyBrowserContextServices(
  118. this);
  119. }
  120. void AtomBrowserContext::InitPrefs() {
  121. auto prefs_path = GetPath().Append(FILE_PATH_LITERAL("Preferences"));
  122. base::ThreadRestrictions::ScopedAllowIO allow_io;
  123. PrefServiceFactory prefs_factory;
  124. scoped_refptr<JsonPrefStore> pref_store =
  125. base::MakeRefCounted<JsonPrefStore>(prefs_path);
  126. pref_store->ReadPrefs(); // Synchronous.
  127. prefs_factory.set_user_prefs(pref_store);
  128. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  129. auto* ext_pref_store = new ExtensionPrefStore(
  130. ExtensionPrefValueMapFactory::GetForBrowserContext(this),
  131. IsOffTheRecord());
  132. prefs_factory.set_extension_prefs(ext_pref_store);
  133. auto registry = WrapRefCounted(new user_prefs::PrefRegistrySyncable);
  134. #else
  135. auto registry = WrapRefCounted(new PrefRegistrySimple);
  136. #endif
  137. registry->RegisterFilePathPref(prefs::kSelectFileLastDirectory,
  138. base::FilePath());
  139. base::FilePath download_dir;
  140. base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_dir);
  141. registry->RegisterFilePathPref(prefs::kDownloadDefaultDirectory,
  142. download_dir);
  143. registry->RegisterDictionaryPref(prefs::kDevToolsFileSystemPaths);
  144. InspectableWebContentsImpl::RegisterPrefs(registry.get());
  145. MediaDeviceIDSalt::RegisterPrefs(registry.get());
  146. ZoomLevelDelegate::RegisterPrefs(registry.get());
  147. PrefProxyConfigTrackerImpl::RegisterPrefs(registry.get());
  148. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  149. extensions::ExtensionPrefs::RegisterProfilePrefs(registry.get());
  150. #endif
  151. prefs_ = prefs_factory.Create(
  152. registry.get(),
  153. std::make_unique<PrefStoreDelegate>(weak_factory_.GetWeakPtr()));
  154. prefs_->UpdateCommandLinePrefStore(new ValueMapPrefStore);
  155. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  156. user_prefs::UserPrefs::Set(this, prefs_.get());
  157. #endif
  158. }
  159. void AtomBrowserContext::SetUserAgent(const std::string& user_agent) {
  160. user_agent_ = user_agent;
  161. }
  162. base::FilePath AtomBrowserContext::GetPath() {
  163. return path_;
  164. }
  165. bool AtomBrowserContext::IsOffTheRecord() {
  166. return in_memory_;
  167. }
  168. bool AtomBrowserContext::CanUseHttpCache() const {
  169. return use_cache_;
  170. }
  171. int AtomBrowserContext::GetMaxCacheSize() const {
  172. return max_cache_size_;
  173. }
  174. content::ResourceContext* AtomBrowserContext::GetResourceContext() {
  175. if (!resource_context_)
  176. resource_context_.reset(new content::ResourceContext);
  177. return resource_context_.get();
  178. }
  179. std::string AtomBrowserContext::GetMediaDeviceIDSalt() {
  180. if (!media_device_id_salt_.get())
  181. media_device_id_salt_.reset(new MediaDeviceIDSalt(prefs_.get()));
  182. return media_device_id_salt_->GetSalt();
  183. }
  184. std::unique_ptr<content::ZoomLevelDelegate>
  185. AtomBrowserContext::CreateZoomLevelDelegate(
  186. const base::FilePath& partition_path) {
  187. if (!IsOffTheRecord()) {
  188. return std::make_unique<ZoomLevelDelegate>(prefs(), partition_path);
  189. }
  190. return std::unique_ptr<content::ZoomLevelDelegate>();
  191. }
  192. content::DownloadManagerDelegate*
  193. AtomBrowserContext::GetDownloadManagerDelegate() {
  194. if (!download_manager_delegate_.get()) {
  195. auto* download_manager = content::BrowserContext::GetDownloadManager(this);
  196. download_manager_delegate_.reset(
  197. new AtomDownloadManagerDelegate(download_manager));
  198. }
  199. return download_manager_delegate_.get();
  200. }
  201. content::BrowserPluginGuestManager* AtomBrowserContext::GetGuestManager() {
  202. if (!guest_manager_)
  203. guest_manager_.reset(new WebViewManager);
  204. return guest_manager_.get();
  205. }
  206. content::PermissionControllerDelegate*
  207. AtomBrowserContext::GetPermissionControllerDelegate() {
  208. if (!permission_manager_.get())
  209. permission_manager_.reset(new AtomPermissionManager);
  210. return permission_manager_.get();
  211. }
  212. storage::SpecialStoragePolicy* AtomBrowserContext::GetSpecialStoragePolicy() {
  213. return storage_policy_.get();
  214. }
  215. std::string AtomBrowserContext::GetUserAgent() const {
  216. return user_agent_;
  217. }
  218. predictors::PreconnectManager* AtomBrowserContext::GetPreconnectManager() {
  219. if (!preconnect_manager_.get()) {
  220. preconnect_manager_.reset(new predictors::PreconnectManager(nullptr, this));
  221. }
  222. return preconnect_manager_.get();
  223. }
  224. scoped_refptr<network::SharedURLLoaderFactory>
  225. AtomBrowserContext::GetURLLoaderFactory() {
  226. if (url_loader_factory_)
  227. return url_loader_factory_;
  228. network::mojom::URLLoaderFactoryPtr network_factory;
  229. mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_request =
  230. mojo::MakeRequest(&network_factory);
  231. // Consult the embedder.
  232. mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>
  233. header_client;
  234. static_cast<content::ContentBrowserClient*>(AtomBrowserClient::Get())
  235. ->WillCreateURLLoaderFactory(
  236. this, nullptr, -1,
  237. content::ContentBrowserClient::URLLoaderFactoryType::kNavigation,
  238. url::Origin(), &factory_request, &header_client, nullptr);
  239. network::mojom::URLLoaderFactoryParamsPtr params =
  240. network::mojom::URLLoaderFactoryParams::New();
  241. params->header_client = std::move(header_client);
  242. params->auth_client = auth_client_.BindNewPipeAndPassRemote();
  243. params->process_id = network::mojom::kBrowserProcessId;
  244. params->is_corb_enabled = false;
  245. // The tests of net module would fail if this setting is true, it seems that
  246. // the non-NetworkService implementation always has web security enabled.
  247. params->disable_web_security = false;
  248. auto* storage_partition =
  249. content::BrowserContext::GetDefaultStoragePartition(this);
  250. storage_partition->GetNetworkContext()->CreateURLLoaderFactory(
  251. std::move(factory_request), std::move(params));
  252. url_loader_factory_ =
  253. base::MakeRefCounted<network::WrapperSharedURLLoaderFactory>(
  254. std::move(network_factory));
  255. return url_loader_factory_;
  256. }
  257. class AuthResponder : public network::mojom::TrustedAuthClient {
  258. public:
  259. AuthResponder() {}
  260. ~AuthResponder() override = default;
  261. private:
  262. void OnAuthRequired(
  263. const base::Optional<::base::UnguessableToken>& window_id,
  264. uint32_t process_id,
  265. uint32_t routing_id,
  266. uint32_t request_id,
  267. const ::GURL& url,
  268. bool first_auth_attempt,
  269. const ::net::AuthChallengeInfo& auth_info,
  270. ::network::mojom::URLResponseHeadPtr head,
  271. mojo::PendingRemote<network::mojom::AuthChallengeResponder>
  272. auth_challenge_responder) override {
  273. api::SimpleURLLoaderWrapper* url_loader =
  274. api::SimpleURLLoaderWrapper::FromID(routing_id);
  275. if (url_loader) {
  276. url_loader->OnAuthRequired(url, first_auth_attempt, auth_info,
  277. std::move(head),
  278. std::move(auth_challenge_responder));
  279. }
  280. }
  281. };
  282. void AtomBrowserContext::OnLoaderCreated(
  283. int32_t request_id,
  284. mojo::PendingReceiver<network::mojom::TrustedAuthClient> auth_client) {
  285. mojo::MakeSelfOwnedReceiver(std::make_unique<AuthResponder>(),
  286. std::move(auth_client));
  287. }
  288. content::PushMessagingService* AtomBrowserContext::GetPushMessagingService() {
  289. return nullptr;
  290. }
  291. content::SSLHostStateDelegate* AtomBrowserContext::GetSSLHostStateDelegate() {
  292. return nullptr;
  293. }
  294. content::BackgroundFetchDelegate*
  295. AtomBrowserContext::GetBackgroundFetchDelegate() {
  296. return nullptr;
  297. }
  298. content::BackgroundSyncController*
  299. AtomBrowserContext::GetBackgroundSyncController() {
  300. return nullptr;
  301. }
  302. content::BrowsingDataRemoverDelegate*
  303. AtomBrowserContext::GetBrowsingDataRemoverDelegate() {
  304. return nullptr;
  305. }
  306. content::ClientHintsControllerDelegate*
  307. AtomBrowserContext::GetClientHintsControllerDelegate() {
  308. return nullptr;
  309. }
  310. void AtomBrowserContext::SetCorsOriginAccessListForOrigin(
  311. const url::Origin& source_origin,
  312. std::vector<network::mojom::CorsOriginPatternPtr> allow_patterns,
  313. std::vector<network::mojom::CorsOriginPatternPtr> block_patterns,
  314. base::OnceClosure closure) {
  315. // TODO(nornagon): actually set the CORS access lists. This is called from
  316. // extensions/browser/renderer_startup_helper.cc.
  317. base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, std::move(closure));
  318. }
  319. ResolveProxyHelper* AtomBrowserContext::GetResolveProxyHelper() {
  320. if (!resolve_proxy_helper_) {
  321. resolve_proxy_helper_ = base::MakeRefCounted<ResolveProxyHelper>(this);
  322. }
  323. return resolve_proxy_helper_.get();
  324. }
  325. // static
  326. scoped_refptr<AtomBrowserContext> AtomBrowserContext::From(
  327. const std::string& partition,
  328. bool in_memory,
  329. const base::DictionaryValue& options) {
  330. PartitionKey key(partition, in_memory);
  331. auto* browser_context = browser_context_map_[key].get();
  332. if (browser_context)
  333. return scoped_refptr<AtomBrowserContext>(browser_context);
  334. auto* new_context = new AtomBrowserContext(partition, in_memory, options);
  335. browser_context_map_[key] = new_context->GetWeakPtr();
  336. return scoped_refptr<AtomBrowserContext>(new_context);
  337. }
  338. } // namespace electron