diff --git a/CMakeLists.txt b/CMakeLists.txt index 2e73818..48ab406 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -172,6 +172,11 @@ add_subdirectory(data) add_subdirectory(services) add_subdirectory(src) +include(CTest) +if(BUILD_TESTING) + add_subdirectory(tests) +endif() + # Display feature summary feature_summary(WHAT ALL FATAL_ON_MISSING_REQUIRED_PACKAGES) diff --git a/data/dconfig/org.deepin.dde.ddm.json.in b/data/dconfig/org.deepin.dde.ddm.json.in index 8ba8c97..ae256bb 100644 --- a/data/dconfig/org.deepin.dde.ddm.json.in +++ b/data/dconfig/org.deepin.dde.ddm.json.in @@ -168,13 +168,13 @@ "visibility": "private" }, "singleSessionCommand": { - "value": "@WAYLAND_SESSION_COMMAND@", - "serial": 0, + "value": "", + "serial": 1, "flags": [], "name": "Single Session Command", "name[zh_CN]": "单例会话命令", - "description": "Path to a script to execute when starting the Treeland user session.", - "description[zh_CN]": "启动 Treeland 用户会话时执行的脚本路径。", + "description": "Optional additional user-session wrapper after DA prepares the login environment. Empty starts the desktop command directly.", + "description[zh_CN]": "DA 准备登录环境后执行的可选用户会话包装程序。留空时直接启动桌面命令。", "permissions": "readwrite", "visibility": "private" }, diff --git a/debian/control b/debian/control index 1a739d4..c670d42 100644 --- a/debian/control +++ b/debian/control @@ -28,6 +28,7 @@ Depends: ${shlibs:Depends}, ${misc:Depends}, dde-seatd, dde-dconfig-daemon, + deepin-authenticate, treeland, libpam-systemd, Recommends: deepin-keyring-whitebox, diff --git a/services/ddm.service.in b/services/ddm.service.in index af44ae1..5fe4a1a 100644 --- a/services/ddm.service.in +++ b/services/ddm.service.in @@ -2,13 +2,13 @@ Description=Deepin Display Manager Documentation=man:ddm(1) Conflicts=getty@tty${DDM_INITIAL_VT}.service -After=systemd-user-sessions.service getty@tty${DDM_INITIAL_VT}.service plymouth-quit.service systemd-logind.service dde-seatd.service dde-dconfig-daemon.service +After=systemd-user-sessions.service getty@tty${DDM_INITIAL_VT}.service plymouth-quit.service systemd-logind.service dde-seatd.service dde-dconfig-daemon.service deepin-session-service.service PartOf=graphical.target StartLimitIntervalSec=30 StartLimitBurst=2 Requires=dde-seatd.service -Wants=dde-dconfig-daemon.service +Wants=dde-dconfig-daemon.service deepin-session-service.service [Service] ExecStart=@CMAKE_INSTALL_FULL_BINDIR@/ddm diff --git a/src/daemon/Auth.cpp b/src/daemon/Auth.cpp index 238ff49..6ad9fb2 100644 --- a/src/daemon/Auth.cpp +++ b/src/daemon/Auth.cpp @@ -18,6 +18,7 @@ #include #include #include +#include namespace DDM { @@ -76,6 +77,8 @@ namespace DDM { QProcess *helper { nullptr }; // Buffer for streaming replies from the helper. QByteArray recvBuffer; + DASessionClient *da { nullptr }; + bool busy { false }; }; Auth::Auth(QObject *parent, QString user) @@ -84,6 +87,12 @@ namespace DDM { , d(new AuthPrivate(this)) {} Auth::~Auth() { + if (type == Display::Treeland) { + // DASessionClient cancels unfinished attempts and detaches running sessions. + delete d->da; + d->da = nullptr; + return; + } if (sessionOpened) { if (sessionPid > 0) kill(sessionPid, SIGTERM); @@ -220,6 +229,10 @@ namespace DDM { } bool Auth::authenticate(const QByteArray &secret) { + if (type == Display::Treeland) { + qWarning() << "[Auth] Treeland requires asynchronous DA authentication"; + return false; + } Q_ASSERT(!user.isEmpty()); qInfo() << "[Auth] Starting..."; @@ -260,6 +273,10 @@ namespace DDM { QString Auth::openSession(const QString &command, QProcessEnvironment env, const QByteArray &cookie) { + if (type == Display::Treeland) { + qWarning() << "[Auth] Treeland requires asynchronous DA session start"; + return {}; + } Q_ASSERT(authenticated); // Everything the helper needs to run the session comes from the @@ -269,10 +286,6 @@ namespace DDM { QString sessionCommand; QString sessionLogFile; switch (type) { - case Display::Treeland: - sessionCommand = mainConfig()->singleSessionCommand(); - sessionLogFile = mainConfig()->waylandSessionLogFile(); - break; case Display::X11: sessionCommand = mainConfig()->x11SessionCommand(); sessionLogFile = mainConfig()->x11SessionLogFile(); @@ -356,6 +369,8 @@ namespace DDM { } bool Auth::closeSession() { + if (type == Display::Treeland) + return d->da && d->da->stop(); if (!sessionOpened) { qWarning() << "[Auth] closeSession: Session was not opened."; return true; @@ -376,6 +391,132 @@ namespace DDM { qInfo() << "[Auth] Session closed."; return true; } + DASessionClient *Auth::ensureDAClient() + { + if (d->da) + return d->da; + d->da = new DASessionClient(this); + connect(d->da, &DASessionClient::authenticationFinished, this, [this](bool success) { + sessionId = d->da->sessionId(); + authenticated = success; + Q_EMIT authenticationFinished(success); + }); + connect(d->da, &DASessionClient::sessionStarted, this, [this] { + const auto info = d->da->info(); + xdgSessionId = info.logindSessionId; + sessionPid = info.pid; + sessionOpened = true; + Q_EMIT sessionStarted(); + }); + connect(d->da, &DASessionClient::sessionStartFailed, this, [this] { + authenticated = false; + Q_EMIT sessionStartFailed(); + }); + connect(d->da, &DASessionClient::sessionFinished, this, [this] { + sessionOpened = false; + authenticated = false; + Q_EMIT sessionFinished(); + }); + connect(d->da, &DASessionClient::informationMessage, this, &Auth::informationMessage); + return d->da; + } + + bool Auth::isBusy() const + { + return d->busy || (d->da && d->da->isBusy()); + } + + void Auth::authenticateAsync(const QByteArray &secret) + { + if (isBusy() || authenticated || sessionOpened || d->da) + return; + if (type == Display::Treeland) { + ensureDAClient()->authenticate(user, pamService == QLatin1String("ddm-autologin") + ? QStringLiteral("autologin") : QStringLiteral("login"), + seat, tty > 0 ? static_cast(tty) : 0, secret); + return; + } + d->busy = true; + QTimer::singleShot(0, this, [this, secret] { + const bool success = authenticate(secret); + d->busy = false; + Q_EMIT authenticationFinished(success); + }); + } + + void Auth::openSessionAsync(const QString &command, QProcessEnvironment env, const QByteArray &cookie) + { + if (isBusy() || !authenticated || sessionOpened) + return; + if (type != Display::Treeland) { + d->busy = true; + QTimer::singleShot(0, this, [this, command, env, cookie] { + const bool success = !openSession(command, env, cookie).isEmpty(); + d->busy = false; + if (success) + Q_EMIT sessionStarted(); + else + Q_EMIT sessionStartFailed(); + }); + return; + } + if (!d->da) + return; + if (!daemonApp->seatdControl()->requestSwitchVt(tty)) { + d->da->cancel(); + authenticated = false; + Q_EMIT sessionStartFailed(); + return; + } + QStringList argv; + const QString wrapper = mainConfig()->singleSessionCommand(); + if (wrapper.isEmpty()) { + argv = QProcess::splitCommand(command); + } else { + argv = QProcess::splitCommand(wrapper); + argv.append(command); + } + DAEnvironment environment; + for (const auto &key : env.keys()) { + if (!DASessionClient::reservedEnvironmentKey(key)) + environment.insert(key, env.value(key)); + } + QStringList namespaces; + const auto configured = mainConfig()->namespaces(); + namespaces.reserve(configured.size()); + for (const QVariant &path : configured) + namespaces.append(path.toString()); + d->da->start(argv, environment, namespaces, mainConfig()->waylandSessionLogFile()); + } + + QList Auth::managedSessions(const QString &seat) + { + return DASessionClient::managedSessions(seat); + } + + bool Auth::adoptManagedSession(const ManagedSessionInfo &info) + { + if (isBusy() || authenticated || sessionOpened || d->da) + return false; + if (!ensureDAClient()->adopt(info)) + return false; + type = Display::Treeland; + seat = info.seat; + user = info.user; + tty = static_cast(info.vt); + sessionId = d->da->sessionId(); + xdgSessionId = info.logindSessionId; + sessionPid = info.pid; + authenticated = true; + sessionOpened = true; + return true; + } + + QString Auth::managedSessionPath() const + { + return d->da ? d->da->objectPath() : QString(); + } + } // namespace DDM #include "Auth.moc" diff --git a/src/daemon/Auth.h b/src/daemon/Auth.h index 8bb115e..49f25ef 100644 --- a/src/daemon/Auth.h +++ b/src/daemon/Auth.h @@ -5,6 +5,7 @@ #define DDM_AUTH_H #include "Display.h" +#include "DASessionClient.h" #include #include @@ -43,6 +44,9 @@ namespace DDM { /** X Display identifier (e.g. :0), if presents */ QString display{}; + /** Seat bound to the DA login object. */ + QString seat{}; + /** Virtual terminal number (e.g. 7 for tty7) */ int tty{ 0 }; @@ -52,7 +56,16 @@ namespace DDM { /** PID of the session process started by session helper. Positive values are valid */ qint64 sessionPid{ 0 }; + bool isBusy() const; + static QList managedSessions(const QString &seat); + bool adoptManagedSession(const ManagedSessionInfo &info); + QString managedSessionPath() const; + public Q_SLOTS: + void authenticateAsync(const QByteArray &secret); + void openSessionAsync(const QString &command, QProcessEnvironment env, + const QByteArray &cookie = QByteArray()); + /** * Sets up the environment and starts the authentication. * @@ -81,12 +94,19 @@ namespace DDM { bool closeSession(); Q_SIGNALS: + void authenticationFinished(bool success); + void sessionStarted(); + void sessionStartFailed(); + void informationMessage(const QString &message); + /** * Emitted when the session process ends. */ void sessionFinished(); private: + DASessionClient *ensureDAClient(); + /** Ensure the session helper is spawned and connected. */ bool ensureHelper(); diff --git a/src/daemon/CMakeLists.txt b/src/daemon/CMakeLists.txt index 2726f79..66deabe 100644 --- a/src/daemon/CMakeLists.txt +++ b/src/daemon/CMakeLists.txt @@ -29,6 +29,7 @@ dtk_add_config_to_cpp(DDM_CONFIG_HEADER set(DAEMON_SOURCES Auth.cpp + DASessionClient.cpp Configuration.cpp DaemonApp.cpp DdeSeatdControl.cpp diff --git a/src/daemon/DASessionClient.cpp b/src/daemon/DASessionClient.cpp new file mode 100644 index 0000000..3a48ac1 --- /dev/null +++ b/src/daemon/DASessionClient.cpp @@ -0,0 +1,755 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "DASessionClient.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace DDM { +namespace { +const QString service = QStringLiteral("org.deepin.dde.Authenticate1.LoginManager"); +const QString root = QStringLiteral("/org/deepin/dde/Authenticate1/LoginManager"); +const QString sessionInterface = service + QStringLiteral(".Session"); +constexpr int callTimeout = 15000; +constexpr int operationTimeout = 120000; + +QDBusMessage message(const QString &path, const QString &method, const QVariantList &arguments = {}) +{ + auto result = QDBusMessage::createMethodCall(service, path, path == root ? service : sessionInterface, method); + result.setArguments(arguments); + return result; +} + +bool validText(const QString &text, int maximum, bool empty = true) +{ + return (empty || !text.isEmpty()) && !text.contains(QChar::Null) + && text.toUtf8().size() <= maximum; +} + +bool validSeat(const QString &seat) +{ + static const QRegularExpression expression(QStringLiteral("\\Aseat[A-Za-z0-9_-]{1,60}\\z")); + return expression.match(seat).hasMatch(); +} + +// A regular anonymous file cannot block a PAM worker waiting for EOF, unlike a pipe. +QDBusUnixFileDescriptor credentialFD(const QByteArray &secret) +{ + if (secret.size() > 1024) + return {}; + QTemporaryFile file; + if (!file.open() || ::unlink(file.fileName().toLocal8Bit().constData()) != 0) + return {}; + const quint32 length = qToLittleEndian(static_cast(secret.size())); + if (file.write(reinterpret_cast(&length), sizeof(length)) != sizeof(length) + || file.write(secret) != secret.size() || !file.flush() || !file.seek(0)) + return {}; + return QDBusUnixFileDescriptor(file.handle()); // Qt duplicates; file closes its original. +} + +bool terminal(const QString &state) +{ + return state == QLatin1String("finished") || state == QLatin1String("failed") + || state == QLatin1String("cancelled"); +} +} + +DASessionClient::DASessionClient(QObject *parent) + : DASessionClient(QDBusConnection::systemBus(), parent) +{ +} + +DASessionClient::DASessionClient(const QDBusConnection &connection, QObject *parent) + : QObject(parent), m_bus(connection), + m_serviceWatcher(new QDBusServiceWatcher(service, m_bus, QDBusServiceWatcher::WatchForOwnerChange, this)) +{ + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); + qDBusRegisterMetaType>(); + m_deadline.setSingleShot(true); + connect(&m_deadline, &QTimer::timeout, this, [this] { fail(QStringLiteral("DA operation timed out")); }); + connect(m_serviceWatcher, &QDBusServiceWatcher::serviceOwnerChanged, this, &DASessionClient::ownerChanged); +} + +DASessionClient::~DASessionClient() +{ + // DDM restart must leave DA-owned running sessions alive. + if (m_phase == Phase::Starting) { + // Destruction never Stops a session that may already have launched. + if (!m_receiptPending && m_info.state != QLatin1String("running") + && m_info.state != QLatin1String("stopping") && m_connected) + m_bus.asyncCall(message(m_info.objectPath, QStringLiteral("Cancel")), callTimeout); + ++m_generation; + } else if (m_phase != Phase::Running && m_phase != Phase::Stopping && m_phase != Phase::Aborting) { + cancel(); + } + unbind(); + clearSecret(); +} + +bool DASessionClient::isBusy() const +{ + return m_phase == Phase::Creating || m_phase == Phase::Authenticating || m_phase == Phase::Starting; +} + +QString DASessionClient::stableSessionId(const QString &path) +{ + static const QRegularExpression expression( + QStringLiteral("\\A/org/deepin/dde/Authenticate1/LoginManager/Session_([0-9a-f]{32})\\z")); + const auto match = expression.match(path); + return match.hasMatch() ? QStringLiteral("Session") + match.captured(1) : QString(); +} + +QString DASessionClient::sessionId() const +{ + return stableSessionId(m_info.objectPath); +} + +void DASessionClient::clearSecret() +{ + // Wipe the owned copy; never modify the greeter's QByteArray. + if (!m_secret.isEmpty()) { + volatile char *bytes = m_secret.data(); + for (qsizetype i = 0; i < m_secret.size(); ++i) + bytes[i] = 0; + } + m_secret.clear(); +} + +void DASessionClient::call(const QString &method, const QVariantList &arguments, + std::function completion) +{ + const auto generation = m_generation; + auto watcher = new QDBusPendingCallWatcher(m_bus.asyncCall(message(m_info.objectPath, method, arguments), callTimeout), this); + connect(watcher, &QDBusPendingCallWatcher::finished, this, + [this, generation, completion = std::move(completion)](QDBusPendingCallWatcher *watcher) { + const auto reply = watcher->reply(); + watcher->deleteLater(); + if (generation == m_generation) + completion(reply); + }); +} + +bool DASessionClient::bind() +{ + if (m_bound) + return true; + const auto &path = m_info.objectPath; + bool ok = m_bus.connect(service, path, sessionInterface, QStringLiteral("Prompt"), this, SLOT(prompt(quint32,int,QString))); + ok = m_bus.connect(service, path, sessionInterface, QStringLiteral("StateChanged"), this, SLOT(stateChanged(QString))) && ok; + ok = m_bus.connect(service, path, sessionInterface, QStringLiteral("Started"), this, SLOT(started(QString,quint32))) && ok; + ok = m_bus.connect(service, path, sessionInterface, QStringLiteral("Finished"), this, SLOT(finished(int,int))) && ok; + ok = m_bus.connect(service, path, sessionInterface, QStringLiteral("Failed"), this, SLOT(failed(QString,int,QString))) && ok; + m_bound = true; // Also clean partial subscriptions if binding failed. + if (!ok) + unbind(); + return ok; +} + +void DASessionClient::unbind() +{ + if (!m_bound) + return; + m_bus.disconnect(service, m_info.objectPath, sessionInterface, QStringLiteral("Prompt"), this, SLOT(prompt(quint32,int,QString))); + m_bus.disconnect(service, m_info.objectPath, sessionInterface, QStringLiteral("StateChanged"), this, SLOT(stateChanged(QString))); + m_bus.disconnect(service, m_info.objectPath, sessionInterface, QStringLiteral("Started"), this, SLOT(started(QString,quint32))); + m_bus.disconnect(service, m_info.objectPath, sessionInterface, QStringLiteral("Finished"), this, SLOT(finished(int,int))); + m_bus.disconnect(service, m_info.objectPath, sessionInterface, QStringLiteral("Failed"), this, SLOT(failed(QString,int,QString))); + m_bound = false; +} + +void DASessionClient::authenticate(const QString &user, const QString &profile, const QString &seat, + quint32 vt, const QByteArray &secret) +{ + if (m_phase != Phase::Idle) + return; + m_phase = Phase::Creating; + m_info.user = user; + m_info.seat = seat; + m_info.vt = vt; + m_profile = profile; + if (!validText(user, 256, false) || !validSeat(seat) || vt == 0 || vt > 65535 + || (profile != QLatin1String("login") && profile != QLatin1String("autologin")) + || secret.size() > 1024 || !m_bus.isConnected() + || !(m_bus.connectionCapabilities() & QDBusConnection::UnixFileDescriptorPassing)) { + fail(QStringLiteral("Invalid DA login context or unavailable bus")); + return; + } + m_secret = QByteArray(secret.constData(), secret.size()); + m_deadline.start(operationTimeout); + const auto generation = ++m_generation; + QPointer self(this); + const auto bus = m_bus; + // Creation can outlive the Auth object: cancel the returned attempt even then. + auto watcher = new QDBusPendingCallWatcher(m_bus.asyncCall(message(root, QStringLiteral("CreateLogin"), + {user, profile, seat, vt}), callTimeout), QCoreApplication::instance()); + connect(watcher, &QDBusPendingCallWatcher::finished, watcher, + [self, bus, generation](QDBusPendingCallWatcher *watcher) { + QDBusPendingReply reply = *watcher; + watcher->deleteLater(); + if (!self || self->m_generation != generation) { + if (!reply.isError() && !stableSessionId(reply.value().path()).isEmpty()) + bus.asyncCall(message(reply.value().path(), QStringLiteral("Cancel")), callTimeout); + return; + } + if (reply.isError() || stableSessionId(reply.value().path()).isEmpty()) { + self->fail(QStringLiteral("DA CreateLogin failed")); + return; + } + self->m_info.objectPath = reply.value().path(); + if (!self->bind()) { + self->fail(QStringLiteral("DA signal subscription failed")); + return; + } + self->m_phase = Phase::Authenticating; + self->call(QStringLiteral("Authenticate"), {}, [self](const QDBusMessage &reply) { + if (self && reply.type() == QDBusMessage::ErrorMessage && self->m_phase == Phase::Authenticating) + self->fail(QStringLiteral("DA Authenticate failed")); + }); + }); +} + +void DASessionClient::prompt(quint32 id, int style, const QString &text) +{ + if (m_phase == Phase::Terminal || !m_connected) + return; + if (!validText(text, 65536) || style < 1 || style > 4) { + fail(QStringLiteral("Invalid DA prompt")); + return; + } + if (style >= 3) { + if (id != 0) { + fail(QStringLiteral("Invalid informational prompt")); + return; + } + Q_EMIT informationMessage(text); + return; + } + if ((m_phase != Phase::Authenticating && m_phase != Phase::Starting) || id == 0 || id <= m_lastPrompt) { + fail(QStringLiteral("Out-of-order DA prompt")); + return; + } + m_lastPrompt = id; + const auto fd = credentialFD(style == 1 ? m_secret : m_info.user.toUtf8()); + if (!fd.isValid()) { + fail(QStringLiteral("Cannot frame DA credential")); + return; + } + call(QStringLiteral("Respond"), {id, QVariant::fromValue(fd)}, [this](const QDBusMessage &reply) { + if (reply.type() == QDBusMessage::ErrorMessage && isBusy()) + fail(QStringLiteral("DA Respond failed")); + }); +} + +void DASessionClient::stateChanged(const QString &state) +{ + if (!m_connected || m_phase == Phase::Terminal) + return; + if (m_phase == Phase::Aborting) { + if (state == QLatin1String("running") || state == QLatin1String("stopping")) { + m_info.state = state; + requestAbort(); + } + if (state == QLatin1String("cancelled")) + finishAbort(); + return; // Finished/Failed carry the real terminal receipt; no timeout can invent it. + } + if (state == QLatin1String("failed")) { + // Failed follows StateChanged on the same bus sender; preserve its PAM detail. + QTimer::singleShot(0, this, [this] { + if (m_phase != Phase::Terminal) + fail(QStringLiteral("DA session failed")); + }); + return; + } + if (state == QLatin1String("cancelled")) { + fail(QStringLiteral("DA session cancelled")); + return; + } + if (state == QLatin1String("finished")) { + if (m_receiptPending) + m_finishPending = true; + else if (m_phase == Phase::Running || m_phase == Phase::Stopping) + finish(); + else + fail(QStringLiteral("DA finished before starting")); + return; + } + static const QStringList states = {QStringLiteral("ready"), QStringLiteral("authenticating"), + QStringLiteral("authenticated"), QStringLiteral("starting"), QStringLiteral("running"), QStringLiteral("stopping")}; + const int incoming = states.indexOf(state); + const int current = m_phase == Phase::Authenticating ? 1 : m_phase == Phase::Authenticated ? 2 + : m_phase == Phase::Starting ? 3 : m_phase == Phase::Running ? 4 : m_phase == Phase::Stopping ? 5 : -1; + if (incoming < 0 || current < 0) { + fail(QStringLiteral("Invalid DA state")); + return; + } + if (incoming <= current) + return; // Delayed worker states may trail the local method reservation. + if (incoming == 2 && m_phase == Phase::Authenticating) { + m_phase = Phase::Authenticated; + m_info.state = state; + Q_EMIT authenticationFinished(true); + } else if (incoming == 4 && m_phase == Phase::Starting) { + m_info.state = state; // Started plus verified GetInfo is the completion receipt. + } else if (incoming == 5 && (m_phase == Phase::Running + || (m_phase == Phase::Starting && m_info.state == QLatin1String("running")))) { + if (m_phase == Phase::Running) + m_phase = Phase::Stopping; + m_info.state = state; + } else { + fail(QStringLiteral("Out-of-order DA state")); + } +} + +bool DASessionClient::reservedEnvironmentKey(const QString &key) +{ + static const QStringList reserved = { + QStringLiteral("HOME"), QStringLiteral("USER"), QStringLiteral("LOGNAME"), QStringLiteral("SHELL"), + QStringLiteral("PWD"), QStringLiteral("XDG_SESSION_ID"), QStringLiteral("XDG_RUNTIME_DIR"), + QStringLiteral("DBUS_SESSION_BUS_ADDRESS"), QStringLiteral("DEEPIN_SESSION_USER_SHELL"), + QStringLiteral("BASH_ENV"), QStringLiteral("ENV"), QStringLiteral("IFS"), QStringLiteral("SHELLOPTS"), + QStringLiteral("BASHOPTS"), QStringLiteral("CDPATH"), QStringLiteral("GLOBIGNORE"), + QStringLiteral("PYTHONPATH"), QStringLiteral("PYTHONHOME"), QStringLiteral("PYTHONSTARTUP"), + QStringLiteral("PERL5LIB"), QStringLiteral("PERLLIB"), QStringLiteral("PERL5OPT"), QStringLiteral("RUBYLIB"), + QStringLiteral("RUBYOPT"), QStringLiteral("NODE_OPTIONS"), QStringLiteral("NODE_PATH"), + QStringLiteral("GCONV_PATH"), QStringLiteral("LOCPATH"), QStringLiteral("GLIBC_TUNABLES"), + QStringLiteral("GETCONF_DIR"), QStringLiteral("NLSPATH"), QStringLiteral("JAVA_TOOL_OPTIONS"), + QStringLiteral("_JAVA_OPTIONS"), QStringLiteral("JDK_JAVA_OPTIONS"), QStringLiteral("GIO_EXTRA_MODULES"), + QStringLiteral("GTK_PATH"), QStringLiteral("QT_PLUGIN_PATH"), QStringLiteral("QT_QPA_PLATFORM_PLUGIN_PATH"), + QStringLiteral("SYSTEMD_BUS_TIMEOUT"), QStringLiteral("SYSTEMD_LOG_TARGET") + }; + return key.startsWith(QLatin1String("LD_")) || key.startsWith(QLatin1String("DYLD_")) || reserved.contains(key); +} + +void DASessionClient::start(const QStringList &argv, const DAEnvironment &environment, + const QStringList &namespacePaths, const QString &logFile) +{ + if (m_phase != Phase::Authenticated) + return; + m_phase = Phase::Starting; + if (argv.isEmpty() || !argv.first().startsWith(QLatin1Char('/')) || argv.first() == QLatin1String("/") + || argv.size() > 128 || namespacePaths.size() > 16 || environment.size() > 128) { + fail(QStringLiteral("Invalid DA start payload")); + return; + } + for (const auto &arg : argv) { + if (!validText(arg, 4096)) { + fail(QStringLiteral("Invalid DA argument")); + return; + } + } + static const QRegularExpression envKey(QStringLiteral("\\A[A-Za-z_][A-Za-z0-9_]{0,255}\\z")); + for (auto it = environment.cbegin(); it != environment.cend(); ++it) { + if (!envKey.match(it.key()).hasMatch() || reservedEnvironmentKey(it.key()) || !validText(it.value(), 4096)) { + fail(QStringLiteral("Invalid DA environment")); + return; + } + } + DANamespaces namespaces; + namespaces.reserve(namespacePaths.size()); + for (const auto &path : namespacePaths) { + if (!validText(path, 4095, false)) { + fail(QStringLiteral("Invalid configured namespace path")); + return; + } + const int fd = ::open(path.toLocal8Bit().constData(), O_RDONLY | O_CLOEXEC); + if (fd < 0) { + fail(QStringLiteral("Cannot open configured namespace")); + return; + } + namespaces.append(QDBusUnixFileDescriptor(fd)); + ::close(fd); + } + m_startSubmitted = true; + call(QStringLiteral("Start"), {argv, QVariant::fromValue(environment), QVariant::fromValue(namespaces), logFile}, + [this](const QDBusMessage &reply) { + if (reply.type() == QDBusMessage::ErrorMessage && m_phase == Phase::Starting) + fail(QStringLiteral("DA Start failed")); + }); +} + +bool DASessionClient::decodeInfo(const QString &path, const QVariantMap &values, ManagedSessionInfo &info, bool runningOnly) +{ + const auto string = [&values](const char *key) { return values.value(QLatin1String(key)).metaType().id() == QMetaType::QString; }; + for (const char *key : {"User", "Profile", "Seat", "State", "LogindSessionID", "Error"}) { + if (!string(key)) + return false; + } + if (values.value(QStringLiteral("VT")).metaType().id() != QMetaType::UInt + || values.value(QStringLiteral("PID")).metaType().id() != QMetaType::UInt + || values.value(QStringLiteral("ExitCode")).metaType().id() != QMetaType::Int + || values.value(QStringLiteral("ExitSignal")).metaType().id() != QMetaType::Int) + return false; + info = {path, values.value(QStringLiteral("User")).toString(), values.value(QStringLiteral("Seat")).toString(), + values.value(QStringLiteral("LogindSessionID")).toString(), values.value(QStringLiteral("State")).toString(), + values.value(QStringLiteral("VT")).toUInt(), values.value(QStringLiteral("PID")).toUInt()}; + const auto profile = values.value(QStringLiteral("Profile")).toString(); + const int exitCode = values.value(QStringLiteral("ExitCode")).toInt(); + const int exitSignal = values.value(QStringLiteral("ExitSignal")).toInt(); + const bool running = info.state == QLatin1String("running") || info.state == QLatin1String("stopping"); + return !stableSessionId(path).isEmpty() && validText(info.user, 256, false) && validSeat(info.seat) + && info.vt > 0 && info.vt <= 65535 && (profile == QLatin1String("login") || profile == QLatin1String("autologin")) + && (running || (!runningOnly && terminal(info.state))) + && validText(info.logindSessionId, 65536, !running) && (!running || info.pid > 0) + && exitCode >= 0 && exitCode <= 255 && exitSignal >= 0 && exitSignal <= 64 + && validText(values.value(QStringLiteral("Error")).toString(), 65536); +} + +bool DASessionClient::matches(const ManagedSessionInfo &info) const +{ + return info.objectPath == m_info.objectPath && info.user == m_info.user && info.seat == m_info.seat && info.vt == m_info.vt; +} + +void DASessionClient::started(const QString &id, quint32 pid) +{ + if (!m_connected || m_phase == Phase::Terminal) + return; + if (m_phase == Phase::Aborting) { + if (validText(id, 65536, false) && pid > 0 && m_info.logindSessionId.isEmpty()) { + m_info.logindSessionId = id; + m_info.pid = pid; + m_info.state = QStringLiteral("running"); + requestAbort(); + } + return; + } + if (m_phase != Phase::Starting || m_receiptPending || !validText(id, 65536, false) || pid == 0) { + fail(QStringLiteral("Invalid DA Started receipt")); + return; + } + m_receiptPending = true; + m_info.logindSessionId = id; + m_info.pid = pid; + readReceipt(id, pid); +} + +void DASessionClient::readReceipt(const QString &id, quint32 pid) +{ + call(QStringLiteral("GetInfo"), {}, [this, id, pid](const QDBusMessage &message) { + QDBusPendingReply reply = QDBusPendingCall::fromCompletedCall(message); + ManagedSessionInfo info; + if (reply.isError() || !decodeInfo(m_info.objectPath, reply.value(), info, false) || !matches(info) + || info.logindSessionId != id || info.pid != pid + || reply.value().value(QStringLiteral("Profile")).toString() != m_profile) { + fail(QStringLiteral("DA runtime metadata disagrees with Started")); + return; + } + m_info = info; + m_receiptPending = false; + m_phase = info.state == QLatin1String("stopping") ? Phase::Stopping : Phase::Running; + m_deadline.stop(); + clearSecret(); + const bool ended = m_finishPending || terminal(info.state); + QPointer self(this); + Q_EMIT sessionStarted(); + if (self && ended) + finish(); + }); +} + +void DASessionClient::finished(int exitCode, int exitSignal) +{ + if (!m_connected || m_phase == Phase::Terminal) + return; + if (exitCode < 0 || exitCode > 255 || exitSignal < 0 || exitSignal > 64) { + fail(QStringLiteral("Invalid DA exit status")); + return; + } + m_terminalReceipt = true; + if (m_phase == Phase::Aborting) { + finishAbort(); + return; + } + if (m_receiptPending) + m_finishPending = true; + else if (m_phase == Phase::Running || m_phase == Phase::Stopping) + finish(); + else + fail(QStringLiteral("Out-of-order DA Finished")); +} + +void DASessionClient::failed(const QString &phase, int code, const QString &text) +{ + Q_UNUSED(code) + if (!m_connected || m_phase == Phase::Terminal) + return; + static const QStringList phases = {QStringLiteral("init"), QStringLiteral("authenticate"), QStringLiteral("account"), + QStringLiteral("credentials"), QStringLiteral("open"), QStringLiteral("start"), QStringLiteral("cleanup"), QStringLiteral("protocol")}; + if ((m_phase == Phase::Starting || m_phase == Phase::Running || m_phase == Phase::Stopping) + && phases.contains(phase) && validText(text, 65536)) + m_terminalReceipt = true; + if (m_phase == Phase::Aborting) { + if (phases.contains(phase) && validText(text, 65536)) + finishAbort(); + else + Q_EMIT informationMessage(QStringLiteral("Invalid DA terminal failure")); + return; + } + fail(phases.contains(phase) && validText(text, 65536) ? text : QStringLiteral("Invalid DA failure")); +} + +void DASessionClient::fail(const QString &text) +{ + if (m_phase == Phase::Idle || m_phase == Phase::Terminal) + return; + if (m_phase == Phase::Aborting) { + Q_EMIT informationMessage(text); + return; + } + if (m_phase == Phase::Starting && m_startSubmitted) { + abortStart(text); + return; + } + if (m_phase == Phase::Running || m_phase == Phase::Stopping) { + QPointer self(this); + Q_EMIT informationMessage(text); + // A transport/protocol error is not proof that PAM and the desktop + // have stopped. Keep the registered session/VT until a real receipt. + if (self && m_terminalReceipt) + finish(); + return; + } + const auto previous = m_phase; + cancel(); + QPointer self(this); + Q_EMIT informationMessage(text); + if (!self) + return; + if (previous == Phase::Creating || previous == Phase::Authenticating) + Q_EMIT authenticationFinished(false); + else if (previous == Phase::Starting || previous == Phase::Authenticated) + Q_EMIT sessionStartFailed(); + else + Q_EMIT sessionFinished(); +} + +void DASessionClient::abortStart(const QString &text) +{ + m_phase = Phase::Aborting; + ++m_generation; + m_receiptPending = false; + m_finishPending = false; + m_deadline.stop(); + clearSecret(); + if (!m_connected) + unbind(); + QPointer self(this); + Q_EMIT informationMessage(text); + if (!self) + return; + if (m_terminalReceipt) + finishAbort(); + else if (m_connected) + requestAbort(); +} + +void DASessionClient::requestAbort() +{ + const bool stopping = !m_info.logindSessionId.isEmpty() || m_info.state == QLatin1String("running") + || m_info.state == QLatin1String("stopping"); + if (stopping && m_stopRequested) + return; + if (stopping) + m_stopRequested = true; + call(stopping ? QStringLiteral("Stop") : QStringLiteral("Cancel"), {}, [this, stopping](const QDBusMessage &reply) { + if (reply.type() != QDBusMessage::ErrorMessage || m_phase != Phase::Aborting) + return; + QPointer self(this); + Q_EMIT informationMessage(QStringLiteral("DA cleanup transport failed; retaining session ownership until recovery")); + // Cancel may race the accepted Start. GetInfo, not a guessed PID, proves whether Stop applies. + if (self && !stopping && m_connected) + reconnect(); + }); +} + +void DASessionClient::finishAbort() +{ + if (m_phase != Phase::Aborting) + return; + m_phase = Phase::Terminal; + ++m_generation; + m_deadline.stop(); + clearSecret(); + unbind(); + Q_EMIT sessionStartFailed(); +} + +void DASessionClient::cancel() +{ + if (m_phase == Phase::Idle || m_phase == Phase::Terminal) + return; + if (m_phase == Phase::Aborting) + return; + if (m_phase == Phase::Starting && m_startSubmitted) { + abortStart(QStringLiteral("DA login cancelled after session launch")); + return; + } + const bool running = m_phase == Phase::Running || m_phase == Phase::Stopping || m_receiptPending; + ++m_generation; + m_deadline.stop(); + clearSecret(); + if (!m_info.objectPath.isEmpty() && m_connected) + m_bus.asyncCall(message(m_info.objectPath, running ? QStringLiteral("Stop") : QStringLiteral("Cancel")), callTimeout); + m_phase = Phase::Terminal; + unbind(); +} + +bool DASessionClient::stop() +{ + if (m_phase == Phase::Stopping) + return true; + if (m_phase != Phase::Running || !m_connected) + return false; + m_phase = Phase::Stopping; + call(QStringLiteral("Stop"), {}, [this](const QDBusMessage &reply) { + if (reply.type() == QDBusMessage::ErrorMessage && m_phase == Phase::Stopping) { + m_phase = Phase::Running; + Q_EMIT informationMessage(QStringLiteral("DA Stop failed")); + } + }); + return true; +} + +void DASessionClient::finish() +{ + if (m_phase == Phase::Terminal) + return; + m_phase = Phase::Terminal; + ++m_generation; + m_deadline.stop(); + clearSecret(); + unbind(); + Q_EMIT sessionFinished(); +} + +void DASessionClient::ownerChanged(const QString &, const QString &oldOwner, const QString &newOwner) +{ + if (!oldOwner.isEmpty()) { + m_connected = false; + if (m_phase == Phase::Running || m_phase == Phase::Stopping || m_phase == Phase::Aborting) { + ++m_generation; + m_stopRequested = false; + unbind(); + } else if (m_phase != Phase::Idle && m_phase != Phase::Terminal) { + fail(QStringLiteral("DA service disconnected during login")); + } + } + if (!newOwner.isEmpty()) { + m_connected = true; + if (m_phase == Phase::Running || m_phase == Phase::Stopping || m_phase == Phase::Aborting) + reconnect(); + } +} + +void DASessionClient::reconnect() +{ + if (!bind()) { + Q_EMIT informationMessage(QStringLiteral("Cannot rebind DA monitor; retaining session ownership")); + return; + } + call(QStringLiteral("GetInfo"), {}, [this](const QDBusMessage &message) { + QDBusPendingReply reply = QDBusPendingCall::fromCompletedCall(message); + ManagedSessionInfo info; + if (m_phase == Phase::Aborting) { + if (reply.isError()) { + if (reply.error().type() == QDBusError::UnknownObject) + finishAbort(); + else + Q_EMIT informationMessage(QStringLiteral("Cannot recover DA cleanup metadata")); + return; + } + if (!decodeInfo(m_info.objectPath, reply.value(), info, false) || !matches(info) + || (!m_info.logindSessionId.isEmpty() && (info.logindSessionId != m_info.logindSessionId + || info.pid != m_info.pid))) { + Q_EMIT informationMessage(QStringLiteral("DA cleanup metadata disagrees with retained receipt")); + return; + } + if (terminal(info.state)) + finishAbort(); + else { + m_info = info; + requestAbort(); + } + return; + } + if (reply.isError()) { + if (reply.error().type() == QDBusError::UnknownObject) + finish(); + else + Q_EMIT informationMessage(QStringLiteral("Cannot recover DA metadata; retaining session ownership")); + return; + } + if (!decodeInfo(m_info.objectPath, reply.value(), info, false) || !matches(info) + || info.logindSessionId != m_info.logindSessionId || info.pid != m_info.pid) { + Q_EMIT informationMessage(QStringLiteral("Recovered DA metadata disagrees with the live session")); + return; + } + if (terminal(info.state)) { + finish(); + return; + } + m_info = info; + m_phase = info.state == QLatin1String("stopping") ? Phase::Stopping : Phase::Running; + }); +} + +QList DASessionClient::managedSessions(const QString &seat, const QDBusConnection &connection) +{ + qDBusRegisterMetaType>(); + QList sessions; + if (!validSeat(seat) || !connection.isConnected()) + return sessions; + QElapsedTimer budget; + budget.start(); + QDBusReply> list(connection.call(message(root, QStringLiteral("ListSessions")), QDBus::Block, 1000)); + if (!list.isValid() || list.value().size() > 128) + return sessions; + for (const auto &path : list.value()) { + const auto remaining = 3000 - budget.elapsed(); + if (remaining <= 0) + break; + if (stableSessionId(path.path()).isEmpty()) + continue; + QDBusReply reply(connection.call(message(path.path(), QStringLiteral("GetInfo")), QDBus::Block, + static_cast(qMin(1000, remaining)))); + ManagedSessionInfo info; + if (reply.isValid() && decodeInfo(path.path(), reply.value(), info, true) && info.seat == seat) + sessions.append(info); + } + return sessions; +} + +bool DASessionClient::adopt(const ManagedSessionInfo &info) +{ + if (m_phase != Phase::Idle || stableSessionId(info.objectPath).isEmpty() || !validText(info.user, 256, false) + || !validSeat(info.seat) || info.vt == 0 || info.vt > 65535 || info.pid <= 0 + || info.pid > std::numeric_limits::max() || !validText(info.logindSessionId, 65536, false) + || (info.state != QLatin1String("running") && info.state != QLatin1String("stopping"))) + return false; + m_info = info; + m_phase = info.state == QLatin1String("stopping") ? Phase::Stopping : Phase::Running; + if (!bind()) { + m_phase = Phase::Idle; + m_info = {}; + return false; + } + // Revalidate after subscribing, closing the ListSessions/GetInfo-to-bind race. + reconnect(); + return true; +} +} diff --git a/src/daemon/DASessionClient.h b/src/daemon/DASessionClient.h new file mode 100644 index 0000000..9302536 --- /dev/null +++ b/src/daemon/DASessionClient.h @@ -0,0 +1,108 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: GPL-2.0-or-later + +#ifndef DDM_DASESSIONCLIENT_H +#define DDM_DASESSIONCLIENT_H + +#include +#include +#include +#include +#include +#include +#include +#include + +class QDBusServiceWatcher; + +namespace DDM { + +struct ManagedSessionInfo { + QString objectPath, user, seat, logindSessionId, state; + quint32 vt = 0; + qint64 pid = 0; +}; + +using DAEnvironment = QMap; +using DANamespaces = QList; + +// The only production transport is the system bus. Injection is for isolated bus tests. +class DASessionClient : public QObject { + Q_OBJECT +public: + explicit DASessionClient(QObject *parent = nullptr); + explicit DASessionClient(const QDBusConnection &connection, QObject *parent = nullptr); + ~DASessionClient() override; + + void authenticate(const QString &user, const QString &profile, const QString &seat, + quint32 vt, const QByteArray &secret); + void start(const QStringList &argv, const DAEnvironment &environment, + const QStringList &namespacePaths, const QString &logFile); + void cancel(); + bool stop(); + bool isBusy() const; + QString objectPath() const { return m_info.objectPath; } + QString sessionId() const; + ManagedSessionInfo info() const { return m_info; } + bool adopt(const ManagedSessionInfo &info); + static QList managedSessions(const QString &seat, + const QDBusConnection &connection = QDBusConnection::systemBus()); + static QString stableSessionId(const QString &objectPath); + static bool reservedEnvironmentKey(const QString &key); + +Q_SIGNALS: + void authenticationFinished(bool success); + void sessionStarted(); + void sessionStartFailed(); + void sessionFinished(); + void informationMessage(const QString &message); + +private Q_SLOTS: + void prompt(quint32 id, int style, const QString &message); + void stateChanged(const QString &state); + void started(const QString &id, quint32 pid); + void finished(int exitCode, int exitSignal); + void failed(const QString &phase, int code, const QString &message); + void ownerChanged(const QString &service, const QString &oldOwner, const QString &newOwner); + +private: + enum class Phase { Idle, Creating, Authenticating, Authenticated, Starting, Running, Stopping, Aborting, Terminal }; + void call(const QString &method, const QVariantList &arguments, + std::function completion); + bool bind(); + void unbind(); + void fail(const QString &message); + void finish(); + void clearSecret(); + void readReceipt(const QString &id, quint32 pid); + void reconnect(); + void abortStart(const QString &message); + void requestAbort(); + void finishAbort(); + static bool decodeInfo(const QString &path, const QVariantMap &values, ManagedSessionInfo &info, + bool runningOnly); + bool matches(const ManagedSessionInfo &info) const; + + QDBusConnection m_bus; + QDBusServiceWatcher *m_serviceWatcher; + QTimer m_deadline; + ManagedSessionInfo m_info; + QString m_profile; + QByteArray m_secret; + Phase m_phase = Phase::Idle; + quint64 m_generation = 0; + quint32 m_lastPrompt = 0; + bool m_bound = false; + bool m_connected = true; + bool m_receiptPending = false; + bool m_finishPending = false; + bool m_terminalReceipt = false; + bool m_startSubmitted = false; + bool m_stopRequested = false; +}; +} + +Q_DECLARE_METATYPE(DDM::DAEnvironment) +Q_DECLARE_METATYPE(DDM::DANamespaces) + +#endif diff --git a/src/daemon/Display.cpp b/src/daemon/Display.cpp index 53c8aca..25d2d52 100644 --- a/src/daemon/Display.cpp +++ b/src/daemon/Display.cpp @@ -43,6 +43,7 @@ #include #include #include +#include #include #include @@ -178,6 +179,8 @@ namespace DDM { bool Display::start() { if (m_started) return true; + if (m_stopping) + return false; if (!daemonApp->seatdControl()->requestSwitchVt(terminalId)) { qCritical() << "Failed to switch to greeter VT" << terminalId; @@ -199,45 +202,76 @@ namespace DDM { // set flags m_started = true; + reconcileManagedSessions(); return true; } + namespace { + struct DetachedManagedSession { + QPointer auth; + int vt{ 0 }; + QMetaObject::Connection started; + QMetaObject::Connection failed; + QMetaObject::Connection finished; + }; + + // Display shutdown detaches DA, but DDM still observes terminal + // signals and owns the grouped VT until another Display takes over. + QHash detachedManagedSessions; + } + void Display::stop() { - // check flag - if (!m_started) + if (m_stopping) return; - - for (auto *auth : std::as_const(auths)) { - disconnect(auth, &Auth::sessionFinished, nullptr, nullptr); - delete auth; - } - auths.clear(); - - // stop socket server - m_socketServer->stop(); - - if (m_x11Server) - m_x11Server->stop(); - - // stop display server - m_treeland->stop(); - - // reset flag + const bool wasStarted = m_started; + m_stopping = true; m_started = false; + const QPointer display(this); + + while (!m_unlocks.isEmpty()) + cancelUnlock(m_unlocks.constBegin().key()); + while (!auths.isEmpty()) { + Auth *auth = auths.constLast(); + if (auth->type == Treeland + && (auth->sessionOpened || m_startingAuths.contains(auth))) { + detachManagedAuth(auth); + } else { + removeAuth(auth); + } + if (!display) + return; + } - // emit signal - emit stopped(); + if (wasStarted) { + m_socketServer->stop(); + if (!display) + return; + if (m_x11Server) + m_x11Server->stop(); + if (!display) + return; + m_treeland->stop(); + if (!display) + return; + } + m_stopping = false; + if (wasStarted) + emit stopped(); } void Display::connected(QLocalSocket *socket) { - // send logged in users (for possible crash recovery) - SocketWriter writer(socket); + const QPointer display(this); + const QPointer connection(socket); + reconcileManagedSessions(); + if (!display || !connection || socket->state() != QLocalSocket::ConnectedState) + return; bool hasActiveUser = false; for (Auth *auth : std::as_const(auths)) { - if (auth->sessionOpened) { + if (auth->sessionOpened && m_registeredAuths.contains(auth)) { hasActiveUser = true; - writer << quint32(DaemonMessages::UserLoggedIn) << auth->user << auth->xdgSessionId; + SocketWriter(socket) << quint32(DaemonMessages::UserLoggedIn) + << auth->user << auth->xdgSessionId; } } @@ -245,12 +279,14 @@ namespace DDM { if (!m_connectedOnce) { m_connectedOnce = true; if (!hasActiveUser && !mainConfig()->autologinUser().isEmpty()) { - if (startAutologin()) + if (startAutologin(socket)) return; } + if (!display || !connection || socket->state() != QLocalSocket::ConnectedState) + return; } - writer << quint32(DaemonMessages::ShowGreeter); + SocketWriter(socket) << quint32(DaemonMessages::ShowGreeter); } void Display::recordLastLogin(const QString &user, const Session *session) { @@ -270,101 +306,288 @@ namespace DDM { qInfo() << "Start login for user" << user; - // Get Auth object - Auth *auth = nullptr; - for (auto *item : std::as_const(auths)) { - if (item->user == user) { - auth = item; - break; - } - } - - if (!auth) - auth = new Auth(this, user); - - if (auth->authenticated) { - qWarning() << "Existing authentication ongoing, aborting"; - return; - } - const bool insertedAuth = !auths.contains(auth); - if (insertedAuth) - auths << auth; - - // Run password check - if (!auth->authenticate(password.toLocal8Bit())) { - if (insertedAuth) { - auths.removeAll(auth); - delete auth; - } - Q_EMIT loginFailed(socket, user); + if (!m_started || m_stopping || !socket + || socket->state() != QLocalSocket::ConnectedState) return; - } - - DaemonApp::instance()->displayManager()->setLastActivatedUser(user); - if (!startUserSession(auth, session)) { - Q_EMIT loginFailed(socket, user); - return; + for (Auth *auth : std::as_const(auths)) { + if (auth->user != user) + continue; + if (auth->type == Treeland && m_registeredAuths.contains(auth) + && auth->sessionOpened && !auth->xdgSessionId.isEmpty()) { + // The lock screen reuses Login for an already running session. + // Verify the credential and unlock instead of starting a second login. + unlock(socket, user, password); + return; + } + if (m_pendingLogins.contains(auth) || auth->isBusy() + || auth->authenticated || auth->sessionOpened) { + qWarning() << "Login already pending or active for user" << user; + emit loginFailed(socket, user); + return; + } } - recordLastLogin(user, &session); + beginLogin(socket, new Auth(this, user), session, password.toLocal8Bit()); } - bool Display::startUserSession(Auth *auth, const Session &session) { - // sanity check - if (!session.isValid()) { - qCritical() << "Invalid session" << session.fileName(); - auths.removeAll(auth); - delete auth; + bool Display::prepareUserSession(Auth *auth, const Session &session) { + if (!session.isValid() || session.xdgSessionType().isEmpty() || session.exec().isEmpty()) { + qCritical() << "Invalid desktop session" << session.fileName(); return false; } - if (session.xdgSessionType().isEmpty()) { - qCritical() << "Failed to find XDG session type for session" << session.fileName(); - auths.removeAll(auth); - delete auth; - return false; - } - if (session.exec().isEmpty()) { - qCritical() << "Failed to find command for session" << session.fileName(); - auths.removeAll(auth); - delete auth; - return false; - } - - const QString sessionId = QStringLiteral("Session%1").arg(daemonApp->newSessionId()); - auth->sessionId = sessionId; - // Special preparation for each display server type - // - // TODO: Let Treeland drop DRM master when inactive, so that X - // server and other Wayland compositor can co-exist with - // greeter (the Treeland) - QByteArray cookie; + auth->seat = name; + auth->sessionId = QStringLiteral("Session%1").arg(daemonApp->newSessionId()); if (session.isSingleMode()) { auth->type = Treeland; const int ownerPid = daemonApp->treelandConnector()->mainPid(); - auth->tty = daemonApp->seatdControl()->createGroupVt(ownerPid, auth->user, sessionId); - if (auth->tty <= 0) { - qCritical() << "Failed to allocate grouped VT for Treeland user session"; - auths.removeAll(auth); - delete auth; - return false; - } - } else if (session.xdgSessionType() == QLatin1String("x11")) { - auth->type = X11; - auth->tty = fetchAvailableUserVt(); + auth->tty = daemonApp->seatdControl()->createGroupVt(ownerPid, auth->user, auth->sessionId); + if (auth->tty > 0) + m_groupVts.insert(auth, auth->tty); } else { - auth->type = Wayland; + auth->type = session.xdgSessionType() == QLatin1String("x11") ? X11 : Wayland; auth->tty = fetchAvailableUserVt(); } - if (auth->tty <= 0) { qCritical() << "Failed to allocate VT for user session"; - auths.removeAll(auth); - delete auth; return false; } + return true; + } + + bool Display::beginLogin(QLocalSocket *socket, Auth *auth, const Session &session, + const QByteArray &secret) { + const QPointer display(this); + const QPointer attempt(auth); + const QPointer connection(socket); + const QSharedPointer loginSession = QSharedPointer::create(session); + auths.append(auth); + m_pendingLogins.insert(auth); + if (!prepareUserSession(auth, session)) { + failLogin(auth, socket); + return false; + } + + connect(auth, &Auth::informationMessage, this, [connection](const QString &message) { + if (connection && connection->state() == QLocalSocket::ConnectedState) + SocketWriter(connection.data()) << quint32(DaemonMessages::InformationMessage) << message; + }); + connect(auth, &Auth::authenticationFinished, this, + [this, display, attempt, connection, loginSession](bool success) { + if (!attempt || !m_pendingLogins.contains(attempt.data())) + return; + if (!success || !connection || connection->state() != QLocalSocket::ConnectedState) { + failLogin(attempt.data(), connection.data()); + return; + } + const bool scheduled = startUserSession(attempt.data(), *loginSession); + if (display && attempt && !scheduled) + failLogin(attempt.data(), connection.data()); + }); + connect(auth, &Auth::sessionStartFailed, this, [this, attempt, connection]() { + if (attempt && m_pendingLogins.contains(attempt.data())) + failLogin(attempt.data(), connection.data()); + }); + connect(auth, &Auth::sessionStarted, this, [this, display, attempt, connection, loginSession]() { + if (!attempt || !m_pendingLogins.remove(attempt.data())) + return; + m_startingAuths.remove(attempt.data()); + if (attempt->type == Treeland + && (!connection || connection->state() != QLocalSocket::ConnectedState)) { + // Cancel cannot stop an accepted Start. An abandoned pending + // login must Stop explicitly, retaining its VT until Finished. + attempt->closeSession(); + return; + } + registerSession(attempt.data(), true); + if (display && attempt && m_registeredAuths.contains(attempt.data())) + recordLastLogin(attempt->user, loginSession.data()); + }); + connect(auth, &Auth::sessionFinished, this, [this, attempt, connection]() { + if (!attempt || !auths.contains(attempt.data())) + return; + if (m_pendingLogins.contains(attempt.data())) + failLogin(attempt.data(), connection.data()); + else + removeAuth(attempt.data()); + }); + const auto socketLost = [display, attempt]() { + if (display && attempt && display->m_pendingLogins.contains(attempt.data()) + && (attempt->type == Treeland || !attempt->authenticated) + && !display->m_startingAuths.contains(attempt.data()) + && !attempt->sessionOpened) + display->removeAuth(attempt.data()); + }; + connect(socket, &QLocalSocket::disconnected, auth, socketLost); + connect(socket, &QObject::destroyed, auth, socketLost); + auth->authenticateAsync(secret); + // The asynchronous contract reports authentication/start failure via + // callbacks; scheduling is enough to keep connected() out of greeter. + return true; + } + + void Display::failLogin(Auth *auth, QLocalSocket *socket) { + const QString user = auth->user; + const QPointer display(this); + const QPointer connection(socket); + removeAuth(auth); + if (!display || !connection || connection->state() != QLocalSocket::ConnectedState) + return; + SocketWriter(connection.data()) << quint32(DaemonMessages::ShowGreeter); + emit loginFailed(connection.data(), user); + } + + void Display::cancelUnlock(Auth *target) { + Auth *verification = m_unlocks.take(target); + if (!verification) + return; + disconnect(verification, nullptr, this, nullptr); + verification->deleteLater(); + } + + void Display::detachManagedAuth(Auth *auth) { + const QString path = auth->managedSessionPath(); + const QString seat = auth->seat; + const QString sessionId = auth->sessionId; + const bool registered = m_registeredAuths.remove(auth); + auths.removeAll(auth); + m_pendingLogins.remove(auth); + m_startingAuths.remove(auth); + cancelUnlock(auth); + disconnect(auth, nullptr, this, nullptr); + auth->setParent(daemonApp); + const QPointer attempt(auth); + DetachedManagedSession detached; + detached.auth = auth; + detached.vt = m_groupVts.take(auth); + const auto finished = [path, attempt]() { + auto entry = detachedManagedSessions.find(path); + if (entry == detachedManagedSessions.end() || entry->auth != attempt) + return; + const int vt = entry->vt; + detachedManagedSessions.erase(entry); + if (vt > 0) + daemonApp->seatdControl()->destroyGroupVt(vt); + if (attempt) + attempt->deleteLater(); + }; + detached.failed = connect(auth, &Auth::sessionStartFailed, auth, finished); + detached.finished = connect(auth, &Auth::sessionFinished, auth, finished); + detached.started = connect(auth, &Auth::sessionStarted, auth, [seat]() { + // A Start accepted during display shutdown can be recovered by a + // restarted display without another login or grouped-VT request. + for (Display *current : std::as_const(daemonApp->seatManager()->displays)) { + if (current->name != seat) + continue; + const QPointer display(current); + QMetaObject::invokeMethod(current, [display]() { + if (display && display->m_started) + display->reconcileManagedSessions(); + }, Qt::QueuedConnection); + } + }); + detachedManagedSessions.insert(path, detached); + if (registered) + daemonApp->displayManager()->RemoveSession(sessionId); + } + + void Display::removeAuth(Auth *auth) { + if (!auths.removeOne(auth)) + return; + const QString sessionId = auth->sessionId; + const bool registered = m_registeredAuths.remove(auth); + m_pendingLogins.remove(auth); + m_startingAuths.remove(auth); + cancelUnlock(auth); + disconnect(auth, nullptr, this, nullptr); + const int vt = m_groupVts.take(auth); + if (vt > 0) + daemonApp->seatdControl()->destroyGroupVt(vt); + auth->deleteLater(); + if (registered) + daemonApp->displayManager()->RemoveSession(sessionId); + } + + void Display::registerSession(Auth *auth, bool activate) { + if (m_registeredAuths.contains(auth)) + return; + const QPointer display(this); + const QPointer session(auth); + m_registeredAuths.insert(auth); + auto *manager = daemonApp->displayManager(); + manager->AddSession(auth->sessionId, name, auth->user, auth->tty); + if (!display || !session || !m_registeredAuths.contains(session.data())) + return; + manager->setLastSession(auth->sessionId); + if (!display || !session || !m_registeredAuths.contains(session.data())) + return; + manager->setLastActivatedUser(auth->user); + if (!display || !session || !m_registeredAuths.contains(session.data())) + return; + if (activate && auth->type == Treeland) + activateSession(auth->user, auth->xdgSessionId); + } + + void Display::reconcileManagedSessions() { + if (m_stopping || !m_started) + return; + const QPointer display(this); + const auto sessions = Auth::managedSessions(name); + if (!display || !m_started) + return; + for (const ManagedSessionInfo &info : sessions) { + bool duplicate = false; + for (Auth *auth : std::as_const(auths)) { + if (auth->managedSessionPath() == info.objectPath + || auth->xdgSessionId == info.logindSessionId || auth->tty == int(info.vt) + || (auth->user == info.user && !auth->sessionOpened)) { + duplicate = true; + break; + } + } + if (duplicate) + continue; + Auth *auth = nullptr; + auto detached = detachedManagedSessions.find(info.objectPath); + if (detached != detachedManagedSessions.end() && detached->auth) { + // Let the pending Start completion populate the existing Auth + // first; its queued recovery callback will revisit this seat. + if (!detached->auth->sessionOpened) + continue; + auth = detached->auth.data(); + disconnect(detached->started); + disconnect(detached->failed); + disconnect(detached->finished); + m_groupVts.insert(auth, detached->vt); + detachedManagedSessions.erase(detached); + auth->setParent(this); + } else { + if (detached != detachedManagedSessions.end()) + detachedManagedSessions.erase(detached); + auth = new Auth(this, info.user); + if (!auth->adoptManagedSession(info)) { + delete auth; + continue; + } + m_groupVts.insert(auth, auth->tty); + } + auths.append(auth); + const QPointer adopted(auth); + connect(auth, &Auth::sessionFinished, this, [this, adopted]() { + if (adopted) + removeAuth(adopted.data()); + }); + registerSession(auth, false); + if (!display || !m_started) + return; + } + } + bool Display::startUserSession(Auth *auth, const Session &session) { + QByteArray cookie; + const QPointer display(this); + const QPointer attempt(auth); qInfo() << "Authentication succeeded for user" << auth->user << ", opening session" << session.fileName() << ", command:" << session.exec() << ", VT:" << auth->tty; @@ -372,7 +595,7 @@ namespace DDM { QProcessEnvironment env; env.insert(session.additionalEnv()); - env.insert(QStringLiteral("XDG_SESSION_PATH"), daemonApp->displayManager()->sessionPath(sessionId)); + env.insert(QStringLiteral("XDG_SESSION_PATH"), daemonApp->displayManager()->sessionPath(auth->sessionId)); env.insert(QStringLiteral("PATH"), mainConfig()->usersDefaultPath()); env.insert(QStringLiteral("DESKTOP_SESSION"), session.desktopSession()); @@ -397,12 +620,13 @@ namespace DDM { qInfo() << "Starting X11 display server"; m_x11Server = new XorgDisplayServer(this); connect(m_x11Server, &XorgDisplayServer::stopped, this, &Display::stop); - if (!m_x11Server->start(auth->tty)) { + const bool started = m_x11Server->start(auth->tty); + if (!display || !attempt || !m_pendingLogins.contains(attempt.data())) + return true; + if (!started) { qCritical() << "Failed to start X11 display server"; delete m_x11Server; m_x11Server = nullptr; - auths.removeAll(auth); - delete auth; return false; } m_x11Server->setupDisplay(); @@ -416,36 +640,17 @@ namespace DDM { QThread::msleep(500); // give some time to treeland to stop properly } - // Open Logind session & Exec the desktop process - const QString xdgSessionId = auth->openSession(session.exec(), env, cookie); - - if (xdgSessionId.isEmpty()) { - qCritical() << "Failed to open logind session for user" << auth->user; - if (auth->type == Treeland) - daemonApp->seatdControl()->destroyGroupVt(auth->tty); - auths.removeAll(auth); - delete auth; - return false; - } - - connect(auth, &Auth::sessionFinished, this, [this, auth]() { - qWarning() << "Session for user" << auth->user << "finished"; - auths.removeAll(auth); - daemonApp->displayManager()->RemoveSession(auth->sessionId); - if (auth->type == Treeland) - daemonApp->seatdControl()->destroyGroupVt(auth->tty); - delete auth; - }); - daemonApp->displayManager()->AddSession(sessionId, name, auth->user, auth->tty); - daemonApp->displayManager()->setLastSession(sessionId); - + // Treeland uses DA; helper-backed displays use the same completion + // signals without changing their display-server preparation. + if (!display || !attempt || !m_pendingLogins.contains(attempt.data())) + return true; if (auth->type == Treeland) - activateSession(auth->user, auth->xdgSessionId); - qInfo() << "Successfully logged in user" << auth->user; + m_startingAuths.insert(auth); + auth->openSessionAsync(session.exec(), env, cookie); return true; } - bool Display::startAutologin() { + bool Display::startAutologin(QLocalSocket *socket) { const QString user = mainConfig()->autologinUser(); if (user.isEmpty()) return false; @@ -481,31 +686,26 @@ namespace DDM { return false; } - // Create Auth with the dedicated autologin PAM service - Auth *auth = new Auth(this, user); - auth->pamService = QStringLiteral("ddm-autologin"); - auths << auth; - - if (!auth->authenticate(QByteArray())) { - qWarning() << "Autologin authentication failed for user" << user; - auths.removeAll(auth); - delete auth; - return false; - } - - DaemonApp::instance()->displayManager()->setLastActivatedUser(user); - - if (!startUserSession(auth, session)) { - qWarning() << "Failed to start automatic login session for user" << user; - return false; + for (Auth *auth : std::as_const(auths)) { + if (auth->user == user + && (m_pendingLogins.contains(auth) || auth->isBusy() + || auth->authenticated || auth->sessionOpened)) + return true; } - recordLastLogin(user, &session); - return true; + Auth *auth = new Auth(this, user); + auth->pamService = QStringLiteral("ddm-autologin"); + return beginLogin(socket, auth, session, QByteArray()); } void Display::logout([[maybe_unused]] QLocalSocket *socket, const QString &id) { qDebug() << "Logout requested for session id" << id; + for (Auth *auth : std::as_const(auths)) { + if (auth->xdgSessionId == id && auth->type == Treeland) { + auth->closeSession(); + return; + } + } // Do not kill the session leader process before // TerminateSession! Logind will only kill the session's // cgroup (session_stop_scope) when the session is not in @@ -534,37 +734,75 @@ namespace DDM { return; } - qInfo() << "Start identify user" << user; + if (!m_started || m_stopping || !socket + || socket->state() != QLocalSocket::ConnectedState) + return; - // Only run password check - // - // No user process execution, so the auth can be thrown away - // immediately after use - Auth auth(this, user); - if (!auth.authenticate(password.toLocal8Bit())) { - Q_EMIT loginFailed(socket, user); + Auth *target = nullptr; + for (Auth *auth : std::as_const(auths)) { + if (auth->user == user && m_registeredAuths.contains(auth) + && auth->sessionOpened && !auth->xdgSessionId.isEmpty()) { + target = auth; + break; + } + } + if (!target) { + qWarning() << "No active session found for user" << user; + emit loginFailed(socket, user); return; } + if (m_unlocks.contains(target)) + return; - DaemonApp::instance()->displayManager()->setLastActivatedUser(user); - recordLastLogin(user); - - // Find the auth that started the session, which contains full informations - for (auto *auth : std::as_const(auths)) { - if (auth->user == user && !auth->xdgSessionId.isEmpty()) { - OrgFreedesktopLogin1ManagerInterface manager(Logind::serviceName(), - Logind::managerPath(), - QDBusConnection::systemBus()); - manager.UnlockSession(auth->xdgSessionId); - if (auth->type == Treeland) - activateSession(user, auth->xdgSessionId); - else if (!daemonApp->seatdControl()->requestSwitchVt(auth->tty)) - qWarning() << "Failed to switch to session VT" << auth->tty << "for user" << user; - qInfo() << "Successfully identified user" << user; + Auth *verification = new Auth(this, user); + verification->type = target->type; + verification->seat = target->seat; + verification->tty = target->tty; + m_unlocks.insert(target, verification); + const QPointer display(this); + const QPointer session(target); + const QPointer attempt(verification); + const QPointer connection(socket); + connect(verification, &Auth::informationMessage, this, [connection](const QString &message) { + if (connection && connection->state() == QLocalSocket::ConnectedState) + SocketWriter(connection.data()) << quint32(DaemonMessages::InformationMessage) << message; + }); + connect(verification, &Auth::authenticationFinished, this, + [this, display, session, attempt, connection, user](bool success) { + if (!session || !attempt || m_unlocks.value(session.data()) != attempt.data()) + return; + cancelUnlock(session.data()); + if (!connection || connection->state() != QLocalSocket::ConnectedState) + return; + if (!success || !auths.contains(session.data()) || !session->sessionOpened) { + emit loginFailed(connection.data(), user); return; } - } - qWarning() << "No active session found for user" << user; - Q_EMIT loginFailed(socket, user); + OrgFreedesktopLogin1ManagerInterface manager(Logind::serviceName(), + Logind::managerPath(), + QDBusConnection::systemBus()); + manager.UnlockSession(session->xdgSessionId); + if (session->type == Treeland) + activateSession(user, session->xdgSessionId); + else if (!daemonApp->seatdControl()->requestSwitchVt(session->tty)) + qWarning() << "Failed to switch to session VT" << session->tty << "for user" << user; + if (!display || !session || !auths.contains(session.data())) + return; + daemonApp->displayManager()->setLastActivatedUser(user); + if (display) + recordLastLogin(user); + }); + const auto cancel = [display, session, attempt]() { + if (display && session && attempt + && display->m_unlocks.value(session.data()) == attempt.data()) + display->cancelUnlock(session.data()); + }; + connect(socket, &QLocalSocket::disconnected, verification, cancel); + connect(socket, &QObject::destroyed, verification, cancel); + connect(target, &QObject::destroyed, verification, [display, target]() { + if (display) + display->cancelUnlock(target); + }); + verification->authenticateAsync(password.toLocal8Bit()); } } diff --git a/src/daemon/Display.h b/src/daemon/Display.h index fa9d41e..079314f 100644 --- a/src/daemon/Display.h +++ b/src/daemon/Display.h @@ -26,6 +26,8 @@ #include #include #include +#include +#include #include "Session.h" @@ -123,22 +125,25 @@ namespace DDM { void loginFailed(QLocalSocket *socket, const QString &user); private: - /** - * Start a user session that has already been authenticated. - * Handles VT allocation, display server startup and logind - * registration. On failure the auth is removed and deleted. - * - * @param auth Authenticated Auth object - * @param session Session to start - * @return true on success, false on failure - */ + /** Validate the desktop and reserve its seat/VT before authentication. */ + bool prepareUserSession(Auth *auth, const Session &session); + + /** Schedule authentication and launch; success is reported only after Start. */ + bool beginLogin(QLocalSocket *socket, Auth *auth, const Session &session, + const QByteArray &secret); + + /** Prepare the authenticated desktop environment and schedule its launch. */ bool startUserSession(Auth *auth, const Session &session); - /** - * Start automatic login for the configured user using the - * "ddm-autologin" PAM service. No-op if autologin is disabled. - */ - bool startAutologin(); + /** Schedule the configured automatic login on the first greeter connection. */ + bool startAutologin(QLocalSocket *socket); + + void failLogin(Auth *auth, QLocalSocket *socket); + void removeAuth(Auth *auth); + void registerSession(Auth *auth, bool activate); + void cancelUnlock(Auth *target); + void detachManagedAuth(Auth *auth); + void reconcileManagedSessions(); /** * Remember the user and optionally the session of a successful @@ -160,6 +165,14 @@ namespace DDM { /** Socket server for communication with Treeland */ SocketServer *m_socketServer { nullptr }; + + /** Pending attempts stay distinct from successfully registered sessions. */ + QSet m_pendingLogins; + QSet m_startingAuths; + QSet m_registeredAuths; + QHash m_groupVts; + QHash m_unlocks; + bool m_stopping{ false }; }; } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt new file mode 100644 index 0000000..e513a47 --- /dev/null +++ b/tests/CMakeLists.txt @@ -0,0 +1,11 @@ +find_package(Qt6 REQUIRED COMPONENTS Test) + +add_executable(tst_dasessionclient + tst_dasessionclient.cpp + ../src/daemon/DASessionClient.cpp + ../src/daemon/DASessionClient.h +) +target_include_directories(tst_dasessionclient PRIVATE ../src/daemon) +target_link_libraries(tst_dasessionclient PRIVATE Qt6::Core Qt6::DBus Qt6::Test) +add_test(NAME dasessionclient COMMAND tst_dasessionclient) +set_tests_properties(dasessionclient PROPERTIES TIMEOUT 30) diff --git a/tests/tst_dasessionclient.cpp b/tests/tst_dasessionclient.cpp new file mode 100644 index 0000000..fbbec08 --- /dev/null +++ b/tests/tst_dasessionclient.cpp @@ -0,0 +1,782 @@ +// Copyright (C) 2026 UnionTech Software Technology Co., Ltd. +// SPDX-License-Identifier: GPL-2.0-or-later + +#include "DASessionClient.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace DDM; +namespace { +const QString service = QStringLiteral("org.deepin.dde.Authenticate1.LoginManager"); +const QString root = QStringLiteral("/org/deepin/dde/Authenticate1/LoginManager"); +const QString path = root + QStringLiteral("/Session_0123456789abcdef0123456789abcdef"); +} + +class SyntheticSession : public QObject, protected QDBusContext { + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "org.deepin.dde.Authenticate1.LoginManager.Session") +public: + QString user = QStringLiteral("alice"), profile = QStringLiteral("login"), seat = QStringLiteral("seat0"); + QString state = QStringLiteral("ready"), logindId = QStringLiteral("opaque/session-with-no-numeric-id"); + quint32 vt = 7, pid = 1234; + int authenticateCount = 0, startCount = 0, cancelCount = 0, stopCount = 0; + bool rejectAuth = false, rejectStart = false, holdAuth = false; + bool rejectStop = false; + bool holdStart = false, raceCancelWithStart = false; + QVariantMap metadataOverrides; + bool rejectInfo = false; + QString missingMetadata; + bool duplicatePrompt = false, startPrompt = false, immediateFinish = false; + quint32 expectedPrompt = 0; + QList frames; + QStringList receivedArgv; + DAEnvironment receivedEnvironment; + int namespaceCount = 0; + bool namespaceReadable = false; + +public Q_SLOTS: + void Authenticate() + { + ++authenticateCount; + if (rejectAuth) { + sendErrorReply(QStringLiteral("org.deepin.Error.Authentication"), QStringLiteral("denied")); + return; + } + state = QStringLiteral("authenticating"); + Q_EMIT StateChanged(state); + if (holdAuth) + return; + expectedPrompt = 1; + Q_EMIT Prompt(0, 4, QStringLiteral("Authentication notice")); + Q_EMIT Prompt(expectedPrompt, 1, QStringLiteral("Password:")); + if (duplicatePrompt) + Q_EMIT Prompt(expectedPrompt, 1, QStringLiteral("Password:")); + } + + void Respond(quint32 id, const QDBusUnixFileDescriptor &descriptor) + { + if (id != expectedPrompt || !descriptor.isValid()) { + sendErrorReply(QStringLiteral("org.deepin.Error.InvalidPrompt"), QStringLiteral("wrong prompt")); + return; + } + QByteArray frame; + char bytes[2048]; + // The fixture reads bounded regular descriptors only; never waits on a pipe. + const ssize_t size = ::pread(descriptor.fileDescriptor(), bytes, sizeof(bytes), 0); + if (size >= 0) + frame.append(bytes, static_cast(size)); + frames.append(frame); + if (state == QLatin1String("starting")) { + publishStarted(); + } else if (id == 1) { + expectedPrompt = 2; + Q_EMIT Prompt(expectedPrompt, 2, QStringLiteral("Username:")); + } else { + expectedPrompt = 0; + state = QStringLiteral("authenticated"); + Q_EMIT StateChanged(state); + } + } + + void Start(const QStringList &argv, const DAEnvironment &environment, + const DANamespaces &namespaces, const QString &logFile) + { + Q_UNUSED(logFile) + ++startCount; + receivedArgv = argv; + receivedEnvironment = environment; + namespaceCount = namespaces.size(); + if (!namespaces.isEmpty()) + namespaceReadable = ::fcntl(namespaces.first().fileDescriptor(), F_GETFD) >= 0; + if (rejectStart) { + sendErrorReply(QStringLiteral("org.deepin.Error.Start"), QStringLiteral("start denied")); + return; + } + state = QStringLiteral("starting"); + Q_EMIT StateChanged(state); + if (holdStart) + return; + if (startPrompt) { + expectedPrompt = 3; + Q_EMIT Prompt(expectedPrompt, 1, QStringLiteral("Open session password:")); + } else { + publishStarted(); + } + } + + void Cancel() + { + ++cancelCount; + if (raceCancelWithStart && state == QLatin1String("starting")) + publishStarted(); + if (state == QLatin1String("running") || state == QLatin1String("stopping") + || state == QLatin1String("finished") || state == QLatin1String("failed") + || state == QLatin1String("cancelled")) { + sendErrorReply(QStringLiteral("org.deepin.Error.Operation"), QStringLiteral("Cancel only applies to unfinished attempts")); + return; + } + state = QStringLiteral("cancelled"); + Q_EMIT StateChanged(state); + } + + void Stop() + { + ++stopCount; + if (rejectStop) { + sendErrorReply(QStringLiteral("org.deepin.Error.Stop"), QStringLiteral("cleanup unavailable")); + return; + } + state = QStringLiteral("finished"); + Q_EMIT StateChanged(state); + Q_EMIT Finished(0, 0); + } + + QVariantMap GetInfo() + { + if (rejectInfo) { + sendErrorReply(QStringLiteral("org.deepin.Error.Transport"), QStringLiteral("metadata temporarily unavailable")); + return {}; + } + QVariantMap values{{QStringLiteral("User"), user}, + {QStringLiteral("Profile"), profile}, {QStringLiteral("Seat"), seat}, + {QStringLiteral("VT"), vt}, {QStringLiteral("State"), state}, + {QStringLiteral("LogindSessionID"), logindId}, {QStringLiteral("PID"), pid}, + {QStringLiteral("ExitCode"), 0}, {QStringLiteral("ExitSignal"), 0}, + {QStringLiteral("Error"), QString()}}; + for (auto it = metadataOverrides.cbegin(); it != metadataOverrides.cend(); ++it) + values.insert(it.key(), it.value()); + if (!missingMetadata.isEmpty()) + values.remove(missingMetadata); + return values; + } + +Q_SIGNALS: + void Prompt(quint32 id, int style, const QString &message); + void StateChanged(const QString &state); + void Started(const QString &id, quint32 pid); + void Finished(int exitCode, int exitSignal); + void Failed(const QString &phase, int code, const QString &message); + +private: + void publishStarted() + { + expectedPrompt = 0; + state = QStringLiteral("running"); + Q_EMIT StateChanged(state); + Q_EMIT Started(logindId, pid); + if (immediateFinish) { + state = QStringLiteral("finished"); + Q_EMIT StateChanged(state); + Q_EMIT Finished(0, 0); + } + } +}; + +class SyntheticManager : public QObject { + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "org.deepin.dde.Authenticate1.LoginManager") +public: + SyntheticSession session; + int createCount = 0; +public Q_SLOTS: + QDBusObjectPath CreateLogin(const QString &user, const QString &profile, const QString &seat, quint32 vt) + { + ++createCount; + session.user = user; + session.profile = profile; + session.seat = seat; + session.vt = vt; + return QDBusObjectPath(path); + } + QList ListSessions() { return {QDBusObjectPath(path)}; } +}; + +class TestDASessionClient : public QObject { + Q_OBJECT +private: + QTemporaryDir directory; + QProcess daemon; + QString address, clientName, backendName; + QThread backendThread; + QObject *worker = nullptr; + SyntheticManager *backend = nullptr; + std::unique_ptr clientBus, backendBus; + int serial = 0; + + template void onBackend(F fn) + { + QMetaObject::invokeMethod(worker, [this, fn] { fn(*backend); }, Qt::BlockingQueuedConnection); + } + + void dropBackend() + { + onBackend([this](SyntheticManager &) { + backendBus->unregisterService(service); + backendBus->unregisterObject(root); + backendBus->unregisterObject(path); + backendBus.reset(); + QDBusConnection::disconnectFromBus(backendName); + }); + } + + void resumeBackend(bool exposeSession = true) + { + bool registered = false; + onBackend([this, exposeSession, ®istered](SyntheticManager &) { + backendBus = std::make_unique(QDBusConnection::connectToBus(address, backendName)); + registered = backendBus->registerObject(root, backend, QDBusConnection::ExportAllSlots) + && (!exposeSession || backendBus->registerObject(path, &backend->session, + QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals)) + && backendBus->registerService(service); + }); + QVERIFY(registered); + } + + static QByteArray payload(const QByteArray &frame) + { + if (frame.size() < 4) + return {}; + const auto length = qFromLittleEndian(reinterpret_cast(frame.constData())); + if (length != static_cast(frame.size() - 4)) + return {}; + return frame.mid(4); + } + + void authenticate(DASessionClient &client, const QByteArray &secret = QByteArray("real credential")) + { + QSignalSpy authenticated(&client, &DASessionClient::authenticationFinished); + client.authenticate(QStringLiteral("alice"), QStringLiteral("login"), QStringLiteral("seat0"), 7, secret); + QTRY_COMPARE_WITH_TIMEOUT(authenticated.count(), 1, 2000); + QVERIFY(authenticated.first().first().toBool()); + } + + void start(DASessionClient &client) + { + QSignalSpy started(&client, &DASessionClient::sessionStarted); + client.start({QStringLiteral("/usr/bin/example-desktop"), QStringLiteral("argument with spaces")}, + {{QStringLiteral("PATH"), QStringLiteral("/usr/local/bin:/usr/bin")}}, {}, QString()); + QTRY_COMPARE_WITH_TIMEOUT(started.count(), 1, 2000); + } + +private Q_SLOTS: + void initTestCase() + { + qDBusRegisterMetaType(); + qDBusRegisterMetaType(); + qDBusRegisterMetaType>(); + QVERIFY(directory.isValid()); + const QString installed = QStandardPaths::findExecutable(QStringLiteral("dbus-daemon")); + QVERIFY2(!installed.isEmpty(), "dbus-daemon is required for private-bus tests"); + const QString copy = directory.filePath(QStringLiteral("private-dbus-daemon")); + QVERIFY(QFile::copy(installed, copy)); + QVERIFY(QFile::setPermissions(copy, QFile::ReadOwner | QFile::WriteOwner | QFile::ExeOwner)); + daemon.setProgram(copy); + daemon.setArguments({QStringLiteral("--session"), QStringLiteral("--nofork"), + QStringLiteral("--nopidfile"), QStringLiteral("--print-address=1")}); + daemon.start(); + QVERIFY(daemon.waitForStarted(2000)); + QVERIFY(daemon.waitForReadyRead(2000)); + address = QString::fromUtf8(daemon.readLine()).trimmed(); + QVERIFY(address.startsWith(QLatin1String("unix:"))); + } + + void init() + { + clientName = QStringLiteral("da-client-%1").arg(++serial); + backendName = QStringLiteral("da-backend-%1").arg(serial); + clientBus = std::make_unique(QDBusConnection::connectToBus(address, clientName)); + QVERIFY(clientBus->isConnected()); + worker = new QObject; + worker->moveToThread(&backendThread); + backendThread.start(); + bool registered = false; + QMetaObject::invokeMethod(worker, [this, ®istered] { + backendBus = std::make_unique(QDBusConnection::connectToBus(address, backendName)); + backend = new SyntheticManager; + backend->setParent(worker); + registered = backendBus->registerObject(root, backend, QDBusConnection::ExportAllSlots) + && backendBus->registerObject(path, &backend->session, + QDBusConnection::ExportAllSlots | QDBusConnection::ExportAllSignals) + && backendBus->registerService(service); + }, Qt::BlockingQueuedConnection); + QVERIFY(registered); + } + + void cleanup() + { + if (worker) { + QMetaObject::invokeMethod(worker, [this] { + if (backendBus) { + backendBus->unregisterService(service); + backendBus->unregisterObject(root); + backendBus->unregisterObject(path); + backendBus.reset(); + QDBusConnection::disconnectFromBus(backendName); + } + delete backend; + backend = nullptr; + }, Qt::BlockingQueuedConnection); + connect(&backendThread, &QThread::finished, worker, &QObject::deleteLater); + backendThread.quit(); + QVERIFY(backendThread.wait(2000)); + worker = nullptr; + } + clientBus.reset(); + QDBusConnection::disconnectFromBus(clientName); + } + + void cleanupTestCase() + { + daemon.terminate(); + if (!daemon.waitForFinished(1000)) { + daemon.kill(); + QVERIFY(daemon.waitForFinished(1000)); + } + } + + void successfulFDExchangeAndLaunch() + { + const QByteArray secret("pa\0ss", 5); + onBackend([](SyntheticManager &manager) { manager.session.startPrompt = true; }); + DASessionClient client(*clientBus); + QStringList order; + connect(&client, &DASessionClient::authenticationFinished, this, [&order] { order.append(QStringLiteral("auth")); }); + connect(&client, &DASessionClient::sessionStarted, this, [&order] { order.append(QStringLiteral("start")); }); + QSignalSpy messages(&client, &DASessionClient::informationMessage); + authenticate(client, secret); + QCOMPARE(client.sessionId(), QStringLiteral("Session0123456789abcdef0123456789abcdef")); + QVERIFY(!client.isBusy()); + const QString ns = directory.filePath(QStringLiteral("namespace-fixture")); + QFile file(ns); + QVERIFY(file.open(QIODevice::WriteOnly)); + file.close(); + QSignalSpy started(&client, &DASessionClient::sessionStarted); + client.start({QStringLiteral("/usr/bin/example-desktop"), QStringLiteral("two words"), QStringLiteral("非ASCII")}, + {{QStringLiteral("PATH"), QStringLiteral("/custom/bin:/usr/bin")}, + {QStringLiteral("XDG_SESSION_TYPE"), QStringLiteral("wayland")}}, {ns}, QString()); + QTRY_COMPARE_WITH_TIMEOUT(started.count(), 1, 2000); + QCOMPARE(order, QStringList({QStringLiteral("auth"), QStringLiteral("start")})); + QCOMPARE(client.info().logindSessionId, QStringLiteral("opaque/session-with-no-numeric-id")); + QCOMPARE(client.info().pid, qint64(1234)); + QCOMPARE(messages.count(), 1); + onBackend([&](SyntheticManager &manager) { + QCOMPARE(manager.session.frames.size(), 3); + QCOMPARE(payload(manager.session.frames[0]), secret); + QCOMPARE(payload(manager.session.frames[1]), QByteArray("alice")); + QCOMPARE(payload(manager.session.frames[2]), secret); + QCOMPARE(manager.session.receivedArgv, QStringList({QStringLiteral("/usr/bin/example-desktop"), QStringLiteral("two words"), QStringLiteral("非ASCII")})); + QCOMPARE(manager.session.receivedEnvironment.value(QStringLiteral("PATH")), QStringLiteral("/custom/bin:/usr/bin")); + QCOMPARE(manager.session.namespaceCount, 1); + QVERIFY(manager.session.namespaceReadable); + }); + QSignalSpy finished(&client, &DASessionClient::sessionFinished); + QVERIFY(client.stop()); + QTRY_COMPARE_WITH_TIMEOUT(finished.count(), 1, 2000); + } + + void authenticationFailure() + { + onBackend([](SyntheticManager &manager) { manager.session.rejectAuth = true; }); + DASessionClient client(*clientBus); + QSignalSpy result(&client, &DASessionClient::authenticationFinished); + client.authenticate(QStringLiteral("alice"), QStringLiteral("login"), QStringLiteral("seat0"), 7, QByteArray("password")); + QTRY_COMPARE_WITH_TIMEOUT(result.count(), 1, 2000); + QVERIFY(!result.first().first().toBool()); + QVERIFY(!client.isBusy()); + } + + void startFailure() + { + onBackend([](SyntheticManager &manager) { manager.session.rejectStart = true; }); + DASessionClient client(*clientBus); + authenticate(client); + QSignalSpy result(&client, &DASessionClient::sessionStartFailed); + QSignalSpy started(&client, &DASessionClient::sessionStarted); + client.start({QStringLiteral("/usr/bin/desktop")}, {}, {}, QString()); + QTRY_COMPARE_WITH_TIMEOUT(result.count(), 1, 2000); + QCOMPARE(started.count(), 0); + } + + void invalidRuntimeReceipt_data() + { + QTest::addColumn("key"); + QTest::addColumn("value"); + QTest::newRow("different user") << QStringLiteral("User") << QVariant(QStringLiteral("mallory")); + QTest::newRow("different seat") << QStringLiteral("Seat") << QVariant(QStringLiteral("seat1")); + QTest::newRow("different VT") << QStringLiteral("VT") << QVariant(quint32(8)); + QTest::newRow("wrong PID type") << QStringLiteral("PID") << QVariant(QStringLiteral("1234")); + QTest::newRow("zero PID") << QStringLiteral("PID") << QVariant(quint32(0)); + QTest::newRow("empty logind ID") << QStringLiteral("LogindSessionID") << QVariant(QString()); + QTest::newRow("different profile") << QStringLiteral("Profile") << QVariant(QStringLiteral("autologin")); + QTest::newRow("non-running state") << QStringLiteral("State") << QVariant(QStringLiteral("authenticated")); + QTest::newRow("wrong exit type") << QStringLiteral("ExitCode") << QVariant(quint32(0)); + QTest::newRow("missing error") << QStringLiteral("Error") << QVariant(); + } + + void invalidRuntimeReceipt() + { + QFETCH(QString, key); + QFETCH(QVariant, value); + onBackend([&](SyntheticManager &manager) { + if (value.isValid()) + manager.session.metadataOverrides.insert(key, value); + else + manager.session.missingMetadata = key; + }); + DASessionClient client(*clientBus); + authenticate(client); + QSignalSpy result(&client, &DASessionClient::sessionStartFailed); + QSignalSpy started(&client, &DASessionClient::sessionStarted); + client.start({QStringLiteral("/usr/bin/desktop")}, {}, {}, QString()); + QTRY_COMPARE_WITH_TIMEOUT(result.count(), 1, 2000); + QCOMPARE(started.count(), 0); + } + + void invalidReceiptRetainsOwnershipUntilRecovery() + { + onBackend([](SyntheticManager &manager) { + manager.session.metadataOverrides.insert(QStringLiteral("User"), QStringLiteral("mallory")); + manager.session.rejectStop = true; + }); + DASessionClient client(*clientBus); + authenticate(client); + QSignalSpy failed(&client, &DASessionClient::sessionStartFailed); + QSignalSpy started(&client, &DASessionClient::sessionStarted); + QSignalSpy messages(&client, &DASessionClient::informationMessage); + client.start({QStringLiteral("/usr/bin/desktop")}, {}, {}, QString()); + QTRY_VERIFY_WITH_TIMEOUT(messages.count() >= 2, 2000); + QCOMPARE(started.count(), 0); + QCOMPARE(failed.count(), 0); + QCOMPARE(client.info().logindSessionId, QStringLiteral("opaque/session-with-no-numeric-id")); + QCOMPARE(client.info().pid, qint64(1234)); + dropBackend(); + onBackend([](SyntheticManager &manager) { + manager.session.metadataOverrides.clear(); + manager.session.rejectStop = false; + }); + resumeBackend(); + QTRY_COMPARE_WITH_TIMEOUT(failed.count(), 1, 2000); + onBackend([](SyntheticManager &manager) { + QCOMPARE(manager.session.stopCount, 2); + QCOMPARE(manager.session.state, QStringLiteral("finished")); + }); + } + + void duplicateAndOutOfOrderCalls() + { + DASessionClient client(*clientBus); + client.start({QStringLiteral("/usr/bin/desktop")}, {}, {}, QString()); + QSignalSpy result(&client, &DASessionClient::authenticationFinished); + client.authenticate(QStringLiteral("alice"), QStringLiteral("login"), QStringLiteral("seat0"), 7, QByteArray("correct")); + client.authenticate(QStringLiteral("mallory"), QStringLiteral("login"), QStringLiteral("seat0"), 7, QByteArray("wrong")); + QTRY_COMPARE_WITH_TIMEOUT(result.count(), 1, 2000); + QVERIFY(result.first().first().toBool()); + start(client); + client.start({QStringLiteral("/usr/bin/other")}, {}, {}, QString()); + onBackend([](SyntheticManager &manager) { + QCOMPARE(manager.createCount, 1); + QCOMPARE(manager.session.authenticateCount, 1); + QCOMPARE(manager.session.startCount, 1); + QCOMPARE(payload(manager.session.frames.first()), QByteArray("correct")); + }); + } + + void accountPolicyFailureSignal() + { + onBackend([](SyntheticManager &manager) { manager.session.holdAuth = true; }); + DASessionClient client(*clientBus); + QSignalSpy result(&client, &DASessionClient::authenticationFinished); + QSignalSpy messages(&client, &DASessionClient::informationMessage); + client.authenticate(QStringLiteral("alice"), QStringLiteral("login"), QStringLiteral("seat0"), 7, QByteArray("secret")); + bool authenticating = false; + QTRY_VERIFY_WITH_TIMEOUT((onBackend([&](SyntheticManager &manager) { + authenticating = manager.session.authenticateCount == 1; + }), authenticating), 2000); + onBackend([](SyntheticManager &manager) { + manager.session.state = QStringLiteral("failed"); + Q_EMIT manager.session.StateChanged(manager.session.state); + Q_EMIT manager.session.Failed(QStringLiteral("account"), 13, QStringLiteral("Account expired")); + }); + QTRY_COMPARE_WITH_TIMEOUT(result.count(), 1, 2000); + QVERIFY(!result.first().first().toBool()); + QVERIFY(!messages.isEmpty()); + } + + void destructionDuringCreateCancelsReturnedObject() + { + { + DASessionClient client(*clientBus); + client.authenticate(QStringLiteral("alice"), QStringLiteral("login"), QStringLiteral("seat0"), 7, QByteArray("secret")); + } + bool cancelled = false; + QTRY_VERIFY_WITH_TIMEOUT((onBackend([&](SyntheticManager &manager) { + cancelled = manager.session.cancelCount == 1; + }), cancelled), 2000); + onBackend([](SyntheticManager &manager) { + QCOMPARE(manager.createCount, 1); + QCOMPARE(manager.session.authenticateCount, 0); + }); + } + + void duplicatePromptFails() + { + onBackend([](SyntheticManager &manager) { manager.session.duplicatePrompt = true; }); + DASessionClient client(*clientBus); + QSignalSpy result(&client, &DASessionClient::authenticationFinished); + client.authenticate(QStringLiteral("alice"), QStringLiteral("login"), QStringLiteral("seat0"), 7, QByteArray("secret")); + QTRY_COMPARE_WITH_TIMEOUT(result.count(), 1, 2000); + QVERIFY(!result.first().first().toBool()); + } + + void cancelPendingAuthentication() + { + onBackend([](SyntheticManager &manager) { manager.session.holdAuth = true; }); + DASessionClient client(*clientBus); + QSignalSpy result(&client, &DASessionClient::authenticationFinished); + client.authenticate(QStringLiteral("alice"), QStringLiteral("login"), QStringLiteral("seat0"), 7, QByteArray("secret")); + QTRY_VERIFY_WITH_TIMEOUT(!client.objectPath().isEmpty(), 2000); + client.cancel(); + QVERIFY(!client.isBusy()); + bool cancelled = false; + QTRY_VERIFY_WITH_TIMEOUT((onBackend([&](SyntheticManager &manager) { cancelled = manager.session.cancelCount == 1; }), cancelled), 2000); + QCOMPARE(result.count(), 0); + } + + void cancelRacingAcceptedStart() + { + onBackend([](SyntheticManager &manager) { + manager.session.holdStart = true; + manager.session.raceCancelWithStart = true; + }); + DASessionClient client(*clientBus); + authenticate(client); + QSignalSpy failed(&client, &DASessionClient::sessionStartFailed); + QSignalSpy started(&client, &DASessionClient::sessionStarted); + client.start({QStringLiteral("/usr/bin/desktop")}, {}, {}, QString()); + bool submitted = false; + QTRY_VERIFY_WITH_TIMEOUT((onBackend([&](SyntheticManager &manager) { + submitted = manager.session.startCount == 1; + }), submitted), 2000); + client.cancel(); + QTRY_COMPARE_WITH_TIMEOUT(failed.count(), 1, 2000); + QCOMPARE(started.count(), 0); + onBackend([](SyntheticManager &manager) { + QCOMPARE(manager.session.cancelCount, 1); + QCOMPARE(manager.session.stopCount, 1); + QCOMPARE(manager.session.state, QStringLiteral("finished")); + }); + } + + void disconnectDuringAuthenticationFails() + { + onBackend([](SyntheticManager &manager) { manager.session.holdAuth = true; }); + DASessionClient client(*clientBus); + QSignalSpy result(&client, &DASessionClient::authenticationFinished); + client.authenticate(QStringLiteral("alice"), QStringLiteral("login"), QStringLiteral("seat0"), 7, QByteArray("secret")); + QTRY_VERIFY_WITH_TIMEOUT(!client.objectPath().isEmpty(), 2000); + bool authenticating = false; + QTRY_VERIFY_WITH_TIMEOUT((onBackend([&](SyntheticManager &manager) { + authenticating = manager.session.authenticateCount == 1; + }), authenticating), 2000); + dropBackend(); + QTRY_COMPARE_WITH_TIMEOUT(result.count(), 1, 2000); + QVERIFY(!result.first().first().toBool()); + resumeBackend(); + onBackend([](SyntheticManager &manager) { QCOMPARE(manager.session.authenticateCount, 1); }); + } + + void brokerRestartAndManagedAdoption() + { + DASessionClient client(*clientBus); + authenticate(client); + start(client); + QSignalSpy finished(&client, &DASessionClient::sessionFinished); + QSignalSpy messages(&client, &DASessionClient::informationMessage); + dropBackend(); + QTest::qWait(50); + QCOMPARE(finished.count(), 0); + resumeBackend(); + const auto sessions = DASessionClient::managedSessions(QStringLiteral("seat0"), *clientBus); + QCOMPARE(sessions.size(), 1); + QCOMPARE(sessions.first().logindSessionId, client.info().logindSessionId); + DASessionClient adopted(*clientBus); + QVERIFY(adopted.adopt(sessions.first())); + QCOMPARE(adopted.sessionId(), client.sessionId()); + QSignalSpy adoptedFinished(&adopted, &DASessionClient::sessionFinished); + onBackend([](SyntheticManager &manager) { + QCOMPARE(manager.session.authenticateCount, 1); + QCOMPARE(manager.session.startCount, 1); + manager.session.Stop(); + }); + QTRY_COMPARE_WITH_TIMEOUT(finished.count(), 1, 2000); + QTRY_COMPARE_WITH_TIMEOUT(adoptedFinished.count(), 1, 2000); + QCOMPARE(messages.count(), 0); + } + + void terminalAfterBrokerRestart() + { + DASessionClient client(*clientBus); + authenticate(client); + start(client); + QSignalSpy finished(&client, &DASessionClient::sessionFinished); + dropBackend(); + onBackend([](SyntheticManager &manager) { manager.session.state = QStringLiteral("finished"); }); + QTest::qWait(50); + QCOMPARE(finished.count(), 0); + resumeBackend(); + QTRY_COMPARE_WITH_TIMEOUT(finished.count(), 1, 2000); + } + + void recoveryErrorDoesNotFinishLiveSession() + { + DASessionClient client(*clientBus); + authenticate(client); + start(client); + const auto receipt = client.info(); + QSignalSpy finished(&client, &DASessionClient::sessionFinished); + QSignalSpy messages(&client, &DASessionClient::informationMessage); + dropBackend(); + onBackend([](SyntheticManager &manager) { manager.session.rejectInfo = true; }); + resumeBackend(); + QTRY_VERIFY_WITH_TIMEOUT(!messages.isEmpty(), 2000); + QCOMPARE(finished.count(), 0); + QCOMPARE(client.info().logindSessionId, receipt.logindSessionId); + dropBackend(); + onBackend([](SyntheticManager &manager) { manager.session.rejectInfo = false; }); + resumeBackend(); + onBackend([](SyntheticManager &manager) { manager.session.Stop(); }); + QTRY_COMPARE_WITH_TIMEOUT(finished.count(), 1, 2000); + } + + void invalidRecoveryMetadataDoesNotReleaseSession() + { + DASessionClient client(*clientBus); + authenticate(client); + start(client); + const auto receipt = client.info(); + QSignalSpy finished(&client, &DASessionClient::sessionFinished); + QSignalSpy messages(&client, &DASessionClient::informationMessage); + dropBackend(); + onBackend([](SyntheticManager &manager) { manager.session.metadataOverrides.insert(QStringLiteral("PID"), quint32(9999)); }); + resumeBackend(); + QTRY_VERIFY_WITH_TIMEOUT(!messages.isEmpty(), 2000); + QCOMPARE(finished.count(), 0); + QCOMPARE(client.info().pid, receipt.pid); + dropBackend(); + onBackend([](SyntheticManager &manager) { manager.session.metadataOverrides.clear(); }); + resumeBackend(); + onBackend([](SyntheticManager &manager) { manager.session.Stop(); }); + QTRY_COMPARE_WITH_TIMEOUT(finished.count(), 1, 2000); + } + + void immediateExitPreservesStartOrder() + { + onBackend([](SyntheticManager &manager) { manager.session.immediateFinish = true; }); + DASessionClient client(*clientBus); + authenticate(client); + QStringList order; + connect(&client, &DASessionClient::sessionStarted, this, [&] { order.append(QStringLiteral("start")); }); + connect(&client, &DASessionClient::sessionFinished, this, [&] { order.append(QStringLiteral("finish")); }); + client.start({QStringLiteral("/usr/bin/desktop")}, {}, {}, QString()); + QTRY_COMPARE_WITH_TIMEOUT(order.size(), 2, 2000); + QCOMPARE(order, QStringList({QStringLiteral("start"), QStringLiteral("finish")})); + } + + void missingObjectAfterRestartFinishes() + { + DASessionClient client(*clientBus); + authenticate(client); + start(client); + QSignalSpy finished(&client, &DASessionClient::sessionFinished); + dropBackend(); + QTest::qWait(50); + QCOMPARE(finished.count(), 0); + resumeBackend(false); + QTRY_COMPARE_WITH_TIMEOUT(finished.count(), 1, 2000); + } + + void runningDestructorDetaches() + { + { + DASessionClient client(*clientBus); + authenticate(client); + start(client); + } + const auto sessions = DASessionClient::managedSessions(QStringLiteral("seat0"), *clientBus); + QCOMPARE(sessions.size(), 1); + onBackend([](SyntheticManager &manager) { + QCOMPARE(manager.session.cancelCount, 0); + QCOMPARE(manager.session.stopCount, 0); + QCOMPARE(manager.session.state, QStringLiteral("running")); + }); + } + + void maximumCredentialFrame() + { + const QByteArray secret(1024, 's'); + DASessionClient client(*clientBus); + authenticate(client, secret); + onBackend([&](SyntheticManager &manager) { + QCOMPARE(manager.session.frames.first().size(), 1028); + QCOMPARE(payload(manager.session.frames.first()), secret); + }); + } + + void secretSizeLimit() + { + DASessionClient client(*clientBus); + QSignalSpy authenticated(&client, &DASessionClient::authenticationFinished); + client.authenticate(QStringLiteral("alice"), QStringLiteral("login"), QStringLiteral("seat0"), 7, QByteArray(1025, 'x')); + QCOMPARE(authenticated.count(), 1); + QVERIFY(!authenticated.first().first().toBool()); + onBackend([](SyntheticManager &manager) { QCOMPARE(manager.createCount, 0); }); + } + + void invalidPayloads_data() + { + QTest::addColumn("kind"); + QTest::newRow("relative executable") << 0; + QTest::newRow("reserved environment") << 1; + QTest::newRow("too many namespaces") << 2; + QTest::newRow("missing namespace") << 3; + } + + void invalidPayloads() + { + QFETCH(int, kind); + DASessionClient client(*clientBus); + authenticate(client); + QStringList argv{QStringLiteral("/usr/bin/desktop")}, namespaces; + DAEnvironment environment; + if (kind == 0) + argv[0] = QStringLiteral("desktop"); + if (kind == 1) + environment.insert(QStringLiteral("HOME"), QStringLiteral("/wrong")); + if (kind == 2) { + for (int i = 0; i < 17; ++i) + namespaces.append(QStringLiteral("/proc/self/ns/mnt")); + } + if (kind == 3) + namespaces.append(directory.filePath(QStringLiteral("missing-namespace"))); + QSignalSpy failed(&client, &DASessionClient::sessionStartFailed); + client.start(argv, environment, namespaces, QString()); + QCOMPARE(failed.count(), 1); + onBackend([](SyntheticManager &manager) { QCOMPARE(manager.session.startCount, 0); }); + } +}; + +QTEST_GUILESS_MAIN(TestDASessionClient) +#include "tst_dasessionclient.moc"