/* * Copyright (c) 2022, Peter Elliott * * SPDX-License-Identifier: BSD-2-Clause */ #include #include #include #include namespace Core::SessionManagement { static ErrorOr get_proc(Core::AllProcessesStatistics const& stats, pid_t pid) { for (auto& proc : stats.processes) { if (proc.pid == pid) return &proc; } return Error::from_string_literal("Could not find pid in process statistics."); } ErrorOr root_session_id(Optional force_sid) { auto stats = TRY(Core::ProcessStatisticsReader::get_all(false)); pid_t sid = (force_sid.has_value()) ? force_sid.value() : TRY(System::getsid()); while (true) { pid_t parent = TRY(get_proc(stats, sid))->ppid; pid_t parent_sid = TRY(get_proc(stats, parent))->sid; if (parent_sid == 0) break; sid = parent_sid; } return sid; } ErrorOr logout(Optional force_sid) { pid_t sid = TRY(root_session_id(force_sid)); TRY(System::kill(-sid, SIGTERM)); return {}; } ErrorOr parse_path_with_sid(StringView general_path, Optional force_sid) { if (general_path.contains("%sid"sv)) { pid_t sid = TRY(root_session_id(force_sid)); return general_path.replace("%sid"sv, DeprecatedString::number(sid), ReplaceMode::All); } return DeprecatedString(general_path); } ErrorOr create_session_temporary_directory_if_needed(uid_t uid, gid_t gid, Optional force_sid) { pid_t sid = TRY(root_session_id(force_sid)); auto const temporary_directory = DeprecatedString::formatted("/tmp/session/{}", sid); auto directory = TRY(Core::Directory::create(temporary_directory, Core::Directory::CreateDirectories::Yes)); TRY(directory.chown(uid, gid)); return {}; } }