Application.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. /*
  2. * Copyright (c) 2024, Andrew Kaster <akaster@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <LibCore/ArgsParser.h>
  8. #include <LibCore/Environment.h>
  9. #include <LibCore/StandardPaths.h>
  10. #include <LibCore/System.h>
  11. #include <LibCore/TimeZoneWatcher.h>
  12. #include <LibFileSystem/FileSystem.h>
  13. #include <LibImageDecoderClient/Client.h>
  14. #include <LibWebView/Application.h>
  15. #include <LibWebView/CookieJar.h>
  16. #include <LibWebView/Database.h>
  17. #include <LibWebView/HelperProcess.h>
  18. #include <LibWebView/URL.h>
  19. #include <LibWebView/UserAgent.h>
  20. #include <LibWebView/Utilities.h>
  21. #include <LibWebView/WebContentClient.h>
  22. namespace WebView {
  23. Application* Application::s_the = nullptr;
  24. Application::Application()
  25. {
  26. VERIFY(!s_the);
  27. s_the = this;
  28. // No need to monitor the system time zone if the TZ environment variable is set, as it overrides system preferences.
  29. if (!Core::Environment::has("TZ"sv)) {
  30. if (auto time_zone_watcher = Core::TimeZoneWatcher::create(); time_zone_watcher.is_error()) {
  31. warnln("Unable to monitor system time zone: {}", time_zone_watcher.error());
  32. } else {
  33. m_time_zone_watcher = time_zone_watcher.release_value();
  34. m_time_zone_watcher->on_time_zone_changed = []() {
  35. WebContentClient::for_each_client([&](WebView::WebContentClient& client) {
  36. client.async_system_time_zone_changed();
  37. return IterationDecision::Continue;
  38. });
  39. };
  40. }
  41. }
  42. m_process_manager.on_process_exited = [this](Process&& process) {
  43. process_did_exit(move(process));
  44. };
  45. }
  46. Application::~Application()
  47. {
  48. s_the = nullptr;
  49. }
  50. void Application::initialize(Main::Arguments const& arguments, URL::URL new_tab_page_url)
  51. {
  52. // Increase the open file limit, as the default limits on Linux cause us to run out of file descriptors with around 15 tabs open.
  53. if (auto result = Core::System::set_resource_limits(RLIMIT_NOFILE, 8192); result.is_error())
  54. warnln("Unable to increase open file limit: {}", result.error());
  55. Vector<ByteString> raw_urls;
  56. Vector<ByteString> certificates;
  57. bool new_window = false;
  58. bool force_new_process = false;
  59. bool allow_popups = false;
  60. bool disable_scripting = false;
  61. bool disable_sql_database = false;
  62. Optional<StringView> debug_process;
  63. Optional<StringView> profile_process;
  64. Optional<StringView> webdriver_content_ipc_path;
  65. Optional<StringView> user_agent_preset;
  66. bool log_all_js_exceptions = false;
  67. bool enable_idl_tracing = false;
  68. bool enable_http_cache = false;
  69. bool enable_autoplay = false;
  70. bool expose_internals_object = false;
  71. bool force_cpu_painting = false;
  72. bool force_fontconfig = false;
  73. bool collect_garbage_on_every_allocation = false;
  74. Core::ArgsParser args_parser;
  75. args_parser.set_general_help("The Ladybird web browser :^)");
  76. args_parser.add_positional_argument(raw_urls, "URLs to open", "url", Core::ArgsParser::Required::No);
  77. args_parser.add_option(certificates, "Path to a certificate file", "certificate", 'C', "certificate");
  78. args_parser.add_option(new_window, "Force opening in a new window", "new-window", 'n');
  79. args_parser.add_option(force_new_process, "Force creation of new browser/chrome process", "force-new-process");
  80. args_parser.add_option(allow_popups, "Disable popup blocking by default", "allow-popups");
  81. args_parser.add_option(disable_scripting, "Disable scripting by default", "disable-scripting");
  82. args_parser.add_option(disable_sql_database, "Disable SQL database", "disable-sql-database");
  83. args_parser.add_option(debug_process, "Wait for a debugger to attach to the given process name (WebContent, RequestServer, etc.)", "debug-process", 0, "process-name");
  84. args_parser.add_option(profile_process, "Enable callgrind profiling of the given process name (WebContent, RequestServer, etc.)", "profile-process", 0, "process-name");
  85. args_parser.add_option(webdriver_content_ipc_path, "Path to WebDriver IPC for WebContent", "webdriver-content-path", 0, "path", Core::ArgsParser::OptionHideMode::CommandLineAndMarkdown);
  86. args_parser.add_option(log_all_js_exceptions, "Log all JavaScript exceptions", "log-all-js-exceptions");
  87. args_parser.add_option(enable_idl_tracing, "Enable IDL tracing", "enable-idl-tracing");
  88. args_parser.add_option(enable_http_cache, "Enable HTTP cache", "enable-http-cache");
  89. args_parser.add_option(enable_autoplay, "Enable multimedia autoplay", "enable-autoplay");
  90. args_parser.add_option(expose_internals_object, "Expose internals object", "expose-internals-object");
  91. args_parser.add_option(force_cpu_painting, "Force CPU painting", "force-cpu-painting");
  92. args_parser.add_option(force_fontconfig, "Force using fontconfig for font loading", "force-fontconfig");
  93. args_parser.add_option(collect_garbage_on_every_allocation, "Collect garbage after every JS heap allocation", "collect-garbage-on-every-allocation", 'g');
  94. args_parser.add_option(Core::ArgsParser::Option {
  95. .argument_mode = Core::ArgsParser::OptionArgumentMode::Required,
  96. .help_string = "Name of the User-Agent preset to use in place of the default User-Agent",
  97. .long_name = "user-agent-preset",
  98. .value_name = "name",
  99. .accept_value = [&](StringView value) {
  100. user_agent_preset = normalize_user_agent_name(value);
  101. return user_agent_preset.has_value();
  102. },
  103. });
  104. create_platform_arguments(args_parser);
  105. args_parser.parse(arguments);
  106. // Our persisted SQL storage assumes it runs in a singleton process. If we have multiple UI processes accessing
  107. // the same underlying database, one of them is likely to fail.
  108. if (force_new_process)
  109. disable_sql_database = true;
  110. Optional<ProcessType> debug_process_type;
  111. Optional<ProcessType> profile_process_type;
  112. if (debug_process.has_value())
  113. debug_process_type = process_type_from_name(*debug_process);
  114. if (profile_process.has_value())
  115. profile_process_type = process_type_from_name(*profile_process);
  116. m_chrome_options = {
  117. .urls = sanitize_urls(raw_urls, new_tab_page_url),
  118. .raw_urls = move(raw_urls),
  119. .new_tab_page_url = move(new_tab_page_url),
  120. .certificates = move(certificates),
  121. .new_window = new_window ? NewWindow::Yes : NewWindow::No,
  122. .force_new_process = force_new_process ? ForceNewProcess::Yes : ForceNewProcess::No,
  123. .allow_popups = allow_popups ? AllowPopups::Yes : AllowPopups::No,
  124. .disable_scripting = disable_scripting ? DisableScripting::Yes : DisableScripting::No,
  125. .disable_sql_database = disable_sql_database ? DisableSQLDatabase::Yes : DisableSQLDatabase::No,
  126. .debug_helper_process = move(debug_process_type),
  127. .profile_helper_process = move(profile_process_type),
  128. };
  129. if (webdriver_content_ipc_path.has_value())
  130. m_chrome_options.webdriver_content_ipc_path = *webdriver_content_ipc_path;
  131. m_web_content_options = {
  132. .command_line = MUST(String::join(' ', arguments.strings)),
  133. .executable_path = MUST(String::from_byte_string(MUST(Core::System::current_executable_path()))),
  134. .user_agent_preset = move(user_agent_preset),
  135. .log_all_js_exceptions = log_all_js_exceptions ? LogAllJSExceptions::Yes : LogAllJSExceptions::No,
  136. .enable_idl_tracing = enable_idl_tracing ? EnableIDLTracing::Yes : EnableIDLTracing::No,
  137. .enable_http_cache = enable_http_cache ? EnableHTTPCache::Yes : EnableHTTPCache::No,
  138. .expose_internals_object = expose_internals_object ? ExposeInternalsObject::Yes : ExposeInternalsObject::No,
  139. .force_cpu_painting = force_cpu_painting ? ForceCPUPainting::Yes : ForceCPUPainting::No,
  140. .force_fontconfig = force_fontconfig ? ForceFontconfig::Yes : ForceFontconfig::No,
  141. .enable_autoplay = enable_autoplay ? EnableAutoplay::Yes : EnableAutoplay::No,
  142. .collect_garbage_on_every_allocation = collect_garbage_on_every_allocation ? CollectGarbageOnEveryAllocation::Yes : CollectGarbageOnEveryAllocation::No,
  143. };
  144. create_platform_options(m_chrome_options, m_web_content_options);
  145. if (m_chrome_options.disable_sql_database == DisableSQLDatabase::No) {
  146. m_database = Database::create().release_value_but_fixme_should_propagate_errors();
  147. m_cookie_jar = CookieJar::create(*m_database).release_value_but_fixme_should_propagate_errors();
  148. } else {
  149. m_cookie_jar = CookieJar::create();
  150. }
  151. }
  152. ErrorOr<void> Application::launch_services()
  153. {
  154. TRY(launch_request_server());
  155. TRY(launch_image_decoder_server());
  156. return {};
  157. }
  158. ErrorOr<void> Application::launch_request_server()
  159. {
  160. // FIXME: Create an abstraction to re-spawn the RequestServer and re-hook up its client hooks to each tab on crash
  161. auto paths = TRY(get_paths_for_helper_process("RequestServer"sv));
  162. m_request_server_client = TRY(launch_request_server_process(paths));
  163. return {};
  164. }
  165. ErrorOr<void> Application::launch_image_decoder_server()
  166. {
  167. auto paths = TRY(get_paths_for_helper_process("ImageDecoder"sv));
  168. m_image_decoder_client = TRY(launch_image_decoder_process(paths));
  169. m_image_decoder_client->on_death = [this]() {
  170. m_image_decoder_client = nullptr;
  171. if (auto result = launch_image_decoder_server(); result.is_error()) {
  172. dbgln("Failed to restart image decoder: {}", result.error());
  173. VERIFY_NOT_REACHED();
  174. }
  175. auto client_count = WebContentClient::client_count();
  176. auto new_sockets = m_image_decoder_client->send_sync_but_allow_failure<Messages::ImageDecoderServer::ConnectNewClients>(client_count);
  177. if (!new_sockets || new_sockets->sockets().is_empty()) {
  178. dbgln("Failed to connect {} new clients to ImageDecoder", client_count);
  179. VERIFY_NOT_REACHED();
  180. }
  181. WebContentClient::for_each_client([sockets = new_sockets->take_sockets()](WebContentClient& client) mutable {
  182. client.async_connect_to_image_decoder(sockets.take_last());
  183. return IterationDecision::Continue;
  184. });
  185. };
  186. return {};
  187. }
  188. int Application::execute()
  189. {
  190. int ret = m_event_loop.exec();
  191. m_in_shutdown = true;
  192. return ret;
  193. }
  194. void Application::add_child_process(WebView::Process&& process)
  195. {
  196. m_process_manager.add_process(move(process));
  197. }
  198. #if defined(AK_OS_MACH)
  199. void Application::set_process_mach_port(pid_t pid, Core::MachPort&& port)
  200. {
  201. m_process_manager.set_process_mach_port(pid, move(port));
  202. }
  203. #endif
  204. Optional<Process&> Application::find_process(pid_t pid)
  205. {
  206. return m_process_manager.find_process(pid);
  207. }
  208. void Application::update_process_statistics()
  209. {
  210. m_process_manager.update_all_process_statistics();
  211. }
  212. String Application::generate_process_statistics_html()
  213. {
  214. return m_process_manager.generate_html();
  215. }
  216. void Application::process_did_exit(Process&& process)
  217. {
  218. if (m_in_shutdown)
  219. return;
  220. dbgln_if(WEBVIEW_PROCESS_DEBUG, "Process {} died, type: {}", process.pid(), process_name_from_type(process.type()));
  221. switch (process.type()) {
  222. case ProcessType::ImageDecoder:
  223. if (auto client = process.client<ImageDecoderClient::Client>(); client.has_value()) {
  224. dbgln_if(WEBVIEW_PROCESS_DEBUG, "Restart ImageDecoder process");
  225. if (auto on_death = move(client->on_death)) {
  226. on_death();
  227. }
  228. }
  229. break;
  230. case ProcessType::RequestServer:
  231. dbgln_if(WEBVIEW_PROCESS_DEBUG, "FIXME: Restart request server");
  232. break;
  233. case ProcessType::WebContent:
  234. if (auto client = process.client<WebContentClient>(); client.has_value()) {
  235. dbgln_if(WEBVIEW_PROCESS_DEBUG, "Restart WebContent process");
  236. if (auto on_web_content_process_crash = move(client->on_web_content_process_crash))
  237. on_web_content_process_crash();
  238. }
  239. break;
  240. case ProcessType::WebWorker:
  241. dbgln_if(WEBVIEW_PROCESS_DEBUG, "WebWorker {} died, not sure what to do.", process.pid());
  242. break;
  243. case ProcessType::Chrome:
  244. dbgln("Invalid process type to be dying: Chrome");
  245. VERIFY_NOT_REACHED();
  246. }
  247. }
  248. ErrorOr<LexicalPath> Application::path_for_downloaded_file(StringView file) const
  249. {
  250. auto downloads_directory = Core::StandardPaths::downloads_directory();
  251. if (!FileSystem::is_directory(downloads_directory)) {
  252. auto maybe_downloads_directory = ask_user_for_download_folder();
  253. if (!maybe_downloads_directory.has_value())
  254. return Error::from_errno(ECANCELED);
  255. downloads_directory = maybe_downloads_directory.release_value();
  256. }
  257. if (!FileSystem::is_directory(downloads_directory))
  258. return Error::from_errno(ENOENT);
  259. return LexicalPath::join(downloads_directory, file);
  260. }
  261. }