Files
FWS-PacManage/providers/pacman-manager.cpp
T
BlackAngelTV 97d99c63a2 fix(credentials): run sudo without a password when the account has none
A passwordless sudo setup (NOPASSWD, or an account without a password) was
still asked for a password: leaving the field empty never satisfied the gate,
so the dialog reopened and the operation could not run at all.

The gate now asks sudo itself (`sudo -n true`) and lets the request through
when it needs nothing, privileged commands fall back to `sudo -n` when no
password is held, and an empty field cancels instead of looping. Releasing the
lock records its own pending request so an answered prompt is replayed rather
than lost.
2026-11-11 18:49:55 +01:00

886 lines
32 KiB
C++

#include "pacman-manager.h"
#include "progress-tracker.h"
#include "provider-trace.h"
#include <array>
#include <cctype>
#include <chrono>
#include <filesystem>
#include <memory>
#include <stdexcept>
#include <string>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <set>
#include <thread>
#include <vector>
#include <cstdlib>
#include <fstream>
#include <unistd.h>
// Helper to run shell commands and capture output
static std::string exec(const char* cmd) {
std::array<char, 256> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe) throw std::runtime_error("popen() failed");
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
// Escape a string so it can be embedded inside single quotes in a shell
// command without breaking out of the quotes (used for the sudo password).
static std::string shellQuote(const std::string& s) {
std::string out = "'";
for (char c : s) {
if (c == '\'') out += "'\\''";
else out += c;
}
out += "'";
return out;
}
// One line of operator trace: the exact command run, a query served from cache,
// what a listing found. The host routes it to the journal only (see
// provider-trace.h), so being verbose here costs nothing in the interface.
static void trace(const std::string& message) {
provider_trace::report("pacman", message);
}
// Keep only the last few lines of a command output for error dialogs, so a
// failure shows the real cause without dumping pages of progress lines.
static std::string lastOutputLines(const std::string& output, int keep = 5) {
std::istringstream iss(output);
std::string line;
std::vector<std::string> lines;
while (std::getline(iss, line)) {
if (!line.empty()) lines.push_back(line);
}
std::string out;
const size_t start = lines.size() > static_cast<size_t>(keep)
? lines.size() - keep
: 0;
for (size_t i = start; i < lines.size(); ++i) {
if (!out.empty()) out += "\n";
out += lines[i];
}
return out;
}
// Run a privileged pacman command as root, piping the password to `sudo -S`
// on stdin — or using `sudo -n` when there is none — and capturing combined
// stdout+stderr. Output is delivered to the progress callback as pacman
// produces it — including its in-place download meters, which is what makes
// the bar move during a long download — and the full output is still returned
// for the auth/error checks.
//
// The percentage comes from ProgressTracker, not from the raw counters: pacman
// restarts "(1/24)" at every phase of the transaction, so forwarding those
// numbers made the bar go backwards several times per update.
static std::string execPrivileged(const std::string& pacmanCmd,
const std::string& password,
ProgressCallback progressCallback) {
// The journal gets the command as the user would type it. The password is
// piped to sudo on stdin and must never reach the trace.
trace("$ sudo " + pacmanCmd);
return runWithProgress(PacmanManager::privilegedCommand(pacmanCmd, password)
+ " 2>&1",
progressCallback);
}
// pacman's database lock file. Every manager that goes through libalpm (pacman,
// pamac, octopi, the AUR helpers) takes it for the duration of a transaction.
static const char* kLockFilePath = "/var/lib/pacman/db.lck";
// Processes that take that lock, used as a fallback when /proc cannot tell us
// who does (the fd table of a root-owned process is not readable by a normal
// user, which is exactly the "sudo pacman in another terminal" case).
static const char* kKnownLockUsers[] = {
"pacman", "pamac", "pamac-manager", "yay", "paru", "pikaur",
"octopi", "octopi-helper", "discover",
};
// How long the recovery waits for a SIGTERM-ed manager to release the lock
// before forcing it, then for the forced stop to take effect.
static constexpr int kTerminateGraceMs = 8000;
static constexpr int kKillGraceMs = 3000;
// Read-only pacman output is reused by several views within a few seconds, so
// it is cached for this long. Short enough that a package installed outside the
// app still appears almost immediately, and every mutating operation drops the
// cache outright.
static constexpr std::chrono::seconds kQueryTtl{10};
std::string PacmanManager::cachedQuery(PacmanManager::CachedQuery& slot,
const char* command) {
const auto now = std::chrono::steady_clock::now();
bool fromCache = false;
{
std::lock_guard<std::mutex> lock(m_queryMutex);
fromCache = slot.valid && now - slot.fetched < kQueryTtl;
}
if (fromCache) {
// Reused for a few seconds: saying so explains why a page opened
// without spawning pacman at all.
trace(std::string("cache · ") + command);
std::lock_guard<std::mutex> lock(m_queryMutex);
return slot.output;
}
trace(std::string("$ ") + command);
// Queried outside the lock: a second thread asking for the same query then
// just runs it too, which is cheaper than serialising the whole app on
// pacman.
std::string fresh = exec(command);
{
std::lock_guard<std::mutex> lock(m_queryMutex);
slot.output = fresh;
slot.fetched = now;
slot.valid = true;
}
return fresh;
}
void PacmanManager::invalidateQueries() {
std::lock_guard<std::mutex> lock(m_queryMutex);
m_installedQuery.valid = false;
m_installedDetailsQuery.valid = false;
m_syncReposQuery.valid = false;
m_updatesQuery.valid = false;
}
std::vector<PackageInfo> PacmanManager::search(const std::string& query) {
std::vector<PackageInfo> results;
std::string cmd = "pacman -Ss " + query + " 2>&1";
std::string output = exec(cmd.c_str());
// Load the installed packages once, so marking search results as
// installed is an in-memory lookup instead of one `pacman -Qi` subprocess
// per result (which made searches with many matches take minutes).
std::set<std::string> installed =
parseInstalledNames(cachedQuery(m_installedQuery, "pacman -Q 2>&1"));
std::istringstream iss(output);
std::string line;
while (std::getline(iss, line)) {
if (line.empty()) continue;
// Repository line: repo/name version
if (line[0] != ' ' && line[0] != '\t') {
PackageInfo pkg;
size_t slashPos = line.find('/');
size_t spacePos = line.find(' ', slashPos);
if (slashPos != std::string::npos) {
pkg.repository = line.substr(0, slashPos);
pkg.name = line.substr(slashPos + 1, spacePos - slashPos - 1);
if (spacePos != std::string::npos) {
size_t nextSpace = line.find(' ', spacePos + 1);
pkg.version = line.substr(spacePos + 1, nextSpace - spacePos - 1);
}
}
pkg.installed = installed.count(pkg.name) > 0;
results.push_back(pkg);
}
// Description line (starts with spaces)
else if (!results.empty()) {
std::string desc = line;
// Trim leading spaces
size_t start = desc.find_first_not_of(" \t");
if (start != std::string::npos) {
desc = desc.substr(start);
}
results.back().description = desc;
}
}
trace("pacman -Ss " + query + " → " + std::to_string(results.size())
+ " résultat(s)");
return results;
}
bool PacmanManager::install(const std::string& packageName,
ProgressCallback progressCallback) {
// The transaction changes the installed set (and may fail halfway): drop
// the cached reads before it runs rather than after.
invalidateQueries();
if (progressCallback) progressCallback("Installation de " + packageName + "...", -1);
std::string output =
execPrivileged("pacman -S --noconfirm " + packageName, m_password, progressCallback);
m_lastError.clear();
// A wrong/expired password must not be silently reused: drop it so the
// next attempt prompts again.
if (authFailed(output)) {
clearPassword();
m_lastError = "Échec d'authentification sudo.";
return false;
}
if (dbLocked(output)) {
m_lastErrorWasLock = true;
m_lastError = dbLockHint();
return false;
}
return isPackageInstalled(packageName);
}
bool PacmanManager::remove(const std::string& packageName,
ProgressCallback progressCallback) {
invalidateQueries();
if (progressCallback) progressCallback("Suppression de " + packageName + "...", -1);
std::string output =
execPrivileged("pacman -R --noconfirm " + packageName, m_password, progressCallback);
m_lastError.clear();
m_lastErrorWasLock = false;
if (authFailed(output)) {
clearPassword();
m_lastError = "Échec d'authentification sudo.";
return false;
}
if (dbLocked(output)) {
m_lastErrorWasLock = true;
m_lastError = dbLockHint();
return false;
}
return !isPackageInstalled(packageName);
}
bool PacmanManager::update(const std::string& packageName,
ProgressCallback progressCallback) {
invalidateQueries();
std::string output;
if (packageName.empty()) {
if (progressCallback) progressCallback("Mise à jour de tous les paquets...", -1);
output = execPrivileged("pacman -Syu --noconfirm", m_password, progressCallback);
} else {
if (progressCallback) progressCallback("Mise à jour de " + packageName + "...", -1);
output = execPrivileged("pacman -S --noconfirm " + packageName,
m_password, progressCallback);
}
m_lastError.clear();
m_lastErrorWasLock = false;
if (authFailed(output)) {
clearPassword();
m_lastError = "Échec d'authentification sudo.";
return false;
}
if (dbLocked(output)) {
m_lastErrorWasLock = true;
m_lastError = dbLockHint();
return false;
}
return true;
}
std::vector<PackageInfo> PacmanManager::listInstalled() {
auto packages = parseInstalledOutput(cachedQuery(m_installedQuery, "pacman -Q 2>&1"));
// Enrich each installed package with its installed size (shown as "Taille")
// and the repository/origin it was installed from. `pacman -Qi` answers for
// every package at once, and `-Sl` only changes on a sync, so both are
// cached across the views that need them.
auto sizes = parseInstalledSizes(
cachedQuery(m_installedDetailsQuery, "pacman -Qi 2>&1"));
auto repos = parseSyncRepos(cachedQuery(m_syncReposQuery, "pacman -Sl 2>&1"));
for (auto& pkg : packages) {
auto sizeIt = sizes.find(pkg.name);
if (sizeIt != sizes.end()) {
pkg.size = sizeIt->second;
pkg.installedSize = sizeIt->second;
}
auto repoIt = repos.find(pkg.name);
if (repoIt != repos.end()) {
pkg.repository = repoIt->second;
} else {
// Not present in any sync repository: foreign package (AUR / manual build).
pkg.repository = "AUR";
}
}
trace("pacman -Q / -Qi / -Sl → " + std::to_string(packages.size())
+ " paquet(s) installé(s), taille et dépôt inclus");
return packages;
}
// Parse `pacman -Qu` output (one "name version" line per outdated package).
// Exposed as static so the parsing can be unit-tested without invoking pacman.
static std::vector<PackageInfo> parseUpdatesOutput(const std::string& output) {
std::vector<PackageInfo> results;
std::istringstream iss(output);
std::string line;
while (std::getline(iss, line)) {
if (line.empty()) continue;
PackageInfo pkg;
size_t spacePos = line.find(' ');
if (spacePos == std::string::npos) continue;
pkg.name = line.substr(0, spacePos);
pkg.version = line.substr(spacePos + 1);
pkg.installed = true;
pkg.updateAvailable = true;
results.push_back(pkg);
}
return results;
}
std::vector<PackageInfo> PacmanManager::listUpdates() {
// Cached like the other read-only queries: the dashboard badge, the updates
// screen and the "Tout mettre à jour" button all ask for it within the same
// second, and one pacman process answers for all of them.
std::vector<PackageInfo> results =
parseUpdatesOutput(cachedQuery(m_updatesQuery, "pacman -Qu 2>&1"));
trace("pacman -Qu → " + std::to_string(results.size())
+ " mise(s) à jour disponible(s)");
return results;
}
// Orphans (-Qdt: no installed package requires them) and legacy packages (-Qm:
// installed from outside the sync databases, i.e. AUR or manual builds).
std::vector<PackageInfo> PacmanManager::listCleanupCandidates() {
// `pacman -Qdt` warns on stderr when the system has no orphan at all: only
// stdout is parsed, so the warning never reaches the candidate list.
std::vector<PackageInfo> results = parseCleanupOutput(exec("pacman -Qdt 2>/dev/null"),
exec("pacman -Qm 2>/dev/null"));
int orphans = 0;
for (const auto& pkg : results) {
if (pkg.orphan) ++orphans;
}
trace("pacman -Qdt / -Qm → " + std::to_string(orphans) + " orphelin(s) et "
+ std::to_string(results.size() - orphans) + " paquet(s) legacy");
return results;
}
bool PacmanManager::removePackages(const std::vector<std::string>& packages,
ProgressCallback progressCallback) {
const std::string command = removePackagesCommand(packages);
if (command.empty()) return true;
invalidateQueries();
if (progressCallback) {
progressCallback("Suppression de " + std::to_string(packages.size())
+ " paquet(s)...", -1);
}
std::string output = execPrivileged(command, m_password, progressCallback);
m_lastError.clear();
m_lastErrorWasLock = false;
if (authFailed(output)) {
clearPassword();
m_lastError = "Échec d'authentification sudo.";
return false;
}
if (dbLocked(output)) {
m_lastErrorWasLock = true;
m_lastError = dbLockHint();
return false;
}
// One missing target or one package still required by another fails the
// whole transaction, so report the real cause instead of a partial cleanup.
if (output.find("error:") != std::string::npos
|| output.find("erreur") != std::string::npos) {
m_lastError = "Échec de la suppression des paquets.\nDétail :\n"
+ lastOutputLines(output);
return false;
}
return true;
}
bool PacmanManager::cleanCache(ProgressCallback progressCallback) {
const bool paccache =
system("command -v paccache > /dev/null 2>&1") == 0;
if (progressCallback) progressCallback("Nettoyage du cache pacman...", -1);
std::string output =
execPrivileged(cleanCacheCommand(paccache), m_password, progressCallback);
m_lastError.clear();
m_lastErrorWasLock = false;
if (authFailed(output)) {
clearPassword();
m_lastError = "Échec d'authentification sudo.";
return false;
}
if (dbLocked(output)) {
m_lastErrorWasLock = true;
m_lastError = dbLockHint();
return false;
}
if (output.find("error:") != std::string::npos
|| output.find("erreur") != std::string::npos) {
m_lastError = "Échec du nettoyage du cache pacman.\nDétail :\n"
+ lastOutputLines(output);
return false;
}
return true;
}
bool PacmanManager::refresh(ProgressCallback progressCallback) {
// A sync rewrites the sync databases the `-Sl` cache is built from.
invalidateQueries();
if (progressCallback) progressCallback("Rafraîchissement des bases de données...", -1);
std::string output =
execPrivileged("pacman -Sy --noconfirm", m_password, progressCallback);
m_lastError.clear();
m_lastErrorWasLock = false;
if (authFailed(output)) {
clearPassword();
m_lastError = "Échec d'authentification sudo.";
return false;
}
if (dbLocked(output)) {
m_lastErrorWasLock = true;
m_lastError = dbLockHint();
return false;
}
// `pacman -Sy` exits 0 even when only some DBs synced; surface the real
// output so a network failure is not reported as success.
if (output.find("error:") != std::string::npos
|| output.find("erreur") != std::string::npos
|| output.find("failed to synchronize") != std::string::npos
|| output.find("synchronisation") != std::string::npos) {
m_lastError = "Échec du rafraîchissement des bases pacman.\n"
"Détail :\n" + lastOutputLines(output);
return false;
}
return true;
}
std::vector<PackageInfo> PacmanManager::parseInstalledOutput(const std::string& output) {
std::vector<PackageInfo> results;
std::istringstream iss(output);
std::string line;
while (std::getline(iss, line)) {
if (line.empty()) continue;
PackageInfo pkg;
// `pacman -Q` prints "name version" separated by a single space;
// splitting on the first space keeps hyphens in names (e.g. python-pip) intact.
size_t spacePos = line.find(' ');
if (spacePos == std::string::npos) continue;
pkg.name = line.substr(0, spacePos);
pkg.version = line.substr(spacePos + 1);
pkg.installed = true;
results.push_back(pkg);
}
return results;
}
std::set<std::string> PacmanManager::parseInstalledNames(const std::string& output) {
std::set<std::string> names;
std::istringstream iss(output);
std::string line;
while (std::getline(iss, line)) {
if (line.empty()) continue;
// Same split as parseInstalledOutput: the first space separates the
// name from the version (hyphens in names are kept intact).
size_t spacePos = line.find(' ');
if (spacePos == std::string::npos) continue;
names.insert(line.substr(0, spacePos));
}
return names;
}
bool PacmanManager::isPackageInstalled(const std::string& name) {
std::string cmd = "pacman -Qi " + name + " > /dev/null 2>&1";
return system(cmd.c_str()) == 0;
}
// Parse `pacman -Qi` output (one blank-line-separated block per package) into a
// map of package name -> installed size (e.g. "263.47 MiB").
std::map<std::string, std::string> PacmanManager::parseInstalledSizes(
const std::string& output) {
std::map<std::string, std::string> sizes;
std::istringstream iss(output);
std::string line;
std::string currentName;
while (std::getline(iss, line)) {
// A blank line ends the current package block.
if (line.empty()) {
currentName.clear();
continue;
}
size_t colon = line.find(':');
if (colon == std::string::npos) continue;
std::string field = line.substr(0, colon);
// Trim trailing whitespace from the label (labels are padded to align).
while (!field.empty() && field.back() == ' ') field.pop_back();
std::string value = line.substr(colon + 1);
// Trim leading whitespace from the value.
size_t start = value.find_first_not_of(" \t");
if (start != std::string::npos) {
value = value.substr(start);
}
if (field == "Name") {
currentName = value;
} else if (field == "Installed Size" && !currentName.empty()) {
sizes[currentName] = value;
}
}
return sizes;
}
// Parse `pacman -Sl` output ("repo name version" per sync-DB package) into a map of
// package name -> repository, so the origin of each installed package can be shown.
std::map<std::string, std::string> PacmanManager::parseSyncRepos(
const std::string& output) {
std::map<std::string, std::string> repos;
std::istringstream iss(output);
std::string line;
bool firstLine = true;
while (std::getline(iss, line)) {
if (firstLine) {
firstLine = false;
continue; // Skip the "Repository Name Version" header.
}
if (line.empty()) continue;
std::istringstream ls(line);
std::string repo;
std::string name;
if (!(ls >> repo >> name)) continue;
repos[name] = repo;
}
return repos;
}
// Orphans first: they are the rows the UI can bulk-remove, and the ones users
// look for. Foreign packages follow, marked so the UI never removes them
// without an explicit per-row confirmation.
std::vector<PackageInfo> PacmanManager::parseCleanupOutput(const std::string& orphans,
const std::string& foreign) {
std::vector<PackageInfo> results = parseInstalledOutput(orphans);
for (auto& pkg : results) {
pkg.orphan = true;
pkg.cleanupReason = "Orphelin";
}
// A foreign package can also be an orphan; the orphan classification is the
// meaningful one (it is the one that may be removed in bulk).
std::set<std::string> seen;
for (const auto& pkg : results) seen.insert(pkg.name);
for (auto& pkg : parseInstalledOutput(foreign)) {
if (!seen.insert(pkg.name).second) continue;
pkg.cleanupReason = "Étranger (AUR / manuel)";
results.push_back(pkg);
}
return results;
}
std::string PacmanManager::removePackagesCommand(const std::vector<std::string>& packages) {
if (packages.empty()) return {};
// -s also drops the dependencies these packages dragged in, -n their
// pacman-managed config backups. --noconfirm keeps the removal unattended:
// the UI already asked the user before starting.
std::string command = "pacman -Rns --noconfirm";
for (const auto& name : packages) {
command += " " + shellQuote(name);
}
return command;
}
std::string PacmanManager::cleanCacheCommand(bool paccacheAvailable) {
// paccache (pacman-contrib) keeps the latest version of every package,
// which is far more conservative than `pacman -Sc`: the latter also drops
// the cached copies of packages that are still installed, so a later
// rollback or reinstall has to download them again.
return paccacheAvailable ? "paccache -rk1" : "pacman -Sc --noconfirm";
}
bool PacmanManager::authFailed(const std::string& output) {
return output.find("incorrect password") != std::string::npos
|| output.find("a password is required") != std::string::npos
|| output.find("Authentication failure") != std::string::npos;
}
// True when pacman refused to run because its database is locked
// (/var/lib/pacman/db.lck): another pacman/pamac/yay run is in progress, or
// a previous run crashed without releasing the lock.
// Name of a process as the user recognizes it (/proc/<pid>/comm).
static std::string processName(int pid) {
std::ifstream comm("/proc/" + std::to_string(pid) + "/comm");
std::string name;
std::getline(comm, name);
while (!name.empty() && (name.back() == '\n' || name.back() == ' ')) {
name.pop_back();
}
return name;
}
// Parent of a process (/proc/<pid>/stat, 4th field); 0 when unknown.
static int parentPid(int pid) {
std::ifstream stat("/proc/" + std::to_string(pid) + "/stat");
std::string line;
if (!std::getline(stat, line)) return 0;
// The command name is parenthesised and may itself contain spaces, so the
// fields after it are read from the last closing parenthesis.
const size_t close = line.rfind(')');
if (close == std::string::npos) return 0;
std::istringstream rest(line.substr(close + 1));
std::string state;
int ppid = 0;
rest >> state >> ppid;
return ppid;
}
// True when this process is keeping `path` open. Nothing takes a lock without
// opening it, so the fd table answers the question directly — and it names the
// exact process, even one we do not know about (a wrapper script, `sh -c`).
static bool processHoldsFile(int pid, const std::string& path) {
std::error_code listingError;
auto it = std::filesystem::directory_iterator(
"/proc/" + std::to_string(pid) + "/fd", listingError);
const auto end = std::filesystem::directory_iterator();
for (; it != end; it.increment(listingError)) {
std::error_code linkError;
const std::filesystem::path target =
std::filesystem::read_symlink(it->path(), linkError);
if (!linkError && target == path) return true;
if (listingError) break;
}
return false;
}
// First pid running `name`, excluding this process and its direct children: a
// pacman we launched ourselves is not "another manager".
static int pgrepPid(const std::string& name) {
const std::string output =
exec(("pgrep -x " + shellQuote(name) + " 2>/dev/null").c_str());
const int self = static_cast<int>(getpid());
std::istringstream iss(output);
std::string line;
while (std::getline(iss, line)) {
if (line.empty()) continue;
const int pid = std::atoi(line.c_str());
if (pid <= 0 || pid == self) continue;
if (parentPid(pid) == self) continue;
return pid;
}
return 0;
}
int PacmanManager::lockHolderPid(const std::string& path) {
std::error_code error;
for (const auto& entry : std::filesystem::directory_iterator("/proc", error)) {
const std::string name = entry.path().filename().string();
if (name.empty() || !std::isdigit(static_cast<unsigned char>(name[0]))) continue;
const int pid = std::atoi(name.c_str());
if (pid <= 0 || pid == static_cast<int>(getpid())) continue;
if (processHoldsFile(pid, path)) return pid;
}
return 0;
}
PacmanManager::LockHolder PacmanManager::detectLockHolder() {
LockHolder holder;
std::error_code error;
holder.lockFilePresent = std::filesystem::exists(kLockFilePath, error);
if (!holder.lockFilePresent) return holder;
holder.pid = lockHolderPid(kLockFilePath);
if (holder.pid > 0) {
holder.name = processName(holder.pid);
return holder;
}
for (const char* tool : kKnownLockUsers) {
const int pid = pgrepPid(tool);
if (pid <= 0) continue;
holder.pid = pid;
holder.name = tool;
return holder;
}
// Nobody holds it: the file is left over from a run that never finished.
holder.stale = true;
return holder;
}
std::string PacmanManager::describeLockHolder(const LockHolder& holder) {
if (holder.pid > 0) {
const std::string name = holder.name.empty() ? "processus inconnu" : holder.name;
return name + " (PID " + std::to_string(holder.pid) + ")";
}
if (holder.stale) {
return "un verrou résiduel laissé par un gestionnaire interrompu";
}
return {};
}
bool PacmanManager::databaseIsFree() {
std::error_code error;
return !std::filesystem::exists(kLockFilePath, error);
}
bool PacmanManager::waitForDatabase(int timeoutMs) {
constexpr int kStepMs = 250;
for (int waited = 0; waited <= timeoutMs; waited += kStepMs) {
if (databaseIsFree()) return true;
std::this_thread::sleep_for(std::chrono::milliseconds(kStepMs));
}
return databaseIsFree();
}
int PacmanManager::runCommand(const std::string& command, bool withSudo) const {
const std::string full = withSudo ? privilegedCommand(command, m_password)
: command;
return system((full + " > /dev/null 2>&1").c_str());
}
bool PacmanManager::terminateProcess(int pid, const char* signal) const {
const std::string command =
"kill -" + std::string(signal) + " " + std::to_string(pid);
if (runCommand(command, /*withSudo=*/false) == 0) return true;
// The holder belongs to another user (a manager started with sudo in a
// terminal): only root can reach it. Called unconditionally: without a
// password this is `sudo -n`, which fails at once when one is required.
return runCommand(command, /*withSudo=*/true) == 0;
}
bool PacmanManager::removeLockFile() const {
const std::string command = std::string("rm -f ") + kLockFilePath;
if (runCommand(command, /*withSudo=*/false) == 0 && databaseIsFree()) return true;
return runCommand(command, /*withSudo=*/true) == 0 && databaseIsFree();
}
bool PacmanManager::releaseDatabaseLock(const LockHolder& holder,
ProgressCallback progressCallback) {
m_lastError.clear();
m_lastErrorWasLock = false;
if (holder.pid > 0) {
const std::string who = describeLockHolder(holder);
trace("db.lck détenu par " + who + " : envoi de SIGTERM");
if (progressCallback) progressCallback("Arrêt de " + who + "...", -1);
if (!terminateProcess(holder.pid, "TERM")) {
m_lastError = "Impossible d'arrêter " + who
+ " : droits insuffisants pour le faire depuis "
"PacManager.";
return false;
}
if (!waitForDatabase(kTerminateGraceMs)) {
if (progressCallback) {
progressCallback(who + " ne répond pas, arrêt forcé...", -1);
}
terminateProcess(holder.pid, "KILL");
waitForDatabase(kKillGraceMs);
}
if (databaseIsFree()) return true;
}
// No process left to stop (or it would not die): the lock file itself is
// what keeps the database closed.
trace("aucun processus à arrêter : suppression du fichier de verrou résiduel");
if (progressCallback) progressCallback("Suppression du verrou résiduel...", -1);
if (removeLockFile()) return true;
m_lastError = "La base pacman est toujours verrouillée : droits insuffisants "
"pour supprimer le verrou.";
return false;
}
bool PacmanManager::dbLocked(const std::string& output) {
return output.find("could not lock database") != std::string::npos
|| output.find("unable to lock database") != std::string::npos
|| output.find("verrouillage de la base") != std::string::npos
|| output.find("db.lck") != std::string::npos
|| output.find("failed to synchronize all databases") != std::string::npos
|| output.find("synchronisation de toutes les bases") != std::string::npos;
}
// Short user-facing hint shown when the DB is locked. Points to the lock
// file when it is stale (no other pacman running) so the user can remove
// it; otherwise tells them to wait for the other run to finish.
std::string PacmanManager::dbLockHint() {
// No Qt here (this file also builds into the Qt-free unit tests):
// a lock file that exists with no other manager running is stale.
const bool lockExists = std::ifstream("/var/lib/pacman/db.lck").good();
const bool otherRunning =
system("pgrep -x pacman > /dev/null 2>&1") == 0
|| system("pgrep -x pamac > /dev/null 2>&1") == 0
|| system("pgrep -x yay > /dev/null 2>&1") == 0
|| system("pgrep -x paru > /dev/null 2>&1") == 0;
if (lockExists && !otherRunning) {
return "La base pacman est verrouillée par un fichier résiduel "
"(/var/lib/pacman/db.lck) alors qu'aucune autre mise à jour "
"ne tourne. Supprimez-le avec : sudo rm /var/lib/pacman/db.lck";
}
return "Un autre gestionnaire de paquets (pacman, pamac, yay, octopi…) "
"utilise déjà la base. Attendez la fin de l'autre opération puis "
"réessayez.";
}
void PacmanManager::setPassword(const std::string& password) {
m_password = password;
}
void PacmanManager::clearPassword() {
m_password.clear();
}
bool PacmanManager::sudoWorksWithoutPassword() {
return system("sudo -n true > /dev/null 2>&1") == 0;
}
std::string PacmanManager::privilegedCommand(const std::string& command,
const std::string& password) {
// No password is not a missing one: it means the account may use a
// passwordless sudo, which `-n` runs without asking. On a setup that does
// require a password, `-n` fails at once ("a password is required"), which
// authFailed() reports as an authentication error instead of hanging on a
// prompt the command cannot answer.
if (password.empty()) return "sudo -n " + command;
return "printf '%s\\n' " + shellQuote(password) + " | sudo -S " + command;
}
bool PacmanManager::hasPassword() const {
return !m_password.empty();
}