Skip to content

Truly independent web browser

6.9 KB
Raw Blame
/*
 * Copyright (c) 2018-2020, Andreas Kling <[email protected]>
 * Copyright (c) 2023, Andrew Kaster <[email protected]>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <AK/ByteString.h>
#include <AK/Format.h>
#include <AK/StringView.h>
#include <AK/Vector.h>
#include <LibCore/ArgsParser.h>
#include <LibCore/CrashHandler.h>
#include <LibCore/EventLoop.h>
#include <LibCore/Platform/TaskRole.h>
#include <LibCore/Platform/ThreadQoS.h>
#include <LibCore/Process.h>
#include <LibCore/StatsLog.h>
#include <LibCore/System.h>
#include <LibFileSystem/FileSystem.h>
#include <LibHTTP/Cache/DiskCache.h>
#include <LibIPC/SingleServer.h>
#include <LibMain/Main.h>
#include <RequestServer/CURL.h>
#include <RequestServer/ConnectionFromClient.h>
#include <RequestServer/ControlConnectionFromClient.h>
#include <RequestServer/Resolver.h>
#include <RequestServer/ResourceSubstitutionMap.h>
#include <RequestServer/Sandbox.h>

namespace RequestServer {

OwnPtr<ResourceSubstitutionMap> g_resource_substitution_map;

}

#ifndef AK_OS_WINDOWS
static void handle_signal(int signal)
{
    VERIFY(signal == SIGINT || signal == SIGTERM);
    Core::EventLoop::current().quit(0);
}
#endif

ErrorOr<int> ladybird_main(Main::Arguments arguments)
{
    AK::set_rich_debug_enabled(true);

    Vector<ByteString> certificates;
    StringView mach_server_name;
    StringView http_disk_cache_mode;
    StringView resource_map_path;
    StringView cache_path;
    StringView top_level_site;
    bool wait_for_debugger = false;
    bool disable_sandbox = false;
    bool enable_test_mode = false;

    int crash_report_fd = -1;
    StringView stats_log_directory;
    Core::ArgsParser args_parser;
    args_parser.add_option(stats_log_directory, "Directory for process statistics (JSON lines)", "stats-log-dir", 0, "path");
    args_parser.add_option(crash_report_fd, "Descriptor for anonymous crash diagnostics", "crash-report-fd", 0, "fd");
    args_parser.add_option(certificates, "Path to a certificate file", "certificate", 'C', "certificate");
    args_parser.add_option(mach_server_name, "Mach server name", "mach-server-name", 0, "mach_server_name");
    args_parser.add_option(http_disk_cache_mode, "HTTP disk cache mode", "http-disk-cache-mode", 0, "mode");
    args_parser.add_option(resource_map_path, "Path to JSON file mapping URLs to local files", "resource-map", 0, "path");
    args_parser.add_option(cache_path, "Path to the profile cache", "cache-path", 0, "path");
    args_parser.add_option(top_level_site, "The top-level site this RequestServer serves", "site", 0, "site");
    args_parser.add_option(wait_for_debugger, "Wait for debugger", "wait-for-debugger");
    args_parser.add_option(disable_sandbox, "Disable process sandboxing", "disable-sandbox");
    args_parser.add_option(enable_test_mode, "Enable test mode", "test-mode");
    args_parser.parse(arguments);

    auto stats_log = TRY(Core::StatsLog::create(stats_log_directory, "RequestServer"sv));

    if (crash_report_fd >= 0) {
        if (auto result = Core::CrashHandler::initialize(crash_report_fd); result.is_error())
            warnln("Could not install crash report handler: {}", result.error());
    }

    if (wait_for_debugger)
        Core::Process::wait_for_debugger_and_break();

    if (auto result = Core::Platform::adopt_foreground_application_task_role(); result.is_error())
        warnln("Could not adopt the foreground application task role: {}", result.error());
    if (auto result = Core::Platform::set_current_thread_qos(Core::Platform::ThreadQoS::UserInitiated); result.is_error())
        warnln("Could not set main thread QoS: {}", result.error());

    if (enable_test_mode)
        RequestServer::DNSInfo::the().loopback_domains.append("test"sv);

    // FIXME: Update RequestServer to support multiple custom root certificates.
    if (!certificates.is_empty())
        RequestServer::set_default_certificate_path(certificates.first());

    if (!resource_map_path.is_empty()) {
        auto map = RequestServer::ResourceSubstitutionMap::load_from_file(resource_map_path);
        if (map.is_error())
            warnln("Unable to load resource substitution map from '{}': {}", resource_map_path, map.error());
        else
            RequestServer::g_resource_substitution_map = map.release_value();
    }

#if !defined(AK_OS_WINDOWS)
    MUST(Core::System::signal(SIGPIPE, SIG_IGN));
#endif

    auto& event_loop = Core::EventLoop::initialize_for_current_thread();
    // FIXME: Have another way to signal the event loop to gracefully quit on windows.
#ifndef AK_OS_WINDOWS
    Core::EventLoop::register_signal(SIGINT, handle_signal);
    Core::EventLoop::register_signal(SIGTERM, handle_signal);
#endif

    Optional<HTTP::DiskCache> disk_cache;

    if (http_disk_cache_mode != "disabled"sv) {
        auto mode = TRY([&]() -> ErrorOr<HTTP::DiskCache::Mode> {
            if (http_disk_cache_mode == "enabled"sv)
                return HTTP::DiskCache::Mode::Normal;
            if (http_disk_cache_mode == "testing"sv)
                return HTTP::DiskCache::Mode::Testing;
            return Error::from_string_literal("Unrecognized disk cache mode");
        }());

        if (auto cache = HTTP::DiskCache::create(mode, LexicalPath { cache_path }); cache.is_error())
            warnln("Unable to create disk cache: {}", cache.error());
        else
            disk_cache = cache.release_value();
    }

    // Alternative services are no longer persisted, so this only holds history.
    if (!cache_path.is_empty())
        (void)FileSystem::remove(LexicalPath::join(cache_path, "alt-svc-cache.txt"sv).string(), FileSystem::RecursionMode::Disallowed);

    if (!top_level_site.is_empty())
        RequestServer::set_process_top_level_site(Utf16String::from_utf8(top_level_site));

    TRY(RequestServer::initialize_libcurl());

    if (!disable_sandbox) {
        Optional<StringView> disk_cache_directory;
        if (disk_cache.has_value())
            disk_cache_directory = disk_cache->cache_directory().string();
        TRY(RequestServer::apply_sandbox(mach_server_name, certificates, disk_cache_directory));
    }

    // Connections are stored on the stack to ensure they are destroyed before static destruction begins. This prevents
    // crashes from notifiers trying to unregister from already-destroyed thread data during process exit.
    RequestServer::ConnectionFromClient::ConnectionMap connections;
    RequestServer::ConnectionFromClient::RequestTransferLeaseMap request_transfer_leases;

    auto client = TRY(IPC::take_over_accepted_client_from_system_server<RequestServer::ControlConnectionFromClient>(
        mach_server_name,
        connections,
        request_transfer_leases,
        disk_cache));

    if (stats_log)
        stats_log->start_sampling([&](JsonObject& values) {
            values.set("requests.clients"sv, connections.size());
            values.set("requests.transfer_leases"sv, request_transfer_leases.size());
        });

    return event_loop.exec();
}