Compare commits

...
4 Commits
Author SHA1 Message Date
BlackAngelTV de60395776 docs: describe the greeter flow that keeps the session open
The old text promised that the greeter closes the current session, which is
no longer true for GDM and LightDM, and it did not explain why SDDM needs a
display manager restart or how the session entry is chosen at login.
2026-11-04 15:42:22 +01:00
BlackAngelTV b48ae70c24 feat(session): verify switches and recover when the greeter stays away
logind accepts loginctl activate and SwitchToGreeter before the graphics
stack moves the seat, and SDDM 0.21 answers SwitchToGreeter with a greeter
whose logins never start a session. Each request is now confirmed within a
timeout and the previous session is reactivated on failure, so no path can
leave a blank VT. When nothing answers, both front-ends offer to restart
display-manager.service through polkit, and only after that is the session
terminated.
2026-11-04 15:42:22 +01:00
BlackAngelTV f7789cd639 feat(session): read session state and greeter entries from logind
Switching needs to know whether a session owns the seat, is closing, or is
the greeter, and which session file the greeter will list for a desktop.
The catalog now keeps the logind State, exposes targeted lookups, and prefers
the active session so a closing one is never activated. Session ids are
compared numerically without std::stoi.
2026-11-04 15:42:22 +01:00
BlackAngelTV 265d0f4648 fix(process): report a failed exec as an unstarted command
A missing binary used to be indistinguishable from a program exiting with
127, so callers treated a command that never ran as a started process. A
close-on-exec pipe now carries the errno back to the parent and the failure
reaches the caller as output.
2026-11-04 15:42:22 +01:00
11 changed files with 833 additions and 122 deletions

No files matched your search

