feat(launch): start desktops without the login screen

The greeter only starts the session its own selector points at, so an
installed environment with no open session could not be reached from
the tool. Starting one needs a one-shot autologin drop-in, a display
manager restart and a guaranteed cleanup, all as root: keep that in a
small pkexec helper so the CLI and the GTK window stay unprivileged.
This commit is contained in:
BlackAngelTV committed 2026-11-13 16:27:41 +01:00
1 parent de60395776
commit e47fd92f47
11 files changed
+709 -38

No files matched your search

+425
View File
@@ -0,0 +1,425 @@
#include "session-launcher.h"
#include "process.h"
#include "session-catalog.h"
#include "session-switcher.h"
#include <limits.h>
#include <pwd.h>
#include <unistd.h>
#include <algorithm>
#include <cctype>
#include <chrono>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <thread>
#include <vector>
namespace fws {
namespace {
constexpr int kPollIntervalMs = 250;
// A display manager restart plus an autologin is slower than a VT switch: the
// unit stops, SDDM starts, PAM opens the session and the desktop paints.
constexpr int kLoginTimeoutMs = 90000;
constexpr const char* kHelperName = "fws-deskmanager-launch";
std::string lower(std::string value) {
std::transform(value.begin(), value.end(), value.begin(),
[](unsigned char character) { return static_cast<char>(std::tolower(character)); });
return value;
}
// The user name and the session file end up in display-manager configuration,
// so only plain tokens are accepted: a newline there would write our own keys.
bool validToken(const std::string& value) {
return !value.empty() &&
std::all_of(value.begin(), value.end(), [](unsigned char character) {
return std::isalnum(character) != 0 || character == '.' || character == '_' ||
character == '-';
});
}
std::string systemdValue(const std::string& unit, const std::string& property) {
const CommandResult result =
runCommand({"systemctl", "show", "-p", property, "--value", unit});
return result.started && result.exitCode == 0 ? trim(result.output) : std::string();
}
std::string displayManagerUnit() { return systemdValue("display-manager.service", "Id"); }
// One-shot autologin drop-in. SDDM and LightDM both read a directory that their
// own configuration does not own, so the launch never edits a file the
// administrator maintains: it adds one and removes it again.
bool autologinFile(const std::string& unit, const std::string& user,
const std::string& sessionFile, std::filesystem::path& path,
std::string& content) {
if (unit == "sddm.service") {
path = "/etc/sddm.conf.d/zz-fws-autologin.conf";
content = "[Autologin]\nUser=" + user + "\nSession=" + sessionFile + "\nRelogin=false\n";
return true;
}
if (unit == "lightdm.service") {
path = "/etc/lightdm/lightdm.conf.d/99-fws-autologin.conf";
content = "[Seat:*]\nautologin-user=" + user + "\nautologin-session=" + sessionFile +
"\nautologin-user-timeout=0\n";
return true;
}
return false;
}
std::string readTextFile(const std::filesystem::path& path) {
std::ifstream stream(path, std::ios::binary);
std::ostringstream content;
content << stream.rdbuf();
return content.str();
}
bool writeTextFile(const std::filesystem::path& path, const std::string& content,
std::string& error) {
std::error_code code;
std::filesystem::create_directories(path.parent_path(), code);
if (code) {
error = "Impossible de creer " + path.parent_path().string() + " : " + code.message();
return false;
}
std::ofstream stream(path, std::ios::binary | std::ios::trunc);
if (!stream) {
error = "Impossible d'ecrire " + path.string() + ".";
return false;
}
stream << content;
stream.close();
if (!stream) {
error = "Impossible d'ecrire " + path.string() + ".";
return false;
}
return true;
}
std::string currentUserName() {
const passwd* account = getpwuid(getuid());
return account != nullptr ? std::string(account->pw_name) : std::string();
}
// The helper is installed next to the caller (build tree included) and has to be
// an absolute path for pkexec.
std::string launchHelperPath() {
char buffer[PATH_MAX] = {};
const ssize_t length = readlink("/proc/self/exe", buffer, sizeof(buffer) - 1);
if (length > 0) {
const std::filesystem::path sibling =
std::filesystem::path(std::string(buffer, static_cast<std::size_t>(length)))
.parent_path() /
kHelperName;
std::error_code code;
if (std::filesystem::is_regular_file(sibling, code) && access(sibling.c_str(), X_OK) == 0) {
return sibling.string();
}
}
return findExecutable(kHelperName);
}
std::vector<std::string> desktopNamesFor(const std::string& sessionFile) {
std::vector<std::string> names;
for (const DesktopEntry& entry : listInstalledDesktops()) {
if (entry.id != sessionFile) {
continue;
}
std::istringstream values(lower(entry.desktops));
std::string value;
while (std::getline(values, value, ';')) {
value = trim(value);
if (!value.empty()) {
names.push_back(value);
}
}
names.push_back(lower(entry.id));
names.push_back(lower(entry.name));
}
return names;
}
// logind reports XDG_CURRENT_DESKTOP ("KDE", "GNOME", "XFCE"...). An empty value
// means the session has not exported it yet, which is not a mismatch.
bool desktopMatches(const SessionInfo& session, const std::vector<std::string>& expected) {
if (session.desktop.empty() || expected.empty()) {
return true;
}
const std::string reported = lower(session.desktop);
for (const std::string& name : expected) {
if (reported.find(name) != std::string::npos || name.find(reported) != std::string::npos) {
return true;
}
}
return false;
}
std::vector<std::string> sessionIdsOf(const std::string& uid) {
std::vector<std::string> ids;
for (const SessionInfo& session : listGraphicalSessionsForUid(uid)) {
ids.push_back(session.id);
}
return ids;
}
// Closing the replaced sessions from inside one of them would kill the helper
// mid-flight, so the cleanup runs from a transient system unit instead.
void closeReplacedSessions(const std::vector<std::string>& ids) {
if (ids.empty()) {
return;
}
std::vector<std::string> arguments = {"systemd-run", "--quiet", "--collect",
"--unit=fws-deskmanager-close-" +
std::to_string(getpid()),
"loginctl", "terminate-session"};
arguments.insert(arguments.end(), ids.begin(), ids.end());
const CommandResult result = runCommand(arguments);
if (result.started && result.exitCode == 0) {
return;
}
// Without systemd-run the helper dies with the session it closes, which is
// still better than leaving the replaced desktop running.
std::vector<std::string> direct = {"loginctl", "terminate-session"};
direct.insert(direct.end(), ids.begin(), ids.end());
runCommand(direct);
}
} // namespace
std::string installedSessionFile(const DesktopProfile& profile) {
const std::vector<DesktopEntry> installed = listInstalledDesktops();
for (const std::string& candidate : profile.sessionFiles) {
for (const DesktopEntry& entry : installed) {
if (entry.id == candidate) {
return entry.id;
}
}
}
// Packaging is free to name the file after the desktop instead of using the
// expected stem, so DesktopNames is the fallback.
for (const DesktopEntry& entry : installed) {
const std::string names = lower(entry.desktops);
for (const std::string& name : profile.sessionNames) {
if (names.find(lower(name)) != std::string::npos) {
return entry.id;
}
}
}
return {};
}
bool canStartWithoutGreeter(std::string& reason) {
if (findExecutable("pkexec").empty()) {
reason = "pkexec est introuvable : l'authentification polkit est necessaire pour "
"demarrer une session sans ecran de connexion.";
return false;
}
const std::string unit = displayManagerUnit();
if (unit.empty()) {
reason = "Aucun gestionnaire d'affichage systemd n'est actif.";
return false;
}
if (unit != "sddm.service" && unit != "lightdm.service") {
reason = unit +
" ne permet pas une connexion automatique ponctuelle ; utilisez l'ecran de "
"connexion et son selecteur de session.";
return false;
}
return true;
}
LaunchOutcome launchDesktop(const DesktopProfile& profile) {
LaunchOutcome outcome;
if (!isDesktopInstalled(profile)) {
outcome.error = profile.name + " n'est pas installe : utilisez d'abord Installer.";
return outcome;
}
std::string running;
if (findActiveSession(profile, running)) {
// Nothing to start: the desktop already owns a session, so this is the
// same verified VT switch as the Basculer button.
if (!activateSession(running, outcome.error)) {
return outcome;
}
outcome.ok = true;
return outcome;
}
std::string reason;
if (!canStartWithoutGreeter(reason)) {
outcome.error = reason;
return outcome;
}
const std::string sessionFile = installedSessionFile(profile);
if (sessionFile.empty()) {
outcome.error = "Aucun fichier de session pour " + profile.name +
" dans /usr/share/xsessions ou /usr/share/wayland-sessions.";
return outcome;
}
const std::string helper = launchHelperPath();
if (helper.empty()) {
outcome.error = std::string(kHelperName) + " est introuvable a cote de l'application.";
return outcome;
}
const std::string user = currentUserName();
if (user.empty()) {
outcome.error = "Impossible d'identifier l'utilisateur courant.";
return outcome;
}
const CommandResult result =
runCommand({"pkexec", helper, "launch", user, sessionFile});
if (!result.started) {
outcome.error = "Impossible de lancer pkexec pour preparer la connexion automatique.";
return outcome;
}
// 126 is polkit's "not authorized": the prompt was dismissed or failed.
if (result.exitCode == 126) {
outcome.error = "Authentification annulee : rien n'a ete ferme.";
return outcome;
}
// -1 without a status means the process was killed: only the session close
// that follows a successful launch does that.
if (result.exitCode != 0 && result.exitCode != -1) {
const std::string message = trim(result.output);
outcome.error = message.empty() ? "Le demarrage de " + profile.name + " a echoue."
: message;
return outcome;
}
outcome.ok = true;
return outcome;
}
int runLaunchHelper(const std::string& user, const std::string& sessionFile) {
if (geteuid() != 0) {
std::cerr << "Cette commande doit etre lancee en root (pkexec).\n";
return 1;
}
if (!validToken(user) || !validToken(sessionFile)) {
std::cerr << "Utilisateur ou fichier de session invalide.\n";
return 1;
}
const passwd* account = getpwnam(user.c_str());
if (account == nullptr) {
std::cerr << "Utilisateur inconnu : " << user << ".\n";
return 1;
}
const std::string uid = std::to_string(account->pw_uid);
std::filesystem::path configPath;
std::string content;
if (!autologinFile(displayManagerUnit(), user, sessionFile, configPath, content)) {
const std::string unit = displayManagerUnit();
std::cerr << (unit.empty() ? std::string("Aucun gestionnaire d'affichage systemd.")
: unit + " ne permet pas de connexion automatique ponctuelle.")
<< " Utilisez l'ecran de connexion.\n";
return 3;
}
std::vector<std::string> previous = sessionIdsOf(uid);
std::string previousActive;
for (const SessionInfo& session : listGraphicalSessionsForUid(uid)) {
if (session.active) {
previousActive = session.id;
}
}
const std::vector<std::string> expected = desktopNamesFor(sessionFile);
std::error_code code;
const bool existed = std::filesystem::exists(configPath, code);
const std::string backup = existed ? readTextFile(configPath) : std::string();
std::string error;
if (!writeTextFile(configPath, content, error)) {
std::cerr << error << "\n";
return 3;
}
std::cout << "Connexion automatique preparee pour " << user << " (" << sessionFile << ").\n";
const CommandResult restart =
runCommand({"systemctl", "restart", "display-manager.service"});
// Wait for the session the display manager just opened: the seat only moves
// to it once logind reports it active. A new session for another desktop
// means the autologin ignored the requested entry: stop waiting at once
// instead of leaving that session running for the whole timeout.
std::string sessionId;
std::string unexpected;
const auto deadline =
std::chrono::steady_clock::now() + std::chrono::milliseconds(kLoginTimeoutMs);
while (std::chrono::steady_clock::now() < deadline) {
for (const SessionInfo& session : listGraphicalSessionsForUid(uid)) {
if (!session.active ||
std::find(previous.begin(), previous.end(), session.id) != previous.end()) {
continue;
}
if (desktopMatches(session, expected)) {
sessionId = session.id;
} else {
unexpected = session.id;
}
break;
}
if (!sessionId.empty() || !unexpected.empty()) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(kPollIntervalMs));
}
// The autologin only exists for this launch: a later boot must show the
// greeter instead of logging the user in on its own.
if (existed) {
writeTextFile(configPath, backup, error);
} else {
std::filesystem::remove(configPath, code);
}
if (sessionId.empty()) {
// A session for the wrong desktop was opened on our behalf: close it
// before giving the seat back, the user never asked for it.
if (!unexpected.empty()) {
closeReplacedSessions({unexpected});
std::cerr << "Le gestionnaire d'affichage a demarre une autre session que "
<< sessionFile << ".";
} else {
std::cerr << "Aucune session " << sessionFile << " n'a demarre";
}
if (!previousActive.empty()) {
runCommand({"loginctl", "activate", previousActive});
}
if (unexpected.empty()) {
if (!restart.started) {
std::cerr << " (systemctl est introuvable)";
} else if (restart.exitCode != 0) {
const std::string message = trim(restart.output);
std::cerr << " : " << (message.empty() ? "le gestionnaire a refuse de redemarrer"
: message);
}
}
std::cerr << " La session precedente a ete reactivee.\n";
return 3;
}
closeReplacedSessions(previous);
std::cout << "Session " << sessionId << " demarree ; sessions precedentes fermees.\n";
return 0;
}
} // namespace fws