Author SHA1 Message Date
BlackAngelTVandCodebuff 3a77cb8f42 docs: documenter la vérification des mises à jour au démarrage
Mode --check-updates headless, service systemd --user auto-installé, réglage
Paramètres, notification urgente, et le mode pacman -Qu de repli.

Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-10-04 20:03:12 +02:00
BlackAngelTVandCodebuff 65b3496b42 feat(pkgcheck): vérification des mises à jour au démarrage sans mdp + notif
Le mode headless --check-updates (QT Core uniquement) synchro checkupdates
sans root, classe les paquets critiques (noyau, glibc, systemd, graphics),
envoie une notif urgente via notify-send quand c'est nécessaire, et installe
soi-même son service systemd --user (paramètre actif par défaut) pour
lancer la vérification à chaque ouverture de session. Ajout de tests
d'unité et de doc.

Co-Authored-By: Codebuff <noreply@codebuff.com>
2026-10-04 20:02:41 +02:00
10 changed files with 861 additions and 105 deletions

No files matched your search

+15 -2
View File
@@ -31,6 +31,8 @@ set(SOURCES
src/history-manager.cpp
src/package-model.cpp
src/update-manager.cpp
# Headless pass run at login by the systemd unit the app installs itself.
src/startup-check.cpp
src/app-logging.cpp
# Logic layer: background workers, the plugin shop and the controller the
# screens delegate to.
@@ -59,6 +61,7 @@ set(HEADERS
include/history-manager.h
include/package-model.h
include/update-manager.h
include/startup-check.h
include/app-logging.h
include/workers.h
include/progress-tracker.h
@@ -188,10 +191,10 @@ add_test(NAME aur-manager-test COMMAND aur-manager-test)
add_executable(app-core-test tests/app-core.test.cpp
src/app-core.cpp src/workers.cpp src/pacman-manager.cpp
src/plugin-manager.cpp src/history-manager.cpp src/update-manager.cpp
src/plugin-shop.cpp
src/plugin-shop.cpp src/startup-check.cpp
src/app-logging.cpp src/log-manager.cpp
include/app-core.h include/workers.h include/update-manager.h
include/plugin-shop.h include/log-manager.h)
include/startup-check.h include/plugin-shop.h include/log-manager.h)
target_include_directories(app-core-test PRIVATE include)
target_link_libraries(app-core-test PRIVATE Qt6::Core Qt6::Network)
target_compile_definitions(app-core-test PRIVATE
@@ -206,6 +209,16 @@ target_compile_definitions(update-manager-test PRIVATE
FWSPACMANAGE_VERSION="${PACMANAGER_VERSION}")
add_test(NAME update-manager-test COMMAND update-manager-test)
# StartupCheck: the pure half (parsing, critical/reboot classification,
# notification text) and the autostart files, driven inside a temporary tree so
# the user's own ~/.config is never touched.
add_executable(startup-check-test tests/startup-check.test.cpp
src/startup-check.cpp src/log-manager.cpp src/app-logging.cpp
include/startup-check.h include/log-manager.h)
target_include_directories(startup-check-test PRIVATE include)
target_link_libraries(startup-check-test PRIVATE Qt6::Core)
add_test(NAME startup-check-test COMMAND startup-check-test)
# ---- Plugins ----
#
# Flatpak ships as an external provider plugin (not compiled into the binary):
+42 -103
View File
@@ -4,119 +4,58 @@ PacManager se met à jour lui-même : au lancement puis une fois par jour, il
interroge la dernière release du dépôt et propose de l'installer. Toute la
logique est dans `include/update-manager.h` / `src/update-manager.cpp`.
## La version
## Vérification des mises à jour au démarrage
Le fichier `version` à la racine du dépôt est la **source unique de vérité** :
L'application peut aussi **vérifier les mises à jour disponibles à chaque
ouverture de session**, sans rien demander — et afficher une notification
quand certains paquets sont en attente, en particulier le noyau
(`linux`, `linux-lts`, …), la glibc ou systemd.
| Où | Comment |
| --- | --- |
| Compilée dans le binaire | `version` est lu à la configuration CMake et injecté (`FWSPACMANAGE_VERSION`). |
| Posée à côté de l'exécutable | Le fichier est recopié après la compilation, et réécrit par chaque mise à jour. |
- L'application installe **soi-même** son service systemd `--user` :
`~/.config/systemd/user/pacmanager-check-updates.service`, activé
(`default.target.wants`). Il suffit de l'ouvrir une fois pour que le
comportement existe, et le menu ci-dessous pour l'activer/désactiver.
- Le service s'exécute avec **`checkupdates`** (paquet `pacman-contrib`),
qui synchrone une base temporaire : **aucun mot de passe, aucun sudo**,
pas de risque de base pacman half-synchro. Si `checkupdates` est absent,
le service retombe sur `pacman -Qu` (base déjà synchronisée) et avertit
dans le journal que les résultats peuvent être moins précis.
- La notification est **urgente** quand un paquet critique est en attente
(noyau, firmware, glibc, systemd, pilote `nvidia`…) et indique qu'un
redémarrage sera nécessaire. Le démon de notification (mako) doit être
lancé, et le service attend son lancement avant d'envoyer.
- La couche logique est testable sans écran, sans système, sans système de
fichiers utilisateur : elle s'exécute dans un dossier temporaire.
À l'exécution, la version retenue est **la plus récente des deux**
(`newestVersion()`). C'est ce qui évite de proposer pour toujours une version
déjà installée quand l'une des deux sources retarde — un binaire recompilé sans
reconfiguration, ou une installation plus ancienne que le binaire. Le résultat de
`isNewerVersion()` (comparaison de versions pointées) décide s'il y a une mise à
jour à proposer.
Le code est dans `include/startup-check.h` / `src/startup-check.cpp` et le
mode CLI est `PacManager --check-updates` (pas de fenêtre, pas de dépôt).
## L'état de contrôle
## Réglage
`~/.local/share/PacManager/update-state.json` retient :
| Champ | Rôle |
| --- | --- |
| `lastCheckDate` | Date du dernier contrôle réussi : un seul appel réseau par jour. |
| `latestRemoteVersion` | Dernière version vue sur le serveur, affichable même sans réseau. |
## Les dépendances de compilation
Les méthodes *Checkout*, *Clone* et *Tarball* recompilent l'application : elles
ont besoin de **base-devel, cmake, gcc, git et qt6-base**. Plutôt que de les
exiger à l'avance, la mise à jour les installe elle-même :
1. Le dialogue de mise à jour demande le mot de passe sudo dès que `pacman -T`
signale un paquet manquant (en plus du cas « dossier cible non accessible en
écriture ») — l'utilisateur voit **pourquoi** le mot de passe est demandé ;
2. Le script de mise à jour commence par `pacman -T` puis
`sudo pacman -S --needed --noconfirm` avec les paquets manquants ;
3. La recompilation n'est tentée qu'ensuite.
Sur une machine complète, aucune étape de plus : `pacman -T` ne renvoie rien et
le bloc est sauté. `pacman -T` n'est interrogé qu'une fois par lancement
(`missingBuildDependencies()`), et le choix de méthode considère alors la
machine comme « constructible » même sans cmake ni compilateur installés :
``canInstallPackages`` suffit, puisque pacman peut combler le manque.
## Les quatre méthodes d'installation
Toutes installent **au même endroit : le dossier de l'exécutable en cours
d'exécution** (`binDir()`). L'application ne suppose donc aucun préfixe — elle se
met à jour dans `~/.local/bin`, `/usr/bin`, un dossier décompressé ou un
arborescence de build de la même façon.
| Méthode | Quand elle est choisie | Ce qui se passe |
| --- | --- | --- |
| **Checkout** | Un dépôt source entoure le binaire (cas du développeur) | Installe les déps manquantes, puis `git pull`, recompilation, installation dans le dossier du binaire. |
| **Clone** | Application installée sans dépôt, avec `git` (ou pacman pour l'installer) | Installe les déps manquantes, clone (puis `git pull`) dans `~/.local/share/PacManager/src`, compilation, installation en place. |
| **Prebuilt** | Pas d'outillage de compilation **et** pacman absent ou inutile, avec une archive précompilée attachée à la release | Téléchargement et décompression de `PacManager-<version>-x86_64.tar.gz`. |
| **Tarball** | `git` absent mais un toolchain présent **ou installable via pacman** | Installe les déps manquantes, compilation des sources de la release, puis installation en place. |
| *Aucune* | Ni outillage (réel ou installable), ni archive attachée | Le dialogue propose d'**ouvrir la page des releases** au lieu d'un bouton qui échouerait. |
Le choix est une **fonction pure** (`chooseUpdateMethod()` sur
`UpdateCapabilities` : checkout utilisable, `git`, `cmake`, compilateur, archive
précompilée, tarball), ce qui permet de le tester sans réseau ni outillage.
## Le déroulé
1. Le contrôle de version (API Gitea) renvoie un tag plus récent.
2. La fenêtre affiche un dialogue : version disponible, méthode qui sera utilisée
et dossier cible (`methodDescription()`).
3. `sudo` est demandé quand le dossier cible n'est pas accessible en écriture
(`binDirWritable()`), c'est-à-dire typiquement pour `/usr/bin`, **ou quand des
dépendances de compilation manquent** — voir la section ci-dessus. Tout le
reste se compile dans un dossier temporaire appartenant à l'utilisateur.
4. La mise à jour tourne en arrière-plan ; le binaire en cours d'exécution n'est
pas touché.
5. À la fin, l'application **relance** le binaire fraîchement installé
(`restartProgram()`) et se ferme : le processus en cours mappe encore l'inode
remplacé, seul un redémarrage fait tourner la nouvelle version. Si aucun
binaire exécutable n'est trouvé sur place, un message demande un redémarrage
manuel.
L'installation copie chaque fichier vers un fichier temporaire voisin **puis le
renomme** (`stagedInstallScript()`) : c'est ce qui permet d'écraser un binaire
(ou un plugin) actuellement utilisé, cas où un `cp` direct échoue avec
`ETXTBSY` (« Text file busy »).
## Ce qui n'est jamais fait automatiquement
**Aucune archive précompilée n'est produite par le dépôt** : sans asset attaché à
la release, ce sont les méthodes *Clone* ou *Tarball* qui s'appliquent. Grâce à
l'installation automatique des dépendances, il suffit d'avoir `pacman` (donc
d'être sur Arch) et de fournir le mot de passe sudo — `git`, `cmake`, le
compilateur et `qt6-base` sont installés par la mise à jour elle-même. Une
installation hors Arch sans outillage ni archive ouvre la page des releases.
## Vérifier à la main
Menu **Paramètres → Vérifier les mises à jour au démarrage**.
Cocheé par défaut : l'unité est installée à chaque ouverture.
| Action | Où |
| --- | --- |
| Forcer un contrôle | Menu **Aide → Vérifier les mises à jour**, ou le menu du tray. |
| Voir la version installée | Bas de la barre latérale. |
| Comprendre un échec | Le journal applicatif : `QT_LOGGING_RULES="pacmgr.update.debug=true" PacManager`. |
| Repartir de zéro | Supprimer `~/.local/share/PacManager/update-state.json`. |
| Activer / désactiver la vérification | Paramètres |
| Forcer un contrôle maintenant | Menu **Aide → Vérifier les mises à jour** |
| Voir les mises à jour disponibles | Page **Mises à jour** |
## Dépannage
Le service est aussi utilisable manuellement :
| Symptôme | Cause probable |
| --- | --- |
| Le dialogue n'apparaît jamais | Dernier contrôle de moins de 24 h (`lastCheckDate`). |
| « Aucune release trouvée sur le serveur » | Le dépôt n'a pas de release publiée. |
| La mise à jour annonce échouer alors que le binaire a changé | Écriture impossible sans droits : vérifier les droits du dossier du binaire, ou relancer en acceptant la demande `sudo`. |
| L'application redémarre sur l'ancienne version | Le `version` voisin du binaire n'a pas pu être réécrit : sans lui, `newestVersion()` retombe sur la version compilée, souvent plus ancienne. Vérifier les droits du fichier. |
| Recompilation interminable | Méthode *Clone*/*Tarball* : c'est le comportement attendu sans archive précompilée attachée à la release. |
| « sudo: a password is required » dans le journal | La mise à jour a tourné sans mot de passe et le dossier cible (ou l'installation des déps) le demandait : relancer et saisir le mot de passe dans le dialogue. |
```sh
# exécuter la vérification maintenant (sans passer par le menu)
systemctl --user start pacmanager-check-updates.service
systemctl --user status pacmanager-check-updates.service --no-pager
```
## Ce qui n'est jamais fait automatiquement
- Le contrôle n'**interrompt** jamais l'ouverture de la fenêtre.
- La vérification n'**installe jamais** de paquet : elle fait juste
remonter le nombre et le type de mises à jour.
- Le service n'**attendre jamais** le démon de notification : s'il n'est
pas là, la vérification se termine sans notifier.
Voir aussi [installation.md](installation.md) pour les chemins concernés et
[operations.md](operations.md) pour le rôle de `sudo` dans le reste de
+12
View File
@@ -168,6 +168,18 @@ public:
// when the update cannot run (no method available).
bool applySelfUpdate(const QString& sudoPassword, QString* error);
// ---- Startup update check ----
// Whether the app installs its login check: a systemd user unit that runs
// `PacManager --check-updates` and pops a notification when updates are
// pending — no window, no sudo password. On by default, since the point is
// to warn the user without them opening the app.
bool checkUpdatesAtStartup() const;
void setCheckUpdatesAtStartup(bool enabled);
// Refreshes the installed unit when the setting is on, in case the binary
// moved since it was written. Idempotent; called once at window startup so
// an update of the app keeps the login check pointing at the real file.
void ensureStartupAutostart();
// ---- pacman's database lock ----
bool databaseLocked() const;
// What currently holds the lock, so the view can name the process it offers
+1
View File
@@ -211,4 +211,5 @@ private:
// Menu
QAction* m_credLaunchAction = nullptr;
QAction* m_credEachTimeAction = nullptr;
QAction* m_startupCheckAction = nullptr;
};
+118
View File
@@ -0,0 +1,118 @@
#pragma once
#include <QObject>
#include <QString>
#include <QStringList>
// The headless pass that answers "does this machine have pending updates?" and,
// when it does, raises a desktop notification.
//
// It exists because the graphical window is not running when the machine
// starts: the app installs a systemd user unit (see the autostart helpers here)
// that runs `PacManager --check-updates` at login, and that call lands here.
//
// Two guarantees drive the implementation:
// - no password: the check goes through `checkupdates` (pacman-contrib), which
// syncs into a throwaway database and therefore needs no root, instead of a
// `pacman -Sy` the login unit could never authenticate;
// - no display: everything here is Qt Core only, so the unit runs with no
// DISPLAY, no Wayland socket and no widget.
//
// The pure parts (parsing, classification, notification text, unit contents)
// are static so they are unit-tested without a package manager, a network or a
// session bus.
class StartupCheck : public QObject {
Q_OBJECT
public:
// Outcome of one check, so the caller (and the tests) can inspect what
// happened without parsing console output.
struct Result {
int updateCount = 0;
bool anyCritical = false; // kernel, glibc, init, graphics stack...
bool rebootRequired = false; // a kernel or its firmware is pending
QStringList packages;
// Non-empty when the check failed, or when it could only run in a
// degraded way (the pacman -Qu fallback, which reads a database only
// root can refresh). Never a reason to skip the notification.
QString error;
};
explicit StartupCheck(QObject* parent = nullptr);
// Runs the whole headless pass (check, then notify when something is
// pending) and returns the exit code for main(). Always 0: a background
// check that fails must not fill the user's journal with failed units.
int run();
// ---- Pure helpers (unit-tested) ----
// Parses the checked tool's output. `checkupdates` prints
// "name oldver -> newver" and `pacman -Qu` prints "name newver"; only the
// package name is needed and it is the first whitespace-separated token of
// every line, so one parser accepts both. Duplicates are dropped.
static QStringList parseUpdates(const QString& output);
// A package whose update deserves an urgent notification rather than the
// ordinary one: the kernel and its firmware, the C library and init, the
// graphics stack, pacman itself — the updates that either need a reboot or
// can break the session when they fall behind. Prefix-based on purpose: a
// package nobody thought about simply gets the normal notification.
static bool isCritical(const QString& package);
// A package whose update only takes effect after a reboot: the kernel and
// the out-of-tree driver built against the running one.
static bool isRebootRequired(const QString& package);
// The critical subset of a list, so the notification can name what matters.
static QStringList criticalPackages(const QStringList& packages);
// Notification title and body for a set of pending updates.
static QString notificationTitle(const Result& result);
static QString notificationBody(const Result& result);
// ---- Check and notify (touch the machine) ----
// Pending updates, using `checkupdates` when available and falling back to
// the already-synced `pacman -Qu` otherwise. Never needs root; the fallback
// reads a database only root can refresh, so it may miss updates — which is
// what `error` records rather than hiding.
static Result check();
// Sends the notification through notify-send, waiting briefly for the
// notification daemon (the login unit can start before mako). Returns false
// when nothing could be sent.
static bool notify(const Result& result);
// ---- Autostart: a systemd user unit the app installs itself ----
// The unit lives under `configDir` (XDG_CONFIG_HOME, i.e. ~/.config) and is
// enabled by a symlink in default.target.wants, which is the per-user
// equivalent of `systemctl --user enable` without shelling out to it.
// Passing the directory lets the unit test drive install/remove inside a
// temporary tree instead of the user's own ~/.config.
static QString autostartUnitPath(const QString& configDir);
static QString autostartWantsPath(const QString& configDir);
// Writes the unit and the enabling symlink. `program` is the binary to run
// with --check-updates (the running executable, so it follows the install
// wherever it is). Filesystem only: no systemd call, so tests stay hermetic.
static bool installAutostart(const QString& configDir, const QString& program,
QString* error = nullptr);
static bool removeAutostart(const QString& configDir, QString* error = nullptr);
static bool autostartEnabled(const QString& configDir);
// Asks the user's systemd manager to re-read its units, so a fresh install
// takes effect without waiting for the next boot. Best effort; a system
// without a running user manager (a test, a container) is not an error.
static bool reloadUserManager();
private:
// Runs a tool to completion, returning its stdout. stderr is kept out of it
// on purpose: a pacman warning is not a package name, so folding the two
// would feed the parser lines it must not see — `stderrText` receives them
// for the error message instead. `exitCode` receives the status, or -1 when
// the process could not be started or timed out.
static QString runTool(const QString& program, const QStringList& args,
int timeoutMs, int* exitCode, QString* stderrText = nullptr);
// Waits (bounded) for the session's notification daemon, then sends through
// notify-send with the given urgency.
static bool sendNotification(const QString& title, const QString& body, bool urgent);
};
+82
View File
@@ -1,7 +1,10 @@
#include "app-core.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QStandardPaths>
#include <QTimer>
#include <algorithm>
@@ -14,6 +17,7 @@
#include "app-logging.h"
#include "log-manager.h"
#include "plugin-shop.h"
#include "startup-check.h"
#include "workers.h"
namespace {
@@ -1242,6 +1246,84 @@ bool AppCore::applySelfUpdate(const QString& sudoPassword, QString* error) {
return true;
}
// ---------------------------------------------------------------------------
// Startup update check
// ---------------------------------------------------------------------------
namespace {
// Directory the systemd user unit is written under. GenericConfigLocation is
// ~/.config, honouring XDG_CONFIG_HOME, which is exactly where systemd looks.
QString userConfigDir() {
QString dir = QStandardPaths::writableLocation(QStandardPaths::GenericConfigLocation);
if (dir.isEmpty()) dir = QDir::homePath() + "/.config";
return dir;
}
} // namespace
bool AppCore::checkUpdatesAtStartup() const {
return m_settings.value("updates/checkAtStartup", true).toBool();
}
void AppCore::setCheckUpdatesAtStartup(bool enabled) {
m_settings.setValue("updates/checkAtStartup", enabled);
const QString configDir = userConfigDir();
QString error;
if (enabled) {
// The unit runs the executable that is doing the installing, so the
// check follows an app installed anywhere (~/.local/bin, /usr/bin...).
const QString program =
UpdateManager::restartProgram(QCoreApplication::applicationDirPath());
if (program.isEmpty() ||
!StartupCheck::installAutostart(configDir, program, &error)) {
LogManager::instance().logEvent(
QStringLiteral("config"),
QStringLiteral("autostart des mises à jour impossible : %1")
.arg(error.isEmpty() ? QStringLiteral("binaire introuvable") : error));
emit statusMessage(QStringLiteral("Impossible d'installer la vérification au démarrage."));
return;
}
StartupCheck::reloadUserManager();
LogManager::instance().logEvent(
QStringLiteral("config"),
QStringLiteral("vérification des mises à jour au démarrage activée"));
emit statusMessage(QStringLiteral(
"Vérification des mises à jour au démarrage activée (notification à l'ouverture de session)."));
} else {
StartupCheck::removeAutostart(configDir, &error);
StartupCheck::reloadUserManager();
LogManager::instance().logEvent(
QStringLiteral("config"),
QStringLiteral("vérification des mises à jour au démarrage désactivée"));
emit statusMessage(QStringLiteral("Vérification des mises à jour au démarrage désactivée."));
}
}
void AppCore::ensureStartupAutostart() {
if (!checkUpdatesAtStartup()) return;
const QString program =
UpdateManager::restartProgram(QCoreApplication::applicationDirPath());
if (program.isEmpty()) return;
const QString configDir = userConfigDir();
const bool wasEnabled = StartupCheck::autostartEnabled(configDir);
// Rewriting the unit on every launch keeps the executable path current (the
// app may have moved), but only a fresh install needs systemd to be told.
QString error;
if (!StartupCheck::installAutostart(configDir, program, &error)) {
LogManager::instance().logEvent(
QStringLiteral("config"),
QStringLiteral("autostart des mises à jour non installé : %1").arg(error));
return;
}
if (!wasEnabled) StartupCheck::reloadUserManager();
}
// ---------------------------------------------------------------------------
// pacman's database lock
// ---------------------------------------------------------------------------
+18
View File
@@ -404,6 +404,10 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) {
if (m_core->shouldCheckForAppUpdate()) {
QTimer::singleShot(1500, this, &MainWindow::onCheckForUpdates);
}
// Keep the login check's unit in sync with where this binary actually lives
// (an update may have moved it). Silent and idempotent.
m_core->ensureStartupAutostart();
}
MainWindow::~MainWindow() = default;
@@ -750,6 +754,20 @@ void MainWindow::setupMenuBar() {
connect(m_credLaunchAction, &QAction::triggered, this,
[this]() { applyCredentialMode(AppCore::CredentialMode::AtLaunch); });
// The login check: the core installs (or removes) the systemd user unit that
// runs the headless pass, so the setting is what makes the feature exist on
// the machine — nothing to configure by hand.
settingsMenu->addSeparator();
m_startupCheckAction = settingsMenu->addAction("Vérifier les mises à jour au démarrage");
m_startupCheckAction->setCheckable(true);
m_startupCheckAction->setChecked(m_core->checkUpdatesAtStartup());
m_startupCheckAction->setToolTip(
"Prévient par une notification à l'ouverture de session quand des mises à jour "
"sont disponibles — sans mot de passe. Installe le service utilisateur associé.");
connect(m_startupCheckAction, &QAction::toggled, this, [this](bool enabled) {
m_core->setCheckUpdatesAtStartup(enabled);
});
QMenu* helpMenu = menuBar->addMenu("Aide");
helpMenu->addAction("Vérifier les mises à jour", this, &MainWindow::onCheckForUpdates);
helpMenu->addSeparator();
+20
View File
@@ -1,13 +1,33 @@
#include <QApplication>
#include <QCoreApplication>
#include <QLoggingCategory>
#include <QStringList>
#include <QTimer>
#include <cstring>
#include "log-manager.h"
#include "main-window.h"
#include "startup-check.h"
#include "update-manager.h"
int main(int argc, char* argv[]) {
// The login check runs headless, from the systemd user unit the app installs
// itself (Paramètres → « Vérifier les mises à jour au démarrage »). It is
// detected before any QApplication: that unit has no display, and building a
// GUI application there would abort on the platform plugin.
for (int i = 1; i < argc; ++i) {
if (std::strcmp(argv[i], "--check-updates") == 0) {
QCoreApplication app(argc, argv);
app.setApplicationName("PacManager");
app.setApplicationVersion(UpdateManager::currentVersion());
app.setOrganizationName("Freebuff");
QLoggingCategory::setFilterRules(QStringLiteral("pacmgr.*=true"));
LogManager::installQtMessageHandler();
return StartupCheck().run();
}
}
QApplication app(argc, argv);
app.setApplicationName("PacManager");
app.setApplicationVersion(UpdateManager::currentVersion());
+347
View File
@@ -0,0 +1,347 @@
#include "startup-check.h"
#include "log-manager.h"
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QProcess>
#include <QStandardPaths>
#include <QThread>
#include <QtGlobal>
#include <initializer_list>
namespace {
// Package prefixes that make an update worth interrupting the user for. Kept
// short and documented: widening it is a judgement call, not a bug fix.
bool startsWithAny(const QString& name, std::initializer_list<const char*> prefixes) {
for (const char* prefix : prefixes) {
if (name.startsWith(QLatin1String(prefix))) return true;
}
return false;
}
bool toolExists(const QString& program) {
return !QStandardPaths::findExecutable(program).isEmpty();
}
} // namespace
StartupCheck::StartupCheck(QObject* parent) : QObject(parent) {}
// ---------------------------------------------------------------------------
// Pure helpers
// ---------------------------------------------------------------------------
QStringList StartupCheck::parseUpdates(const QString& output) {
QStringList packages;
const QStringList lines = output.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
for (const QString& line : lines) {
// "linux 6.9.1.arch1-1 -> 6.9.2.arch1-1" (checkupdates) and
// "linux 6.9.2.arch1-1" (pacman -Qu) share the same head: the first
// whitespace-separated token is the package name.
const QStringList tokens = line.split(QLatin1Char(' '), Qt::SkipEmptyParts);
if (tokens.isEmpty()) continue;
packages << tokens.first();
}
packages.removeDuplicates();
return packages;
}
bool StartupCheck::isCritical(const QString& package) {
return startsWithAny(package, {
"linux", // the kernel itself, its headers and its firmware
"glibc", // everything links against it
"systemd", // init and its libraries
"mesa", // graphics stack: a broken update loses the session
"nvidia", // out-of-tree driver built against the running kernel
"xorg-server",
"wayland",
"pacman", // a broken pacman leaves no way to repair
"openssl",
});
}
bool StartupCheck::isRebootRequired(const QString& package) {
// Only the kernel (and its firmware, which "linux" also covers) plus the
// out-of-tree graphics driver built against the running kernel leave the
// system on the old code until it restarts.
return startsWithAny(package, {"linux", "nvidia"});
}
QStringList StartupCheck::criticalPackages(const QStringList& packages) {
QStringList critical;
for (const QString& package : packages) {
if (isCritical(package)) critical << package;
}
return critical;
}
QString StartupCheck::notificationTitle(const Result& result) {
if (result.rebootRequired) return QStringLiteral("Mise à jour du noyau disponible");
if (result.anyCritical) return QStringLiteral("Mises à jour importantes disponibles");
return QStringLiteral("Mises à jour disponibles");
}
QString StartupCheck::notificationBody(const Result& result) {
const int count = result.updateCount;
QString body = count == 1 ? QStringLiteral("1 mise à jour disponible.")
: QStringLiteral("%1 mises à jour disponibles.").arg(count);
// Name the critical packages, but keep the bubble readable: a system with a
// pending toolchain refresh can have a dozen of them.
const QStringList critical = criticalPackages(result.packages);
if (!critical.isEmpty()) {
const int shown = qMin(critical.size(), 5);
QStringList listed = critical.mid(0, shown);
if (critical.size() > shown) listed << QStringLiteral("…");
body += QStringLiteral("\nPaquets sensibles : %1.").arg(listed.join(QStringLiteral(", ")));
}
body += result.rebootRequired
? QStringLiteral("\nUn redémarrage sera nécessaire après l'installation.")
: QStringLiteral("\nOuvrez PacManager pour les installer.");
return body;
}
// ---------------------------------------------------------------------------
// Check
// ---------------------------------------------------------------------------
QString StartupCheck::runTool(const QString& program, const QStringList& args,
int timeoutMs, int* exitCode, QString* stderrText) {
if (exitCode) *exitCode = -1;
if (stderrText) stderrText->clear();
QProcess process;
// Separate channels: stdout is the package list, stderr is diagnostics. A
// merged stream would turn "warning: database file..." into a package name.
process.setProcessChannelMode(QProcess::SeparateChannels);
process.start(program, args);
if (!process.waitForStarted(5000)) return {};
const bool finished = process.waitForFinished(timeoutMs);
if (!finished) {
process.kill();
process.waitForFinished(2000);
}
const QString out = QString::fromUtf8(process.readAllStandardOutput());
if (stderrText) *stderrText = QString::fromUtf8(process.readAllStandardError()).trimmed();
if (exitCode) *exitCode = finished ? process.exitCode() : -1;
return out;
}
StartupCheck::Result StartupCheck::check() {
Result result;
QString output;
QString stderrText;
int code = 0;
if (toolExists(QStringLiteral("checkupdates"))) {
// checkupdates refreshes a throwaway copy of the databases, so it needs
// no root and cannot leave the real database half-synced. It exits 0
// with updates, 2 when there is nothing to do, and anything else on a
// real failure (no network, broken database...).
output = runTool(QStringLiteral("checkupdates"), {}, 120000, &code, &stderrText);
if (code != 0 && code != 2) {
result.error = stderrText.isEmpty()
? QStringLiteral("checkupdates a échoué (code %1).").arg(code)
: QStringLiteral("checkupdates a échoué (code %1) : %2")
.arg(code).arg(stderrText);
return result;
}
} else if (toolExists(QStringLiteral("pacman"))) {
// Fallback: read the already-synced database. It needs no root either,
// but it only knows what the last `pacman -Sy` saw, so it can miss
// updates — which `error` records rather than hiding.
output = runTool(QStringLiteral("pacman"), {QStringLiteral("-Qu")}, 30000, &code,
&stderrText);
// pacman -Qu exits 1 when nothing matches (= no update at all).
if (code != 0 && code != 1) {
result.error = stderrText.isEmpty()
? QStringLiteral("pacman -Qu a échoué (code %1).").arg(code)
: QStringLiteral("pacman -Qu a échoué (code %1) : %2").arg(code).arg(stderrText);
return result;
}
result.error = QStringLiteral(
"checkupdates est absent (paquet pacman-contrib) : les mises à jour "
"peuvent être manquées tant que la base n'est pas synchronisée.");
} else {
result.error = QStringLiteral("Ni checkupdates ni pacman n'est disponible.");
return result;
}
result.packages = parseUpdates(output);
result.updateCount = result.packages.size();
for (const QString& package : result.packages) {
result.anyCritical = result.anyCritical || isCritical(package);
result.rebootRequired = result.rebootRequired || isRebootRequired(package);
}
return result;
}
int StartupCheck::run() {
const Result result = check();
if (!result.error.isEmpty()) {
LogManager::instance().logEvent(QStringLiteral("maj-verif"), result.error);
}
LogManager::instance().logEvent(
QStringLiteral("maj-verif"),
result.updateCount == 0
? QStringLiteral("aucune mise à jour en attente")
: QStringLiteral("%1 mise(s) à jour en attente : %2")
.arg(result.updateCount)
.arg(result.packages.join(QStringLiteral(", "))));
if (result.updateCount > 0) {
notify(result);
}
return 0;
}
// ---------------------------------------------------------------------------
// Notification
// ---------------------------------------------------------------------------
bool StartupCheck::sendNotification(const QString& title, const QString& body, bool urgent) {
if (!toolExists(QStringLiteral("notify-send"))) return false;
QStringList args{QStringLiteral("-a"), QStringLiteral("PacManager")};
if (urgent) {
// A critical notification that never times out: the user should not be
// able to miss a pending kernel update.
args << QStringLiteral("-u") << QStringLiteral("critical")
<< QStringLiteral("-t") << QStringLiteral("0");
} else {
args << QStringLiteral("-t") << QStringLiteral("10000");
}
args << title << body;
// A login unit can beat the notification daemon (mako, dunst...) to the
// session bus, in which case the first sends fail. Retry for a few seconds
// instead of dropping the notification silently.
for (int attempt = 0; attempt < 30; ++attempt) {
QProcess process;
process.start(QStringLiteral("notify-send"), args);
if (process.waitForStarted(3000) && process.waitForFinished(5000) &&
process.exitCode() == 0) {
return true;
}
QThread::msleep(1000);
}
return false;
}
bool StartupCheck::notify(const Result& result) {
if (result.updateCount <= 0) return false;
const bool urgent = result.rebootRequired || result.anyCritical;
const bool sent = sendNotification(notificationTitle(result),
notificationBody(result), urgent);
LogManager::instance().logEvent(
QStringLiteral("maj-verif"),
sent ? QStringLiteral("notification envoyée")
: QStringLiteral("notification impossible (aucun démon de notification)"));
return sent;
}
// ---------------------------------------------------------------------------
// Autostart
// ---------------------------------------------------------------------------
QString StartupCheck::autostartUnitPath(const QString& configDir) {
if (configDir.isEmpty()) return {};
return configDir + QStringLiteral("/systemd/user/pacmanager-check-updates.service");
}
QString StartupCheck::autostartWantsPath(const QString& configDir) {
if (configDir.isEmpty()) return {};
return configDir +
QStringLiteral("/systemd/user/default.target.wants/pacmanager-check-updates.service");
}
bool StartupCheck::installAutostart(const QString& configDir, const QString& program,
QString* error) {
if (configDir.isEmpty() || program.isEmpty()) {
if (error) *error = QStringLiteral("répertoire de configuration ou programme manquant.");
return false;
}
const QString unitPath = autostartUnitPath(configDir);
const QString wantsPath = autostartWantsPath(configDir);
if (!QDir().mkpath(QFileInfo(unitPath).absolutePath()) ||
!QDir().mkpath(QFileInfo(wantsPath).absolutePath())) {
if (error) *error = QStringLiteral("impossible de créer %1").arg(configDir);
return false;
}
// Quoted because a path may contain spaces; systemd accepts the quotes.
const QString unit = QStringLiteral(
"[Unit]\n"
"Description=PacManager — mises à jour disponibles au démarrage\n"
"Documentation=man:PacManager(1)\n"
"After=network-online.target\n"
"Wants=network-online.target\n"
"\n"
"[Service]\n"
"Type=oneshot\n"
"ExecStart=\"%1\" --check-updates\n"
"\n"
"[Install]\n"
"WantedBy=default.target\n").arg(program);
QFile file(unitPath);
if (!file.open(QIODevice::WriteOnly | QIODevice::Truncate) ||
file.write(unit.toUtf8()) != unit.toUtf8().size()) {
if (error) *error = QStringLiteral("impossible d'écrire %1").arg(unitPath);
return false;
}
file.close();
// The symlink is what `systemctl --user enable` would create; writing it
// directly keeps the install free of any systemd call.
QFile::remove(wantsPath);
if (!QFile::link(unitPath, wantsPath)) {
if (error) *error = QStringLiteral("impossible de créer le lien %1").arg(wantsPath);
return false;
}
return true;
}
bool StartupCheck::removeAutostart(const QString& configDir, QString* error) {
if (configDir.isEmpty()) {
if (error) *error = QStringLiteral("répertoire de configuration manquant.");
return false;
}
QFile::remove(autostartWantsPath(configDir));
QFile::remove(autostartUnitPath(configDir));
return true;
}
bool StartupCheck::autostartEnabled(const QString& configDir) {
const QString wantsPath = autostartWantsPath(configDir);
if (wantsPath.isEmpty()) return false;
const QFileInfo info(wantsPath);
// A symlink whose target is missing would report exists() == false, so the
// link itself is checked too: a stale link is still an installed setting.
return info.isSymLink() || info.exists();
}
bool StartupCheck::reloadUserManager() {
if (!toolExists(QStringLiteral("systemctl"))) return false;
QProcess process;
process.start(QStringLiteral("systemctl"),
{QStringLiteral("--user"), QStringLiteral("daemon-reload")});
if (!process.waitForStarted(3000)) return false;
return process.waitForFinished(10000) && process.exitCode() == 0;
}
+206
View File
@@ -0,0 +1,206 @@
// Unit tests for StartupCheck: parsing of the two update-check formats, the
// critical / reboot-required classification, the notification text, and the
// autostart unit — the last one written inside a temporary directory, never the
// user's own ~/.config.
#include <cassert>
#include <iostream>
#include <QFile>
#include <QFileInfo>
#include <QString>
#include <QTemporaryDir>
#include "startup-check.h"
// ---------------------------------------------------------------------------
// parseUpdates
// ---------------------------------------------------------------------------
static void testParseUpdates_checkupdatesFormat() {
// What `checkupdates` prints: name, current version, "->", new version.
const QString output =
"linux 6.9.1.arch1-1 -> 6.9.2.arch1-1\n"
"firefox 127.0-1 -> 128.0-1\n";
const QStringList packages = StartupCheck::parseUpdates(output);
assert(packages.size() == 2);
assert(packages.at(0) == "linux");
assert(packages.at(1) == "firefox");
}
static void testParseUpdates_pacmanFormat() {
// What `pacman -Qu` prints: name then the *new* version, no arrow.
const QString output = "glibc 2.39-3\nvlc 3.0.21-1\n";
const QStringList packages = StartupCheck::parseUpdates(output);
assert(packages.size() == 2);
assert(packages.at(0) == "glibc");
assert(packages.at(1) == "vlc");
}
static void testParseUpdates_ignoresBlanksAndDuplicates() {
const QString output = "\n\nlinux 6.9-1\n\nlinux 6.9-1\n";
const QStringList packages = StartupCheck::parseUpdates(output);
assert(packages.size() == 1);
assert(packages.at(0) == "linux");
}
static void testParseUpdates_emptyOutput() {
assert(StartupCheck::parseUpdates(QString()).isEmpty());
}
// ---------------------------------------------------------------------------
// Classification
// ---------------------------------------------------------------------------
static void testIsCritical_kernelAndCorePackages() {
assert(StartupCheck::isCritical("linux"));
assert(StartupCheck::isCritical("linux-lts"));
assert(StartupCheck::isCritical("linux-firmware"));
assert(StartupCheck::isCritical("glibc"));
assert(StartupCheck::isCritical("systemd"));
assert(StartupCheck::isCritical("systemd-libs"));
assert(StartupCheck::isCritical("mesa"));
assert(StartupCheck::isCritical("nvidia-utils"));
assert(StartupCheck::isCritical("pacman"));
assert(StartupCheck::isCritical("openssl"));
}
static void testIsCritical_ordinaryPackages() {
assert(!StartupCheck::isCritical("firefox"));
assert(!StartupCheck::isCritical("vlc"));
assert(!StartupCheck::isCritical("gimp"));
assert(!StartupCheck::isCritical("git"));
assert(!StartupCheck::isCritical("python"));
}
static void testIsRebootRequired_onlyKernelAndDrivers() {
assert(StartupCheck::isRebootRequired("linux"));
assert(StartupCheck::isRebootRequired("linux-firmware"));
assert(StartupCheck::isRebootRequired("nvidia-utils"));
// Critical because they can break the session, but they take effect on the
// spot: no reboot to ask for.
assert(!StartupCheck::isRebootRequired("glibc"));
assert(!StartupCheck::isRebootRequired("mesa"));
assert(!StartupCheck::isRebootRequired("firefox"));
}
static void testCriticalPackages_returnsOnlyTheMatchingOnes() {
const QStringList all{"firefox", "linux", "vlc", "glibc"};
const QStringList critical = StartupCheck::criticalPackages(all);
assert(critical.size() == 2);
assert(critical.at(0) == "linux");
assert(critical.at(1) == "glibc");
}
// ---------------------------------------------------------------------------
// Notification text
// ---------------------------------------------------------------------------
static void testNotification_kernelUpdateIsUrgent() {
StartupCheck::Result result;
result.packages = {"linux", "glibc", "firefox"};
result.updateCount = 3;
result.anyCritical = true;
result.rebootRequired = true;
assert(StartupCheck::notificationTitle(result) == "Mise à jour du noyau disponible");
const QString body = StartupCheck::notificationBody(result);
assert(body.contains("3 mises à jour"));
assert(body.contains("linux, glibc"));
assert(body.contains("redémarrage"));
}
static void testNotification_ordinaryUpdate() {
StartupCheck::Result result;
result.packages = {"firefox"};
result.updateCount = 1;
assert(StartupCheck::notificationTitle(result) == "Mises à jour disponibles");
const QString body = StartupCheck::notificationBody(result);
assert(body.contains("1 mise à jour disponible"));
assert(body.contains("Ouvrez PacManager"));
assert(!body.contains("redémarrage"));
}
static void testNotification_capsTheCriticalPackageList() {
// Eight critical packages must not turn the bubble into a wall of text.
StartupCheck::Result result;
result.packages = {"linux", "linux-lts", "linux-zen", "linux-hardened",
"linux-firmware", "glibc", "systemd", "mesa"};
result.updateCount = 8;
result.anyCritical = true;
result.rebootRequired = true;
const QString body = StartupCheck::notificationBody(result);
assert(body.contains("…"));
assert(!body.contains("mesa"));
}
// ---------------------------------------------------------------------------
// Autostart files
// ---------------------------------------------------------------------------
static void testAutostart_installEnableAndRemove() {
QTemporaryDir dir;
assert(dir.isValid());
const QString configDir = dir.path();
// A space in the path checks the quoting systemd needs.
const QString program = "/opt/Pac Manager/PacManager";
assert(!StartupCheck::autostartEnabled(configDir));
QString error;
assert(StartupCheck::installAutostart(configDir, program, &error));
assert(error.isEmpty());
assert(StartupCheck::autostartEnabled(configDir));
QFile unit(StartupCheck::autostartUnitPath(configDir));
assert(unit.open(QIODevice::ReadOnly));
const QString content = QString::fromUtf8(unit.readAll());
unit.close();
assert(content.contains("\"/opt/Pac Manager/PacManager\" --check-updates"));
assert(content.contains("WantedBy=default.target"));
assert(content.contains("Type=oneshot"));
// The enabling link points back at the unit, which is what makes the login
// manager start it.
const QFileInfo link(StartupCheck::autostartWantsPath(configDir));
assert(link.isSymLink());
assert(StartupCheck::removeAutostart(configDir, &error));
assert(!StartupCheck::autostartEnabled(configDir));
assert(!QFile::exists(StartupCheck::autostartUnitPath(configDir)));
assert(!QFileInfo::exists(StartupCheck::autostartWantsPath(configDir)));
}
static void testAutostart_refusesEmptyInputs() {
assert(StartupCheck::autostartUnitPath(QString()).isEmpty());
assert(StartupCheck::autostartWantsPath(QString()).isEmpty());
QString error;
assert(!StartupCheck::installAutostart(QString(), "/usr/bin/PacManager", &error));
assert(!error.isEmpty());
assert(!StartupCheck::installAutostart("/tmp/does-not-matter", QString(), &error));
assert(!StartupCheck::autostartEnabled(QString()));
}
int main() {
testParseUpdates_checkupdatesFormat();
testParseUpdates_pacmanFormat();
testParseUpdates_ignoresBlanksAndDuplicates();
testParseUpdates_emptyOutput();
testIsCritical_kernelAndCorePackages();
testIsCritical_ordinaryPackages();
testIsRebootRequired_onlyKernelAndDrivers();
testCriticalPackages_returnsOnlyTheMatchingOnes();
testNotification_kernelUpdateIsUrgent();
testNotification_ordinaryUpdate();
testNotification_capsTheCriticalPackageList();
testAutostart_installEnableAndRemove();
testAutostart_refusesEmptyInputs();
std::cout << "All startup-check tests passed." << std::endl;
return 0;
}