electron_browser_client.cc 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760
  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/electron_browser_client.h"
  5. #if defined(OS_WIN)
  6. #include <shlobj.h>
  7. #endif
  8. #include <memory>
  9. #include <utility>
  10. #include "base/base_switches.h"
  11. #include "base/command_line.h"
  12. #include "base/debug/crash_logging.h"
  13. #include "base/environment.h"
  14. #include "base/files/file_util.h"
  15. #include "base/json/json_reader.h"
  16. #include "base/lazy_instance.h"
  17. #include "base/no_destructor.h"
  18. #include "base/path_service.h"
  19. #include "base/stl_util.h"
  20. #include "base/strings/string_number_conversions.h"
  21. #include "base/strings/string_util.h"
  22. #include "base/strings/utf_string_conversions.h"
  23. #include "base/task/post_task.h"
  24. #include "chrome/browser/browser_process.h"
  25. #include "chrome/common/chrome_paths.h"
  26. #include "chrome/common/chrome_switches.h"
  27. #include "chrome/common/chrome_version.h"
  28. #include "components/embedder_support/user_agent_utils.h"
  29. #include "components/net_log/chrome_net_log.h"
  30. #include "components/network_hints/common/network_hints.mojom.h"
  31. #include "content/browser/keyboard_lock/keyboard_lock_service_impl.h" // nogncheck
  32. #include "content/browser/site_instance_impl.h" // nogncheck
  33. #include "content/public/browser/browser_main_runner.h"
  34. #include "content/public/browser/browser_ppapi_host.h"
  35. #include "content/public/browser/browser_task_traits.h"
  36. #include "content/public/browser/client_certificate_delegate.h"
  37. #include "content/public/browser/login_delegate.h"
  38. #include "content/public/browser/overlay_window.h"
  39. #include "content/public/browser/render_frame_host.h"
  40. #include "content/public/browser/render_process_host.h"
  41. #include "content/public/browser/render_view_host.h"
  42. #include "content/public/browser/service_worker_version_base_info.h"
  43. #include "content/public/browser/site_instance.h"
  44. #include "content/public/browser/tts_controller.h"
  45. #include "content/public/browser/tts_platform.h"
  46. #include "content/public/common/content_descriptors.h"
  47. #include "content/public/common/content_paths.h"
  48. #include "content/public/common/content_switches.h"
  49. #include "content/public/common/url_constants.h"
  50. #include "electron/buildflags/buildflags.h"
  51. #include "electron/grit/electron_resources.h"
  52. #include "electron/shell/common/api/api.mojom.h"
  53. #include "mojo/public/cpp/bindings/binder_map.h"
  54. #include "net/base/escape.h"
  55. #include "net/ssl/ssl_cert_request_info.h"
  56. #include "ppapi/buildflags/buildflags.h"
  57. #include "ppapi/host/ppapi_host.h"
  58. #include "printing/buildflags/buildflags.h"
  59. #include "services/device/public/cpp/geolocation/location_provider.h"
  60. #include "services/network/public/cpp/features.h"
  61. #include "services/network/public/cpp/resource_request_body.h"
  62. #include "services/network/public/cpp/self_deleting_url_loader_factory.h"
  63. #include "shell/app/electron_crash_reporter_client.h"
  64. #include "shell/browser/api/electron_api_app.h"
  65. #include "shell/browser/api/electron_api_crash_reporter.h"
  66. #include "shell/browser/api/electron_api_protocol.h"
  67. #include "shell/browser/api/electron_api_session.h"
  68. #include "shell/browser/api/electron_api_web_contents.h"
  69. #include "shell/browser/api/electron_api_web_request.h"
  70. #include "shell/browser/badging/badge_manager.h"
  71. #include "shell/browser/child_web_contents_tracker.h"
  72. #include "shell/browser/electron_api_ipc_handler_impl.h"
  73. #include "shell/browser/electron_autofill_driver_factory.h"
  74. #include "shell/browser/electron_browser_context.h"
  75. #include "shell/browser/electron_browser_main_parts.h"
  76. #include "shell/browser/electron_navigation_throttle.h"
  77. #include "shell/browser/electron_quota_permission_context.h"
  78. #include "shell/browser/electron_speech_recognition_manager_delegate.h"
  79. #include "shell/browser/electron_web_contents_utility_handler_impl.h"
  80. #include "shell/browser/font_defaults.h"
  81. #include "shell/browser/javascript_environment.h"
  82. #include "shell/browser/media/media_capture_devices_dispatcher.h"
  83. #include "shell/browser/native_window.h"
  84. #include "shell/browser/net/network_context_service.h"
  85. #include "shell/browser/net/network_context_service_factory.h"
  86. #include "shell/browser/net/proxying_url_loader_factory.h"
  87. #include "shell/browser/net/proxying_websocket.h"
  88. #include "shell/browser/net/system_network_context_manager.h"
  89. #include "shell/browser/network_hints_handler_impl.h"
  90. #include "shell/browser/notifications/notification_presenter.h"
  91. #include "shell/browser/notifications/platform_notification_service.h"
  92. #include "shell/browser/protocol_registry.h"
  93. #include "shell/browser/serial/electron_serial_delegate.h"
  94. #include "shell/browser/session_preferences.h"
  95. #include "shell/browser/ui/devtools_manager_delegate.h"
  96. #include "shell/browser/web_contents_permission_helper.h"
  97. #include "shell/browser/web_contents_preferences.h"
  98. #include "shell/browser/window_list.h"
  99. #include "shell/common/api/api.mojom.h"
  100. #include "shell/common/application_info.h"
  101. #include "shell/common/electron_paths.h"
  102. #include "shell/common/logging.h"
  103. #include "shell/common/options_switches.h"
  104. #include "shell/common/platform_util.h"
  105. #include "third_party/blink/public/common/loader/url_loader_throttle.h"
  106. #include "third_party/blink/public/common/tokens/tokens.h"
  107. #include "third_party/blink/public/common/web_preferences/web_preferences.h"
  108. #include "third_party/blink/public/mojom/badging/badging.mojom.h"
  109. #include "ui/base/resource/resource_bundle.h"
  110. #include "ui/native_theme/native_theme.h"
  111. #include "v8/include/v8.h"
  112. #if defined(OS_WIN)
  113. #include "sandbox/win/src/sandbox_policy.h"
  114. #endif
  115. #if defined(USE_NSS_CERTS)
  116. #include "net/ssl/client_cert_store_nss.h"
  117. #elif defined(OS_WIN)
  118. #include "net/ssl/client_cert_store_win.h"
  119. #elif defined(OS_MAC)
  120. #include "net/ssl/client_cert_store_mac.h"
  121. #elif defined(USE_OPENSSL)
  122. #include "net/ssl/client_cert_store.h"
  123. #endif
  124. #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
  125. #include "chrome/browser/spellchecker/spell_check_host_chrome_impl.h" // nogncheck
  126. #include "components/spellcheck/common/spellcheck.mojom.h" // nogncheck
  127. #endif
  128. #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER)
  129. #include "shell/browser/fake_location_provider.h"
  130. #endif // BUILDFLAG(OVERRIDE_LOCATION_PROVIDER)
  131. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  132. #include "chrome/common/webui_url_constants.h"
  133. #include "content/public/browser/child_process_security_policy.h"
  134. #include "content/public/browser/file_url_loader.h"
  135. #include "content/public/browser/web_ui_url_loader_factory.h"
  136. #include "extensions/browser/api/mime_handler_private/mime_handler_private.h"
  137. #include "extensions/browser/api/web_request/web_request_api.h"
  138. #include "extensions/browser/browser_context_keyed_api_factory.h"
  139. #include "extensions/browser/event_router.h"
  140. #include "extensions/browser/extension_host.h"
  141. #include "extensions/browser/extension_message_filter.h"
  142. #include "extensions/browser/extension_navigation_throttle.h"
  143. #include "extensions/browser/extension_navigation_ui_data.h"
  144. #include "extensions/browser/extension_prefs.h"
  145. #include "extensions/browser/extension_protocols.h"
  146. #include "extensions/browser/extension_registry.h"
  147. #include "extensions/browser/extensions_browser_client.h"
  148. #include "extensions/browser/guest_view/extensions_guest_view_message_filter.h"
  149. #include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
  150. #include "extensions/browser/info_map.h"
  151. #include "extensions/browser/process_manager.h"
  152. #include "extensions/browser/process_map.h"
  153. #include "extensions/browser/url_loader_factory_manager.h"
  154. #include "extensions/common/api/mime_handler.mojom.h"
  155. #include "extensions/common/constants.h"
  156. #include "extensions/common/extension.h"
  157. #include "extensions/common/switches.h"
  158. #include "shell/browser/extensions/electron_extension_message_filter.h"
  159. #include "shell/browser/extensions/electron_extension_system.h"
  160. #include "shell/browser/extensions/electron_extension_web_contents_observer.h"
  161. #include "third_party/blink/public/common/associated_interfaces/associated_interface_registry.h"
  162. #endif
  163. #if BUILDFLAG(ENABLE_PLUGINS)
  164. #include "chrome/browser/plugins/plugin_response_interceptor_url_loader_throttle.h" // nogncheck
  165. #include "shell/browser/plugins/plugin_utils.h"
  166. #endif
  167. #if defined(OS_MAC)
  168. #include "content/common/mac_helpers.h"
  169. #include "content/public/common/child_process_host.h"
  170. #endif
  171. #if defined(OS_LINUX) && !defined(MAS_BUILD)
  172. #include "base/debug/leak_annotations.h"
  173. #include "components/crash/content/browser/crash_handler_host_linux.h"
  174. #include "components/crash/core/app/breakpad_linux.h" // nogncheck
  175. #include "components/crash/core/app/crash_switches.h" // nogncheck
  176. #include "components/crash/core/app/crashpad.h" // nogncheck
  177. #endif
  178. #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) && defined(OS_WIN)
  179. #include "chrome/browser/ui/views/overlay/overlay_window_views.h"
  180. #include "shell/browser/browser.h"
  181. #include "ui/aura/window.h"
  182. #include "ui/aura/window_tree_host.h"
  183. #include "ui/base/win/shell.h"
  184. #include "ui/views/widget/widget.h"
  185. #endif
  186. #if BUILDFLAG(ENABLE_PRINTING)
  187. #include "shell/browser/printing/print_view_manager_electron.h"
  188. #endif
  189. #if BUILDFLAG(ENABLE_PDF_VIEWER)
  190. #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck
  191. #endif
  192. using content::BrowserThread;
  193. namespace electron {
  194. namespace {
  195. ElectronBrowserClient* g_browser_client = nullptr;
  196. base::LazyInstance<std::string>::DestructorAtExit
  197. g_io_thread_application_locale = LAZY_INSTANCE_INITIALIZER;
  198. base::NoDestructor<std::string> g_application_locale;
  199. void SetApplicationLocaleOnIOThread(const std::string& locale) {
  200. DCHECK_CURRENTLY_ON(BrowserThread::IO);
  201. g_io_thread_application_locale.Get() = locale;
  202. }
  203. void BindNetworkHintsHandler(
  204. content::RenderFrameHost* frame_host,
  205. mojo::PendingReceiver<network_hints::mojom::NetworkHintsHandler> receiver) {
  206. NetworkHintsHandlerImpl::Create(frame_host, std::move(receiver));
  207. }
  208. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  209. // Used by the GetPrivilegeRequiredByUrl() and GetProcessPrivilege() functions
  210. // below. Extension, and isolated apps require different privileges to be
  211. // granted to their RenderProcessHosts. This classification allows us to make
  212. // sure URLs are served by hosts with the right set of privileges.
  213. enum class RenderProcessHostPrivilege {
  214. kNormal,
  215. kHosted,
  216. kIsolated,
  217. kExtension,
  218. };
  219. // Copied from chrome/browser/extensions/extension_util.cc.
  220. bool AllowFileAccess(const std::string& extension_id,
  221. content::BrowserContext* context) {
  222. return base::CommandLine::ForCurrentProcess()->HasSwitch(
  223. ::switches::kDisableExtensionsFileAccessCheck) ||
  224. extensions::ExtensionPrefs::Get(context)->AllowFileAccess(
  225. extension_id);
  226. }
  227. RenderProcessHostPrivilege GetPrivilegeRequiredByUrl(
  228. const GURL& url,
  229. extensions::ExtensionRegistry* registry) {
  230. // Default to a normal renderer cause it is lower privileged. This should only
  231. // occur if the URL on a site instance is either malformed, or uninitialized.
  232. // If it is malformed, then there is no need for better privileges anyways.
  233. // If it is uninitialized, but eventually settles on being an a scheme other
  234. // than normal webrenderer, the navigation logic will correct us out of band
  235. // anyways.
  236. if (!url.is_valid())
  237. return RenderProcessHostPrivilege::kNormal;
  238. if (!url.SchemeIs(extensions::kExtensionScheme))
  239. return RenderProcessHostPrivilege::kNormal;
  240. return RenderProcessHostPrivilege::kExtension;
  241. }
  242. RenderProcessHostPrivilege GetProcessPrivilege(
  243. content::RenderProcessHost* process_host,
  244. extensions::ProcessMap* process_map,
  245. extensions::ExtensionRegistry* registry) {
  246. std::set<std::string> extension_ids =
  247. process_map->GetExtensionsInProcess(process_host->GetID());
  248. if (extension_ids.empty())
  249. return RenderProcessHostPrivilege::kNormal;
  250. return RenderProcessHostPrivilege::kExtension;
  251. }
  252. const extensions::Extension* GetEnabledExtensionFromEffectiveURL(
  253. content::BrowserContext* context,
  254. const GURL& effective_url) {
  255. if (!effective_url.SchemeIs(extensions::kExtensionScheme))
  256. return nullptr;
  257. extensions::ExtensionRegistry* registry =
  258. extensions::ExtensionRegistry::Get(context);
  259. if (!registry)
  260. return nullptr;
  261. return registry->enabled_extensions().GetByID(effective_url.host());
  262. }
  263. #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  264. #if defined(OS_LINUX)
  265. breakpad::CrashHandlerHostLinux* CreateCrashHandlerHost(
  266. const std::string& process_type) {
  267. base::FilePath dumps_path;
  268. base::PathService::Get(electron::DIR_CRASH_DUMPS, &dumps_path);
  269. {
  270. ANNOTATE_SCOPED_MEMORY_LEAK;
  271. bool upload = ElectronCrashReporterClient::Get()->GetCollectStatsConsent();
  272. breakpad::CrashHandlerHostLinux* crash_handler =
  273. new breakpad::CrashHandlerHostLinux(process_type, dumps_path, upload);
  274. crash_handler->StartUploaderThread();
  275. return crash_handler;
  276. }
  277. }
  278. int GetCrashSignalFD(const base::CommandLine& command_line) {
  279. if (crash_reporter::IsCrashpadEnabled()) {
  280. int fd;
  281. pid_t pid;
  282. return crash_reporter::GetHandlerSocket(&fd, &pid) ? fd : -1;
  283. }
  284. // Extensions have the same process type as renderers.
  285. if (command_line.HasSwitch(extensions::switches::kExtensionProcess)) {
  286. static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
  287. if (!crash_handler)
  288. crash_handler = CreateCrashHandlerHost("extension");
  289. return crash_handler->GetDeathSignalSocket();
  290. }
  291. std::string process_type =
  292. command_line.GetSwitchValueASCII(::switches::kProcessType);
  293. if (process_type == ::switches::kRendererProcess) {
  294. static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
  295. if (!crash_handler)
  296. crash_handler = CreateCrashHandlerHost(process_type);
  297. return crash_handler->GetDeathSignalSocket();
  298. }
  299. if (process_type == ::switches::kPpapiPluginProcess) {
  300. static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
  301. if (!crash_handler)
  302. crash_handler = CreateCrashHandlerHost(process_type);
  303. return crash_handler->GetDeathSignalSocket();
  304. }
  305. if (process_type == ::switches::kGpuProcess) {
  306. static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
  307. if (!crash_handler)
  308. crash_handler = CreateCrashHandlerHost(process_type);
  309. return crash_handler->GetDeathSignalSocket();
  310. }
  311. if (process_type == ::switches::kUtilityProcess) {
  312. static breakpad::CrashHandlerHostLinux* crash_handler = nullptr;
  313. if (!crash_handler)
  314. crash_handler = CreateCrashHandlerHost(process_type);
  315. return crash_handler->GetDeathSignalSocket();
  316. }
  317. return -1;
  318. }
  319. #endif // defined(OS_LINUX)
  320. } // namespace
  321. // static
  322. ElectronBrowserClient* ElectronBrowserClient::Get() {
  323. return g_browser_client;
  324. }
  325. // static
  326. void ElectronBrowserClient::SetApplicationLocale(const std::string& locale) {
  327. if (!BrowserThread::IsThreadInitialized(BrowserThread::IO) ||
  328. !base::PostTask(
  329. FROM_HERE, {BrowserThread::IO},
  330. base::BindOnce(&SetApplicationLocaleOnIOThread, locale))) {
  331. g_io_thread_application_locale.Get() = locale;
  332. }
  333. *g_application_locale = locale;
  334. }
  335. ElectronBrowserClient::ElectronBrowserClient() {
  336. DCHECK(!g_browser_client);
  337. g_browser_client = this;
  338. }
  339. ElectronBrowserClient::~ElectronBrowserClient() {
  340. DCHECK(g_browser_client);
  341. g_browser_client = nullptr;
  342. }
  343. content::WebContents* ElectronBrowserClient::GetWebContentsFromProcessID(
  344. int process_id) {
  345. // If the process is a pending process, we should use the web contents
  346. // for the frame host passed into RegisterPendingProcess.
  347. const auto iter = pending_processes_.find(process_id);
  348. if (iter != std::end(pending_processes_))
  349. return iter->second;
  350. // Certain render process will be created with no associated render view,
  351. // for example: ServiceWorker.
  352. return WebContentsPreferences::GetWebContentsFromProcessID(process_id);
  353. }
  354. content::SiteInstance* ElectronBrowserClient::GetSiteInstanceFromAffinity(
  355. content::BrowserContext* browser_context,
  356. const GURL& url,
  357. content::RenderFrameHost* rfh) const {
  358. return nullptr;
  359. }
  360. bool ElectronBrowserClient::IsRendererSubFrame(int process_id) const {
  361. return base::Contains(renderer_is_subframe_, process_id);
  362. }
  363. void ElectronBrowserClient::RenderProcessWillLaunch(
  364. content::RenderProcessHost* host) {
  365. // When a render process is crashed, it might be reused.
  366. int process_id = host->GetID();
  367. auto* browser_context = host->GetBrowserContext();
  368. ALLOW_UNUSED_LOCAL(browser_context);
  369. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  370. host->AddFilter(
  371. new extensions::ExtensionMessageFilter(process_id, browser_context));
  372. host->AddFilter(new extensions::ExtensionsGuestViewMessageFilter(
  373. process_id, browser_context));
  374. host->AddFilter(
  375. new ElectronExtensionMessageFilter(process_id, browser_context));
  376. #endif
  377. // ensure the ProcessPreferences is removed later
  378. host->AddObserver(this);
  379. }
  380. content::SpeechRecognitionManagerDelegate*
  381. ElectronBrowserClient::CreateSpeechRecognitionManagerDelegate() {
  382. return new ElectronSpeechRecognitionManagerDelegate;
  383. }
  384. content::TtsPlatform* ElectronBrowserClient::GetTtsPlatform() {
  385. return nullptr;
  386. }
  387. void ElectronBrowserClient::OverrideWebkitPrefs(
  388. content::WebContents* web_contents,
  389. blink::web_pref::WebPreferences* prefs) {
  390. prefs->javascript_enabled = true;
  391. prefs->web_security_enabled = true;
  392. prefs->plugins_enabled = true;
  393. prefs->dom_paste_enabled = true;
  394. prefs->allow_scripts_to_close_windows = true;
  395. prefs->javascript_can_access_clipboard = true;
  396. prefs->local_storage_enabled = true;
  397. prefs->databases_enabled = true;
  398. prefs->allow_universal_access_from_file_urls = true;
  399. prefs->allow_file_access_from_file_urls = true;
  400. prefs->webgl1_enabled = true;
  401. prefs->webgl2_enabled = true;
  402. prefs->allow_running_insecure_content = false;
  403. prefs->default_minimum_page_scale_factor = 1.f;
  404. prefs->default_maximum_page_scale_factor = 1.f;
  405. prefs->navigate_on_drag_drop = false;
  406. #if !BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
  407. prefs->picture_in_picture_enabled = false;
  408. #endif
  409. ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForNativeUi();
  410. prefs->preferred_color_scheme =
  411. native_theme->ShouldUseDarkColors()
  412. ? blink::mojom::PreferredColorScheme::kDark
  413. : blink::mojom::PreferredColorScheme::kLight;
  414. auto preloads =
  415. SessionPreferences::GetValidPreloads(web_contents->GetBrowserContext());
  416. if (!preloads.empty())
  417. prefs->preloads = preloads;
  418. SetFontDefaults(prefs);
  419. // Custom preferences of guest page.
  420. auto* web_preferences = WebContentsPreferences::From(web_contents);
  421. if (web_preferences) {
  422. web_preferences->OverrideWebkitPrefs(prefs);
  423. }
  424. }
  425. void ElectronBrowserClient::RegisterPendingSiteInstance(
  426. content::RenderFrameHost* rfh,
  427. content::SiteInstance* pending_site_instance) {
  428. // Remember the original web contents for the pending renderer process.
  429. auto* web_contents = content::WebContents::FromRenderFrameHost(rfh);
  430. auto* pending_process = pending_site_instance->GetProcess();
  431. pending_processes_[pending_process->GetID()] = web_contents;
  432. if (rfh->GetParent())
  433. renderer_is_subframe_.insert(pending_process->GetID());
  434. else
  435. renderer_is_subframe_.erase(pending_process->GetID());
  436. }
  437. void ElectronBrowserClient::AppendExtraCommandLineSwitches(
  438. base::CommandLine* command_line,
  439. int process_id) {
  440. // Make sure we're about to launch a known executable
  441. {
  442. base::ThreadRestrictions::ScopedAllowIO allow_io;
  443. base::FilePath child_path;
  444. base::FilePath program =
  445. base::MakeAbsoluteFilePath(command_line->GetProgram());
  446. #if defined(OS_MAC)
  447. auto renderer_child_path = content::ChildProcessHost::GetChildPath(
  448. content::ChildProcessHost::CHILD_RENDERER);
  449. auto gpu_child_path = content::ChildProcessHost::GetChildPath(
  450. content::ChildProcessHost::CHILD_GPU);
  451. #if BUILDFLAG(ENABLE_PLUGINS)
  452. auto plugin_child_path = content::ChildProcessHost::GetChildPath(
  453. content::ChildProcessHost::CHILD_PLUGIN);
  454. #endif
  455. if (program != renderer_child_path && program != gpu_child_path
  456. #if BUILDFLAG(ENABLE_PLUGINS)
  457. && program != plugin_child_path
  458. #endif
  459. ) {
  460. child_path = content::ChildProcessHost::GetChildPath(
  461. content::ChildProcessHost::CHILD_NORMAL);
  462. CHECK_EQ(program, child_path)
  463. << "Aborted from launching unexpected helper executable";
  464. }
  465. #else
  466. if (!base::PathService::Get(content::CHILD_PROCESS_EXE, &child_path)) {
  467. CHECK(false) << "Unable to get child process binary name.";
  468. }
  469. SCOPED_CRASH_KEY_STRING256("ChildProcess", "child_process_exe",
  470. child_path.AsUTF8Unsafe());
  471. SCOPED_CRASH_KEY_STRING256("ChildProcess", "program",
  472. program.AsUTF8Unsafe());
  473. CHECK_EQ(program, child_path);
  474. #endif
  475. }
  476. std::string process_type =
  477. command_line->GetSwitchValueASCII(::switches::kProcessType);
  478. #if defined(OS_LINUX)
  479. bool enable_crash_reporter = false;
  480. if (crash_reporter::IsCrashpadEnabled()) {
  481. command_line->AppendSwitch(::switches::kEnableCrashpad);
  482. enable_crash_reporter = true;
  483. int fd;
  484. pid_t pid;
  485. if (crash_reporter::GetHandlerSocket(&fd, &pid)) {
  486. command_line->AppendSwitchASCII(
  487. crash_reporter::switches::kCrashpadHandlerPid,
  488. base::NumberToString(pid));
  489. }
  490. } else {
  491. enable_crash_reporter = breakpad::IsCrashReporterEnabled();
  492. }
  493. // Zygote Process gets booted before any JS runs, accessing GetClientId
  494. // will end up touching DIR_USER_DATA path provider and this will
  495. // configure default value because app.name from browser_init has
  496. // not run yet.
  497. if (enable_crash_reporter && process_type != ::switches::kZygoteProcess) {
  498. std::string switch_value =
  499. api::crash_reporter::GetClientId() + ",no_channel";
  500. command_line->AppendSwitchASCII(::switches::kEnableCrashReporter,
  501. switch_value);
  502. if (!crash_reporter::IsCrashpadEnabled()) {
  503. for (const auto& pair : api::crash_reporter::GetGlobalCrashKeys()) {
  504. if (!switch_value.empty())
  505. switch_value += ",";
  506. switch_value += pair.first;
  507. switch_value += "=";
  508. switch_value += pair.second;
  509. }
  510. command_line->AppendSwitchASCII(switches::kGlobalCrashKeys, switch_value);
  511. }
  512. }
  513. #endif
  514. // The zygote process is booted before JS runs, so DIR_USER_DATA isn't usable
  515. // at that time. It doesn't need --user-data-dir to be correct anyway, since
  516. // the zygote itself doesn't access anything in that directory.
  517. if (process_type != ::switches::kZygoteProcess) {
  518. base::FilePath user_data_dir;
  519. if (base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir))
  520. command_line->AppendSwitchPath(::switches::kUserDataDir, user_data_dir);
  521. }
  522. if (process_type == ::switches::kUtilityProcess ||
  523. process_type == ::switches::kRendererProcess) {
  524. // Copy following switches to child process.
  525. static const char* const kCommonSwitchNames[] = {
  526. switches::kStandardSchemes, switches::kEnableSandbox,
  527. switches::kSecureSchemes, switches::kBypassCSPSchemes,
  528. switches::kCORSSchemes, switches::kFetchSchemes,
  529. switches::kServiceWorkerSchemes, switches::kStreamingSchemes};
  530. command_line->CopySwitchesFrom(*base::CommandLine::ForCurrentProcess(),
  531. kCommonSwitchNames,
  532. base::size(kCommonSwitchNames));
  533. }
  534. if (process_type == ::switches::kRendererProcess) {
  535. #if defined(OS_WIN)
  536. // Append --app-user-model-id.
  537. PWSTR current_app_id;
  538. if (SUCCEEDED(GetCurrentProcessExplicitAppUserModelID(&current_app_id))) {
  539. command_line->AppendSwitchNative(switches::kAppUserModelId,
  540. current_app_id);
  541. CoTaskMemFree(current_app_id);
  542. }
  543. #endif
  544. if (delegate_) {
  545. auto app_path = static_cast<api::App*>(delegate_)->GetAppPath();
  546. command_line->AppendSwitchPath(switches::kAppPath, app_path);
  547. }
  548. auto env = base::Environment::Create();
  549. if (env->HasVar("ELECTRON_PROFILE_INIT_SCRIPTS")) {
  550. command_line->AppendSwitch("profile-electron-init");
  551. }
  552. // Extension background pages don't have WebContentsPreferences, but they
  553. // support WebSQL by default.
  554. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  555. content::RenderProcessHost* process =
  556. content::RenderProcessHost::FromID(process_id);
  557. if (extensions::ProcessMap::Get(process->GetBrowserContext())
  558. ->Contains(process_id))
  559. command_line->AppendSwitch(switches::kEnableWebSQL);
  560. #endif
  561. content::WebContents* web_contents =
  562. GetWebContentsFromProcessID(process_id);
  563. if (web_contents) {
  564. auto* web_preferences = WebContentsPreferences::From(web_contents);
  565. if (web_preferences)
  566. web_preferences->AppendCommandLineSwitches(
  567. command_line, IsRendererSubFrame(process_id));
  568. }
  569. }
  570. }
  571. void ElectronBrowserClient::DidCreatePpapiPlugin(
  572. content::BrowserPpapiHost* host) {}
  573. // attempt to get api key from env
  574. std::string ElectronBrowserClient::GetGeolocationApiKey() {
  575. auto env = base::Environment::Create();
  576. std::string api_key;
  577. env->GetVar("GOOGLE_API_KEY", &api_key);
  578. return api_key;
  579. }
  580. scoped_refptr<content::QuotaPermissionContext>
  581. ElectronBrowserClient::CreateQuotaPermissionContext() {
  582. return base::MakeRefCounted<ElectronQuotaPermissionContext>();
  583. }
  584. content::GeneratedCodeCacheSettings
  585. ElectronBrowserClient::GetGeneratedCodeCacheSettings(
  586. content::BrowserContext* context) {
  587. // TODO(deepak1556): Use platform cache directory.
  588. base::FilePath cache_path = context->GetPath();
  589. // If we pass 0 for size, disk_cache will pick a default size using the
  590. // heuristics based on available disk size. These are implemented in
  591. // disk_cache::PreferredCacheSize in net/disk_cache/cache_util.cc.
  592. return content::GeneratedCodeCacheSettings(true, 0, cache_path);
  593. }
  594. void ElectronBrowserClient::AllowCertificateError(
  595. content::WebContents* web_contents,
  596. int cert_error,
  597. const net::SSLInfo& ssl_info,
  598. const GURL& request_url,
  599. bool is_main_frame_request,
  600. bool strict_enforcement,
  601. base::OnceCallback<void(content::CertificateRequestResultType)> callback) {
  602. if (delegate_) {
  603. delegate_->AllowCertificateError(web_contents, cert_error, ssl_info,
  604. request_url, is_main_frame_request,
  605. strict_enforcement, std::move(callback));
  606. }
  607. }
  608. base::OnceClosure ElectronBrowserClient::SelectClientCertificate(
  609. content::WebContents* web_contents,
  610. net::SSLCertRequestInfo* cert_request_info,
  611. net::ClientCertIdentityList client_certs,
  612. std::unique_ptr<content::ClientCertificateDelegate> delegate) {
  613. if (!client_certs.empty() && delegate_) {
  614. delegate_->SelectClientCertificate(web_contents, cert_request_info,
  615. std::move(client_certs),
  616. std::move(delegate));
  617. }
  618. return base::OnceClosure();
  619. }
  620. bool ElectronBrowserClient::CanCreateWindow(
  621. content::RenderFrameHost* opener,
  622. const GURL& opener_url,
  623. const GURL& opener_top_level_frame_url,
  624. const url::Origin& source_origin,
  625. content::mojom::WindowContainerType container_type,
  626. const GURL& target_url,
  627. const content::Referrer& referrer,
  628. const std::string& frame_name,
  629. WindowOpenDisposition disposition,
  630. const blink::mojom::WindowFeatures& features,
  631. const std::string& raw_features,
  632. const scoped_refptr<network::ResourceRequestBody>& body,
  633. bool user_gesture,
  634. bool opener_suppressed,
  635. bool* no_javascript_access) {
  636. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  637. content::WebContents* web_contents =
  638. content::WebContents::FromRenderFrameHost(opener);
  639. WebContentsPreferences* prefs = WebContentsPreferences::From(web_contents);
  640. if (prefs && prefs->ShouldUseNativeWindowOpen()) {
  641. if (prefs->ShouldDisablePopups()) {
  642. // <webview> without allowpopups attribute should return
  643. // null from window.open calls
  644. return false;
  645. } else {
  646. *no_javascript_access = false;
  647. return true;
  648. }
  649. }
  650. if (delegate_) {
  651. return delegate_->CanCreateWindow(
  652. opener, opener_url, opener_top_level_frame_url, source_origin,
  653. container_type, target_url, referrer, frame_name, disposition, features,
  654. raw_features, body, user_gesture, opener_suppressed,
  655. no_javascript_access);
  656. }
  657. return false;
  658. }
  659. #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE)
  660. std::unique_ptr<content::OverlayWindow>
  661. ElectronBrowserClient::CreateWindowForPictureInPicture(
  662. content::PictureInPictureWindowController* controller) {
  663. auto overlay_window = content::OverlayWindow::Create(controller);
  664. #if defined(OS_WIN)
  665. std::wstring app_user_model_id = Browser::Get()->GetAppUserModelID();
  666. if (!app_user_model_id.empty()) {
  667. auto* overlay_window_view =
  668. static_cast<OverlayWindowViews*>(overlay_window.get());
  669. ui::win::SetAppIdForWindow(app_user_model_id,
  670. overlay_window_view->GetNativeWindow()
  671. ->GetHost()
  672. ->GetAcceleratedWidget());
  673. }
  674. #endif
  675. return overlay_window;
  676. }
  677. #endif
  678. void ElectronBrowserClient::GetAdditionalAllowedSchemesForFileSystem(
  679. std::vector<std::string>* additional_schemes) {
  680. auto schemes_list = api::GetStandardSchemes();
  681. if (!schemes_list.empty())
  682. additional_schemes->insert(additional_schemes->end(), schemes_list.begin(),
  683. schemes_list.end());
  684. additional_schemes->push_back(content::kChromeDevToolsScheme);
  685. additional_schemes->push_back(content::kChromeUIScheme);
  686. }
  687. void ElectronBrowserClient::GetAdditionalWebUISchemes(
  688. std::vector<std::string>* additional_schemes) {
  689. additional_schemes->push_back(content::kChromeDevToolsScheme);
  690. }
  691. void ElectronBrowserClient::SiteInstanceGotProcess(
  692. content::SiteInstance* site_instance) {
  693. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  694. auto* browser_context =
  695. static_cast<ElectronBrowserContext*>(site_instance->GetBrowserContext());
  696. if (!browser_context->IsOffTheRecord()) {
  697. extensions::ExtensionRegistry* registry =
  698. extensions::ExtensionRegistry::Get(browser_context);
  699. const extensions::Extension* extension =
  700. registry->enabled_extensions().GetExtensionOrAppByURL(
  701. site_instance->GetSiteURL());
  702. if (!extension)
  703. return;
  704. extensions::ProcessMap::Get(browser_context)
  705. ->Insert(extension->id(), site_instance->GetProcess()->GetID(),
  706. site_instance->GetId());
  707. }
  708. #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  709. }
  710. bool ElectronBrowserClient::IsSuitableHost(
  711. content::RenderProcessHost* process_host,
  712. const GURL& site_url) {
  713. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  714. auto* browser_context = process_host->GetBrowserContext();
  715. extensions::ExtensionRegistry* registry =
  716. extensions::ExtensionRegistry::Get(browser_context);
  717. extensions::ProcessMap* process_map =
  718. extensions::ProcessMap::Get(browser_context);
  719. // Otherwise, just make sure the process privilege matches the privilege
  720. // required by the site.
  721. RenderProcessHostPrivilege privilege_required =
  722. GetPrivilegeRequiredByUrl(site_url, registry);
  723. return GetProcessPrivilege(process_host, process_map, registry) ==
  724. privilege_required;
  725. #else
  726. return content::ContentBrowserClient::IsSuitableHost(process_host, site_url);
  727. #endif
  728. }
  729. bool ElectronBrowserClient::ShouldUseProcessPerSite(
  730. content::BrowserContext* browser_context,
  731. const GURL& effective_url) {
  732. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  733. const extensions::Extension* extension =
  734. GetEnabledExtensionFromEffectiveURL(browser_context, effective_url);
  735. return extension != nullptr;
  736. #else
  737. return content::ContentBrowserClient::ShouldUseProcessPerSite(browser_context,
  738. effective_url);
  739. #endif
  740. }
  741. bool ElectronBrowserClient::ArePersistentMediaDeviceIDsAllowed(
  742. content::BrowserContext* browser_context,
  743. const GURL& scope,
  744. const net::SiteForCookies& site_for_cookies,
  745. const absl::optional<url::Origin>& top_frame_origin) {
  746. return true;
  747. }
  748. base::FilePath ElectronBrowserClient::GetLoggingFileName(
  749. const base::CommandLine& cmd_line) {
  750. return logging::GetLogFileName(cmd_line);
  751. }
  752. void ElectronBrowserClient::SiteInstanceDeleting(
  753. content::SiteInstance* site_instance) {
  754. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  755. // Don't do anything if we're shutting down.
  756. if (content::BrowserMainRunner::ExitedMainMessageLoop())
  757. return;
  758. auto* browser_context =
  759. static_cast<ElectronBrowserContext*>(site_instance->GetBrowserContext());
  760. if (!browser_context->IsOffTheRecord()) {
  761. // If this isn't an extension renderer there's nothing to do.
  762. extensions::ExtensionRegistry* registry =
  763. extensions::ExtensionRegistry::Get(browser_context);
  764. const extensions::Extension* extension =
  765. registry->enabled_extensions().GetExtensionOrAppByURL(
  766. site_instance->GetSiteURL());
  767. if (!extension)
  768. return;
  769. extensions::ProcessMap::Get(browser_context)
  770. ->Remove(extension->id(), site_instance->GetProcess()->GetID(),
  771. site_instance->GetId());
  772. }
  773. #endif
  774. }
  775. std::unique_ptr<net::ClientCertStore>
  776. ElectronBrowserClient::CreateClientCertStore(
  777. content::BrowserContext* browser_context) {
  778. #if defined(USE_NSS_CERTS)
  779. return std::make_unique<net::ClientCertStoreNSS>(
  780. net::ClientCertStoreNSS::PasswordDelegateFactory());
  781. #elif defined(OS_WIN)
  782. return std::make_unique<net::ClientCertStoreWin>();
  783. #elif defined(OS_MAC)
  784. return std::make_unique<net::ClientCertStoreMac>();
  785. #elif defined(USE_OPENSSL)
  786. return std::unique_ptr<net::ClientCertStore>();
  787. #endif
  788. }
  789. std::unique_ptr<device::LocationProvider>
  790. ElectronBrowserClient::OverrideSystemLocationProvider() {
  791. #if BUILDFLAG(OVERRIDE_LOCATION_PROVIDER)
  792. return std::make_unique<FakeLocationProvider>();
  793. #else
  794. return nullptr;
  795. #endif
  796. }
  797. void ElectronBrowserClient::ConfigureNetworkContextParams(
  798. content::BrowserContext* browser_context,
  799. bool in_memory,
  800. const base::FilePath& relative_partition_path,
  801. network::mojom::NetworkContextParams* network_context_params,
  802. cert_verifier::mojom::CertVerifierCreationParams*
  803. cert_verifier_creation_params) {
  804. DCHECK(browser_context);
  805. return NetworkContextServiceFactory::GetForContext(browser_context)
  806. ->ConfigureNetworkContextParams(network_context_params,
  807. cert_verifier_creation_params);
  808. }
  809. network::mojom::NetworkContext*
  810. ElectronBrowserClient::GetSystemNetworkContext() {
  811. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  812. DCHECK(g_browser_process->system_network_context_manager());
  813. return g_browser_process->system_network_context_manager()->GetContext();
  814. }
  815. std::unique_ptr<content::BrowserMainParts>
  816. ElectronBrowserClient::CreateBrowserMainParts(
  817. content::MainFunctionParams params) {
  818. auto browser_main_parts =
  819. std::make_unique<ElectronBrowserMainParts>(std::move(params));
  820. #if defined(OS_MAC)
  821. browser_main_parts_ = browser_main_parts.get();
  822. #endif
  823. return browser_main_parts;
  824. }
  825. void ElectronBrowserClient::WebNotificationAllowed(
  826. content::RenderFrameHost* rfh,
  827. base::OnceCallback<void(bool, bool)> callback) {
  828. content::WebContents* web_contents =
  829. content::WebContents::FromRenderFrameHost(rfh);
  830. if (!web_contents) {
  831. std::move(callback).Run(false, false);
  832. return;
  833. }
  834. auto* permission_helper =
  835. WebContentsPermissionHelper::FromWebContents(web_contents);
  836. if (!permission_helper) {
  837. std::move(callback).Run(false, false);
  838. return;
  839. }
  840. permission_helper->RequestWebNotificationPermission(
  841. base::BindOnce(std::move(callback), web_contents->IsAudioMuted()));
  842. }
  843. void ElectronBrowserClient::RenderProcessHostDestroyed(
  844. content::RenderProcessHost* host) {
  845. int process_id = host->GetID();
  846. pending_processes_.erase(process_id);
  847. renderer_is_subframe_.erase(process_id);
  848. host->RemoveObserver(this);
  849. }
  850. void ElectronBrowserClient::RenderProcessReady(
  851. content::RenderProcessHost* host) {
  852. if (delegate_) {
  853. static_cast<api::App*>(delegate_)->RenderProcessReady(host);
  854. }
  855. }
  856. void ElectronBrowserClient::RenderProcessExited(
  857. content::RenderProcessHost* host,
  858. const content::ChildProcessTerminationInfo& info) {
  859. if (delegate_) {
  860. static_cast<api::App*>(delegate_)->RenderProcessExited(host);
  861. }
  862. }
  863. void OnOpenExternal(const GURL& escaped_url, bool allowed) {
  864. if (allowed) {
  865. platform_util::OpenExternal(
  866. escaped_url, platform_util::OpenExternalOptions(), base::DoNothing());
  867. }
  868. }
  869. void HandleExternalProtocolInUI(
  870. const GURL& url,
  871. content::WebContents::OnceGetter web_contents_getter,
  872. bool has_user_gesture) {
  873. content::WebContents* web_contents = std::move(web_contents_getter).Run();
  874. if (!web_contents)
  875. return;
  876. auto* permission_helper =
  877. WebContentsPermissionHelper::FromWebContents(web_contents);
  878. if (!permission_helper)
  879. return;
  880. GURL escaped_url(net::EscapeExternalHandlerValue(url.spec()));
  881. auto callback = base::BindOnce(&OnOpenExternal, escaped_url);
  882. permission_helper->RequestOpenExternalPermission(std::move(callback),
  883. has_user_gesture, url);
  884. }
  885. bool ElectronBrowserClient::HandleExternalProtocol(
  886. const GURL& url,
  887. content::WebContents::Getter web_contents_getter,
  888. int child_id,
  889. int frame_tree_node_id,
  890. content::NavigationUIData* navigation_data,
  891. bool is_main_frame,
  892. network::mojom::WebSandboxFlags sandbox_flags,
  893. ui::PageTransition page_transition,
  894. bool has_user_gesture,
  895. const absl::optional<url::Origin>& initiating_origin,
  896. mojo::PendingRemote<network::mojom::URLLoaderFactory>* out_factory) {
  897. base::PostTask(
  898. FROM_HERE, {BrowserThread::UI},
  899. base::BindOnce(&HandleExternalProtocolInUI, url,
  900. std::move(web_contents_getter), has_user_gesture));
  901. return true;
  902. }
  903. std::vector<std::unique_ptr<content::NavigationThrottle>>
  904. ElectronBrowserClient::CreateThrottlesForNavigation(
  905. content::NavigationHandle* handle) {
  906. std::vector<std::unique_ptr<content::NavigationThrottle>> throttles;
  907. throttles.push_back(std::make_unique<ElectronNavigationThrottle>(handle));
  908. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  909. throttles.push_back(
  910. std::make_unique<extensions::ExtensionNavigationThrottle>(handle));
  911. #endif
  912. return throttles;
  913. }
  914. content::MediaObserver* ElectronBrowserClient::GetMediaObserver() {
  915. return MediaCaptureDevicesDispatcher::GetInstance();
  916. }
  917. std::unique_ptr<content::DevToolsManagerDelegate>
  918. ElectronBrowserClient::CreateDevToolsManagerDelegate() {
  919. return std::make_unique<DevToolsManagerDelegate>();
  920. }
  921. NotificationPresenter* ElectronBrowserClient::GetNotificationPresenter() {
  922. if (!notification_presenter_) {
  923. notification_presenter_.reset(NotificationPresenter::Create());
  924. }
  925. return notification_presenter_.get();
  926. }
  927. content::PlatformNotificationService*
  928. ElectronBrowserClient::GetPlatformNotificationService() {
  929. if (!notification_service_) {
  930. notification_service_ = std::make_unique<PlatformNotificationService>(this);
  931. }
  932. return notification_service_.get();
  933. }
  934. base::FilePath ElectronBrowserClient::GetDefaultDownloadDirectory() {
  935. base::FilePath download_path;
  936. if (base::PathService::Get(chrome::DIR_DEFAULT_DOWNLOADS, &download_path))
  937. return download_path;
  938. return base::FilePath();
  939. }
  940. scoped_refptr<network::SharedURLLoaderFactory>
  941. ElectronBrowserClient::GetSystemSharedURLLoaderFactory() {
  942. if (!g_browser_process)
  943. return nullptr;
  944. return g_browser_process->shared_url_loader_factory();
  945. }
  946. void ElectronBrowserClient::OnNetworkServiceCreated(
  947. network::mojom::NetworkService* network_service) {
  948. if (!g_browser_process)
  949. return;
  950. g_browser_process->system_network_context_manager()->OnNetworkServiceCreated(
  951. network_service);
  952. }
  953. std::vector<base::FilePath>
  954. ElectronBrowserClient::GetNetworkContextsParentDirectory() {
  955. base::FilePath user_data_dir;
  956. base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
  957. DCHECK(!user_data_dir.empty());
  958. return {user_data_dir};
  959. }
  960. std::string ElectronBrowserClient::GetProduct() {
  961. return "Chrome/" CHROME_VERSION_STRING;
  962. }
  963. std::string ElectronBrowserClient::GetUserAgent() {
  964. if (user_agent_override_.empty())
  965. return GetApplicationUserAgent();
  966. return user_agent_override_;
  967. }
  968. void ElectronBrowserClient::SetUserAgent(const std::string& user_agent) {
  969. user_agent_override_ = user_agent;
  970. }
  971. blink::UserAgentMetadata ElectronBrowserClient::GetUserAgentMetadata() {
  972. return embedder_support::GetUserAgentMetadata();
  973. }
  974. void ElectronBrowserClient::RegisterNonNetworkNavigationURLLoaderFactories(
  975. int frame_tree_node_id,
  976. ukm::SourceIdObj ukm_source_id,
  977. NonNetworkURLLoaderFactoryMap* factories) {
  978. content::WebContents* web_contents =
  979. content::WebContents::FromFrameTreeNodeId(frame_tree_node_id);
  980. content::BrowserContext* context = web_contents->GetBrowserContext();
  981. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  982. factories->emplace(
  983. extensions::kExtensionScheme,
  984. extensions::CreateExtensionNavigationURLLoaderFactory(
  985. context, ukm_source_id,
  986. false /* we don't support extensions::WebViewGuest */));
  987. #endif
  988. // Always allow navigating to file:// URLs.
  989. auto* protocol_registry = ProtocolRegistry::FromBrowserContext(context);
  990. protocol_registry->RegisterURLLoaderFactories(factories,
  991. true /* allow_file_access */);
  992. }
  993. void ElectronBrowserClient::
  994. RegisterNonNetworkWorkerMainResourceURLLoaderFactories(
  995. content::BrowserContext* browser_context,
  996. NonNetworkURLLoaderFactoryMap* factories) {
  997. auto* protocol_registry =
  998. ProtocolRegistry::FromBrowserContext(browser_context);
  999. // Workers are not allowed to request file:// URLs, there is no particular
  1000. // reason for it, and we could consider supporting it in future.
  1001. protocol_registry->RegisterURLLoaderFactories(factories,
  1002. false /* allow_file_access */);
  1003. }
  1004. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  1005. namespace {
  1006. // The FileURLLoaderFactory provided to the extension background pages.
  1007. // Checks with the ChildProcessSecurityPolicy to validate the file access.
  1008. class FileURLLoaderFactory : public network::SelfDeletingURLLoaderFactory {
  1009. public:
  1010. static mojo::PendingRemote<network::mojom::URLLoaderFactory> Create(
  1011. int child_id) {
  1012. mojo::PendingRemote<network::mojom::URLLoaderFactory> pending_remote;
  1013. // The FileURLLoaderFactory will delete itself when there are no more
  1014. // receivers - see the SelfDeletingURLLoaderFactory::OnDisconnect method.
  1015. new FileURLLoaderFactory(child_id,
  1016. pending_remote.InitWithNewPipeAndPassReceiver());
  1017. return pending_remote;
  1018. }
  1019. // disable copy
  1020. FileURLLoaderFactory(const FileURLLoaderFactory&) = delete;
  1021. FileURLLoaderFactory& operator=(const FileURLLoaderFactory&) = delete;
  1022. private:
  1023. explicit FileURLLoaderFactory(
  1024. int child_id,
  1025. mojo::PendingReceiver<network::mojom::URLLoaderFactory> factory_receiver)
  1026. : network::SelfDeletingURLLoaderFactory(std::move(factory_receiver)),
  1027. child_id_(child_id) {}
  1028. ~FileURLLoaderFactory() override = default;
  1029. // network::mojom::URLLoaderFactory:
  1030. void CreateLoaderAndStart(
  1031. mojo::PendingReceiver<network::mojom::URLLoader> loader,
  1032. int32_t request_id,
  1033. uint32_t options,
  1034. const network::ResourceRequest& request,
  1035. mojo::PendingRemote<network::mojom::URLLoaderClient> client,
  1036. const net::MutableNetworkTrafficAnnotationTag& traffic_annotation)
  1037. override {
  1038. if (!content::ChildProcessSecurityPolicy::GetInstance()->CanRequestURL(
  1039. child_id_, request.url)) {
  1040. mojo::Remote<network::mojom::URLLoaderClient>(std::move(client))
  1041. ->OnComplete(
  1042. network::URLLoaderCompletionStatus(net::ERR_ACCESS_DENIED));
  1043. return;
  1044. }
  1045. content::CreateFileURLLoaderBypassingSecurityChecks(
  1046. request, std::move(loader), std::move(client),
  1047. /*observer=*/nullptr,
  1048. /* allow_directory_listing */ true);
  1049. }
  1050. int child_id_;
  1051. };
  1052. } // namespace
  1053. #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  1054. void ElectronBrowserClient::RegisterNonNetworkSubresourceURLLoaderFactories(
  1055. int render_process_id,
  1056. int render_frame_id,
  1057. NonNetworkURLLoaderFactoryMap* factories) {
  1058. auto* render_process_host =
  1059. content::RenderProcessHost::FromID(render_process_id);
  1060. DCHECK(render_process_host);
  1061. if (!render_process_host || !render_process_host->GetBrowserContext())
  1062. return;
  1063. content::RenderFrameHost* frame_host =
  1064. content::RenderFrameHost::FromID(render_process_id, render_frame_id);
  1065. content::WebContents* web_contents =
  1066. content::WebContents::FromRenderFrameHost(frame_host);
  1067. // Allow accessing file:// subresources from non-file protocols if web
  1068. // security is disabled.
  1069. bool allow_file_access = false;
  1070. if (web_contents) {
  1071. const auto& web_preferences = web_contents->GetOrCreateWebPreferences();
  1072. if (!web_preferences.web_security_enabled)
  1073. allow_file_access = true;
  1074. }
  1075. ProtocolRegistry::FromBrowserContext(render_process_host->GetBrowserContext())
  1076. ->RegisterURLLoaderFactories(factories, allow_file_access);
  1077. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  1078. auto factory = extensions::CreateExtensionURLLoaderFactory(render_process_id,
  1079. render_frame_id);
  1080. if (factory)
  1081. factories->emplace(extensions::kExtensionScheme, std::move(factory));
  1082. if (!web_contents)
  1083. return;
  1084. extensions::ElectronExtensionWebContentsObserver* web_observer =
  1085. extensions::ElectronExtensionWebContentsObserver::FromWebContents(
  1086. web_contents);
  1087. // There is nothing to do if no ElectronExtensionWebContentsObserver is
  1088. // attached to the |web_contents|.
  1089. if (!web_observer)
  1090. return;
  1091. const extensions::Extension* extension =
  1092. web_observer->GetExtensionFromFrame(frame_host, false);
  1093. if (!extension)
  1094. return;
  1095. // Support for chrome:// scheme if appropriate.
  1096. if (extension->is_extension() &&
  1097. extensions::Manifest::IsComponentLocation(extension->location())) {
  1098. // Components of chrome that are implemented as extensions or platform apps
  1099. // are allowed to use chrome://resources/ and chrome://theme/ URLs.
  1100. factories->emplace(content::kChromeUIScheme,
  1101. content::CreateWebUIURLLoaderFactory(
  1102. frame_host, content::kChromeUIScheme,
  1103. {content::kChromeUIResourcesHost}));
  1104. }
  1105. // Extensions with the necessary permissions get access to file:// URLs that
  1106. // gets approval from ChildProcessSecurityPolicy. Keep this logic in sync with
  1107. // ExtensionWebContentsObserver::RenderFrameCreated.
  1108. extensions::Manifest::Type type = extension->GetType();
  1109. if (type == extensions::Manifest::TYPE_EXTENSION &&
  1110. AllowFileAccess(extension->id(), web_contents->GetBrowserContext())) {
  1111. factories->emplace(url::kFileScheme,
  1112. FileURLLoaderFactory::Create(render_process_id));
  1113. }
  1114. #endif
  1115. }
  1116. bool ElectronBrowserClient::ShouldTreatURLSchemeAsFirstPartyWhenTopLevel(
  1117. base::StringPiece scheme,
  1118. bool is_embedded_origin_secure) {
  1119. if (is_embedded_origin_secure && scheme == content::kChromeUIScheme)
  1120. return true;
  1121. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  1122. return scheme == extensions::kExtensionScheme;
  1123. #else
  1124. return false;
  1125. #endif
  1126. }
  1127. bool ElectronBrowserClient::WillInterceptWebSocket(
  1128. content::RenderFrameHost* frame) {
  1129. if (!frame)
  1130. return false;
  1131. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1132. v8::HandleScope scope(isolate);
  1133. auto* browser_context = frame->GetProcess()->GetBrowserContext();
  1134. auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context);
  1135. // NOTE: Some unit test environments do not initialize
  1136. // BrowserContextKeyedAPI factories for e.g. WebRequest.
  1137. if (!web_request.get())
  1138. return false;
  1139. bool has_listener = web_request->HasListener();
  1140. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  1141. const auto* web_request_api =
  1142. extensions::BrowserContextKeyedAPIFactory<extensions::WebRequestAPI>::Get(
  1143. browser_context);
  1144. if (web_request_api)
  1145. has_listener |= web_request_api->MayHaveProxies();
  1146. #endif
  1147. return has_listener;
  1148. }
  1149. void ElectronBrowserClient::CreateWebSocket(
  1150. content::RenderFrameHost* frame,
  1151. WebSocketFactory factory,
  1152. const GURL& url,
  1153. const net::SiteForCookies& site_for_cookies,
  1154. const absl::optional<std::string>& user_agent,
  1155. mojo::PendingRemote<network::mojom::WebSocketHandshakeClient>
  1156. handshake_client) {
  1157. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1158. v8::HandleScope scope(isolate);
  1159. auto* browser_context = frame->GetProcess()->GetBrowserContext();
  1160. auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context);
  1161. DCHECK(web_request.get());
  1162. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  1163. if (!web_request->HasListener()) {
  1164. auto* web_request_api = extensions::BrowserContextKeyedAPIFactory<
  1165. extensions::WebRequestAPI>::Get(browser_context);
  1166. if (web_request_api && web_request_api->MayHaveProxies()) {
  1167. web_request_api->ProxyWebSocket(frame, std::move(factory), url,
  1168. site_for_cookies, user_agent,
  1169. std::move(handshake_client));
  1170. return;
  1171. }
  1172. }
  1173. #endif
  1174. ProxyingWebSocket::StartProxying(
  1175. web_request.get(), std::move(factory), url, site_for_cookies, user_agent,
  1176. std::move(handshake_client), true, frame->GetProcess()->GetID(),
  1177. frame->GetRoutingID(), frame->GetLastCommittedOrigin(), browser_context,
  1178. &next_id_);
  1179. }
  1180. bool ElectronBrowserClient::WillCreateURLLoaderFactory(
  1181. content::BrowserContext* browser_context,
  1182. content::RenderFrameHost* frame_host,
  1183. int render_process_id,
  1184. URLLoaderFactoryType type,
  1185. const url::Origin& request_initiator,
  1186. absl::optional<int64_t> navigation_id,
  1187. ukm::SourceIdObj ukm_source_id,
  1188. mojo::PendingReceiver<network::mojom::URLLoaderFactory>* factory_receiver,
  1189. mojo::PendingRemote<network::mojom::TrustedURLLoaderHeaderClient>*
  1190. header_client,
  1191. bool* bypass_redirect_checks,
  1192. bool* disable_secure_dns,
  1193. network::mojom::URLLoaderFactoryOverridePtr* factory_override) {
  1194. v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
  1195. v8::HandleScope scope(isolate);
  1196. auto web_request = api::WebRequest::FromOrCreate(isolate, browser_context);
  1197. DCHECK(web_request.get());
  1198. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  1199. if (!web_request->HasListener()) {
  1200. auto* web_request_api = extensions::BrowserContextKeyedAPIFactory<
  1201. extensions::WebRequestAPI>::Get(browser_context);
  1202. DCHECK(web_request_api);
  1203. bool use_proxy_for_web_request =
  1204. web_request_api->MaybeProxyURLLoaderFactory(
  1205. browser_context, frame_host, render_process_id, type, navigation_id,
  1206. ukm_source_id, factory_receiver, header_client);
  1207. if (bypass_redirect_checks)
  1208. *bypass_redirect_checks = use_proxy_for_web_request;
  1209. if (use_proxy_for_web_request)
  1210. return true;
  1211. }
  1212. #endif
  1213. auto proxied_receiver = std::move(*factory_receiver);
  1214. mojo::PendingRemote<network::mojom::URLLoaderFactory> target_factory_remote;
  1215. *factory_receiver = target_factory_remote.InitWithNewPipeAndPassReceiver();
  1216. // Required by WebRequestInfoInitParams.
  1217. //
  1218. // Note that in Electron we allow webRequest to capture requests sent from
  1219. // browser process, so creation of |navigation_ui_data| is different from
  1220. // Chromium which only does for renderer-initialized navigations.
  1221. std::unique_ptr<extensions::ExtensionNavigationUIData> navigation_ui_data;
  1222. if (navigation_id.has_value()) {
  1223. navigation_ui_data =
  1224. std::make_unique<extensions::ExtensionNavigationUIData>();
  1225. }
  1226. mojo::PendingReceiver<network::mojom::TrustedURLLoaderHeaderClient>
  1227. header_client_receiver;
  1228. if (header_client)
  1229. header_client_receiver = header_client->InitWithNewPipeAndPassReceiver();
  1230. auto* protocol_registry =
  1231. ProtocolRegistry::FromBrowserContext(browser_context);
  1232. new ProxyingURLLoaderFactory(
  1233. web_request.get(), protocol_registry->intercept_handlers(),
  1234. render_process_id,
  1235. frame_host ? frame_host->GetRoutingID() : MSG_ROUTING_NONE,
  1236. frame_host ? frame_host->GetRenderViewHost()->GetRoutingID()
  1237. : MSG_ROUTING_NONE,
  1238. &next_id_, std::move(navigation_ui_data), std::move(navigation_id),
  1239. std::move(proxied_receiver), std::move(target_factory_remote),
  1240. std::move(header_client_receiver), type);
  1241. if (bypass_redirect_checks)
  1242. *bypass_redirect_checks = true;
  1243. return true;
  1244. }
  1245. void ElectronBrowserClient::OverrideURLLoaderFactoryParams(
  1246. content::BrowserContext* browser_context,
  1247. const url::Origin& origin,
  1248. bool is_for_isolated_world,
  1249. network::mojom::URLLoaderFactoryParams* factory_params) {
  1250. if (factory_params->top_frame_id) {
  1251. // Bypass CORB and CORS when web security is disabled.
  1252. auto* rfh = content::RenderFrameHost::FromFrameToken(
  1253. factory_params->process_id,
  1254. blink::LocalFrameToken(factory_params->top_frame_id.value()));
  1255. auto* web_contents = content::WebContents::FromRenderFrameHost(rfh);
  1256. auto* prefs = WebContentsPreferences::From(web_contents);
  1257. if (prefs && !prefs->IsWebSecurityEnabled()) {
  1258. factory_params->is_corb_enabled = false;
  1259. factory_params->disable_web_security = true;
  1260. }
  1261. }
  1262. extensions::URLLoaderFactoryManager::OverrideURLLoaderFactoryParams(
  1263. browser_context, origin, is_for_isolated_world, factory_params);
  1264. }
  1265. #if defined(OS_WIN)
  1266. bool ElectronBrowserClient::PreSpawnChild(sandbox::TargetPolicy* policy,
  1267. sandbox::mojom::Sandbox sandbox_type,
  1268. ChildSpawnFlags flags) {
  1269. // Allow crashpad to communicate via named pipe.
  1270. sandbox::ResultCode result = policy->AddRule(
  1271. sandbox::TargetPolicy::SUBSYS_FILES,
  1272. sandbox::TargetPolicy::FILES_ALLOW_ANY, L"\\??\\pipe\\crashpad_*");
  1273. if (result != sandbox::SBOX_ALL_OK)
  1274. return false;
  1275. return true;
  1276. }
  1277. #endif // defined(OS_WIN)
  1278. bool BindElectronApiIPC(
  1279. mojo::PendingAssociatedReceiver<electron::mojom::ElectronApiIPC> receiver,
  1280. content::RenderFrameHost* frame_host) {
  1281. auto* contents = content::WebContents::FromRenderFrameHost(frame_host);
  1282. if (contents) {
  1283. auto* prefs = WebContentsPreferences::From(contents);
  1284. if (frame_host->GetFrameTreeNodeId() ==
  1285. contents->GetMainFrame()->GetFrameTreeNodeId() ||
  1286. (prefs && prefs->AllowsNodeIntegrationInSubFrames())) {
  1287. ElectronApiIPCHandlerImpl::Create(frame_host, std::move(receiver));
  1288. return true;
  1289. }
  1290. }
  1291. return false;
  1292. }
  1293. void BindElectronWebContentsUtility(
  1294. mojo::PendingAssociatedReceiver<electron::mojom::ElectronWebContentsUtility>
  1295. receiver,
  1296. content::RenderFrameHost* frame_host) {
  1297. ElectronWebContentsUtilityHandlerImpl::Create(frame_host,
  1298. std::move(receiver));
  1299. }
  1300. bool ElectronBrowserClient::BindAssociatedReceiverFromFrame(
  1301. content::RenderFrameHost* render_frame_host,
  1302. const std::string& interface_name,
  1303. mojo::ScopedInterfaceEndpointHandle* handle) {
  1304. if (interface_name == mojom::ElectronAutofillDriver::Name_) {
  1305. AutofillDriverFactory::BindAutofillDriver(
  1306. mojo::PendingAssociatedReceiver<mojom::ElectronAutofillDriver>(
  1307. std::move(*handle)),
  1308. render_frame_host);
  1309. return true;
  1310. }
  1311. if (interface_name == electron::mojom::ElectronApiIPC::Name_) {
  1312. return BindElectronApiIPC(
  1313. mojo::PendingAssociatedReceiver<electron::mojom::ElectronApiIPC>(
  1314. std::move(*handle)),
  1315. render_frame_host);
  1316. }
  1317. if (interface_name == electron::mojom::ElectronWebContentsUtility::Name_) {
  1318. BindElectronWebContentsUtility(
  1319. mojo::PendingAssociatedReceiver<
  1320. electron::mojom::ElectronWebContentsUtility>(std::move(*handle)),
  1321. render_frame_host);
  1322. return true;
  1323. }
  1324. #if BUILDFLAG(ENABLE_PRINTING)
  1325. if (interface_name == printing::mojom::PrintManagerHost::Name_) {
  1326. mojo::PendingAssociatedReceiver<printing::mojom::PrintManagerHost> receiver(
  1327. std::move(*handle));
  1328. PrintViewManagerElectron::BindPrintManagerHost(std::move(receiver),
  1329. render_frame_host);
  1330. return true;
  1331. }
  1332. #endif
  1333. #if BUILDFLAG(ENABLE_EXTENSIONS)
  1334. if (interface_name == extensions::mojom::LocalFrameHost::Name_) {
  1335. extensions::ExtensionWebContentsObserver::BindLocalFrameHost(
  1336. mojo::PendingAssociatedReceiver<extensions::mojom::LocalFrameHost>(
  1337. std::move(*handle)),
  1338. render_frame_host);
  1339. return true;
  1340. }
  1341. #endif
  1342. #if BUILDFLAG(ENABLE_PDF_VIEWER)
  1343. if (interface_name == pdf::mojom::PdfService::Name_) {
  1344. pdf::PDFWebContentsHelper::BindPdfService(
  1345. mojo::PendingAssociatedReceiver<pdf::mojom::PdfService>(
  1346. std::move(*handle)),
  1347. render_frame_host);
  1348. return true;
  1349. }
  1350. #endif
  1351. return false;
  1352. }
  1353. std::string ElectronBrowserClient::GetApplicationLocale() {
  1354. if (BrowserThread::CurrentlyOn(BrowserThread::IO))
  1355. return g_io_thread_application_locale.Get();
  1356. return *g_application_locale;
  1357. }
  1358. base::FilePath ElectronBrowserClient::GetFontLookupTableCacheDir() {
  1359. base::FilePath user_data_dir;
  1360. base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
  1361. DCHECK(!user_data_dir.empty());
  1362. return user_data_dir.Append(FILE_PATH_LITERAL("FontLookupTableCache"));
  1363. }
  1364. bool ElectronBrowserClient::ShouldEnableStrictSiteIsolation() {
  1365. // Enable site isolation. It is off by default in Chromium <= 69.
  1366. return true;
  1367. }
  1368. void ElectronBrowserClient::BindHostReceiverForRenderer(
  1369. content::RenderProcessHost* render_process_host,
  1370. mojo::GenericPendingReceiver receiver) {
  1371. #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER)
  1372. if (auto host_receiver = receiver.As<spellcheck::mojom::SpellCheckHost>()) {
  1373. SpellCheckHostChromeImpl::Create(render_process_host->GetID(),
  1374. std::move(host_receiver));
  1375. return;
  1376. }
  1377. #endif
  1378. }
  1379. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  1380. void BindMimeHandlerService(
  1381. content::RenderFrameHost* frame_host,
  1382. mojo::PendingReceiver<extensions::mime_handler::MimeHandlerService>
  1383. receiver) {
  1384. content::WebContents* contents =
  1385. content::WebContents::FromRenderFrameHost(frame_host);
  1386. auto* guest_view =
  1387. extensions::MimeHandlerViewGuest::FromWebContents(contents);
  1388. if (!guest_view)
  1389. return;
  1390. extensions::MimeHandlerServiceImpl::Create(guest_view->GetStreamWeakPtr(),
  1391. std::move(receiver));
  1392. }
  1393. void BindBeforeUnloadControl(
  1394. content::RenderFrameHost* frame_host,
  1395. mojo::PendingReceiver<extensions::mime_handler::BeforeUnloadControl>
  1396. receiver) {
  1397. auto* web_contents = content::WebContents::FromRenderFrameHost(frame_host);
  1398. if (!web_contents)
  1399. return;
  1400. auto* guest_view =
  1401. extensions::MimeHandlerViewGuest::FromWebContents(web_contents);
  1402. if (!guest_view)
  1403. return;
  1404. guest_view->FuseBeforeUnloadControl(std::move(receiver));
  1405. }
  1406. #endif
  1407. void ElectronBrowserClient::ExposeInterfacesToRenderer(
  1408. service_manager::BinderRegistry* registry,
  1409. blink::AssociatedInterfaceRegistry* associated_registry,
  1410. content::RenderProcessHost* render_process_host) {
  1411. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  1412. associated_registry->AddInterface(base::BindRepeating(
  1413. &extensions::EventRouter::BindForRenderer, render_process_host->GetID()));
  1414. #endif
  1415. }
  1416. void ElectronBrowserClient::RegisterBrowserInterfaceBindersForFrame(
  1417. content::RenderFrameHost* render_frame_host,
  1418. mojo::BinderMapWithContext<content::RenderFrameHost*>* map) {
  1419. map->Add<network_hints::mojom::NetworkHintsHandler>(
  1420. base::BindRepeating(&BindNetworkHintsHandler));
  1421. map->Add<blink::mojom::BadgeService>(
  1422. base::BindRepeating(&badging::BadgeManager::BindFrameReceiver));
  1423. map->Add<blink::mojom::KeyboardLockService>(base::BindRepeating(
  1424. &content::KeyboardLockServiceImpl::CreateMojoService));
  1425. #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  1426. map->Add<extensions::mime_handler::MimeHandlerService>(
  1427. base::BindRepeating(&BindMimeHandlerService));
  1428. map->Add<extensions::mime_handler::BeforeUnloadControl>(
  1429. base::BindRepeating(&BindBeforeUnloadControl));
  1430. content::WebContents* web_contents =
  1431. content::WebContents::FromRenderFrameHost(render_frame_host);
  1432. if (!web_contents)
  1433. return;
  1434. const GURL& site = render_frame_host->GetSiteInstance()->GetSiteURL();
  1435. if (!site.SchemeIs(extensions::kExtensionScheme))
  1436. return;
  1437. content::BrowserContext* browser_context =
  1438. render_frame_host->GetProcess()->GetBrowserContext();
  1439. auto* extension = extensions::ExtensionRegistry::Get(browser_context)
  1440. ->enabled_extensions()
  1441. .GetByID(site.host());
  1442. if (!extension)
  1443. return;
  1444. extensions::ExtensionsBrowserClient::Get()
  1445. ->RegisterBrowserInterfaceBindersForFrame(map, render_frame_host,
  1446. extension);
  1447. #endif
  1448. }
  1449. #if defined(OS_LINUX)
  1450. void ElectronBrowserClient::GetAdditionalMappedFilesForChildProcess(
  1451. const base::CommandLine& command_line,
  1452. int child_process_id,
  1453. content::PosixFileDescriptorInfo* mappings) {
  1454. int crash_signal_fd = GetCrashSignalFD(command_line);
  1455. if (crash_signal_fd >= 0) {
  1456. mappings->Share(kCrashDumpSignal, crash_signal_fd);
  1457. }
  1458. }
  1459. #endif
  1460. std::unique_ptr<content::LoginDelegate>
  1461. ElectronBrowserClient::CreateLoginDelegate(
  1462. const net::AuthChallengeInfo& auth_info,
  1463. content::WebContents* web_contents,
  1464. const content::GlobalRequestID& request_id,
  1465. bool is_main_frame,
  1466. const GURL& url,
  1467. scoped_refptr<net::HttpResponseHeaders> response_headers,
  1468. bool first_auth_attempt,
  1469. LoginAuthRequiredCallback auth_required_callback) {
  1470. return std::make_unique<LoginHandler>(
  1471. auth_info, web_contents, is_main_frame, url, response_headers,
  1472. first_auth_attempt, std::move(auth_required_callback));
  1473. }
  1474. std::vector<std::unique_ptr<blink::URLLoaderThrottle>>
  1475. ElectronBrowserClient::CreateURLLoaderThrottles(
  1476. const network::ResourceRequest& request,
  1477. content::BrowserContext* browser_context,
  1478. const base::RepeatingCallback<content::WebContents*()>& wc_getter,
  1479. content::NavigationUIData* navigation_ui_data,
  1480. int frame_tree_node_id) {
  1481. DCHECK_CURRENTLY_ON(BrowserThread::UI);
  1482. std::vector<std::unique_ptr<blink::URLLoaderThrottle>> result;
  1483. #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  1484. result.push_back(std::make_unique<PluginResponseInterceptorURLLoaderThrottle>(
  1485. request.destination, frame_tree_node_id));
  1486. #endif
  1487. return result;
  1488. }
  1489. base::flat_set<std::string>
  1490. ElectronBrowserClient::GetPluginMimeTypesWithExternalHandlers(
  1491. content::BrowserContext* browser_context) {
  1492. base::flat_set<std::string> mime_types;
  1493. #if BUILDFLAG(ENABLE_PLUGINS) && BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS)
  1494. auto map = PluginUtils::GetMimeTypeToExtensionIdMap(browser_context);
  1495. for (const auto& pair : map)
  1496. mime_types.insert(pair.first);
  1497. #endif
  1498. return mime_types;
  1499. }
  1500. content::SerialDelegate* ElectronBrowserClient::GetSerialDelegate() {
  1501. if (!serial_delegate_)
  1502. serial_delegate_ = std::make_unique<ElectronSerialDelegate>();
  1503. return serial_delegate_.get();
  1504. }
  1505. content::BluetoothDelegate* ElectronBrowserClient::GetBluetoothDelegate() {
  1506. if (!bluetooth_delegate_)
  1507. bluetooth_delegate_ = std::make_unique<ElectronBluetoothDelegate>();
  1508. return bluetooth_delegate_.get();
  1509. }
  1510. content::FontAccessDelegate* ElectronBrowserClient::GetFontAccessDelegate() {
  1511. if (!font_access_delegate_)
  1512. font_access_delegate_ = std::make_unique<ElectronFontAccessDelegate>();
  1513. return font_access_delegate_.get();
  1514. }
  1515. void BindBadgeServiceForServiceWorker(
  1516. const content::ServiceWorkerVersionBaseInfo& info,
  1517. mojo::PendingReceiver<blink::mojom::BadgeService> receiver) {
  1518. DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
  1519. content::RenderProcessHost* render_process_host =
  1520. content::RenderProcessHost::FromID(info.process_id);
  1521. if (!render_process_host)
  1522. return;
  1523. badging::BadgeManager::BindServiceWorkerReceiver(
  1524. render_process_host, info.scope, std::move(receiver));
  1525. }
  1526. void ElectronBrowserClient::RegisterBrowserInterfaceBindersForServiceWorker(
  1527. mojo::BinderMapWithContext<const content::ServiceWorkerVersionBaseInfo&>*
  1528. map) {
  1529. map->Add<blink::mojom::BadgeService>(
  1530. base::BindRepeating(&BindBadgeServiceForServiceWorker));
  1531. }
  1532. device::GeolocationManager* ElectronBrowserClient::GetGeolocationManager() {
  1533. #if defined(OS_MAC)
  1534. return browser_main_parts_->GetGeolocationManager();
  1535. #else
  1536. return nullptr;
  1537. #endif
  1538. }
  1539. content::HidDelegate* ElectronBrowserClient::GetHidDelegate() {
  1540. if (!hid_delegate_)
  1541. hid_delegate_ = std::make_unique<ElectronHidDelegate>();
  1542. return hid_delegate_.get();
  1543. }
  1544. } // namespace electron