atom_browser_client.cc 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  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 "atom/browser/atom_browser_client.h"
  5. #if defined(OS_WIN)
  6. #include <shlobj.h>
  7. #endif
  8. #include <memory>
  9. #include <utility>
  10. #include "atom/app/manifests.h"
  11. #include "atom/browser/api/atom_api_app.h"
  12. #include "atom/browser/api/atom_api_protocol.h"
  13. #include "atom/browser/api/atom_api_web_contents.h"
  14. #include "atom/browser/atom_browser_context.h"
  15. #include "atom/browser/atom_browser_main_parts.h"
  16. #include "atom/browser/atom_navigation_throttle.h"
  17. #include "atom/browser/atom_quota_permission_context.h"
  18. #include "atom/browser/atom_resource_dispatcher_host_delegate.h"
  19. #include "atom/browser/atom_speech_recognition_manager_delegate.h"
  20. #include "atom/browser/child_web_contents_tracker.h"
  21. #include "atom/browser/font_defaults.h"
  22. #include "atom/browser/io_thread.h"
  23. #include "atom/browser/media/media_capture_devices_dispatcher.h"
  24. #include "atom/browser/native_window.h"
  25. #include "atom/browser/net/network_context_service.h"
  26. #include "atom/browser/net/network_context_service_factory.h"
  27. #include "atom/browser/notifications/notification_presenter.h"
  28. #include "atom/browser/notifications/platform_notification_service.h"
  29. #include "atom/browser/session_preferences.h"
  30. #include "atom/browser/ui/devtools_manager_delegate.h"
  31. #include "atom/browser/web_contents_permission_helper.h"
  32. #include "atom/browser/web_contents_preferences.h"
  33. #include "atom/browser/window_list.h"
  34. #include "atom/common/application_info.h"
  35. #include "atom/common/options_switches.h"
  36. #include "atom/common/platform_util.h"
  37. #include "base/command_line.h"
  38. #include "base/environment.h"
  39. #include "base/files/file_util.h"
  40. #include "base/json/json_reader.h"
  41. #include "base/lazy_instance.h"
  42. #include "base/no_destructor.h"
  43. #include "base/path_service.h"
  44. #include "base/stl_util.h"
  45. #include "base/strings/string_number_conversions.h"
  46. #include "base/strings/string_util.h"
  47. #include "base/strings/utf_string_conversions.h"
  48. #include "base/task/post_task.h"
  49. #include "chrome/browser/browser_process.h"
  50. #include "chrome/common/chrome_version.h"
  51. #include "components/net_log/chrome_net_log.h"
  52. #include "content/public/browser/browser_ppapi_host.h"
  53. #include "content/public/browser/browser_task_traits.h"
  54. #include "content/public/browser/client_certificate_delegate.h"
  55. #include "content/public/browser/render_frame_host.h"
  56. #include "content/public/browser/render_process_host.h"
  57. #include "content/public/browser/render_view_host.h"
  58. #include "content/public/browser/resource_dispatcher_host.h"
  59. #include "content/public/browser/site_instance.h"
  60. #include "content/public/browser/web_contents.h"
  61. #include "content/public/common/content_paths.h"
  62. #include "content/public/common/content_switches.h"
  63. #include "content/public/common/service_names.mojom.h"
  64. #include "content/public/common/url_constants.h"
  65. #include "content/public/common/web_preferences.h"
  66. #include "electron/buildflags/buildflags.h"
  67. #include "electron/grit/electron_resources.h"
  68. #include "net/base/escape.h"
  69. #include "net/ssl/ssl_cert_request_info.h"
  70. #include "ppapi/host/ppapi_host.h"
  71. #include "printing/buildflags/buildflags.h"
  72. #include "services/device/public/cpp/geolocation/location_provider.h"
  73. #include "services/network/public/cpp/features.h"
  74. #include "services/network/public/cpp/resource_request_body.h"
  75. #include "ui/base/l10n/l10n_util.h"
  76. #include "ui/base/resource/resource_bundle.h"
  77. #include "ui/native_theme/native_theme.h"
  78. #include "v8/include/v8.h"
  79. #if defined(OS_WIN)
  80. #include "sandbox/win/src/sandbox_policy.h"
  81. #endif
  82. #if defined(USE_NSS_CERTS)
  83. #include "net/ssl/client_cert_store_nss.h"
  84. #elif defined(OS_WIN)
  85. #include "net/ssl/client_cert_store_win.h"
  86. #elif defined(OS_MACOSX)
  87. #include "net/ssl/client_cert_store_mac.h"
  88. #include "services/audio/public/mojom/constants.mojom.h"
  89. #include "services/video_capture/public/mojom/constants.mojom.h"
  90. #elif defined(USE_OPENSSL)
  91. #include "net/ssl/client_cert_store.h"
  92. #endif
  93. #if BUILDFLAG(ENABLE_PEPPER_FLASH)
  94. #include "chrome/browser/renderer_host/pepper/chrome_browser_pepper_host_factory.h"
  95. #endif // BUILDFLAG(ENABLE_PEPPER_FLASH)
  96. #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER)
  97. #include "atom/browser/fake_location_provider.h"
  98. #endif // BUILDFLAG(OVERRIDE_LOCATION_PROVIDER)
  99. #if BUILDFLAG(ENABLE_TTS)
  100. #include "chrome/browser/speech/tts_controller_delegate_impl.h"
  101. #include "chrome/browser/speech/tts_message_filter.h"
  102. #endif // BUILDFLAG(ENABLE_TTS)
  103. #if BUILDFLAG(ENABLE_PRINTING)
  104. #include "chrome/browser/printing/printing_message_filter.h"
  105. #endif // BUILDFLAG(ENABLE_PRINTING)
  106. #if defined(OS_MACOSX)
  107. #include "content/common/mac_helpers.h"
  108. #include "content/public/common/child_process_host.h"
  109. #endif
  110. using content::BrowserThread;
  111. namespace atom {
  112. namespace {
  113. // Next navigation should not restart renderer process.
  114. bool g_suppress_renderer_process_restart = false;
  115. bool IsSameWebSite(content::BrowserContext* browser_context,
  116. content::SiteInstance* site_instance,
  117. const GURL& dest_url) {
  118. return site_instance->IsSameSiteWithURL(dest_url) ||
  119. // `IsSameSiteWithURL` doesn't seem to work for some URIs such as
  120. // `file:`, handle these scenarios by comparing only the site as
  121. // defined by `GetSiteForURL`.
  122. (content::SiteInstance::GetSiteForURL(browser_context, dest_url) ==
  123. site_instance->GetSiteURL());
  124. }
  125. AtomBrowserClient* g_browser_client = nullptr;
  126. base::LazyInstance<std::string>::DestructorAtExit
  127. g_io_thread_application_locale = LAZY_INSTANCE_INITIALIZER;
  128. base::NoDestructor<std::string> g_application_locale;
  129. void SetApplicationLocaleOnIOThread(const std::string& locale) {
  130. DCHECK_CURRENTLY_ON(BrowserThread::IO);
  131. g_io_thread_application_locale.Get() = locale;
  132. }
  133. } // namespace
  134. // static
  135. void AtomBrowserClient::SuppressRendererProcessRestartForOnce() {
  136. g_suppress_renderer_process_restart = true;
  137. }
  138. AtomBrowserClient* AtomBrowserClient::Get() {
  139. return g_browser_client;
  140. }
  141. // static
  142. void AtomBrowserClient::SetApplicationLocale(const std::string& locale) {
  143. if (!BrowserThread::IsThreadInitialized(BrowserThread::IO) ||
  144. !base::PostTaskWithTraits(
  145. FROM_HERE, {BrowserThread::IO},
  146. base::BindOnce(&SetApplicationLocaleOnIOThread, locale))) {
  147. g_io_thread_application_locale.Get() = locale;
  148. }
  149. *g_application_locale = locale;
  150. }
  151. AtomBrowserClient::AtomBrowserClient() {
  152. DCHECK(!g_browser_client);
  153. g_browser_client = this;
  154. }
  155. AtomBrowserClient::~AtomBrowserClient() {
  156. DCHECK(g_browser_client);
  157. g_browser_client = nullptr;
  158. }
  159. content::WebContents* AtomBrowserClient::GetWebContentsFromProcessID(
  160. int process_id) {
  161. // If the process is a pending process, we should use the web contents
  162. // for the frame host passed into RegisterPendingProcess.
  163. if (base::ContainsKey(pending_processes_, process_id))
  164. return pending_processes_[process_id];
  165. // Certain render process will be created with no associated render view,
  166. // for example: ServiceWorker.
  167. return WebContentsPreferences::GetWebContentsFromProcessID(process_id);
  168. }
  169. bool AtomBrowserClient::ShouldForceNewSiteInstance(
  170. content::RenderFrameHost* current_rfh,
  171. content::RenderFrameHost* speculative_rfh,
  172. content::BrowserContext* browser_context,
  173. const GURL& url,
  174. bool has_response_started) const {
  175. if (url.SchemeIs(url::kJavaScriptScheme))
  176. // "javacript:" scheme should always use same SiteInstance
  177. return false;
  178. content::SiteInstance* current_instance = current_rfh->GetSiteInstance();
  179. content::SiteInstance* speculative_instance =
  180. speculative_rfh ? speculative_rfh->GetSiteInstance() : nullptr;
  181. int process_id = current_instance->GetProcess()->GetID();
  182. if (NavigationWasRedirectedCrossSite(browser_context, current_instance,
  183. speculative_instance, url,
  184. has_response_started)) {
  185. // Navigation was redirected. We can't force the current, speculative or a
  186. // new unrelated site instance to be used. Delegate to the content layer.
  187. return false;
  188. } else if (IsRendererSandboxed(process_id)) {
  189. // Renderer is sandboxed, delegate the decision to the content layer for all
  190. // origins.
  191. return false;
  192. } else if (!RendererUsesNativeWindowOpen(process_id)) {
  193. // non-sandboxed renderers without native window.open should always create
  194. // a new SiteInstance
  195. return true;
  196. } else {
  197. auto* web_contents = content::WebContents::FromRenderFrameHost(current_rfh);
  198. if (!ChildWebContentsTracker::FromWebContents(web_contents)) {
  199. // Root WebContents should always create new process to make sure
  200. // native addons are loaded correctly after reload / navigation.
  201. // (Non-root WebContents opened by window.open() should try to
  202. // reuse process to allow synchronous cross-window scripting.)
  203. return true;
  204. }
  205. }
  206. // Create new a SiteInstance if navigating to a different site.
  207. return !IsSameWebSite(browser_context, current_instance, url);
  208. }
  209. bool AtomBrowserClient::NavigationWasRedirectedCrossSite(
  210. content::BrowserContext* browser_context,
  211. content::SiteInstance* current_instance,
  212. content::SiteInstance* speculative_instance,
  213. const GURL& dest_url,
  214. bool has_response_started) const {
  215. bool navigation_was_redirected = false;
  216. if (has_response_started) {
  217. navigation_was_redirected =
  218. !IsSameWebSite(browser_context, current_instance, dest_url);
  219. } else {
  220. navigation_was_redirected =
  221. speculative_instance &&
  222. !IsSameWebSite(browser_context, speculative_instance, dest_url);
  223. }
  224. return navigation_was_redirected;
  225. }
  226. void AtomBrowserClient::AddProcessPreferences(
  227. int process_id,
  228. AtomBrowserClient::ProcessPreferences prefs) {
  229. base::AutoLock auto_lock(process_preferences_lock_);
  230. process_preferences_[process_id] = prefs;
  231. }
  232. void AtomBrowserClient::RemoveProcessPreferences(int process_id) {
  233. base::AutoLock auto_lock(process_preferences_lock_);
  234. process_preferences_.erase(process_id);
  235. }
  236. bool AtomBrowserClient::IsProcessObserved(int process_id) const {
  237. base::AutoLock auto_lock(process_preferences_lock_);
  238. return process_preferences_.find(process_id) != process_preferences_.end();
  239. }
  240. bool AtomBrowserClient::IsRendererSandboxed(int process_id) const {
  241. base::AutoLock auto_lock(process_preferences_lock_);
  242. auto it = process_preferences_.find(process_id);
  243. return it != process_preferences_.end() && it->second.sandbox;
  244. }
  245. bool AtomBrowserClient::RendererUsesNativeWindowOpen(int process_id) const {
  246. base::AutoLock auto_lock(process_preferences_lock_);
  247. auto it = process_preferences_.find(process_id);
  248. return it != process_preferences_.end() && it->second.native_window_open;
  249. }
  250. bool AtomBrowserClient::RendererDisablesPopups(int process_id) const {
  251. base::AutoLock auto_lock(process_preferences_lock_);
  252. auto it = process_preferences_.find(process_id);
  253. return it != process_preferences_.end() && it->second.disable_popups;
  254. }
  255. std::string AtomBrowserClient::GetAffinityPreference(
  256. content::RenderFrameHost* rfh) const {
  257. auto* web_contents = content::WebContents::FromRenderFrameHost(rfh);
  258. auto* web_preferences = WebContentsPreferences::From(web_contents);
  259. std::string affinity;
  260. if (web_preferences &&
  261. web_preferences->GetPreference("affinity", &affinity) &&
  262. !affinity.empty()) {
  263. affinity = base::ToLowerASCII(affinity);
  264. }
  265. return affinity;
  266. }
  267. content::SiteInstance* AtomBrowserClient::GetSiteInstanceFromAffinity(
  268. content::BrowserContext* browser_context,
  269. const GURL& url,
  270. content::RenderFrameHost* rfh) const {
  271. std::string affinity = GetAffinityPreference(rfh);
  272. if (!affinity.empty()) {
  273. auto iter = site_per_affinities_.find(affinity);
  274. GURL dest_site = content::SiteInstance::GetSiteForURL(browser_context, url);
  275. if (iter != site_per_affinities_.end() &&
  276. IsSameWebSite(browser_context, iter->second, dest_site)) {
  277. return iter->second;
  278. }
  279. }
  280. return nullptr;
  281. }
  282. void AtomBrowserClient::ConsiderSiteInstanceForAffinity(
  283. content::RenderFrameHost* rfh,
  284. content::SiteInstance* site_instance) {
  285. std::string affinity = GetAffinityPreference(rfh);
  286. if (!affinity.empty()) {
  287. site_per_affinities_[affinity] = site_instance;
  288. }
  289. }
  290. void AtomBrowserClient::RenderProcessWillLaunch(
  291. content::RenderProcessHost* host,
  292. service_manager::mojom::ServiceRequest* service_request) {
  293. // When a render process is crashed, it might be reused.
  294. int process_id = host->GetID();
  295. if (IsProcessObserved(process_id))
  296. return;
  297. #if BUILDFLAG(ENABLE_PRINTING)
  298. host->AddFilter(new printing::PrintingMessageFilter(
  299. process_id, host->GetBrowserContext()));
  300. #endif
  301. #if BUILDFLAG(ENABLE_TTS)
  302. host->AddFilter(new TtsMessageFilter(host->GetBrowserContext()));
  303. #endif
  304. ProcessPreferences prefs;
  305. auto* web_preferences =
  306. WebContentsPreferences::From(GetWebContentsFromProcessID(process_id));
  307. if (web_preferences) {
  308. prefs.sandbox = web_preferences->IsEnabled(options::kSandbox);
  309. prefs.native_window_open =
  310. web_preferences->IsEnabled(options::kNativeWindowOpen);
  311. prefs.disable_popups = web_preferences->IsEnabled("disablePopups");
  312. prefs.web_security = web_preferences->IsEnabled(options::kWebSecurity,
  313. true /* default value */);
  314. }
  315. AddProcessPreferences(host->GetID(), prefs);
  316. // ensure the ProcessPreferences is removed later
  317. host->AddObserver(this);
  318. }
  319. content::SpeechRecognitionManagerDelegate*
  320. AtomBrowserClient::CreateSpeechRecognitionManagerDelegate() {
  321. return new AtomSpeechRecognitionManagerDelegate;
  322. }
  323. content::TtsControllerDelegate* AtomBrowserClient::GetTtsControllerDelegate() {
  324. #if BUILDFLAG(ENABLE_TTS)
  325. return TtsControllerDelegateImpl::GetInstance();
  326. #else
  327. return nullptr;
  328. #endif
  329. }
  330. void AtomBrowserClient::OverrideWebkitPrefs(content::RenderViewHost* host,
  331. content::WebPreferences* prefs) {
  332. prefs->javascript_enabled = true;
  333. prefs->web_security_enabled = true;
  334. prefs->plugins_enabled = true;
  335. prefs->dom_paste_enabled = true;
  336. prefs->allow_scripts_to_close_windows = true;
  337. prefs->javascript_can_access_clipboard = true;
  338. prefs->local_storage_enabled = true;
  339. prefs->databases_enabled = true;
  340. prefs->application_cache_enabled = true;
  341. prefs->allow_universal_access_from_file_urls = true;
  342. prefs->allow_file_access_from_file_urls = true;
  343. prefs->webgl1_enabled = true;
  344. prefs->webgl2_enabled = true;
  345. prefs->allow_running_insecure_content = false;
  346. prefs->default_minimum_page_scale_factor = 1.f;
  347. prefs->default_maximum_page_scale_factor = 1.f;
  348. prefs->navigate_on_drag_drop = false;
  349. ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForNativeUi();
  350. prefs->preferred_color_scheme = native_theme->SystemDarkModeEnabled()
  351. ? blink::PreferredColorScheme::kDark
  352. : blink::PreferredColorScheme::kLight;
  353. SetFontDefaults(prefs);
  354. // Custom preferences of guest page.
  355. auto* web_contents = content::WebContents::FromRenderViewHost(host);
  356. auto* web_preferences = WebContentsPreferences::From(web_contents);
  357. if (web_preferences)
  358. web_preferences->OverrideWebkitPrefs(prefs);
  359. }
  360. void AtomBrowserClient::SetCanUseCustomSiteInstance(bool should_disable) {
  361. disable_process_restart_tricks_ = should_disable;
  362. }
  363. bool AtomBrowserClient::CanUseCustomSiteInstance() {
  364. return disable_process_restart_tricks_;
  365. }
  366. content::ContentBrowserClient::SiteInstanceForNavigationType
  367. AtomBrowserClient::ShouldOverrideSiteInstanceForNavigation(
  368. content::RenderFrameHost* current_rfh,
  369. content::RenderFrameHost* speculative_rfh,
  370. content::BrowserContext* browser_context,
  371. const GURL& url,
  372. bool has_navigation_started,
  373. bool has_response_started,
  374. content::SiteInstance** affinity_site_instance) const {
  375. if (g_suppress_renderer_process_restart) {
  376. g_suppress_renderer_process_restart = false;
  377. return SiteInstanceForNavigationType::ASK_CHROMIUM;
  378. }
  379. // Do we have an affinity site to manage ?
  380. content::SiteInstance* site_instance_from_affinity =
  381. GetSiteInstanceFromAffinity(browser_context, url, current_rfh);
  382. if (site_instance_from_affinity) {
  383. *affinity_site_instance = site_instance_from_affinity;
  384. return SiteInstanceForNavigationType::FORCE_AFFINITY;
  385. }
  386. if (!ShouldForceNewSiteInstance(current_rfh, speculative_rfh, browser_context,
  387. url, has_response_started)) {
  388. return SiteInstanceForNavigationType::ASK_CHROMIUM;
  389. }
  390. // ShouldOverrideSiteInstanceForNavigation will be called more than once
  391. // during a navigation (currently twice, on request and when it's about
  392. // to commit in the renderer), look at
  393. // RenderFrameHostManager::GetFrameHostForNavigation.
  394. // In the default mode we should reuse the same site instance until the
  395. // request commits otherwise it will get destroyed. Currently there is no
  396. // unique lifetime tracker for a navigation request during site instance
  397. // creation. We check for the state of the request, which should be one of
  398. // (WAITING_FOR_RENDERER_RESPONSE, STARTED, RESPONSE_STARTED, FAILED) along
  399. // with the availability of a speculative render frame host.
  400. if (has_response_started) {
  401. return SiteInstanceForNavigationType::FORCE_CURRENT;
  402. }
  403. if (!has_navigation_started) {
  404. // If the navigation didn't start yet, ignore any candidate site instance.
  405. // If such instance exists, it belongs to a previous navigation still
  406. // taking place. Fixes https://github.com/electron/electron/issues/17576.
  407. return SiteInstanceForNavigationType::FORCE_NEW;
  408. }
  409. return SiteInstanceForNavigationType::FORCE_CANDIDATE_OR_NEW;
  410. }
  411. void AtomBrowserClient::RegisterPendingSiteInstance(
  412. content::RenderFrameHost* rfh,
  413. content::SiteInstance* pending_site_instance) {
  414. // Do we have an affinity site to manage?
  415. ConsiderSiteInstanceForAffinity(rfh, pending_site_instance);
  416. // Remember the original web contents for the pending renderer process.
  417. auto* web_contents = content::WebContents::FromRenderFrameHost(rfh);
  418. auto* pending_process = pending_site_instance->GetProcess();
  419. pending_processes_[pending_process->GetID()] = web_contents;
  420. }
  421. void AtomBrowserClient::AppendExtraCommandLineSwitches(
  422. base::CommandLine* command_line,
  423. int process_id) {
  424. // Make sure we're about to launch a known executable
  425. {
  426. base::ThreadRestrictions::ScopedAllowIO allow_io;
  427. base::FilePath child_path;
  428. base::FilePath program =
  429. base::MakeAbsoluteFilePath(command_line->GetProgram());
  430. #if defined(OS_MACOSX)
  431. auto renderer_child_path = content::ChildProcessHost::GetChildPath(
  432. content::ChildProcessHost::CHILD_RENDERER);
  433. auto gpu_child_path = content::ChildProcessHost::GetChildPath(
  434. content::ChildProcessHost::CHILD_GPU);
  435. auto plugin_child_path = content::ChildProcessHost::GetChildPath(
  436. content::ChildProcessHost::CHILD_PLUGIN);
  437. if (program != renderer_child_path && program != gpu_child_path &&
  438. program != plugin_child_path) {
  439. child_path = content::ChildProcessHost::GetChildPath(
  440. content::ChildProcessHost::CHILD_NORMAL);
  441. CHECK_EQ(program, child_path)
  442. << "Aborted from launching unexpected helper executable";
  443. }
  444. #else
  445. base::PathService::Get(content::CHILD_PROCESS_EXE, &child_path);
  446. CHECK_EQ(program, child_path);
  447. #endif
  448. }
  449. std::string process_type =
  450. command_line->GetSwitchValueASCII(::switches::kProcessType);
  451. if (process_type != ::switches::kRendererProcess)
  452. return;
  453. // Copy following switches to child process.
  454. static const char* const kCommonSwitchNames[] = {
  455. switches::kStandardSchemes, switches::kEnableSandbox,
  456. switches::kSecureSchemes, switches::kBypassCSPSchemes,
  457. switches::kCORSSchemes, switches::kFetchSchemes,
  458. switches::kServiceWorkerSchemes};
  459. command_line->CopySwitchesFrom(*base::CommandLine::ForCurrentProcess(),
  460. kCommonSwitchNames,
  461. base::size(kCommonSwitchNames));
  462. #if defined(OS_WIN)
  463. // Append --app-user-model-id.
  464. PWSTR current_app_id;
  465. if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) {
  466. command_line->AppendSwitchNative(switches::kAppUserModelId, current_app_id);
  467. CoTaskMemFree(current_app_id);
  468. }
  469. #endif
  470. if (delegate_) {
  471. auto app_path = static_cast<api::App*>(delegate_)->GetAppPath();
  472. command_line->AppendSwitchPath(switches::kAppPath, app_path);
  473. }
  474. content::WebContents* web_contents = GetWebContentsFromProcessID(process_id);
  475. if (web_contents) {
  476. if (web_contents->GetVisibleURL().SchemeIs("devtools")) {
  477. command_line->AppendSwitch(switches::kDisableRemoteModule);
  478. }
  479. auto* web_preferences = WebContentsPreferences::From(web_contents);
  480. if (web_preferences)
  481. web_preferences->AppendCommandLineSwitches(command_line);
  482. SessionPreferences::AppendExtraCommandLineSwitches(
  483. web_contents->GetBrowserContext(), command_line);
  484. if (CanUseCustomSiteInstance()) {
  485. command_line->AppendSwitch(
  486. switches::kDisableElectronSiteInstanceOverrides);
  487. }
  488. }
  489. }
  490. void AtomBrowserClient::AdjustUtilityServiceProcessCommandLine(
  491. const service_manager::Identity& identity,
  492. base::CommandLine* command_line) {
  493. #if defined(OS_MACOSX)
  494. if (identity.name() == video_capture::mojom::kServiceName ||
  495. identity.name() == audio::mojom::kServiceName)
  496. command_line->AppendSwitch(::switches::kMessageLoopTypeUi);
  497. #endif
  498. }
  499. void AtomBrowserClient::DidCreatePpapiPlugin(content::BrowserPpapiHost* host) {
  500. #if BUILDFLAG(ENABLE_PEPPER_FLASH)
  501. host->GetPpapiHost()->AddHostFactoryFilter(
  502. base::WrapUnique(new ChromeBrowserPepperHostFactory(host)));
  503. #endif
  504. }
  505. // attempt to get api key from env
  506. std::string AtomBrowserClient::GetGeolocationApiKey() {
  507. std::unique_ptr<base::Environment> env(base::Environment::Create());
  508. std::string api_key;
  509. env->GetVar("GOOGLE_API_KEY", &api_key);
  510. return api_key;
  511. }
  512. scoped_refptr<content::QuotaPermissionContext>
  513. AtomBrowserClient::CreateQuotaPermissionContext() {
  514. return new AtomQuotaPermissionContext;
  515. }
  516. content::GeneratedCodeCacheSettings
  517. AtomBrowserClient::GetGeneratedCodeCacheSettings(
  518. content::BrowserContext* context) {
  519. // TODO(deepak1556): Use platform cache directory.
  520. base::FilePath cache_path = context->GetPath();
  521. // If we pass 0 for size, disk_cache will pick a default size using the
  522. // heuristics based on available disk size. These are implemented in
  523. // disk_cache::PreferredCacheSize in net/disk_cache/cache_util.cc.
  524. return content::GeneratedCodeCacheSettings(true, 0, cache_path);
  525. }
  526. void AtomBrowserClient::AllowCertificateError(
  527. content::WebContents* web_contents,
  528. int cert_error,
  529. const net::SSLInfo& ssl_info,
  530. const GURL& request_url,
  531. bool is_main_frame_request,
  532. bool strict_enforcement,
  533. bool expired_previous_decision,
  534. const base::Callback<void(content::CertificateRequestResultType)>&
  535. callback) {
  536. if (delegate_) {
  537. delegate_->AllowCertificateError(
  538. web_contents, cert_error, ssl_info, request_url, is_main_frame_request,
  539. strict_enforcement, expired_previous_decision, callback);
  540. }
  541. }
  542. void AtomBrowserClient::SelectClientCertificate(
  543. content::WebContents* web_contents,
  544. net::SSLCertRequestInfo* cert_request_info,
  545. net::ClientCertIdentityList client_certs,
  546. std::unique_ptr<content::ClientCertificateDelegate> delegate) {
  547. if (!client_certs.empty() && delegate_) {
  548. delegate_->SelectClientCertificate(web_contents, cert_request_info,
  549. std::move(client_certs),
  550. std::move(delegate));
  551. }
  552. }
  553. void AtomBrowserClient::ResourceDispatcherHostCreated() {
  554. resource_dispatcher_host_delegate_.reset(
  555. new AtomResourceDispatcherHostDelegate);
  556. content::ResourceDispatcherHost::Get()->SetDelegate(
  557. resource_dispatcher_host_delegate_.get());
  558. }
  559. bool AtomBrowserClient::CanCreateWindow(
  560. content::RenderFrameHost* opener,
  561. const GURL& opener_url,
  562. const GURL& opener_top_level_frame_url,
  563. const url::Origin& source_origin,
  564. content::mojom::WindowContainerType container_type,
  565. const GURL& target_url,
  566. const content::Referrer& referrer,
  567. const std::string& frame_name,
  568. WindowOpenDisposition disposition,
  569. const blink::mojom::WindowFeatures& features,
  570. const std::vector<std::string>& additional_features,
  571. const scoped_refptr<network::ResourceRequestBody>& body,
  572. bool user_gesture,
  573. bool opener_suppressed,
  574. bool* no_javascript_access) {
  575. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  576. int opener_render_process_id = opener->GetProcess()->GetID();
  577. if (RendererUsesNativeWindowOpen(opener_render_process_id)) {
  578. if (RendererDisablesPopups(opener_render_process_id)) {
  579. // <webview> without allowpopups attribute should return
  580. // null from window.open calls
  581. return false;
  582. } else {
  583. *no_javascript_access = false;
  584. return true;
  585. }
  586. }
  587. if (delegate_) {
  588. return delegate_->CanCreateWindow(
  589. opener, opener_url, opener_top_level_frame_url, source_origin,
  590. container_type, target_url, referrer, frame_name, disposition, features,
  591. additional_features, body, user_gesture, opener_suppressed,
  592. no_javascript_access);
  593. }
  594. return false;
  595. }
  596. void AtomBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
  597. std::vector<std::string>* additional_schemes) {
  598. auto schemes_list = api::GetStandardSchemes();
  599. if (!schemes_list.empty())
  600. additional_schemes->insert(additional_schemes->end(), schemes_list.begin(),
  601. schemes_list.end());
  602. additional_schemes->push_back(content::kChromeDevToolsScheme);
  603. }
  604. void AtomBrowserClient::GetAdditionalWebUISchemes(
  605. std::vector<std::string>* additional_schemes) {
  606. additional_schemes->push_back(content::kChromeDevToolsScheme);
  607. }
  608. void AtomBrowserClient::SiteInstanceDeleting(
  609. content::SiteInstance* site_instance) {
  610. // We are storing weak_ptr, is it fundamental to maintain the map up-to-date
  611. // when an instance is destroyed.
  612. for (auto iter = site_per_affinities_.begin();
  613. iter != site_per_affinities_.end(); ++iter) {
  614. if (iter->second == site_instance) {
  615. site_per_affinities_.erase(iter);
  616. break;
  617. }
  618. }
  619. }
  620. std::unique_ptr<net::ClientCertStore> AtomBrowserClient::CreateClientCertStore(
  621. content::ResourceContext* resource_context) {
  622. #if defined(USE_NSS_CERTS)
  623. return std::make_unique<net::ClientCertStoreNSS>(
  624. net::ClientCertStoreNSS::PasswordDelegateFactory());
  625. #elif defined(OS_WIN)
  626. return std::make_unique<net::ClientCertStoreWin>();
  627. #elif defined(OS_MACOSX)
  628. return std::make_unique<net::ClientCertStoreMac>();
  629. #elif defined(USE_OPENSSL)
  630. return std::unique_ptr<net::ClientCertStore>();
  631. #endif
  632. }
  633. std::unique_ptr<device::LocationProvider>
  634. AtomBrowserClient::OverrideSystemLocationProvider() {
  635. #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER)
  636. return std::make_unique<FakeLocationProvider>();
  637. #else
  638. return nullptr;
  639. #endif
  640. }
  641. network::mojom::NetworkContextPtr AtomBrowserClient::CreateNetworkContext(
  642. content::BrowserContext* browser_context,
  643. bool /*in_memory*/,
  644. const base::FilePath& /*relative_partition_path*/) {
  645. if (!browser_context)
  646. return nullptr;
  647. if (base::FeatureList::IsEnabled(network::features::kNetworkService)) {
  648. return NetworkContextServiceFactory::GetForContext(browser_context)
  649. ->CreateNetworkContext();
  650. } else {
  651. return static_cast<AtomBrowserContext*>(browser_context)
  652. ->GetNetworkContext();
  653. }
  654. }
  655. network::mojom::NetworkContext* AtomBrowserClient::GetSystemNetworkContext() {
  656. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  657. DCHECK(g_browser_process->system_network_context_manager());
  658. return g_browser_process->system_network_context_manager()->GetContext();
  659. }
  660. base::Optional<service_manager::Manifest>
  661. AtomBrowserClient::GetServiceManifestOverlay(base::StringPiece name) {
  662. if (name == content::mojom::kBrowserServiceName)
  663. return GetElectronContentBrowserOverlayManifest();
  664. return base::nullopt;
  665. }
  666. std::vector<service_manager::Manifest>
  667. AtomBrowserClient::GetExtraServiceManifests() {
  668. return GetElectronBuiltinServiceManifests();
  669. }
  670. net::NetLog* AtomBrowserClient::GetNetLog() {
  671. return g_browser_process->net_log();
  672. }
  673. std::unique_ptr<content::BrowserMainParts>
  674. AtomBrowserClient::CreateBrowserMainParts(
  675. const content::MainFunctionParams& params) {
  676. return std::make_unique<AtomBrowserMainParts>(params);
  677. }
  678. void AtomBrowserClient::WebNotificationAllowed(
  679. int render_process_id,
  680. const base::Callback<void(bool, bool)>& callback) {
  681. content::WebContents* web_contents =
  682. WebContentsPreferences::GetWebContentsFromProcessID(render_process_id);
  683. if (!web_contents) {
  684. callback.Run(false, false);
  685. return;
  686. }
  687. auto* permission_helper =
  688. WebContentsPermissionHelper::FromWebContents(web_contents);
  689. if (!permission_helper) {
  690. callback.Run(false, false);
  691. return;
  692. }
  693. permission_helper->RequestWebNotificationPermission(
  694. base::Bind(callback, web_contents->IsAudioMuted()));
  695. }
  696. void AtomBrowserClient::RenderProcessHostDestroyed(
  697. content::RenderProcessHost* host) {
  698. int process_id = host->GetID();
  699. pending_processes_.erase(process_id);
  700. RemoveProcessPreferences(process_id);
  701. }
  702. void AtomBrowserClient::RenderProcessReady(content::RenderProcessHost* host) {
  703. render_process_host_pids_[host->GetID()] =
  704. base::GetProcId(host->GetProcess().Handle());
  705. if (delegate_) {
  706. static_cast<api::App*>(delegate_)->RenderProcessReady(host);
  707. }
  708. }
  709. void AtomBrowserClient::RenderProcessExited(
  710. content::RenderProcessHost* host,
  711. const content::ChildProcessTerminationInfo& info) {
  712. auto host_pid = render_process_host_pids_.find(host->GetID());
  713. if (host_pid != render_process_host_pids_.end()) {
  714. if (delegate_) {
  715. static_cast<api::App*>(delegate_)->RenderProcessDisconnected(
  716. host_pid->second);
  717. }
  718. render_process_host_pids_.erase(host_pid);
  719. }
  720. }
  721. void OnOpenExternal(const GURL& escaped_url, bool allowed) {
  722. if (allowed)
  723. platform_util::OpenExternal(
  724. #if defined(OS_WIN)
  725. base::UTF8ToUTF16(escaped_url.spec()),
  726. #else
  727. escaped_url,
  728. #endif
  729. platform_util::OpenExternalOptions());
  730. }
  731. void HandleExternalProtocolInUI(
  732. const GURL& url,
  733. const content::ResourceRequestInfo::WebContentsGetter& web_contents_getter,
  734. bool has_user_gesture) {
  735. content::WebContents* web_contents = web_contents_getter.Run();
  736. if (!web_contents)
  737. return;
  738. auto* permission_helper =
  739. WebContentsPermissionHelper::FromWebContents(web_contents);
  740. if (!permission_helper)
  741. return;
  742. GURL escaped_url(net::EscapeExternalHandlerValue(url.spec()));
  743. auto callback = base::Bind(&OnOpenExternal, escaped_url);
  744. permission_helper->RequestOpenExternalPermission(callback, has_user_gesture,
  745. url);
  746. }
  747. bool AtomBrowserClient::HandleExternalProtocol(
  748. const GURL& url,
  749. content::ResourceRequestInfo::WebContentsGetter web_contents_getter,
  750. int child_id,
  751. content::NavigationUIData* navigation_data,
  752. bool is_main_frame,
  753. ui::PageTransition page_transition,
  754. bool has_user_gesture,
  755. network::mojom::URLLoaderFactoryRequest* factory_request,
  756. // clang-format off
  757. network::mojom::URLLoaderFactory*& out_factory) { // NOLINT
  758. // clang-format on
  759. base::PostTaskWithTraits(
  760. FROM_HERE, {BrowserThread::UI},
  761. base::BindOnce(&HandleExternalProtocolInUI, url, web_contents_getter,
  762. has_user_gesture));
  763. return true;
  764. }
  765. std::vector<std::unique_ptr<content::NavigationThrottle>>
  766. AtomBrowserClient::CreateThrottlesForNavigation(
  767. content::NavigationHandle* handle) {
  768. std::vector<std::unique_ptr<content::NavigationThrottle>> throttles;
  769. throttles.push_back(std::make_unique<AtomNavigationThrottle>(handle));
  770. return throttles;
  771. }
  772. content::MediaObserver* AtomBrowserClient::GetMediaObserver() {
  773. return MediaCaptureDevicesDispatcher::GetInstance();
  774. }
  775. content::DevToolsManagerDelegate*
  776. AtomBrowserClient::GetDevToolsManagerDelegate() {
  777. return new DevToolsManagerDelegate;
  778. }
  779. NotificationPresenter* AtomBrowserClient::GetNotificationPresenter() {
  780. if (!notification_presenter_) {
  781. notification_presenter_.reset(NotificationPresenter::Create());
  782. }
  783. return notification_presenter_.get();
  784. }
  785. content::PlatformNotificationService*
  786. AtomBrowserClient::GetPlatformNotificationService(
  787. content::BrowserContext* browser_context) {
  788. if (!notification_service_) {
  789. notification_service_.reset(new PlatformNotificationService(this));
  790. }
  791. return notification_service_.get();
  792. }
  793. base::FilePath AtomBrowserClient::GetDefaultDownloadDirectory() {
  794. // ~/Downloads
  795. base::FilePath path;
  796. if (base::PathService::Get(base::DIR_HOME, &path))
  797. path = path.Append(FILE_PATH_LITERAL("Downloads"));
  798. return path;
  799. }
  800. scoped_refptr<network::SharedURLLoaderFactory>
  801. AtomBrowserClient::GetSystemSharedURLLoaderFactory() {
  802. if (!g_browser_process)
  803. return nullptr;
  804. return g_browser_process->shared_url_loader_factory();
  805. }
  806. void AtomBrowserClient::OnNetworkServiceCreated(
  807. network::mojom::NetworkService* network_service) {
  808. if (!g_browser_process ||
  809. !base::FeatureList::IsEnabled(network::features::kNetworkService))
  810. return;
  811. g_browser_process->system_network_context_manager()->OnNetworkServiceCreated(
  812. network_service);
  813. }
  814. bool AtomBrowserClient::ShouldBypassCORB(int render_process_id) const {
  815. // This is called on the network thread.
  816. base::AutoLock auto_lock(process_preferences_lock_);
  817. auto it = process_preferences_.find(render_process_id);
  818. return it != process_preferences_.end() && !it->second.web_security;
  819. }
  820. std::string AtomBrowserClient::GetProduct() const {
  821. return "Chrome/" CHROME_VERSION_STRING;
  822. }
  823. std::string AtomBrowserClient::GetUserAgent() const {
  824. if (user_agent_override_.empty())
  825. return GetApplicationUserAgent();
  826. return user_agent_override_;
  827. }
  828. void AtomBrowserClient::SetUserAgent(const std::string& user_agent) {
  829. user_agent_override_ = user_agent;
  830. }
  831. #if defined(OS_WIN)
  832. bool AtomBrowserClient::PreSpawnRenderer(sandbox::TargetPolicy* policy) {
  833. // Allow crashpad to communicate via named pipe.
  834. sandbox::ResultCode result = policy->AddRule(
  835. sandbox::TargetPolicy::SUBSYS_FILES,
  836. sandbox::TargetPolicy::FILES_ALLOW_ANY, L"\\??\\pipe\\crashpad_*");
  837. if (result != sandbox::SBOX_ALL_OK)
  838. return false;
  839. return true;
  840. }
  841. #endif // defined(OS_WIN)
  842. std::string AtomBrowserClient::GetApplicationLocale() {
  843. if (BrowserThread::CurrentlyOn(BrowserThread::IO))
  844. return g_io_thread_application_locale.Get();
  845. return *g_application_locale;
  846. }
  847. bool AtomBrowserClient::ShouldEnableStrictSiteIsolation() {
  848. // Enable site isolation. It is off by default in Chromium <= 69.
  849. return true;
  850. }
  851. } // namespace atom