#include "startup-check.h" #include "log-manager.h" #include #include #include #include #include #include #include #include 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 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; }