#include "session-launcher.h" #include "process.h" #include "session-catalog.h" #include "session-switcher.h" #include #include #include #include #include #include #include #include #include #include #include #include #include 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"; // Hidden switch that turns the single binary into the privileged helper. constexpr const char* kHelperMode = "--privileged-launch"; // Hidden switch for the privileged removal of a drop-in. The watchdog unit calls // it on its own, so it has to work with no other argument. constexpr const char* kCleanupMode = "--privileged-cleanup"; // One-shot autologin drop-ins this tool owns. Display managers read a directory // rather than a single file, so a launch adds a file of its own instead of // editing the configuration the administrator maintains. constexpr const char* kSddmDropIn = "/etc/sddm.conf.d/zz-fws-autologin.conf"; constexpr const char* kLightdmDropIn = "/etc/lightdm/lightdm.conf.d/99-fws-autologin.conf"; // First line of every drop-in. A launch killed before its cleanup leaves the // file behind, and this marker is what lets the tool delete it later without // ever touching a configuration it did not write. constexpr const char* kDropInMarker = "# FWS-DeskManager one-shot autologin - removed automatically"; // A killed launch must not keep the autologin armed: the transient unit started // alongside the drop-in deletes it when stopped, on timeout, and while the // machine shuts down. constexpr int kWatchdogSeconds = 180; // The helper waits up to ninety seconds for the seat: a terminated launch still // has to reach its cleanup instead of dying inside the sleep. volatile std::sig_atomic_t g_interrupted = 0; void onTerminationSignal(int) { g_interrupted = 1; } void catchTerminationSignals() { struct sigaction action {}; action.sa_handler = onTerminationSignal; sigemptyset(&action.sa_mask); sigaction(SIGTERM, &action, nullptr); sigaction(SIGINT, &action, nullptr); sigaction(SIGHUP, &action, nullptr); } std::string lower(std::string value) { std::transform(value.begin(), value.end(), value.begin(), [](unsigned char character) { return static_cast(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 = kSddmDropIn; content = std::string(kDropInMarker) + "\n[Autologin]\nUser=" + user + "\nSession=" + sessionFile + "\nRelogin=false\n"; return true; } if (unit == "lightdm.service") { path = kLightdmDropIn; content = std::string(kDropInMarker) + "\n[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::vector dropInPaths() { return {kSddmDropIn, kLightdmDropIn}; } bool carriesMarker(const std::string& content) { return content.find(kDropInMarker) != std::string::npos; } // Drop-ins written by builds that had no marker are still ours when they hold // nothing but the keys this tool writes: one launch or `cleanup` clears them. bool onlyOwnedKeys(const std::string& content) { static const std::vector kOwnedKeys = { "[autologin]", "[seat:*]", "user=", "session=", "relogin=", "autologin-user=", "autologin-session=", "autologin-user-timeout="}; for (const std::string& line : splitLines(content)) { if (line[0] == '#' || line[0] == ';') { continue; } std::string key = lower(line); const std::size_t equals = key.find('='); if (equals != std::string::npos) { key = key.substr(0, equals + 1); } if (std::find(kOwnedKeys.begin(), kOwnedKeys.end(), key) == kOwnedKeys.end()) { return false; } } return true; } bool ownsDropIn(const std::filesystem::path& path) { std::error_code code; if (!std::filesystem::is_regular_file(path, code)) { return false; } const std::string content = readTextFile(path); if (content.empty()) { return false; } return carriesMarker(content) || onlyOwnedKeys(content); } std::string firstOwnedDropIn() { for (const std::string& path : dropInPaths()) { if (ownsDropIn(path)) { return path; } } return {}; } bool removeOwnedDropIns(std::vector& removed, std::string& error) { bool ok = true; for (const std::string& path : dropInPaths()) { if (!ownsDropIn(path)) { continue; } std::error_code code; if (std::filesystem::remove(path, code)) { removed.push_back(path); } else { ok = false; error = "Impossible de supprimer " + path + " : " + code.message(); } } return ok; } std::string currentUserName() { const passwd* account = getpwuid(getuid()); return account != nullptr ? std::string(account->pw_name) : std::string(); } // The privileged mode lives in the same executable, so pkexec has to run this // very binary; it needs an absolute path either way. 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 self(std::string(buffer, static_cast(length))); std::error_code code; if (std::filesystem::is_regular_file(self, code) && access(self.c_str(), X_OK) == 0) { return self.string(); } } return findExecutable(kHelperName); } // The drop-in is only safe if something outside the helper can delete it. The // unit below lives for the whole launch and its ExecStopPost fires when the unit // is stopped by us, when RuntimeMaxSec expires after a killed helper, and when // systemd shuts the machine down. std::string startCleanupWatchdog(const std::string& helper, std::string& error) { if (helper.empty()) { error = "Le nettoyage de l'autologin n'a pas de binaire a appeler"; return {}; } std::string stopCommand = helper; if (stopCommand.find(' ') != std::string::npos) { stopCommand = "\"" + stopCommand + "\""; } stopCommand += std::string(" ") + kCleanupMode; const std::string unit = "fws-deskmanager-autologin-" + std::to_string(getpid()); const CommandResult result = runCommand( {"systemd-run", "--quiet", "--collect", "--unit=" + unit, "--property=RuntimeMaxSec=" + std::to_string(kWatchdogSeconds), "--property=ExecStopPost=" + stopCommand, "/bin/sleep", std::to_string(kWatchdogSeconds)}); if (!result.started || result.exitCode != 0) { const std::string detail = trim(result.output); error = "Nettoyage automatique de l'autologin impossible (systemd-run)"; if (!detail.empty()) { error += " : " + detail; } return {}; } return unit; } void stopCleanupWatchdog(const std::string& unit) { if (!unit.empty()) { runCommand({"systemctl", "stop", unit}); } } std::vector desktopNamesFor(const std::string& sessionFile) { std::vector 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& 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 sessionIdsOf(const std::string& uid) { std::vector 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& ids) { if (ids.empty()) { return; } std::vector 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 direct = {"loginctl", "terminate-session"}; direct.insert(direct.end(), ids.begin(), ids.end()); runCommand(direct); } } // namespace std::string installedSessionFile(const DesktopProfile& profile) { const std::vector 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; } std::string staleAutologinFile() { return firstOwnedDropIn(); } int runAutologinCleanup() { if (geteuid() != 0) { std::cerr << "Cette commande doit etre lancee en root (pkexec).\n"; return 1; } std::vector removed; std::string error; if (!removeOwnedDropIns(removed, error)) { std::cerr << error << "\n"; return 1; } for (const std::string& path : removed) { std::cout << "Autologin residuel supprime : " << path << "\n"; } return 0; } 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."; 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, kHelperMode, 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; if (!firstOwnedDropIn().empty()) { outcome.error += " Un autologin residuel subsiste ; l'unite de nettoyage le retirera, au plus " "tard a l'extinction."; } 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); // A previous launch may have been killed before its cleanup: start from a // clean state, so the drop-in written below is the only one in place. std::vector staleFiles; std::string staleError; if (!removeOwnedDropIns(staleFiles, staleError)) { std::cerr << staleError << "\n"; return 3; } for (const std::string& stale : staleFiles) { std::cout << "Autologin residuel supprime : " << stale << "\n"; } 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 previous = sessionIdsOf(uid); std::string previousActive; for (const SessionInfo& session : listGraphicalSessionsForUid(uid)) { if (session.active) { previousActive = session.id; } } const std::vector expected = desktopNamesFor(sessionFile); std::error_code code; const bool existed = std::filesystem::exists(configPath, code); const std::string backup = existed ? readTextFile(configPath) : std::string(); // What an earlier launch left at this path is removed, never restored. const bool staleBackup = existed && ownsDropIn(configPath); // Never arm an autologin that nothing would disarm: without the cleanup unit // the launch is refused instead of leaving a password-free boot behind. std::string watchdogError; const std::string watchdog = startCleanupWatchdog(launchHelperPath(), watchdogError); if (watchdog.empty()) { std::cerr << watchdogError << ". Lancement annule pour ne pas laisser " << configPath.string() << " en place.\n"; return 3; } catchTerminationSignals(); std::string error; if (!writeTextFile(configPath, content, error)) { stopCleanupWatchdog(watchdog); 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 && g_interrupted == 0) { 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. Stopping the cleanup // unit already deletes the drop-in; removing it here as well keeps the // helper independent from systemd having kept the unit alive. stopCleanupWatchdog(watchdog); std::filesystem::remove(configPath, code); if (existed && !staleBackup) { std::string restoreError; if (!writeTextFile(configPath, backup, restoreError)) { std::cerr << restoreError << "\n"; return 3; } } if (ownsDropIn(configPath)) { std::cerr << "L'autologin " << configPath.string() << " n'a pas pu etre retire ; supprimez-le avant le prochain demarrage.\n"; return 3; } if (g_interrupted != 0) { std::cerr << "Lancement interrompu ; l'autologin a ete retire.\n"; if (!previousActive.empty()) { runCommand({"loginctl", "activate", previousActive}); } return 3; } 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