diff --git a/CMakeLists.txt b/CMakeLists.txt index 511a82d..4493880 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -13,6 +13,7 @@ add_library(fws-core STATIC src/process.cpp src/session-catalog.cpp src/session-switcher.cpp + src/session-launcher.cpp src/user-interface.cpp src/desktop-catalog.cpp ) @@ -28,4 +29,10 @@ add_executable(fws-deskmanager-gui src/gui.cpp) target_link_libraries(fws-deskmanager-gui PRIVATE fws-core PkgConfig::GTK4) target_compile_options(fws-deskmanager-gui PRIVATE -Wall -Wextra -Wpedantic) -install(TARGETS fws-deskmanager fws-deskmanager-gui RUNTIME DESTINATION bin) +# Only part of the tool that runs as root, and solely through pkexec. +add_executable(fws-deskmanager-launch src/launch-helper.cpp) +target_link_libraries(fws-deskmanager-launch PRIVATE fws-core) +target_compile_options(fws-deskmanager-launch PRIVATE -Wall -Wextra -Wpedantic) + +install(TARGETS fws-deskmanager fws-deskmanager-gui fws-deskmanager-launch + RUNTIME DESTINATION bin) diff --git a/README.md b/README.md index a553fea..d8ef764 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,8 @@ Aucun privilège root, aucun service à installer, aucun redémarrage. choisir un environnement qui n'a pas encore de session ouverte. Avec GDM/LightDM la session courante n'est pas fermée ; avec SDDM 0.21 il faut redémarrer le gestionnaire (`--force`), ce qui ferme la session. +- `launch` : démarre un environnement sans passer par l'écran de connexion (autologin + temporaire via polkit), bascule sur la nouvelle session puis ferme la précédente. - `ui` : sélecteur léger — zenity, sinon kdialog, sinon menu terminal. - Sortie `--json` pour l'intégration. - Aucune dépendance externe : C++17 et appels directs à `loginctl`/`busctl`. @@ -43,10 +45,12 @@ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release cmake --build build -j"$(nproc)" ``` -Deux binaires sont produits : +Trois binaires sont produits : -- `build/fws-deskmanager` — CLI (`list`, `switch`, `greeter`, `ui`) ; -- `build/fws-deskmanager-gui` — interface graphique GTK4. +- `build/fws-deskmanager` — CLI (`list`, `switch`, `greeter`, `launch`, `ui`) ; +- `build/fws-deskmanager-gui` — interface graphique GTK4 ; +- `build/fws-deskmanager-launch` — seule partie exécutée en root, uniquement via + `pkexec` pendant le lancement d'un environnement. Installation optionnelle : @@ -70,10 +74,11 @@ La fenêtre liste **XFCE, GNOME, KDE Plasma, Hyprland et i3** avec leur état : - **Installé, session actuelle** → bouton « Écran de connexion » (se basculer sur soi-même n'aurait aucun effet). Le dialogue rappelle qu'il faut choisir un autre environnement dans le greeter : lancer deux fois le même environnement échoue. -- **Installé, aucune session** → bouton « Écran de connexion » : le greeter reprend - l'écran et le dialogue donne le nom exact de l'entrée à sélectionner (par ex. - « Xfce Session »). La session courante reste ouverte ; si le gestionnaire - d'affichage ne répond pas, l'outil propose explicitement de la fermer. +- **Installé, aucune session** → bouton « Lancer » : l'environnement est démarré sans + sélection dans le greeter. La confirmation rappelle que la session courante sera + fermée ; polkit demande l'authentification. Avec un gestionnaire d'affichage qui + n'accepte pas d'autologin ponctuel (GDM), le bouton reste « Écran de connexion » et + le dialogue donne le nom exact de l'entrée à sélectionner (par ex. « Xfce Session »). Le choix de l'environnement se fait **dans le greeter** : SDDM/GDM démarrent la session sur laquelle leur propre sélecteur est positionné (souvent la dernière @@ -110,6 +115,10 @@ fws-deskmanager list --json fws-deskmanager switch 3 fws-deskmanager switch GNOME +# Démarrer un environnement sans écran de connexion (ferme la session courante) +fws-deskmanager launch plasma +fws-deskmanager launch gnome --yes # sans confirmation, pour un script + # Afficher l'écran de connexion (la session courante reste ouverte) fws-deskmanager greeter fws-deskmanager greeter --yes # sans confirmation, pour un script @@ -152,7 +161,14 @@ l'autre en un clic, sans fermer la moindre application. 2. `session-switcher` appelle `loginctl activate ` : logind change de VT. Le changement est confirmé (`loginctl show-session -p Active`, jusqu'à 5 s) ; s'il n'aboutit pas, la session précédente est réactivée et l'échec est signalé. -3. `greeter` demande l'écran de connexion, sans rien tuer : interface +3. `launch` écrit un autologin ponctuel (`/etc/sddm.conf.d` ou + `/etc/lightdm/lightdm.conf.d`) via `pkexec`, redémarre `display-manager.service`, + attend qu'une session graphique de l'utilisateur devienne active sur le siège, puis + supprime le fichier : le compte n'est jamais laissé en connexion automatique. Les + sessions remplacées sont fermées par une unité systemd transitoire, pour que le + nettoyage survive à la session qu'il ferme. En cas d'échec, le fichier est retiré et + la session précédente réactivée. +4. `greeter` demande l'écran de connexion, sans rien tuer : interface `org.freedesktop.DisplayManager` (`SwitchToGreeter`) implémentée par GDM, SDDM et LightDM, puis `dm-tool switch-to-greeter`, puis activation d'une session `Class=greeter` déjà connue de logind. Après chaque tentative, l'outil vérifie que le siège a bien @@ -178,8 +194,15 @@ identifiants de session sont validés comme numériques. ## Limites connues -- **Session cible absente** : la bascule instantanée n'est possible qu'entre sessions - déjà ouvertes. Sinon, utiliser `greeter` (la session courante est fermée). +- **Session cible absente** : `launch` en démarre une (SDDM et LightDM), au prix de la + session courante et d'une authentification polkit ; avec GDM il faut passer par + `greeter`. +- **`launch` ferme la session courante** : les applications non enregistrées sont + perdues, comme une déconnexion. Les sessions des autres environnements déjà ouvertes + sont également fermées. +- **`launch` modifie la configuration du gestionnaire d'affichage** : un fichier + d'autologin est ajouté le temps du démarrage puis supprimé. Si le processus est tué + entre-temps, le supprimer à la main (`/etc/sddm.conf.d/zz-fws-autologin.conf`). - **Wayland** : impossible de lancer un compositeur Wayland depuis une session Wayland sans passer par logind/DRM master ; le démarrage direct n'est pas implémenté (#6). - **`greeter` ne ferme plus la session courante** : au login suivant, SDDM/GDM peuvent @@ -202,6 +225,8 @@ src/desktop-catalog.{h,cpp} XFCE/GNOME/KDE/Hyprland/i3, état pacman src/process.{h,cpp} Exécution sans shell, capture de sortie src/session-catalog.{h,cpp} Inventaire .desktop + logind src/session-switcher.{h,cpp} Activation de session, retour au greeter +src/session-launcher.{h,cpp} Démarrage sans greeter (autologin ponctuel) +src/launch-helper.cpp Binaire root appelé par pkexec src/user-interface.{h,cpp} Sélecteur zenity / kdialog / terminal ``` diff --git a/src/desktop-catalog.cpp b/src/desktop-catalog.cpp index 24b05c0..c62f177 100644 --- a/src/desktop-catalog.cpp +++ b/src/desktop-catalog.cpp @@ -32,15 +32,34 @@ bool targetInstalled(const std::string& target) { const std::vector& supportedDesktops() { static const std::vector desktops = { - {"xfce", "XFCE", {"xfce4"}, {"xfce", "xfce4"}}, - {"gnome", "GNOME", {"gnome"}, {"gnome"}}, - {"plasma", "KDE Plasma", {"plasma-meta"}, {"kde", "plasma"}}, - {"hyprland", "Hyprland", {"hyprland"}, {"hyprland"}}, - {"i3", "i3", {"i3"}, {"i3"}}, + {"xfce", "XFCE", {"xfce4"}, {"xfce", "xfce4"}, {"xfce", "xfce4-session"}}, + {"gnome", "GNOME", {"gnome"}, {"gnome"}, {"gnome", "gnome-xorg"}}, + // Plasma 6 renamed its session files; the Wayland entry comes first. + {"plasma", + "KDE Plasma", + {"plasma-meta"}, + {"kde", "plasma"}, + {"plasma", "plasmawayland", "plasmax11", "plasmadesktop"}}, + {"hyprland", "Hyprland", {"hyprland"}, {"hyprland"}, {"hyprland"}}, + {"i3", "i3", {"i3"}, {"i3"}, {"i3"}}, }; return desktops; } +const DesktopProfile* findDesktopProfile(const std::string& name) { + const std::string wanted = lower(name); + if (wanted.empty()) { + return nullptr; + } + for (const DesktopProfile& profile : supportedDesktops()) { + if (lower(profile.id) == wanted || lower(profile.name) == wanted || + lower(profile.name).rfind(wanted, 0) == 0) { + return &profile; + } + } + return nullptr; +} + bool isDesktopInstalled(const DesktopProfile& profile) { return std::all_of(profile.packages.begin(), profile.packages.end(), targetInstalled); } diff --git a/src/desktop-catalog.h b/src/desktop-catalog.h index 6446e8a..f9f4706 100644 --- a/src/desktop-catalog.h +++ b/src/desktop-catalog.h @@ -10,10 +10,14 @@ struct DesktopProfile { std::string name; std::vector packages; // pacman targets (packages or groups) std::vector sessionNames; // logind Desktop values to match + std::vector sessionFiles; // installed .desktop stems, most wanted first }; const std::vector& supportedDesktops(); +// Looks a profile up by id or name (case-insensitive), nullptr when unknown. +const DesktopProfile* findDesktopProfile(const std::string& name); + // True when every pacman target of the profile is installed. bool isDesktopInstalled(const DesktopProfile& profile); diff --git a/src/gui.cpp b/src/gui.cpp index a64ac17..272c856 100644 --- a/src/gui.cpp +++ b/src/gui.cpp @@ -5,11 +5,12 @@ #include "desktop-catalog.h" #include "session-catalog.h" +#include "session-launcher.h" #include "session-switcher.h" namespace { -enum class RowMode { Install, SwitchTo, Greeter }; +enum class RowMode { Install, SwitchTo, Greeter, Launch }; struct RowWidgets { const fws::DesktopProfile* profile = nullptr; @@ -72,6 +73,9 @@ private: case RowMode::Greeter: self->askGreeter(*row.profile); break; + case RowMode::Launch: + self->askLaunch(*row.profile); + break; } } @@ -125,6 +129,21 @@ private: self->goToGreeter(true); } + static void onLaunchChosen(GObject* source, GAsyncResult* result, gpointer data) { + auto* self = static_cast(data); + GError* error = nullptr; + const int response = + gtk_alert_dialog_choose_finish(GTK_ALERT_DIALOG(source), result, &error); + if (error != nullptr) { + g_error_free(error); + return; + } + if (response != 1 || self->launchProfile_ == nullptr) { + return; + } + self->startLaunch(*self->launchProfile_); + } + void buildWindow(GtkApplication* application) { window_ = gtk_application_window_new(application); gtk_window_set_title(GTK_WINDOW(window_), "FWS DeskManager"); @@ -149,8 +168,8 @@ private: gtk_window_set_child(GTK_WINDOW(window_), root); GtkWidget* intro = gtk_label_new( - "Installez un environnement puis basculez dessus sans redémarrer. " - "La bascule instantanée nécessite une session déjà ouverte pour cet environnement."); + "Installez un environnement puis lancez-le sans passer par l'ecran de connexion : " + "la session precedente est fermee au profit de la nouvelle."); gtk_label_set_wrap(GTK_LABEL(intro), TRUE); gtk_label_set_xalign(GTK_LABEL(intro), 0.0F); gtk_widget_add_css_class(intro, "dim-label"); @@ -291,23 +310,41 @@ private: gtk_widget_add_css_class(row.action, "suggested-action"); row.mode = RowMode::SwitchTo; } else { - // The greeter opens on the session it remembered, not on the one - // this row points at, so the entry to pick is named right here. - const std::string entry = fws::greeterSessionName(row.profile->sessionNames); - if (entry.empty()) { + // Without a display manager that supports one-shot autologin, + // the greeter stays the only way in. + std::string reason; + if (fws::canStartWithoutGreeter(reason)) { gtk_label_set_markup(GTK_LABEL(row.status), - "Installé · aucune session"); + "Installé · aucune " + "session"); + gtk_button_set_label(GTK_BUTTON(row.action), "Lancer"); + gtk_widget_set_tooltip_text( + row.action, + "Démarrer l'environnement sans écran de connexion : la session " + "actuelle sera fermée."); + gtk_widget_add_css_class(row.action, "suggested-action"); + row.mode = RowMode::Launch; } else { - gchar* markup = g_markup_printf_escaped( - "Installé · aucune session · choisir " - "« %s » au greeter", - entry.c_str()); - gtk_label_set_markup(GTK_LABEL(row.status), markup); - g_free(markup); + // The greeter opens on the session it remembered, not on the one + // this row points at, so the entry to pick is named right here. + const std::string entry = fws::greeterSessionName(row.profile->sessionNames); + if (entry.empty()) { + gtk_label_set_markup(GTK_LABEL(row.status), + "Installé · " + "aucune session"); + } else { + gchar* markup = g_markup_printf_escaped( + "Installé · aucune session · " + "choisir « %s » au greeter", + entry.c_str()); + gtk_label_set_markup(GTK_LABEL(row.status), markup); + g_free(markup); + } + gtk_button_set_label(GTK_BUTTON(row.action), "Écran de connexion"); + gtk_widget_set_tooltip_text(row.action, nullptr); + gtk_widget_add_css_class(row.action, "destructive-action"); + row.mode = RowMode::Greeter; } - gtk_button_set_label(GTK_BUTTON(row.action), "Écran de connexion"); - gtk_widget_add_css_class(row.action, "destructive-action"); - row.mode = RowMode::Greeter; } gtk_widget_set_sensitive(row.action, selfBusy() ? FALSE : TRUE); @@ -471,6 +508,44 @@ private: setStatus("Retour à l'écran de connexion impossible."); } + // Starting a session replaces the current one, so the decision is explicit + // before polkit asks for the password. + void askLaunch(const fws::DesktopProfile& profile) { + launchProfile_ = &profile; + const std::string message = + "Lancer " + profile.name + + " sans passer par l'ecran de connexion ?\n\nLa session courante sera fermee : " + "les applications non enregistrees seront perdues. L'authentification est " + "demandee par polkit."; + GtkAlertDialog* dialog = gtk_alert_dialog_new("%s", message.c_str()); + const char* buttons[] = {"Annuler", "Lancer et fermer", nullptr}; + gtk_alert_dialog_set_buttons(dialog, buttons); + gtk_alert_dialog_set_cancel_button(dialog, 0); + gtk_alert_dialog_set_default_button(dialog, 1); + gtk_alert_dialog_choose(dialog, GTK_WINDOW(window_), nullptr, + &ManagerWindow::onLaunchChosen, this); + g_object_unref(dialog); + } + + void startLaunch(const fws::DesktopProfile& profile) { + setStatus("Lancement de " + profile.name + " sans écran de connexion…"); + setBusy(true, "Lancement de " + profile.name + "…"); + flushPendingEvents(); + + // Blocks while the display manager restarts and autologins; the window is + // then closed with the session it belongs to. + const fws::LaunchOutcome outcome = fws::launchDesktop(profile); + if (!outcome.ok) { + setBusy(false, "Échec du lancement de " + profile.name + "."); + showError(outcome.error); + refreshRows(); + return; + } + + setBusy(false, profile.name + " a démarré ; la session précédente se ferme."); + refreshRows(); + } + void showError(const std::string& message) { GtkAlertDialog* dialog = gtk_alert_dialog_new("%s", message.c_str()); gtk_alert_dialog_show(dialog, GTK_WINDOW(window_)); @@ -506,6 +581,8 @@ private: std::vector rows_; GSubprocess* pending_ = nullptr; bool busy_ = false; + // Filled by askLaunch(): the profile the pending dialog starts. + const fws::DesktopProfile* launchProfile_ = nullptr; // Filled by askGreeter(): the greeter entry to name once it is on screen. std::string greeterEntry_; bool greeterIsCurrent_ = false; diff --git a/src/launch-helper.cpp b/src/launch-helper.cpp new file mode 100644 index 0000000..1147bb6 --- /dev/null +++ b/src/launch-helper.cpp @@ -0,0 +1,19 @@ +#include "session-launcher.h" + +#include +#include + +// Installed setuid-free helper started by session-launcher.cpp through pkexec: +// it is the only part of the tool that runs as root, and only for as long as one +// launch takes. +int main(int argc, char** argv) { + if (argc < 2 || std::string(argv[1]) != "launch") { + std::cerr << "Usage : fws-deskmanager-launch launch \n"; + return 1; + } + if (argc != 4) { + std::cerr << "Usage : fws-deskmanager-launch launch \n"; + return 1; + } + return fws::runLaunchHelper(argv[2], argv[3]); +} diff --git a/src/main.cpp b/src/main.cpp index e62857d..a4755cf 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -1,5 +1,6 @@ #include "process.h" #include "session-catalog.h" +#include "session-launcher.h" #include "session-switcher.h" #include "user-interface.h" @@ -33,6 +34,10 @@ void printUsage() { " --force redemarre le gestionnaire " "d'affichage et ferme la session)\n" " fws-deskmanager ui selecteur zenity / kdialog / terminal\n" + " fws-deskmanager launch [--yes]\n" + " demarrer un environnement sans ecran de " + "connexion\n" + " (la session courante est fermee)\n" " fws-deskmanager help afficher cette aide\n\n" "Codes de sortie : 0 succes, 1 usage, 2 introuvable, 3 echec.\n"; } @@ -168,6 +173,15 @@ bool resolveSession(const std::string& target, const std::vector [--yes]\n"; + return kExitUsage; + } + + bool assumeYes = false; + for (int index = 3; index < argc; ++index) { + const std::string flag = argv[index]; + if (flag == "--yes" || flag == "-y") { + assumeYes = true; + } else { + std::cerr << "Option inconnue : " << flag << "\n"; + return kExitUsage; + } + } + + const fws::DesktopProfile* profile = fws::findDesktopProfile(argv[2]); + if (profile == nullptr) { + std::cerr << "Environnement inconnu : " << argv[2] + << "\nEnvironnements geres : xfce, gnome, plasma, hyprland, i3.\n"; + return kExitNotFound; + } + + if (!confirmLaunch(assumeYes, profile->name)) { + std::cout << "Annule.\n"; + return kExitOk; + } + + const fws::LaunchOutcome outcome = fws::launchDesktop(*profile); + if (!outcome.ok) { + std::cerr << "Echec du lancement : " << outcome.error << "\n"; + return kExitFailure; + } + return kExitOk; + } + if (command == "ui") { return fws::runUi(); } diff --git a/src/session-catalog.cpp b/src/session-catalog.cpp index a88e899..845f3d5 100644 --- a/src/session-catalog.cpp +++ b/src/session-catalog.cpp @@ -224,8 +224,11 @@ std::string greeterSessionName(const std::vector& desktopNames) { } std::vector listGraphicalSessions() { + return listGraphicalSessionsForUid(std::to_string(getuid())); +} + +std::vector listGraphicalSessionsForUid(const std::string& uid) { std::vector sessions; - const std::string uid = std::to_string(getuid()); for (const SessionRow& row : listSessionRows()) { if (row.uid != uid) { continue; diff --git a/src/session-catalog.h b/src/session-catalog.h index 0590f1a..00a469c 100644 --- a/src/session-catalog.h +++ b/src/session-catalog.h @@ -31,6 +31,9 @@ std::vector listInstalledDesktops(); // Reads the current user's graphical sessions from systemd-logind. std::vector listGraphicalSessions(); +// Same, for one uid: the privileged helper looks at another account. +std::vector listGraphicalSessionsForUid(const std::string& uid); + // Looks up one of the current user's graphical sessions by logind id. bool findGraphicalSession(const std::string& id, SessionInfo& session); diff --git a/src/session-launcher.cpp b/src/session-launcher.cpp new file mode 100644 index 0000000..18c53ff --- /dev/null +++ b/src/session-launcher.cpp @@ -0,0 +1,425 @@ +#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 + +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(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(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 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; +} + +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 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(); + + 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 diff --git a/src/session-launcher.h b/src/session-launcher.h new file mode 100644 index 0000000..c32bd4f --- /dev/null +++ b/src/session-launcher.h @@ -0,0 +1,30 @@ +#pragma once + +#include + +#include "desktop-catalog.h" + +namespace fws { + +struct LaunchOutcome { + bool ok = false; + std::string error; +}; + +// Installed session file (.desktop stem) of the profile, empty when the +// environment itself is missing. +std::string installedSessionFile(const DesktopProfile& profile); + +// True when the display manager can be driven by a one-shot autologin, which is +// what makes starting a session possible without picking it in the greeter. +bool canStartWithoutGreeter(std::string& reason); + +// Activates the profile's running session, or starts one through the privileged +// helper (polkit) and closes the sessions it replaces. +LaunchOutcome launchDesktop(const DesktopProfile& profile); + +// Privileged side, run by fws-deskmanager-launch as root. Returns 0 when the +// requested session took the seat and the replaced sessions are closing. +int runLaunchHelper(const std::string& user, const std::string& sessionFile); + +} // namespace fws