Truly independent web browser
Hub: End with the UI even when the main thread cannot notice it
Andreas Kling63a1c8b13cc3
diff --git a/Services/Hub/Application.cpp b/Services/Hub/Application.cppindex 90194255066..a1f532105f4 100644--- a/Services/Hub/Application.cpp+++ b/Services/Hub/Application.cpp@@ -27,6 +27,8 @@ void Application::create_platform_arguments(Core::ArgsParser& args_parser){args_parser.add_option(m_encoded_ui_info, "What the UI tells the Hub to start with", "ui-info", 0, "hex");args_parser.add_option(m_ui_mach_server_name, "Mach server to get the connection to the UI from", "ui-mach-server", 0, "name");+ // NB: main() reads this itself, before the arguments are parsed.+ args_parser.add_option(m_ui_pid, "Process of the UI, which the Hub ends with", "ui-pid", 0, "pid");}Hub::UIInfo const* Application::ui_info() constdiff --git a/Services/Hub/Application.h b/Services/Hub/Application.hindex 047acedb6db..427cbca5835 100644--- a/Services/Hub/Application.h+++ b/Services/Hub/Application.h@@ -126,6 +126,7 @@ private:ApplicationHost* m_host { nullptr };StringView m_encoded_ui_info;StringView m_ui_mach_server_name;+ StringView m_ui_pid;mutable Optional<Hub::UIInfo> m_ui_info;HashMap<u64, NonnullOwnPtr<View>> m_views;Optional<u64> m_active_view_id;diff --git a/Services/Hub/CMakeLists.txt b/Services/Hub/CMakeLists.txtindex ac37293ab58..410288c3b7b 100644--- a/Services/Hub/CMakeLists.txt+++ b/Services/Hub/CMakeLists.txt@@ -29,6 +29,6 @@ target_link_libraries(hubservice PRIVATE LibCore LibGfx LibHTTP LibIPC LibRequesadd_executable(Hub main.cpp)target_include_directories(Hub PRIVATE ${LADYBIRD_SOURCE_DIR}/Services/)-target_link_libraries(Hub PRIVATE hubservice hubipc LibCore LibHTTP LibIPC LibMain LibRequests LibURL LibWebView)+target_link_libraries(Hub PRIVATE hubservice hubipc LibCore LibHTTP LibIPC LibMain LibRequests LibThreading LibURL LibWebView)ladybird_sign_helper_process(Hub)diff --git a/Services/Hub/main.cpp b/Services/Hub/main.cppindex afb60928e6c..7a404b8fa40 100644--- a/Services/Hub/main.cpp+++ b/Services/Hub/main.cpp@@ -8,13 +8,104 @@#include <Hub/ConnectionFromUI.h>#include <Hub/Proxies.h>#include <LibCore/GeolocationProvider.h>+#include <LibCore/Process.h>#include <LibIPC/StartupTransport.h>#include <LibMain/Main.h>+#include <LibThreading/Thread.h>++#if defined(AK_OS_MACOS) || defined(AK_OS_BSD_GENERIC)+# include <sys/event.h>+#elif defined(AK_OS_LINUX)+# include <poll.h>+# include <sys/syscall.h>+#endif+#if !defined(AK_OS_WINDOWS)+# include <errno.h>+# include <signal.h>+# include <unistd.h>+#endif++#if !defined(AK_OS_WINDOWS)+// How long the Hub may take to end by itself once the UI is gone.+static constexpr u32 seconds_to_outlive_the_ui = 10;++static void wait_for_process_to_exit(pid_t pid)+{+# if defined(AK_OS_MACOS) || defined(AK_OS_BSD_GENERIC)+ auto queue = kqueue();+ if (queue >= 0) {+ struct kevent change {};+ EV_SET(&change, pid, EVFILT_PROC, EV_ADD | EV_ONESHOT, NOTE_EXIT, 0, nullptr);+ struct kevent event {};+ for (;;) {+ auto count = kevent(queue, &change, 1, &event, 1, nullptr);+ // NB: A process that is gone already cannot be watched. That, like any other failure to watch, is+ // reported as an event when there is room for one.+ auto failed_to_watch = count > 0 && (event.flags & EV_ERROR) != 0;+ auto error = failed_to_watch ? static_cast<int>(event.data) : errno;+ if ((count > 0 && !failed_to_watch) || ((count < 0 || failed_to_watch) && error == ESRCH)) {+ (void)close(queue);+ return;+ }+ if (failed_to_watch || (count < 0 && error != EINTR))+ break;+ }+ (void)close(queue);+ }+# elif defined(AK_OS_LINUX)+ auto process_fd = static_cast<int>(syscall(SYS_pidfd_open, pid, 0));+ if (process_fd >= 0) {+ // NB: The descriptor of a process becomes readable once the process has exited.+ pollfd poll_fd { .fd = process_fd, .events = POLLIN, .revents = 0 };+ while (poll(&poll_fd, 1, -1) < 0 && errno == EINTR)+ ;+ (void)close(process_fd);+ return;+ }+ if (errno == ESRCH)+ return;+# endif++ // NB: Without a way to be told of the exit, look for the process now and then.+ while (kill(pid, 0) == 0 || errno != ESRCH)+ sleep(1);+}+#endif++// The Hub ends when the UI does, which it learns from its connection to the UI. It does not learn that while it has+// not taken that connection yet, or while its main thread waits for something else. A Hub that the UI left behind has+// no window to tell the user of it, yet it keeps its helpers running and the profile to itself. So this watches the UI+// from a thread of its own, and ends a Hub that does not end by itself.+static void end_with_ui_process([[maybe_unused]] Main::Arguments const& arguments)+{+ // FIXME: Do this on Windows as well.+#if !defined(AK_OS_WINDOWS)+ // NB: This starts before the arguments are parsed, as that is where the Hub may begin to wait.+ Optional<pid_t> ui_pid;+ for (auto argument : arguments.strings) {+ if (argument.starts_with("--ui-pid="sv))+ ui_pid = argument.substring_view("--ui-pid="sv.length()).to_number<pid_t>();+ }+ if (!ui_pid.has_value() || *ui_pid <= 0)+ return;++ auto watcher = Threading::Thread::construct("UIExitWatcher"sv, [pid = *ui_pid]() -> intptr_t {+ wait_for_process_to_exit(pid);+ sleep(seconds_to_outlive_the_ui);+ // NB: Nothing is logged here, as a Hub that is stuck writing to its output would keep us from ending it.+ Core::Process::terminate_immediately(1);+ });+ watcher->start();+ watcher->detach();+#endif+}ErrorOr<int> ladybird_main(Main::Arguments arguments){AK::set_rich_debug_enabled(true);+ end_with_ui_process(arguments);+auto application = TRY(Hub::Application::create(arguments, nullptr));if (application->should_exit_after_profile_coordination()) {outln("Opening in existing process");diff --git a/UI/Qt/Application.cpp b/UI/Qt/Application.cppindex c73d2adb1b3..ed4de5f3390 100644--- a/UI/Qt/Application.cpp+++ b/UI/Qt/Application.cpp@@ -92,6 +92,11 @@# include <UI/Qt/X11Window.h>#endif+#if !defined(AK_OS_WINDOWS)+# include <sys/wait.h>+# include <unistd.h>+#endif+#include <QAction>#include <QClipboard>#include <QDesktopServices>@@ -825,6 +830,7 @@ ErrorOr<void> Application::connect_to_hub(Main::Arguments const& arguments)hub_arguments.extend(take_urls_from_launch_apple_events());# endifhub_arguments.append(ByteString::formatted("--ui-info={}", encode_hex(ui_info_buffer.data().span())));+ hub_arguments.append(ByteString::formatted("--ui-pid={}", Core::System::getpid()));Core::ProcessSpawnOptions spawn_options {.name = "Hub"sv,@@ -2499,8 +2505,28 @@ Optional<Application::RestartCommand> Application::take_restart_command()// this process has ended, so this process ends only after the Hub has.ErrorOr<void> Application::RestartCommand::run(){- if (hub.has_value())+ if (hub.has_value()) {+#if !defined(AK_OS_WINDOWS)+ // NB: The new browser needs the profile, which the Hub has until it ends. A Hub that does not end by itself+ // would keep us waiting with no window to show for it, so it is ended then.+ static constexpr auto time_for_hub_to_end = AK::Duration::from_seconds(10);+ auto deadline = MonotonicTime::now() + time_for_hub_to_end;+ for (;;) {+ int status = 0;+ auto result = waitpid(hub->pid(), &status, WNOHANG);+ if (result == hub->pid() || (result < 0 && errno != EINTR))+ break;+ if (MonotonicTime::now() >= deadline) {+ (void)Core::Process::terminate_process(hub->pid(), Core::Process::TerminationMode::Forceful);+ TRY(hub->wait_for_termination());+ break;+ }+ usleep(10'000);+ }+#elseTRY(hub->wait_for_termination());+#endif+ }if (!relaunched_by_updater)TRY(Core::Process::spawn({ .executable = executable, .arguments = arguments }));return {};