blob: 21fa6662cc09d412e9c2b7792459b31fbaf0897c [file]
// Copyright 2026 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/linux/user_desktop_session_backend.h"
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <tuple>
#include <utility>
#include <vector>
#include "base/barrier_callback.h"
#include "base/containers/span.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/json/string_escape.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/sequence_checker.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/task_traits.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "base/timer/timer.h"
#include "base/types/expected.h"
#include "remoting/base/errors.h"
#include "remoting/base/logging.h"
#include "remoting/base/passwd_utils.h"
#include "remoting/base/source_location.h"
#include "remoting/host/daemon_process.h"
#include "remoting/host/desktop_session.h"
#include "remoting/host/linux/created_session_tracker.h"
#include "remoting/host/linux/desktop_session_linux.h"
#include "remoting/host/linux/gdbus_connection_ref.h"
#include "remoting/host/linux/gdm_remote_user_desktop_session_creator.h"
#include "remoting/host/linux/gvariant_ref.h"
#include "remoting/host/linux/login_session_manager.h"
#include "remoting/host/linux/session_routing_config.h"
#include "remoting/host/linux/user_session_eligibility.h"
#include "remoting/host/mojom/desktop_session.mojom.h"
#include "remoting/host/pam_utils.h"
namespace remoting {
namespace {
// How long to wait for a requested session to show up in logind. Session
// creators may report success before the user is authenticated, and don't
// report later failures (e.g. PAM rejecting the login), so a timeout is the
// only way to detect them. The D-Bus call timeout in
// GdmRemoteUserDesktopSessionCreator is longer than this.
constexpr base::TimeDelta kSessionCreationTimeout = base::Seconds(30);
// How long to wait for the blocking local graphical session to be removed from
// logind after calling TerminateSession().
constexpr base::TimeDelta kSessionTerminationTimeout = base::Seconds(30);
// Substring of the D-Bus error returned by logind when a session doesn't
// exist.
constexpr std::string_view kNoSuchSessionError =
"org.freedesktop.login1.NoSuchSession";
bool IsActiveGraphicalUserSession(
const LoginSessionManager::SessionInfo& session) {
return session.session_class == "user" &&
(session.session_type == "wayland" || session.session_type == "x11") &&
session.state != "closing";
}
void LogIfTrackerError(std::string_view operation,
base::expected<void, Loggable> result) {
if (!result.has_value()) {
LOG(ERROR) << "Failed to " << operation
<< " created sessions: " << result.error();
}
}
} // namespace
// static
const LoginSessionManager::SessionInfo*
UserDesktopSessionBackend::SelectBestGraphicalSession(
base::span<const LoginSessionManager::SessionInfo> sessions) {
const LoginSessionManager::SessionInfo* best_session = nullptr;
std::tuple<int, bool, bool> best_priority = {-1, false, false};
for (const auto& session : sessions) {
if (!IsActiveGraphicalUserSession(session)) {
continue;
}
// Priority ranking:
// 1. service == "chrome-remote-desktop": dedicated CRD user session (see
// chrome-remote-desktop-x11-session@.service).
// 2. is_remote == true: prefer remote/headless sessions over local console
// sessions to avoid displaying remote user activity on a physical
// monitor and ensure compatibility with curtain mode.
// 3. state == "active": prefer active (foreground) sessions over online
// (background) sessions.
std::tuple<int, bool, bool> priority = {
session.service == "chrome-remote-desktop" ? 1 : 0,
session.is_remote,
session.state == "active",
};
// `std::tuple::operator>` compares elements lexicographically from left to
// right (where `true > false` for `bool`), so tier 1 is compared first,
// followed by tier 2 on ties, and tier 3 on ties. Using strict `>`
// preserves the first matching session when all three elements are equal.
if (priority > best_priority) {
best_priority = priority;
best_session = &session;
}
}
return best_session;
}
// static
UserDesktopSessionBackend::LocalSessionCurtainAction
UserDesktopSessionBackend::DecideLocalSessionCurtainAction(
bool create_remote_user_sessions,
bool terminate_local_session,
bool is_eligible_for_remote_session) {
if (!create_remote_user_sessions) {
return LocalSessionCurtainAction::kRejectUncurtainable;
}
if (!is_eligible_for_remote_session) {
return LocalSessionCurtainAction::kRejectIneligible;
}
return terminate_local_session
? LocalSessionCurtainAction::kTerminateAndCreateRemote
: LocalSessionCurtainAction::kRejectLocalSessionRunning;
}
// static
base::expected<void, Loggable>
UserDesktopSessionBackend::CheckCreateRemoteSessionUserInfo(
std::string_view requested_username,
const PasswdUserInfo& user_info,
base::span<const base::FilePath> valid_shells) {
// Require the canonical name, so that the session creator and logind refer to
// the same user that the routing config resolved to.
if (user_info.username != requested_username) {
return base::unexpected(Loggable(
FROM_HERE, "Username " + base::GetQuotedJSONString(requested_username) +
" does not match the canonical passwd name " +
base::GetQuotedJSONString(user_info.username) + "."));
}
if (!IsUidAllowedForDesktopSession(user_info.uid, /*is_greeter=*/false)) {
return base::unexpected(
Loggable(FROM_HERE, "UID " + base::NumberToString(user_info.uid) +
" is not allowed to have a desktop session."));
}
if (!IsValidLoginShell(user_info.shell, valid_shells)) {
return base::unexpected(Loggable(
FROM_HERE,
"Login shell " + base::GetQuotedJSONString(user_info.shell.value()) +
" is not listed in /etc/shells or doesn't allow logins."));
}
return base::ok();
}
// static
base::expected<PasswdUserInfo, Loggable>
UserDesktopSessionBackend::CheckCreateRemoteSessionEligibility(
const std::string& username) {
auto user_info = GetPasswdUserInfo(username);
if (!user_info.has_value()) {
return std::move(user_info.error())
.UnexpectedWithContext(FROM_HERE, "While looking up the passwd entry");
}
auto result = CheckCreateRemoteSessionUserInfo(username, *user_info,
GetValidLoginShells());
if (!result.has_value()) {
return base::unexpected(std::move(result.error()));
}
if (!IsLocalLoginAllowed(username)) {
return base::unexpected(
Loggable(FROM_HERE, "PAM does not allow the user to log in."));
}
return std::move(*user_info);
}
// static
bool UserDesktopSessionBackend::ShouldTrackCreatedSession(
const LoginSessionManager::SessionInfo& session) {
// Sessions created via `session_creator_` are remote. Don't record a local
// session that the user happened to start while CRD was waiting for the
// requested session.
return session.is_remote;
}
// static
bool UserDesktopSessionBackend::ShouldTerminateTrackedSession(
const CreatedSessionTracker::Entry& entry,
const LoginSessionManager::SessionInfo& session) {
// Only graphical sessions are ever tracked, so this also rules out e.g. an
// SSH session of the same user that reuses the session ID.
return session.session_id == entry.session_id && session.uid == entry.uid &&
session.username == entry.username && session.is_remote &&
IsActiveGraphicalUserSession(session);
}
// static
bool UserDesktopSessionBackend::IsNoSuchSessionError(std::string_view error) {
return error.contains(kNoSuchSessionError);
}
UserDesktopSessionBackend::ActiveSessionEntry::ActiveSessionEntry() = default;
UserDesktopSessionBackend::ActiveSessionEntry::ActiveSessionEntry(
std::string username,
base::WeakPtr<DesktopSessionLinux> desktop_session,
bool terminate_local_session)
: username(std::move(username)),
desktop_session(std::move(desktop_session)),
terminate_local_session(terminate_local_session) {}
UserDesktopSessionBackend::ActiveSessionEntry::~ActiveSessionEntry() = default;
UserDesktopSessionBackend::ActiveSessionEntry::ActiveSessionEntry(
ActiveSessionEntry&&) = default;
UserDesktopSessionBackend::ActiveSessionEntry&
UserDesktopSessionBackend::ActiveSessionEntry::operator=(ActiveSessionEntry&&) =
default;
UserDesktopSessionBackend::UserDesktopSessionBackend(
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner,
SessionRoutingConfig routing_config)
: io_task_runner_(io_task_runner),
routing_config_(std::move(routing_config)),
created_session_tracker_(base::ThreadPool::CreateSequencedTaskRunner(
{base::MayBlock(), base::TaskPriority::USER_VISIBLE})) {}
UserDesktopSessionBackend::~UserDesktopSessionBackend() {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
}
void UserDesktopSessionBackend::Start(Callback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
GDBusConnectionRef::CreateForSystemBus(
base::BindOnce(&UserDesktopSessionBackend::OnCreateDbusConnectionResult,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
std::unique_ptr<DesktopSession> UserDesktopSessionBackend::CreateDesktopSession(
int id,
DaemonProcess* daemon_process,
const mojom::DesktopSessionOptions& options) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
auto desktop_session = std::make_unique<DesktopSessionLinux>(
daemon_process, id, io_task_runner_,
base::IgnoreArgs<DesktopSessionLinux::DestructionReason>(
base::BindOnce(&UserDesktopSessionBackend::RemoveDesktopSession,
weak_ptr_factory_.GetWeakPtr(), id)),
DesktopSessionLinux::Options{
.required_username = options.required_username,
.client_id = options.client_id,
.curtain_required = options.curtain_required,
.is_greeter_allowed = false,
});
auto resolved_user = ValidateClientSession(options);
if (!resolved_user.has_value()) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&DesktopSessionLinux::TerminateSession,
desktop_session->GetWeakPtr(),
ErrorCode::SESSION_REJECTED,
resolved_user.error(), FROM_HERE));
return desktop_session;
}
desktop_sessions_[id] =
ActiveSessionEntry(*resolved_user, desktop_session->GetWeakPtr(),
options.terminate_local_session);
if (login_session_manager_) {
ListUserSessions(id);
}
return desktop_session;
}
base::expected<std::string, std::string>
UserDesktopSessionBackend::ValidateClientSession(
const mojom::DesktopSessionOptions& options) const {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
auto resolved_user = routing_config_.ResolveSessionUser(options.client_id);
if (!resolved_user.has_value()) {
LOG(ERROR) << "Client " << options.client_id
<< " is not permitted by session routing configuration.";
return base::unexpected(
"Client is not permitted by session routing config.");
}
if (!options.required_username.empty() &&
!base::EqualsCaseInsensitiveASCII(options.required_username,
*resolved_user)) {
LOG(ERROR) << "Resolved session user (" << *resolved_user
<< ") does not match required username ("
<< options.required_username << ").";
return base::unexpected(
"Resolved session user does not match required username.");
}
// This generally shouldn't happen because DaemonProcess persists desktop
// sessions across reconnection, but we disconnect in case of unexpected
// situations.
for (const auto& [existing_id, entry] : desktop_sessions_) {
if (entry.desktop_session &&
base::EqualsCaseInsensitiveASCII(entry.username, *resolved_user)) {
LOG(ERROR) << "User " << *resolved_user
<< " already has an active remote desktop session.";
return base::unexpected(
"Target user already has an active remote desktop session.");
}
}
return base::ok(*std::move(resolved_user));
}
void UserDesktopSessionBackend::TerminateAllSessions(Callback callback) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// DaemonProcess destroys the DesktopSessionLinux objects (and their worker
// processes) during shutdown. Login sessions not created by CRD are
// externally managed, so they are left alone. Login sessions that CRD
// created via `session_creator_`, including ones created by an earlier
// daemon instance, are terminated, so that they don't conflict with whatever
// runs next (e.g. after migrate-host) or linger after the host is removed.
// This only runs on SIGTERM. Host upgrades and config updates kill the
// daemon without running this, so those sessions are kept and re-adopted.
desktop_sessions_.clear();
if (!login_session_manager_) {
// The system D-Bus connection hasn't been established yet. Keep the
// tracked sessions, so that the next daemon instance can terminate them.
LOG(WARNING) << "Not terminating created sessions, since the system D-Bus "
<< "connection is not ready.";
std::move(callback).Run(base::ok());
return;
}
created_session_tracker_.AsyncCall(&CreatedSessionTracker::Load)
.Then(base::BindOnce(&UserDesktopSessionBackend::OnTrackedSessionsLoaded,
weak_ptr_factory_.GetWeakPtr(),
std::move(callback)));
}
DesktopSession* UserDesktopSessionBackend::GetSessionByUid(uid_t uid) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
for (const auto& [id, entry] : desktop_sessions_) {
if (entry.desktop_session && entry.desktop_session->current_uid() == uid) {
return entry.desktop_session.get();
}
}
return nullptr;
}
void UserDesktopSessionBackend::OnCreateDbusConnectionResult(
Callback callback,
base::expected<GDBusConnectionRef, Loggable> result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!result.has_value()) {
LOG(ERROR) << "Failed to connect to system D-Bus: " << result.error();
std::move(callback).Run(base::unexpected(std::move(result).error()));
return;
}
connection_ = std::move(*result);
login_session_manager_ = std::make_unique<LoginSessionManager>(connection_);
session_removed_subscription_ =
login_session_manager_->SubscribeSessionRemoved(
base::BindRepeating(&UserDesktopSessionBackend::OnSessionRemoved,
weak_ptr_factory_.GetWeakPtr()));
if (routing_config_.create_remote_user_sessions()) {
// GDM is currently the only supported way to create remote user sessions.
// If others are added (e.g. a future XDG API), select one here and fall
// back to GDM.
session_creator_ =
std::make_unique<GdmRemoteUserDesktopSessionCreator>(connection_);
session_new_subscription_ = login_session_manager_->SubscribeSessionNew(
base::BindRepeating(&UserDesktopSessionBackend::OnSessionNew,
weak_ptr_factory_.GetWeakPtr()));
}
// Start session discovery for any desktop sessions created while the system
// D-Bus connection was still being initialized.
for (const auto& [id, entry] : desktop_sessions_) {
if (entry.desktop_session) {
ListUserSessions(id);
}
}
std::move(callback).Run(base::ok());
}
void UserDesktopSessionBackend::ListUserSessions(int terminal_id) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
auto it = desktop_sessions_.find(terminal_id);
if (it == desktop_sessions_.end()) {
return;
}
DCHECK(login_session_manager_);
login_session_manager_->ListUserSessions(
it->second.username,
base::BindOnce(&UserDesktopSessionBackend::OnListUserSessionsResult,
weak_ptr_factory_.GetWeakPtr(), terminal_id));
}
void UserDesktopSessionBackend::OnListUserSessionsResult(
int terminal_id,
base::expected<std::vector<LoginSessionManager::SessionInfo>, Loggable>
result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
auto it = desktop_sessions_.find(terminal_id);
if (it == desktop_sessions_.end() || !it->second.desktop_session) {
return;
}
ActiveSessionEntry& entry = it->second;
auto desktop_session = entry.desktop_session;
if (entry.state == SessionState::kTerminatingLocalSession ||
entry.state == SessionState::kAttached) {
// Already attached to a session (e.g. a concurrent SessionNew lookup
// attached first), or waiting for the local session to terminate.
// Calling SetSessionInfo() again would relaunch the desktop process.
return;
}
if (!result.has_value()) {
LOG(ERROR) << "Failed to list sessions for user " << entry.username << ": "
<< result.error();
// This erases `entry` synchronously, which also stops `state_timeout`.
desktop_session->TerminateSession(
ErrorCode::INVALID_STATE, "Failed to query systemd-logind sessions.",
FROM_HERE);
return;
}
const auto* best_session = SelectBestGraphicalSession(*result);
if (!best_session) {
if (entry.state == SessionState::kCreatingRemoteSession) {
// Still waiting for the requested session to show up.
return;
}
if (routing_config_.create_remote_user_sessions()) {
CreateRemoteUserSession(terminal_id);
return;
}
LOG(ERROR) << "No graphical user session found for " << entry.username;
desktop_session->TerminateSession(
ErrorCode::SESSION_REJECTED,
"No graphical user session found for user.", FROM_HERE);
return;
}
if (desktop_session->curtain_required() &&
!DesktopSessionLinux::IsSessionCompatibleWithCurtainMode(*best_session)) {
if (entry.state == SessionState::kCreatingRemoteSession) {
// Still waiting for the requested remote session to show up.
return;
}
std::optional<PasswdUserInfo> eligible_user_info;
if (routing_config_.create_remote_user_sessions()) {
auto eligibility = CheckCreateRemoteSessionEligibility(entry.username);
if (eligibility.has_value()) {
eligible_user_info = std::move(*eligibility);
} else {
LOG(WARNING) << "User " << entry.username
<< " is not eligible for remote session creation: "
<< eligibility.error();
}
}
switch (DecideLocalSessionCurtainAction(
routing_config_.create_remote_user_sessions(),
entry.terminate_local_session, eligible_user_info.has_value())) {
case LocalSessionCurtainAction::kRejectUncurtainable:
RejectUncurtainedLocalSession(*desktop_session, *best_session,
ErrorCode::UNCURTAINED_SESSION);
return;
case LocalSessionCurtainAction::kRejectIneligible:
desktop_session->TerminateSession(
ErrorCode::SESSION_REJECTED,
"User is not allowed to have a remote session created.", FROM_HERE);
return;
case LocalSessionCurtainAction::kRejectLocalSessionRunning:
RejectUncurtainedLocalSession(*desktop_session, *best_session,
ErrorCode::LOCAL_SESSION_RUNNING);
return;
case LocalSessionCurtainAction::kTerminateAndCreateRemote:
TerminateLocalThenCreateRemoteSession(terminal_id, *best_session,
eligible_user_info->uid);
return;
}
}
bool was_pending_creation =
entry.state == SessionState::kCreatingRemoteSession;
entry.state = SessionState::kAttached;
entry.state_timeout.reset();
if (was_pending_creation && ShouldTrackCreatedSession(*best_session)) {
// Track the session before any of the checks below, since it has been
// created regardless of whether the connection can attach to it.
TrackCreatedSession(*best_session);
}
auto user_info = GetPasswdUserInfo(best_session->username);
if (!user_info.has_value()) {
LOG(ERROR) << "Failed to find passwd entry for session user "
<< best_session->username << ": " << user_info.error();
desktop_session->TerminateSession(ErrorCode::INVALID_STATE,
"Failed to look up user credentials.",
FROM_HERE);
return;
}
if (user_info->uid != best_session->uid) {
LOG(ERROR) << "UID mismatch between passwd (" << user_info->uid
<< ") and systemd session (" << best_session->uid << ")";
desktop_session->TerminateSession(ErrorCode::INVALID_STATE,
"Session UID does not match passwd UID.",
FROM_HERE);
return;
}
HOST_LOG << "Attaching desktop session " << terminal_id
<< " to graphical session " << best_session->session_id
<< " (type=" << best_session->session_type
<< ", state=" << best_session->state
<< ", service=" << best_session->service << ") for user "
<< entry.username;
desktop_session->SetSessionInfo(*best_session, *user_info);
}
void UserDesktopSessionBackend::RejectUncurtainedLocalSession(
DesktopSessionLinux& desktop_session,
const LoginSessionManager::SessionInfo& session,
ErrorCode error_code) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
auto user_info = GetPasswdUserInfo(session.username);
if (!user_info.has_value()) {
LOG(ERROR) << "Failed to find passwd entry for session user "
<< session.username << ": " << user_info.error();
desktop_session.TerminateSession(ErrorCode::INVALID_STATE,
"Failed to look up user credentials.",
FROM_HERE);
return;
}
if (!desktop_session.ValidateSessionAccess(session, *user_info)) {
return;
}
LOG(ERROR) << "Curtain mode is not supported for local session "
<< session.session_id;
desktop_session.TerminateSession(
error_code,
"A local graphical session is already running while curtain mode is "
"required.",
FROM_HERE);
}
void UserDesktopSessionBackend::TerminateLocalThenCreateRemoteSession(
int terminal_id,
const LoginSessionManager::SessionInfo& session,
uid_t expected_uid) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ActiveSessionEntry* entry =
GetEntryInState(terminal_id, SessionState::kDiscovering);
if (!entry) {
return;
}
if (session.username != entry->username || session.uid != expected_uid) {
LOG(ERROR) << "Refusing to terminate local session " << session.session_id
<< " (user " << session.username << ", UID " << session.uid
<< ") because it does not match target user " << entry->username
<< " (UID " << expected_uid << ").";
entry->desktop_session->TerminateSession(
ErrorCode::INVALID_STATE,
"Session credentials do not match target user.", FROM_HERE);
return;
}
// If the user somehow has multiple local graphical sessions (rare), only the
// selected one is terminated; if remote session creation fails as a result,
// a retry handles the next one, otherwise the extra local session is left
// running.
entry->state = SessionState::kTerminatingLocalSession;
entry->pending_termination_session_id = session.session_id;
entry->state_timeout = std::make_unique<base::OneShotTimer>();
entry->state_timeout->Start(
FROM_HERE, kSessionTerminationTimeout,
base::BindOnce(
&UserDesktopSessionBackend::OnLocalSessionTerminationTimeout,
weak_ptr_factory_.GetWeakPtr(), terminal_id));
HOST_LOG << "Terminating local graphical session " << session.session_id
<< " for user " << entry->username << ".";
login_session_manager_->TerminateSession(
session.object_path,
base::BindOnce(&UserDesktopSessionBackend::OnTerminateLocalSessionResult,
weak_ptr_factory_.GetWeakPtr(), terminal_id,
session.session_id));
}
void UserDesktopSessionBackend::OnTerminateLocalSessionResult(
int terminal_id,
std::string session_id,
base::expected<void, Loggable> result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ActiveSessionEntry* entry =
GetEntryInState(terminal_id, SessionState::kTerminatingLocalSession);
if (!entry) {
return;
}
if (result.has_value()) {
// Termination accepted by logind; wait for SessionRemoved before
// requesting a remote session.
return;
}
// If the local session exited on its own between ListUserSessions() and
// TerminateSession(), Session.Terminate fails (e.g. UnknownObject). Terminate
// cleanly with INVALID_STATE so no stale state remains and a retry succeeds.
LOG(ERROR) << "Failed to terminate local graphical session " << session_id
<< " for user " << entry->username << ": " << result.error();
entry->desktop_session->TerminateSession(
ErrorCode::INVALID_STATE, "Failed to terminate local graphical session.",
FROM_HERE);
}
void UserDesktopSessionBackend::OnLocalSessionTerminationTimeout(
int terminal_id) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ActiveSessionEntry* entry =
GetEntryInState(terminal_id, SessionState::kTerminatingLocalSession);
if (!entry) {
return;
}
LOG(ERROR) << "Timed out waiting for local graphical session for user "
<< entry->username << " to terminate.";
entry->desktop_session->TerminateSession(
ErrorCode::OPERATION_TIMEOUT,
"Timed out waiting for local graphical session to terminate.", FROM_HERE);
}
void UserDesktopSessionBackend::CreateRemoteUserSession(int terminal_id) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
auto it = desktop_sessions_.find(terminal_id);
if (it == desktop_sessions_.end() || !it->second.desktop_session) {
return;
}
ActiveSessionEntry& entry = it->second;
HOST_LOG << "Requesting a remote graphical session for user "
<< entry.username << ".";
// The session is created without interactive authentication, so make sure
// that the user is allowed to log in first.
// DesktopSessionLinux::SetSessionInfo() checks the UID and PAM account again
// after the session is created.
auto eligibility = CheckCreateRemoteSessionEligibility(entry.username);
if (!eligibility.has_value()) {
LOG(ERROR) << "Not creating a remote session for user " << entry.username
<< ": " << eligibility.error();
entry.desktop_session->TerminateSession(
ErrorCode::SESSION_REJECTED,
"User is not allowed to have a remote session created.", FROM_HERE);
return;
}
entry.state = SessionState::kCreatingRemoteSession;
entry.state_timeout = std::make_unique<base::OneShotTimer>();
entry.state_timeout->Start(
FROM_HERE, kSessionCreationTimeout,
base::BindOnce(&UserDesktopSessionBackend::OnSessionCreationTimeout,
weak_ptr_factory_.GetWeakPtr(), terminal_id));
DCHECK(session_creator_);
session_creator_->CreateSession(
entry.username,
base::BindOnce(&UserDesktopSessionBackend::OnCreateSessionResult,
weak_ptr_factory_.GetWeakPtr(), terminal_id));
}
void UserDesktopSessionBackend::OnCreateSessionResult(
int terminal_id,
base::expected<void, Loggable> result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ActiveSessionEntry* entry =
GetEntryInState(terminal_id, SessionState::kCreatingRemoteSession);
if (!entry) {
return;
}
if (!result.has_value()) {
LOG(ERROR) << "Failed to create a remote session for user "
<< entry->username << ": " << result.error();
// This erases `entry` synchronously, which also stops `state_timeout`.
entry->desktop_session->TerminateSession(
ErrorCode::SESSION_REJECTED, "Failed to create remote user session.",
FROM_HERE);
return;
}
// Nothing to do on success. The requested session is attached when its
// `SessionNew` signal arrives, or the connection times out.
}
void UserDesktopSessionBackend::OnSessionCreationTimeout(int terminal_id) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
ActiveSessionEntry* entry =
GetEntryInState(terminal_id, SessionState::kCreatingRemoteSession);
if (!entry) {
return;
}
LOG(ERROR) << "Timed out waiting for the remote session for user "
<< entry->username << " to start.";
// This erases `entry` synchronously, including `state_timeout`.
entry->desktop_session->TerminateSession(
ErrorCode::INVALID_STATE,
"Timed out waiting for the remote user session to start.", FROM_HERE);
}
void UserDesktopSessionBackend::OnSessionNew(
std::string /*session_id*/,
gvariant::ObjectPath /*object_path*/) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// The signal doesn't say which user the session belongs to, so look up the
// sessions of every connection waiting for a requested session. There are
// rarely more than a few.
for (const auto& [id, entry] : desktop_sessions_) {
if (entry.desktop_session &&
entry.state == SessionState::kCreatingRemoteSession) {
ListUserSessions(id);
}
}
}
UserDesktopSessionBackend::ActiveSessionEntry*
UserDesktopSessionBackend::GetEntryInState(int terminal_id,
SessionState expected_state) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
auto it = desktop_sessions_.find(terminal_id);
if (it == desktop_sessions_.end() || !it->second.desktop_session ||
it->second.state != expected_state) {
return nullptr;
}
return &it->second;
}
void UserDesktopSessionBackend::OnSessionRemoved(
std::string session_id,
gvariant::ObjectPath /*object_path*/) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
// The session no longer needs to be terminated if CRD created it. This is a
// no-op for sessions that aren't tracked.
created_session_tracker_.AsyncCall(&CreatedSessionTracker::Remove)
.WithArgs(std::vector<std::string>{session_id})
.Then(base::BindOnce(&LogIfTrackerError, "untrack"));
std::vector<base::WeakPtr<DesktopSessionLinux>> sessions_to_terminate;
std::vector<int> ready_terminal_ids;
for (auto& [id, entry] : desktop_sessions_) {
if (!entry.desktop_session) {
continue;
}
if (entry.desktop_session->current_session_id() == session_id) {
sessions_to_terminate.push_back(entry.desktop_session);
} else if (entry.state == SessionState::kTerminatingLocalSession &&
entry.pending_termination_session_id == session_id) {
entry.pending_termination_session_id.clear();
ready_terminal_ids.push_back(id);
}
}
for (auto& session : sessions_to_terminate) {
if (session) {
session->TerminateSession(ErrorCode::SESSION_REJECTED,
"Login session terminated.", FROM_HERE);
}
}
for (int terminal_id : ready_terminal_ids) {
CreateRemoteUserSession(terminal_id);
}
}
void UserDesktopSessionBackend::RemoveDesktopSession(int terminal_id) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
desktop_sessions_.erase(terminal_id);
}
void UserDesktopSessionBackend::TrackCreatedSession(
const LoginSessionManager::SessionInfo& session) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
HOST_LOG << "Recording graphical session " << session.session_id
<< " as created by CRD for user " << session.username << ".";
created_session_tracker_.AsyncCall(&CreatedSessionTracker::Add)
.WithArgs(CreatedSessionTracker::Entry{session.session_id,
session.username, session.uid})
.Then(base::BindOnce(&LogIfTrackerError, "track"));
}
void UserDesktopSessionBackend::OnTrackedSessionsLoaded(
Callback callback,
base::expected<std::vector<CreatedSessionTracker::Entry>, Loggable>
entries) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
DCHECK(login_session_manager_);
if (!entries.has_value()) {
std::move(callback).Run(std::move(entries).error().UnexpectedWithContext(
FROM_HERE, "While loading created sessions"));
return;
}
if (entries->empty()) {
std::move(callback).Run(base::ok());
return;
}
// Look up and terminate all sessions in parallel, so that a slow session
// doesn't hold up the others within the SIGTERM time budget.
auto barrier = base::BarrierCallback<std::optional<std::string>>(
entries->size(),
base::BindOnce(&UserDesktopSessionBackend::OnAllTrackedSessionsHandled,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
for (CreatedSessionTracker::Entry& entry : *entries) {
std::string session_id = entry.session_id;
login_session_manager_->GetSessionInfo(
session_id,
base::BindOnce(&UserDesktopSessionBackend::OnTrackedSessionInfo,
weak_ptr_factory_.GetWeakPtr(), std::move(entry),
barrier));
}
}
void UserDesktopSessionBackend::OnTrackedSessionInfo(
CreatedSessionTracker::Entry entry,
TrackedSessionDoneCallback done,
base::expected<LoginSessionManager::SessionInfo, Loggable> result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!result.has_value()) {
// Note that if the session ends between the two D-Bus calls made by
// GetSessionInfo(), the error is not NoSuchSession, so the entry is kept
// and dropped the next time the host is stopped.
if (IsNoSuchSessionError(result.error().ToString())) {
// The session has already ended.
done.Run(std::move(entry.session_id));
return;
}
LOG(ERROR) << "Failed to look up created session " << entry.session_id
<< ": " << result.error();
done.Run(std::nullopt);
return;
}
if (!ShouldTerminateTrackedSession(entry, *result)) {
LOG(WARNING) << "Not terminating session " << entry.session_id
<< ", since it doesn't match the session that CRD created "
<< "for user " << entry.username << " (UID " << entry.uid
<< "). Found: user " << result->username << " (UID "
<< result->uid << "), class " << result->session_class
<< ", type " << result->session_type << ", "
<< (result->is_remote ? "remote" : "local") << ", state "
<< result->state << ".";
done.Run(std::move(entry.session_id));
return;
}
HOST_LOG << "Terminating graphical session " << entry.session_id
<< " created by CRD for user " << entry.username << ".";
login_session_manager_->TerminateSession(
result->object_path,
base::BindOnce(&UserDesktopSessionBackend::OnTrackedSessionTerminated,
weak_ptr_factory_.GetWeakPtr(),
std::move(entry.session_id), std::move(done)));
}
void UserDesktopSessionBackend::OnTrackedSessionTerminated(
std::string session_id,
TrackedSessionDoneCallback done,
base::expected<void, Loggable> result) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
if (!result.has_value()) {
LOG(ERROR) << "Failed to terminate created session " << session_id << ": "
<< result.error();
done.Run(std::nullopt);
return;
}
done.Run(std::move(session_id));
}
void UserDesktopSessionBackend::OnAllTrackedSessionsHandled(
Callback callback,
std::vector<std::optional<std::string>> removable_session_ids) {
DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
std::vector<std::string> session_ids_to_remove;
size_t failure_count = 0;
for (std::optional<std::string>& session_id : removable_session_ids) {
if (session_id.has_value()) {
session_ids_to_remove.push_back(std::move(*session_id));
} else {
++failure_count;
}
}
base::expected<void, Loggable> termination_result = base::ok();
if (failure_count > 0) {
termination_result = base::unexpected(Loggable(
FROM_HERE,
base::StringPrintf("Failed to terminate %zu created session(s). They "
"will be retried the next time the host is stopped.",
failure_count)));
}
if (session_ids_to_remove.empty()) {
std::move(callback).Run(std::move(termination_result));
return;
}
// Run `callback` only after the tracker has been updated, since the daemon
// process exits right after.
created_session_tracker_.AsyncCall(&CreatedSessionTracker::Remove)
.WithArgs(std::move(session_ids_to_remove))
.Then(base::BindOnce(&UserDesktopSessionBackend::OnTrackedSessionsRemoved,
std::move(callback), std::move(termination_result)));
}
// static
void UserDesktopSessionBackend::OnTrackedSessionsRemoved(
Callback callback,
base::expected<void, Loggable> termination_result,
base::expected<void, Loggable> remove_result) {
if (!remove_result.has_value()) {
std::move(callback).Run(
std::move(remove_result)
.error()
.UnexpectedWithContext(FROM_HERE,
"While untracking terminated sessions"));
return;
}
std::move(callback).Run(std::move(termination_result));
}
} // namespace remoting