+55 -10
View File
@@ -20,8 +20,10 @@ Aucun privilège root, aucun service à installer, aucun redémarrage.
- `list` : environnement installés (`.desktop`) et sessions graphiques actives (logind).
- `switch` : bascule vers une session existante, par identifiant ou par environnement.
- `greeter` : retour au gestionnaire d'affichage (SDDM/LightDM) sans reboot, pour
choisir un environnement qui n'a pas encore de session ouverte.
- `greeter` : retour au gestionnaire d'affichage (GDM/SDDM/LightDM) sans reboot, pour
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.
- `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`.
@@ -63,9 +65,36 @@ La fenêtre liste **XFCE, GNOME, KDE Plasma, Hyprland et i3** avec leur état :
- **Non installé** → bouton « Installer » : `pkexec pacman -S --needed` (authentification
polkit, aucune élévation permanente).
- **Installé, session active** → bouton « Basculer » : `loginctl activate`, sans fermer
la session quittée.
- **Installé, aucune session** → bouton « Écran de connexion » : retour au greeter pour
ouvrir l'environnement (la session courante est fermée).
la session quittée. La bascule est vérifiée : si le siège ne change pas, l'outil
revient de lui-même à la session précédente.
- **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.
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
utilisée) et aucun outil externe ne peut changer cette sélection à leur place —
sur SDDM, c'est le bouton en forme de roue dentée à côté du champ mot de passe.
Avec **SDDM 0.21**, `SwitchToGreeter` ouvre un greeter supplémentaire (VT en plus,
serveur X en plus) dont les connexions n'aboutissent pas : SDDM arrête ce greeter
sans jamais afficher `Session started`, et le siège revient au VT quitté. L'outil
n'appelle donc **pas** cette interface quand le gestionnaire d'affichage est
SDDM : il propose de redémarrer le gestionnaire (`--force` en CLI, second dialogue
en GUI).
Ce redémarrage ne dépend pas du gestionnaire installé : `display-manager.service`
est l'alias systemd commun à SDDM, GDM, LightDM et Ly, et un démon redémarré
reprend l'écran par lui-même avec un greeter neuf — c'est le seul chemin qui
fonctionne quel que soit le gestionnaire. L'outil vérifie ensuite qu'une session
`greeter` est bien devenue active sur le siège, et signale l'échec au lieu de
laisser croire que l'écran de connexion est là. Si aucun `display-manager.service`
n'existe (greetd, `startx`), il ferme la session et laisse le gestionnaire
afficher son écran de connexion, comme un logout classique.
Le bouton d'actualisation relit l'état pacman et les sessions logind. Les détails de
l'installation (sortie pacman) sont disponibles dans un panneau dépliable.
@@ -81,9 +110,10 @@ fws-deskmanager list --json
fws-deskmanager switch 3
fws-deskmanager switch GNOME
# Revenir au greeter (ferme la session courante)
# Afficher l'écran de connexion (la session courante reste ouverte)
fws-deskmanager greeter
fws-deskmanager greeter --yes # sans confirmation, pour un script
fws-deskmanager greeter --force # redémarre le gestionnaire d'affichage (dernier recours)
# Sélecteur graphique ou terminal
fws-deskmanager ui
@@ -119,9 +149,20 @@ l'autre en un clic, sans fermer la moindre application.
1. `session-catalog` lit `/usr/share/xsessions` et `/usr/share/wayland-sessions`, puis
interroge `loginctl list-sessions` et `loginctl show-session` (Type, Class, Active,
Desktop, TTY).
2. `session-switcher` appelle `loginctl activate <id>` : logind change de VT.
3. `greeter` utilise l'interface standard `org.freedesktop.DisplayManager.Seat.SwitchToGreeter`
via `busctl`, avec `dm-tool switch-to-greeter` en secours.
2. `session-switcher` appelle `loginctl activate <id>` : 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
`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
bougé et sinon réactive la session courante : aucun VT noir n'est laissé derrière.
Sous SDDM 0.21 cette interface est contournée (voir « Interface graphique »),
pour la même raison que ci-dessus. `--force` redémarre
`display-manager.service` via polkit — l'alias commun à tous les gestionnaires —
puis vérifie qu'une session `greeter` est devenue active sur le siège. Sans
`display-manager.service` (greetd, `startx`), il ferme la session
(`loginctl terminate-session`) et c'est le gestionnaire qui reprend l'écran.
Les commandes sont exécutées sans shell intermédiaire (`fork`/`execvp`), et les
identifiants de session sont validés comme numériques.
@@ -141,7 +182,11 @@ identifiants de session sont validés comme numériques.
déjà ouvertes. Sinon, utiliser `greeter` (la session courante est fermée).
- **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` ferme la session courante** : les applications non enregistrées sont perdues.
- **`greeter` ne ferme plus la session courante** : au login suivant, SDDM/GDM peuvent
proposer de revenir à la session encore ouverte. `--force` redémarre le gestionnaire
d'affichage pour forcer un démarrage propre de l'environnement choisi (applications
non enregistrées perdues, authentification polkit demandée) ; si l'authentification
est annulée, rien n'est fermé.
- **polkit** : `loginctl activate` ou `SwitchToGreeter` peuvent demander une
authentification selon la configuration du système.
- **Non testé sur cette machine** : seuls Hyprland et Openbox y sont installés ; la
+25 -3
View File
@@ -46,16 +46,38 @@ bool isDesktopInstalled(const DesktopProfile& profile) {
}
bool findActiveSession(const DesktopProfile& profile, std::string& sessionId) {
// Prefer the session that owns the seat: a stale or closing session of the
// same desktop would activate a VT that has nothing left to draw.
std::string fallback;
for (const SessionInfo& session : listGraphicalSessions()) {
if (session.state == "closing" || session.state == "closing-failed") {
continue;
}
const std::string desktop = lower(session.desktop);
bool matches = false;
for (const std::string& name : profile.sessionNames) {
if (desktop == lower(name)) {
sessionId = session.id;
return true;
matches = true;
break;
}
}
if (!matches) {
continue;
}
if (session.active) {
sessionId = session.id;
return true;
}
if (fallback.empty()) {
fallback = session.id;
}
}
return false;
if (fallback.empty()) {
return false;
}
sessionId = fallback;
return true;
}
std::vector<std::string> installArguments(const DesktopProfile& profile) {
+1 -1
View File
@@ -17,7 +17,7 @@ const std::vector<DesktopProfile>& supportedDesktops();
// True when every pacman target of the profile is installed.
bool isDesktopInstalled(const DesktopProfile& profile);
// Finds an active logind session for the profile.
// Finds a logind session for the profile, preferring the one on the seat.
bool findActiveSession(const DesktopProfile& profile, std::string& sessionId);
// pkexec + pacman command used to install the profile.
+156 -16
View File
@@ -4,6 +4,7 @@
#include <vector>
#include "desktop-catalog.h"
#include "session-catalog.h"
#include "session-switcher.h"
namespace {
@@ -69,7 +70,7 @@ private:
self->switchTo(*row.profile);
break;
case RowMode::Greeter:
self->askGreeter();
self->askGreeter(*row.profile);
break;
}
}
@@ -92,18 +93,36 @@ private:
g_clear_object(&self->pending_);
}
static void onGreeterResponse(GtkAlertDialog*, int response, gpointer data) {
// GtkAlertDialog exposes no "response" signal: the chosen button index is
// only available from gtk_alert_dialog_choose_finish().
static void onGreeterChosen(GObject* source, GAsyncResult* result, gpointer data) {
auto* self = static_cast<ManagerWindow*>(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) {
return;
}
self->goToGreeter(false);
}
static void onForceChosen(GObject* source, GAsyncResult* result, gpointer data) {
auto* self = static_cast<ManagerWindow*>(data);
std::string error;
if (!fws::switchToGreeter(error)) {
self->showError("Impossible de revenir au greeter : " + error);
} else {
self->setStatus("Retour à l'écran de connexion…");
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) {
return;
}
self->goToGreeter(true);
}
void buildWindow(GtkApplication* application) {
@@ -223,11 +242,30 @@ private:
}
}
// The session this window runs in: XDG_SESSION_ID, or the seat's active one
// when the variable is missing (pkexec, systemd-run...).
fws::SessionInfo currentSession() const {
fws::SessionInfo session;
if (fws::findGraphicalSession(fws::currentSessionId(), session)) {
return session;
}
fws::findGraphicalSession(fws::activeGraphicalSessionId(), session);
return session;
}
// Lets the status text paint before the blocking logind calls run.
static void flushPendingEvents() {
while (g_main_context_iteration(nullptr, FALSE) != FALSE) {
}
}
void refreshRows() {
const std::string current = currentSession().id;
for (RowWidgets& row : rows_) {
std::string sessionId;
const bool installed = fws::isDesktopInstalled(*row.profile);
const bool active = installed && fws::findActiveSession(*row.profile, sessionId);
const bool isCurrent = active && !current.empty() && sessionId == current;
gtk_widget_remove_css_class(row.action, "suggested-action");
gtk_widget_remove_css_class(row.action, "destructive-action");
@@ -238,6 +276,14 @@ private:
gtk_button_set_label(GTK_BUTTON(row.action), "Installer");
gtk_widget_add_css_class(row.action, "suggested-action");
row.mode = RowMode::Install;
} else if (isCurrent) {
gtk_label_set_markup(GTK_LABEL(row.status),
"<span foreground='#26a269'>Installé</span> · session actuelle");
// Activating the session already on screen would do nothing, so
// the useful action from here is leaving for the greeter.
gtk_button_set_label(GTK_BUTTON(row.action), "Écran de connexion");
gtk_widget_add_css_class(row.action, "suggested-action");
row.mode = RowMode::Greeter;
} else if (active) {
gtk_label_set_markup(GTK_LABEL(row.status),
"<span foreground='#26a269'>Installé</span> · session active");
@@ -245,8 +291,20 @@ private:
gtk_widget_add_css_class(row.action, "suggested-action");
row.mode = RowMode::SwitchTo;
} else {
gtk_label_set_markup(GTK_LABEL(row.status),
"<span foreground='#26a269'>Installé</span> · aucune session");
// 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),
"<span foreground='#26a269'>Installé</span> · aucune session");
} else {
gchar* markup = g_markup_printf_escaped(
"<span foreground='#26a269'>Installé</span> · 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_add_css_class(row.action, "destructive-action");
row.mode = RowMode::Greeter;
@@ -312,28 +370,107 @@ private:
return;
}
if (sessionId == currentSession().id) {
setStatus("Vous êtes déjà sur " + profile.name + ".");
return;
}
// activateSession waits for the seat to move and rolls back, so the
// window blocks for a few seconds instead of leaving a black VT behind.
setStatus("Bascule vers " + profile.name + "…");
flushPendingEvents();
std::string error;
if (!fws::activateSession(sessionId, error)) {
showError("Échec de la bascule : " + error);
setStatus("La session précédente a été conservée.");
return;
}
setStatus("Bascule vers " + profile.name + "…");
}
void askGreeter() {
GtkAlertDialog* dialog = gtk_alert_dialog_new(
"%s",
"La session graphique courante sera fermée. Les applications non enregistrées "
"seront perdues. Continuer ?");
// The greeter starts whichever session its own selector is set on, and no
// bus API lets us choose it: the dialog names the entry to pick before the
// user is sent to another VT, where this window is no longer visible.
void askGreeter(const fws::DesktopProfile& profile) {
std::string sessionId;
const bool running = fws::findActiveSession(profile, sessionId);
greeterIsCurrent_ = running && sessionId == currentSession().id;
greeterEntry_ = fws::greeterSessionName(profile.sessionNames);
std::string message;
if (greeterIsCurrent_) {
message = profile.name +
" tourne deja dans votre session. Sur l'ecran de connexion, ouvrez le "
"selecteur de session et choisissez un autre environnement : relancer "
"le meme environnement ne demarre pas une seconde session. Rien n'est "
"ferme ici.";
} else if (!greeterEntry_.empty()) {
message = "L'ecran de connexion va s'afficher. Choisissez « " + greeterEntry_ +
" » dans le selecteur de session, puis connectez-vous : c'est ce choix "
"qui decide de l'environnement demarre.";
} else {
message = "L'ecran de connexion va s'afficher. Choisissez " + profile.name +
" dans le selecteur de session, puis connectez-vous.";
}
GtkAlertDialog* dialog = gtk_alert_dialog_new("%s", message.c_str());
const char* buttons[] = {"Annuler", "Continuer", nullptr};
gtk_alert_dialog_set_buttons(dialog, buttons);
gtk_alert_dialog_set_cancel_button(dialog, 0);
gtk_alert_dialog_set_default_button(dialog, 1);
g_signal_connect(dialog, "response", G_CALLBACK(&ManagerWindow::onGreeterResponse), this);
gtk_alert_dialog_show(dialog, GTK_WINDOW(window_));
gtk_alert_dialog_choose(dialog, GTK_WINDOW(window_), nullptr,
&ManagerWindow::onGreeterChosen, this);
g_object_unref(dialog);
}
void askForce(const std::string& reason) {
const std::string message =
reason +
"\n\nRedemarrer le gestionnaire d'affichage pour retrouver un ecran de connexion ? "
"L'authentification est demandee par polkit ; la session courante sera fermee et "
"les applications non enregistrees seront perdues.";
GtkAlertDialog* dialog = gtk_alert_dialog_new("%s", message.c_str());
const char* buttons[] = {"Annuler", "Redemarrer 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, 0);
gtk_alert_dialog_choose(dialog, GTK_WINDOW(window_), nullptr,
&ManagerWindow::onForceChosen, this);
g_object_unref(dialog);
}
void goToGreeter(bool force) {
setStatus(force ? "Redémarrage de l'écran de connexion…"
: "Ouverture de l'écran de connexion…");
flushPendingEvents();
const fws::GreeterOutcome outcome = fws::switchToGreeter(force);
if (outcome.ok) {
if (force) {
setStatus("Écran de connexion redémarré.");
} else if (!greeterIsCurrent_ && !greeterEntry_.empty()) {
setStatus("Écran de connexion affiché : choisissez « " + greeterEntry_ +
" » dans le sélecteur de session pour l'ouvrir.");
} else {
setStatus("Écran de connexion affiché ; la session reste ouverte.");
}
refreshRows();
return;
}
// Nothing has been closed yet: offer the destructive path explicitly
// instead of dropping the user on a blank VT.
if (outcome.forceRequired && !force) {
askForce(outcome.error);
setStatus("La session courante a été conservée.");
return;
}
showError(outcome.error);
setStatus("Retour à l'écran de connexion impossible.");
}
void showError(const std::string& message) {
GtkAlertDialog* dialog = gtk_alert_dialog_new("%s", message.c_str());
gtk_alert_dialog_show(dialog, GTK_WINDOW(window_));
@@ -369,6 +506,9 @@ private:
std::vector<RowWidgets> rows_;
GSubprocess* pending_ = nullptr;
bool busy_ = false;
// Filled by askGreeter(): the greeter entry to name once it is on screen.
std::string greeterEntry_;
bool greeterIsCurrent_ = false;
};
} // namespace
+38 -9
View File
@@ -27,7 +27,11 @@ void printUsage() {
"Usage :\n"
" fws-deskmanager list [--json] inventaire des environnements et sessions\n"
" fws-deskmanager switch <id> activer une session graphique existante\n"
" fws-deskmanager greeter [--yes] revenir au gestionnaire d'affichage\n"
" fws-deskmanager greeter [--yes] [--force]\n"
" afficher l'ecran de connexion (session "
"conservee ;\n"
" --force redemarre le gestionnaire "
"d'affichage et ferme la session)\n"
" fws-deskmanager ui selecteur zenity / kdialog / terminal\n"
" fws-deskmanager help afficher cette aide\n\n"
"Codes de sortie : 0 succes, 1 usage, 2 introuvable, 3 echec.\n";
@@ -164,12 +168,18 @@ bool resolveSession(const std::string& target, const std::vector<fws::SessionInf
return false;
}
bool confirmGreeter(bool assumeYes) {
bool confirmGreeter(bool assumeYes, bool force) {
if (assumeYes) {
return true;
}
std::cout << "La session graphique va etre fermee et les applications non enregistrees "
"seront perdues.\nContinuer ? [o/N] ";
if (force) {
std::cout << "Le gestionnaire d'affichage va etre redemarre (authentification "
"demandee) : la session graphique courante sera fermee et les "
"applications non enregistrees seront perdues.\nContinuer ? [o/N] ";
} else {
std::cout << "L'ecran de connexion du gestionnaire d'affichage va s'afficher ; la "
"session courante reste ouverte.\nContinuer ? [o/N] ";
}
std::string answer;
if (!std::getline(std::cin, answer)) {
return false;
@@ -229,15 +239,34 @@ int main(int argc, char** argv) {
}
if (command == "greeter") {
const bool assumeYes = argc >= 3 && std::string(argv[2]) == "--yes";
if (!confirmGreeter(assumeYes)) {
bool assumeYes = false;
bool force = false;
for (int index = 2; index < argc; ++index) {
const std::string flag = argv[index];
if (flag == "--yes" || flag == "-y") {
assumeYes = true;
} else if (flag == "--force") {
force = true;
} else {
std::cerr << "Option inconnue : " << flag << "\n";
return kExitUsage;
}
}
if (!confirmGreeter(assumeYes, force)) {
std::cout << "Annule.\n";
return kExitOk;
}
std::string error;
if (!fws::switchToGreeter(error)) {
std::cerr << "Echec du retour au greeter : " << error << "\n";
// Without --force nothing is terminated, so a display manager that stays
// silent can never leave the machine on a blank VT.
const fws::GreeterOutcome outcome = fws::switchToGreeter(force);
if (!outcome.ok) {
std::cerr << "Echec du retour au greeter : " << outcome.error << "\n";
if (outcome.forceRequired) {
std::cerr << "Relancez avec --force pour redemarrer le gestionnaire "
"d'affichage et retrouver un ecran de connexion.\n";
}
return kExitFailure;
}
return kExitOk;
+52 -13
View File
@@ -6,8 +6,11 @@
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <fcntl.h>
namespace fws {
CommandResult runCommand(const std::vector<std::string>& arguments) {
@@ -16,23 +19,44 @@ CommandResult runCommand(const std::vector<std::string>& arguments) {
return result;
}
int pipeFds[2];
if (pipe(pipeFds) != 0) {
int outputPipe[2];
if (pipe(outputPipe) != 0) {
return result;
}
int execPipe[2];
if (pipe(execPipe) != 0) {
close(outputPipe[0]);
close(outputPipe[1]);
return result;
}
// A close-on-exec pipe reports whether execvp() took over: the parent reads
// EOF only when the program really started, so a missing binary is no longer
// reported as exit code 127 from a successfully started command.
if (fcntl(execPipe[1], F_SETFD, FD_CLOEXEC) != 0) {
close(outputPipe[0]);
close(outputPipe[1]);
close(execPipe[0]);
close(execPipe[1]);
return result;
}
const pid_t pid = fork();
if (pid < 0) {
close(pipeFds[0]);
close(pipeFds[1]);
close(outputPipe[0]);
close(outputPipe[1]);
close(execPipe[0]);
close(execPipe[1]);
return result;
}
if (pid == 0) {
close(pipeFds[0]);
dup2(pipeFds[1], STDOUT_FILENO);
dup2(pipeFds[1], STDERR_FILENO);
close(pipeFds[1]);
close(outputPipe[0]);
close(execPipe[0]);
dup2(outputPipe[1], STDOUT_FILENO);
dup2(outputPipe[1], STDERR_FILENO);
close(outputPipe[1]);
std::vector<char*> argv;
argv.reserve(arguments.size() + 1);
@@ -42,23 +66,38 @@ CommandResult runCommand(const std::vector<std::string>& arguments) {
argv.push_back(nullptr);
execvp(argv[0], argv.data());
const int failure = errno;
// Short write to a fresh pipe cannot block; the value is only a hint.
ssize_t written = write(execPipe[1], &failure, sizeof(failure));
(void)written;
_exit(127);
}
close(pipeFds[1]);
close(outputPipe[1]);
close(execPipe[1]);
int execFailure = 0;
const ssize_t execRead = read(execPipe[0], &execFailure, sizeof(execFailure));
close(execPipe[0]);
char buffer[4096];
ssize_t count = 0;
while ((count = read(pipeFds[0], buffer, sizeof(buffer))) > 0) {
while ((count = read(outputPipe[0], buffer, sizeof(buffer))) > 0) {
result.output.append(buffer, static_cast<std::size_t>(count));
}
close(pipeFds[0]);
close(outputPipe[0]);
int status = 0;
while (waitpid(pid, &status, 0) < 0 && errno == EINTR) {
}
result.started = true;
result.exitCode = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
result.started = execRead == 0;
if (result.started) {
result.exitCode = WIFEXITED(status) ? WEXITSTATUS(status) : -1;
} else if (execFailure != 0) {
result.output += std::string("execvp: ") + std::strerror(execFailure);
}
return result;
}
+162 -41
View File
@@ -74,6 +74,89 @@ std::string valueForKey(const std::vector<std::string>& lines, const std::string
return {};
}
bool isSessionId(const std::string& value) {
return !value.empty() &&
std::all_of(value.begin(), value.end(),
[](unsigned char character) { return std::isdigit(character) != 0; });
}
struct SessionRow {
std::string id;
std::string uid;
std::string user;
std::string seat;
std::string tty;
};
// Every logind session, whatever its owner: greeter sessions belong to the
// display manager account, not to the person in front of the screen.
std::vector<SessionRow> listSessionRows() {
std::vector<SessionRow> rows;
const CommandResult listing = runCommand({"loginctl", "list-sessions", "--no-legend"});
if (!listing.started || listing.exitCode != 0) {
return rows;
}
for (const std::string& line : splitLines(listing.output)) {
std::istringstream stream(line);
SessionRow row;
if (!(stream >> row.id >> row.uid >> row.user >> row.seat >> row.tty)) {
continue;
}
if (!isSessionId(row.id)) {
continue;
}
rows.push_back(std::move(row));
}
return rows;
}
std::vector<std::string> sessionProperties(const std::string& id,
const std::vector<std::string>& names) {
std::vector<std::string> arguments = {"loginctl", "show-session", id};
for (const std::string& name : names) {
arguments.push_back("-p");
arguments.push_back(name);
}
const CommandResult details = runCommand(arguments);
if (!details.started || details.exitCode != 0) {
return {};
}
return splitLines(details.output);
}
SessionInfo describeSession(const SessionRow& row) {
SessionInfo info;
info.id = row.id;
info.user = row.user;
info.seat = row.seat;
info.tty = row.tty;
const std::vector<std::string> properties =
sessionProperties(row.id, {"Type", "Class", "Active", "Desktop", "TTY", "Seat", "State"});
if (properties.empty()) {
return info;
}
info.type = valueForKey(properties, "Type");
// logind is authoritative: the list columns can lag behind a VT switch.
info.seat = valueForKey(properties, "Seat");
info.tty = valueForKey(properties, "TTY");
info.desktop = valueForKey(properties, "Desktop");
info.state = valueForKey(properties, "State");
info.active = valueForKey(properties, "Active") == "yes";
info.graphical = valueForKey(properties, "Class") == "user" &&
(info.type == "x11" || info.type == "wayland");
return info;
}
// Session ids are numeric, so comparing length first keeps the order numeric
// without parsing (and without std::stoi throwing on an unexpected value).
bool idBefore(const std::string& left, const std::string& right) {
return left.size() != right.size() ? left.size() < right.size() : left < right;
}
} // namespace
std::vector<DesktopEntry> listInstalledDesktops() {
@@ -117,60 +200,98 @@ std::vector<DesktopEntry> listInstalledDesktops() {
return entries;
}
std::string greeterSessionName(const std::vector<std::string>& desktopNames) {
std::string fromDesktopNames;
for (const DesktopEntry& entry : listInstalledDesktops()) {
for (const std::string& name : desktopNames) {
const std::string wanted = lower(name);
if (lower(entry.id) == wanted || lower(entry.name) == wanted) {
return entry.name;
}
// DesktopNames is a semicolon separated list, e.g. "XFCE".
std::istringstream values(lower(entry.desktops));
std::string value;
while (std::getline(values, value, ';')) {
if (trim(value) == wanted && fromDesktopNames.empty()) {
fromDesktopNames = entry.name;
}
}
}
}
// DesktopNames also matches the other session files of the same desktop, so
// the id/name match above wins and this is only the fallback.
return fromDesktopNames;
}
std::vector<SessionInfo> listGraphicalSessions() {
std::vector<SessionInfo> sessions;
const CommandResult listing = runCommand({"loginctl", "list-sessions", "--no-legend"});
if (!listing.started || listing.exitCode != 0) {
return sessions;
}
const std::string uid = std::to_string(getuid());
for (const std::string& line : splitLines(listing.output)) {
std::istringstream stream(line);
std::string id;
std::string sessionUid;
std::string user;
std::string seat;
std::string tty;
if (!(stream >> id >> sessionUid >> user >> seat >> tty)) {
for (const SessionRow& row : listSessionRows()) {
if (row.uid != uid) {
continue;
}
if (sessionUid != uid) {
SessionInfo info = describeSession(row);
if (!info.graphical) {
continue;
}
const CommandResult details = runCommand(
{"loginctl", "show-session", id, "-p", "Type", "-p", "Class", "-p", "Active",
"-p", "Desktop", "-p", "TTY", "-p", "Seat"});
if (!details.started || details.exitCode != 0) {
continue;
}
const std::vector<std::string> properties = splitLines(details.output);
const std::string type = valueForKey(properties, "Type");
const std::string sessionClass = valueForKey(properties, "Class");
if (sessionClass != "user" || (type != "x11" && type != "wayland")) {
continue;
}
SessionInfo info;
info.id = id;
info.user = user;
info.seat = valueForKey(properties, "Seat");
info.tty = valueForKey(properties, "TTY");
info.type = type;
info.desktop = valueForKey(properties, "Desktop");
info.active = valueForKey(properties, "Active") == "yes";
info.graphical = true;
sessions.push_back(std::move(info));
}
std::sort(sessions.begin(), sessions.end(), [](const SessionInfo& left, const SessionInfo& right) {
return std::stoi(left.id) < std::stoi(right.id);
});
std::sort(sessions.begin(), sessions.end(),
[](const SessionInfo& left, const SessionInfo& right) { return idBefore(left.id, right.id); });
return sessions;
}
bool findGraphicalSession(const std::string& id, SessionInfo& session) {
if (!isSessionId(id)) {
return false;
}
for (const SessionInfo& candidate : listGraphicalSessions()) {
if (candidate.id == id) {
session = candidate;
return true;
}
}
return false;
}
bool isSessionActive(const std::string& id) {
if (!isSessionId(id)) {
return false;
}
const std::vector<std::string> properties = sessionProperties(id, {"Active"});
return valueForKey(properties, "Active") == "yes";
}
std::string activeGraphicalSessionId() {
for (const SessionInfo& session : listGraphicalSessions()) {
if (session.active) {
return session.id;
}
}
return {};
}
std::string findGreeterSessionId(const std::string& seat) {
std::string inactive;
for (const SessionRow& row : listSessionRows()) {
const std::vector<std::string> properties = sessionProperties(row.id, {"Class", "Seat", "Active"});
if (properties.empty() || valueForKey(properties, "Class") != "greeter") {
continue;
}
if (!seat.empty() && valueForKey(properties, "Seat") != seat) {
continue;
}
if (valueForKey(properties, "Active") == "yes") {
return row.id;
}
if (inactive.empty()) {
inactive = row.id;
}
}
return inactive;
}
std::string currentSessionId() {
const char* value = std::getenv("XDG_SESSION_ID");
return value != nullptr ? value : "";
+17
View File
@@ -20,6 +20,7 @@ struct SessionInfo {
std::string tty;
std::string type; // x11, wayland, tty, ...
std::string desktop; // KDE, GNOME, Hyprland, ...
std::string state; // logind State: active, online, closing, ...
bool active = false;
bool graphical = false;
};
@@ -30,6 +31,22 @@ std::vector<DesktopEntry> listInstalledDesktops();
// Reads the current user's graphical sessions from systemd-logind.
std::vector<SessionInfo> listGraphicalSessions();
// Looks up one of the current user's graphical sessions by logind id.
bool findGraphicalSession(const std::string& id, SessionInfo& session);
// True when logind reports the session as the active one on its seat.
bool isSessionActive(const std::string& id);
// Id of the active graphical session of the current user, empty when none.
std::string activeGraphicalSessionId();
// Greeter session (Class=greeter) known to logind, optionally on one seat.
std::string findGreeterSessionId(const std::string& seat);
// Name of the installed session file the greeter lists for one of these desktop
// names, empty when nothing matches (the greeter then keeps its own default).
std::string greeterSessionName(const std::vector<std::string>& desktopNames);
std::string currentSessionId();
std::string currentDesktopName();
+297 -20
View File
@@ -1,19 +1,213 @@
#include "session-switcher.h"
#include "process.h"
#include "session-catalog.h"
#include <algorithm>
#include <cctype>
#include <chrono>
#include <thread>
#include <vector>
namespace fws {
namespace {
constexpr int kPollIntervalMs = 100;
constexpr int kVerifyTimeoutMs = 5000;
// A display manager restart is slower than a VT switch: the unit stops, a new
// greeter starts and logind hands it the seat.
constexpr int kRestartTimeoutMs = 15000;
bool isSessionId(const std::string& value) {
return !value.empty() &&
std::all_of(value.begin(), value.end(),
[](unsigned char character) { return std::isdigit(character) != 0; });
}
void sleepMilliseconds(int milliseconds) {
std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
}
// logind accepts a request before the graphics stack has moved the seat, so
// every switch is confirmed instead of assumed; a blank VT is the cost of an
// assumption that turns out to be wrong.
template <typename Predicate>
bool waitUntil(Predicate predicate, int timeoutMs) {
const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs);
while (std::chrono::steady_clock::now() < deadline) {
if (predicate()) {
return true;
}
sleepMilliseconds(kPollIntervalMs);
}
return predicate();
}
std::string commandError(const CommandResult& result, const std::string& fallback) {
const std::string message = trim(result.output);
return message.empty() ? fallback : message;
}
// The session this process belongs to, falling back to the seat's active one
// when XDG_SESSION_ID is missing or stale (pkexec, systemd-run, ssh...).
SessionInfo resolveCurrentSession() {
SessionInfo session;
const std::string fromEnvironment = currentSessionId();
if (isSessionId(fromEnvironment) && findGraphicalSession(fromEnvironment, session)) {
return session;
}
const std::string active = activeGraphicalSessionId();
if (!active.empty() && findGraphicalSession(active, session)) {
return session;
}
return {};
}
std::vector<std::string> displayManagerSeats() {
std::vector<std::string> paths;
const CommandResult listing = runCommand(
{"busctl", "--system", "call", "org.freedesktop.DisplayManager",
"/org/freedesktop/DisplayManager", "org.freedesktop.DisplayManager", "GetSeats"});
if (listing.started && listing.exitCode == 0) {
const std::string& output = listing.output;
std::size_t position = output.find("\"/org/freedesktop/DisplayManager/Seat");
while (position != std::string::npos) {
const auto end = output.find('"', position + 1);
if (end == std::string::npos) {
break;
}
paths.push_back(output.substr(position + 1, end - position - 1));
position = output.find("\"/org/freedesktop/DisplayManager/Seat", end + 1);
}
}
if (paths.empty()) {
// Older SDDM builds export the seat objects without a working manager
// listing, so probe the usual seat paths as a fallback.
for (int index = 0; index < 4; ++index) {
paths.push_back("/org/freedesktop/DisplayManager/Seat" + std::to_string(index));
}
}
return paths;
}
// GDM, SDDM and LightDM implement org.freedesktop.DisplayManager: this asks the
// greeter to take the seat back and never ends the session, so the worst case is
// that nothing happens.
bool requestGreeterThroughDisplayManager() {
for (const std::string& seat : displayManagerSeats()) {
const CommandResult result = runCommand(
{"busctl", "--system", "call", "org.freedesktop.DisplayManager", seat,
"org.freedesktop.DisplayManager.Seat", "SwitchToGreeter"});
if (result.started && result.exitCode == 0) {
return true;
}
}
return false;
}
// LightDM's own helper, kept for setups without the bus interface.
bool requestGreeterThroughDmTool() {
const std::string dmTool = findExecutable("dm-tool");
if (dmTool.empty()) {
return false;
}
const CommandResult result = runCommand({dmTool, "switch-to-greeter"});
return result.started && result.exitCode == 0;
}
bool greeterIsShowing(const SessionInfo& previous) {
const std::string greeter = findGreeterSessionId(previous.seat);
if (!greeter.empty() && isSessionActive(greeter)) {
return true;
}
// GDM reuses its own seat, so a seat that left our session is the other
// signal that the request was honoured.
return !previous.id.empty() && !isSessionActive(previous.id);
}
// Puts the user back on the session they came from when the greeter never
// appeared: whatever the display manager ignored, the screen cannot stay blank.
void restoreSession(const SessionInfo& session) {
if (!session.id.empty() && !isSessionActive(session.id)) {
runCommand({"loginctl", "activate", session.id});
}
}
// Unit behind display-manager.service: greeter behaviour is per display manager,
// so the name decides which path is safe.
std::string displayManagerUnit() {
const CommandResult result =
runCommand({"systemctl", "show", "-p", "Id", "--value", "display-manager.service"});
return result.started && result.exitCode == 0 ? trim(result.output) : std::string();
}
// SDDM 0.21 answers SwitchToGreeter by creating an extra greeter display. A login
// made from that display stops the greeter and never starts the session, so the
// seat falls back to the VT the user came from: the requested environment never
// runs. This is the only per-display-manager exception in here: every other one
// goes through the standard interfaces below.
bool displayManagerIsSddm() { return displayManagerUnit() == "sddm.service"; }
bool displayManagerIsActive() {
const CommandResult result = runCommand({"systemctl", "is-active", "display-manager.service"});
return result.started && trim(result.output) == "active";
}
// Last resort: end the session and let the display manager spawn a fresh
// greeter. Refused when no display manager is around to take the seat back,
// because that is exactly the configuration that ends in a black screen.
bool terminateCurrentSession(std::string& error) {
const SessionInfo current = resolveCurrentSession();
if (current.id.empty()) {
error = "Impossible d'identifier la session graphique courante.";
return false;
}
if (!displayManagerIsActive()) {
error = "Aucun gestionnaire d'affichage actif : fermer la session laisserait "
"un ecran noir sans moyen de revenir.";
return false;
}
const CommandResult result = runCommand({"loginctl", "terminate-session", current.id});
if (!result.started) {
error = "Unable to run loginctl. Is systemd-logind available?";
return false;
}
if (result.exitCode != 0) {
error = commandError(result, "loginctl terminate-session failed.");
return false;
}
return true;
}
// Ending the session is what makes the greeter come back, but the way back is
// display-manager specific. Restarting display-manager.service is not: the name
// is the systemd alias every display manager installs, and a restarted daemon
// takes the seat with a fresh greeter whatever its implementation. Unavailable
// means nothing to restart (greetd, startx, no pkexec), and the caller has to
// fall back to ending the session.
enum class RestartOutcome { Restarted, Unavailable, Refused };
RestartOutcome restartDisplayManager(std::string& error) {
if (displayManagerUnit().empty() || findExecutable("pkexec").empty()) {
return RestartOutcome::Unavailable;
}
const CommandResult result =
runCommand({"pkexec", "systemctl", "restart", "display-manager.service"});
if (!result.started) {
error = "Impossible de lancer pkexec.";
return RestartOutcome::Refused;
}
if (result.exitCode != 0) {
error = commandError(result, "Le redemarrage du gestionnaire d'affichage a ete "
"refuse ou annule ; la session est restee ouverte.");
return RestartOutcome::Refused;
}
return RestartOutcome::Restarted;
}
} // namespace
bool activateSession(const std::string& sessionId, std::string& error) {
@@ -23,39 +217,122 @@ bool activateSession(const std::string& sessionId, std::string& error) {
return false;
}
SessionInfo target;
if (!findGraphicalSession(sessionId, target)) {
error = "La session " + sessionId + " n'existe plus.";
return false;
}
if (target.active) {
// Already on this VT: logind has nothing to do.
return true;
}
if (target.state == "closing" || target.state == "closing-failed") {
error = "La session " + sessionId + " est en cours de fermeture.";
return false;
}
// A session without a seat or a VT cannot be displayed; activating it is how
// a black screen with no way back happens.
if (target.seat.empty() || target.tty.empty()) {
error = "La session " + sessionId + " n'est rattachee a aucun ecran.";
return false;
}
const std::string previous = activeGraphicalSessionId();
const CommandResult result = runCommand({"loginctl", "activate", sessionId});
if (!result.started) {
error = "Unable to run loginctl. Is systemd-logind available?";
return false;
}
if (result.exitCode != 0) {
error = trim(result.output);
if (error.empty()) {
error = "loginctl activate failed.";
}
error = commandError(result, "loginctl activate failed.");
return false;
}
return true;
}
bool switchToGreeter(std::string& error) {
// Freedesktop DisplayManager interface, implemented by SDDM and LightDM.
const CommandResult busctl = runCommand(
{"busctl", "--system", "call", "org.freedesktop.DisplayManager",
"/org/freedesktop/DisplayManager/Seat0", "org.freedesktop.DisplayManager.Seat",
"SwitchToGreeter"});
if (busctl.started && busctl.exitCode == 0) {
if (waitUntil([&sessionId] { return isSessionActive(sessionId); }, kVerifyTimeoutMs)) {
return true;
}
// LightDM's own helper, kept as a fallback for older setups.
const CommandResult dmTool = runCommand({"dm-tool", "switch-to-greeter"});
if (dmTool.started && dmTool.exitCode == 0) {
return true;
// logind answered but the seat never moved: return to the session that is
// still alive instead of leaving the new VT blank.
if (!previous.empty() && previous != sessionId) {
runCommand({"loginctl", "activate", previous});
}
error = "No compatible display manager answered (SDDM/LightDM expected).";
error = "La bascule vers la session " + sessionId +
" n'a pas abouti ; retour a la session precedente.";
return false;
}
GreeterOutcome switchToGreeter(bool allowTerminate) {
GreeterOutcome outcome;
const SessionInfo current = resolveCurrentSession();
const bool sddm = displayManagerIsSddm();
if (!sddm) {
if (requestGreeterThroughDisplayManager() &&
waitUntil([&current] { return greeterIsShowing(current); }, kVerifyTimeoutMs)) {
outcome.ok = true;
return outcome;
}
if (requestGreeterThroughDmTool() &&
waitUntil([&current] { return greeterIsShowing(current); }, kVerifyTimeoutMs)) {
outcome.ok = true;
return outcome;
}
// A greeter session that logind already knows can simply be activated.
const std::string greeter = findGreeterSessionId(current.seat);
if (!greeter.empty() && greeter != current.id && isSessionId(greeter)) {
const CommandResult result = runCommand({"loginctl", "activate", greeter});
if (result.started && result.exitCode == 0 &&
waitUntil([&greeter] { return isSessionActive(greeter); }, kVerifyTimeoutMs)) {
outcome.ok = true;
return outcome;
}
}
}
if (!allowTerminate) {
// Nothing has been killed at this point, so make sure the screen still
// shows the session the user started from.
restoreSession(current);
outcome.forceRequired = true;
outcome.error =
"Le gestionnaire d'affichage n'a pas repris l'ecran. Le redemarrer "
"(authentification demandee) ferme la session courante et affiche un ecran "
"de connexion neuf.";
return outcome;
}
std::string failure;
const RestartOutcome restart = restartDisplayManager(failure);
if (restart == RestartOutcome::Refused) {
restoreSession(current);
outcome.error = failure;
return outcome;
}
if (restart == RestartOutcome::Restarted) {
// Nothing can be rolled back past this point: the caller dies with its
// session, so a restart that leaves the seat empty is exactly the black
// VT this path exists to avoid. Say so instead of reporting success.
if (!waitUntil([&current] { return greeterIsShowing(current); }, kRestartTimeoutMs)) {
outcome.error =
"Le gestionnaire d'affichage a redemarre mais aucun ecran de connexion "
"n'a repris l'ecran. Basculez sur un autre terminal (Ctrl+Alt+F2) puis "
"redemarrez-le a la main.";
return outcome;
}
outcome.ok = true;
return outcome;
}
if (!terminateCurrentSession(failure)) {
restoreSession(current);
outcome.error = failure;
return outcome;
}
outcome.ok = true;
return outcome;
}
} // namespace fws
+18 -3
View File
@@ -4,10 +4,25 @@
namespace fws {
// Switches the seat to the given logind session (VT activation).
// Switches the seat to the given logind session (VT activation). The switch is
// verified and rolled back to the previous session when the seat never moves.
bool activateSession(const std::string& sessionId, std::string& error);
// Returns to the display manager greeter without rebooting.
bool switchToGreeter(std::string& error);
struct GreeterOutcome {
bool ok = false;
// True when no display manager answered and showing the greeter would end
// the current session: the caller has to confirm before retrying with
// allowTerminate = true.
bool forceRequired = false;
std::string error;
};
// Shows the display manager greeter again. GDM and LightDM are asked to switch
// without ending anything; SDDM 0.21 cannot do that safely (its SwitchToGreeter
// leaves a greeter whose logins never start a session), so the call reports
// forceRequired and the caller has to confirm first. With allowTerminate the
// session does not come back: GDM and LightDM have it terminated, and SDDM is
// restarted through polkit so a working greeter takes the seat again.
GreeterOutcome switchToGreeter(bool allowTerminate);
} // namespace fws
+12 -6
View File
@@ -34,7 +34,7 @@ std::vector<Choice> buildChoices(const std::vector<SessionInfo>& sessions) {
return choices;
}
bool confirm(const std::string& question) {
bool ask(const std::string& question) {
const std::string zenity = findExecutable("zenity");
if (!zenity.empty()) {
const CommandResult result =
@@ -51,15 +51,21 @@ bool confirm(const std::string& question) {
}
bool runGreeter() {
if (!confirm("La session graphique va etre fermee et les applications non enregistrees "
"seront perdues. Continuer ?")) {
if (!ask("Afficher l'ecran de connexion ? La session courante reste ouverte.")) {
std::cout << "Annule.\n";
return true;
}
std::string error;
if (!switchToGreeter(error)) {
std::cerr << "Echec du retour au greeter : " << error << "\n";
fws::GreeterOutcome outcome = switchToGreeter(false);
if (!outcome.ok && outcome.forceRequired &&
ask(outcome.error +
"\nRedemarrer le gestionnaire d'affichage (la session courante sera fermee et "
"les applications non enregistrees perdues) ?")) {
outcome = switchToGreeter(true);
}
if (!outcome.ok) {
std::cerr << "Echec du retour au greeter : " << outcome.error << "\n";
return false;
}
return true;