refactor(tree): split the plugin host from the providers it loads
plugins/ held two unrelated things: the host that discovers and installs plugins, and the plugins themselves. The host moves to plugins/ with the built-in pacman provider beside it in providers/, where the external providers already live — so plugins/ is now one thing, and the name says which. The external plugin projects only change folder, not layout: providers/ holds aur-provider, flatpak-provider, example-provider and example-addon.
This commit is contained in:
15 files changed
+39
-39
No files matched your search
@@ -1,833 +0,0 @@
|
||||
#include "pacman-manager.h"
|
||||
|
||||
#include "progress-tracker.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;
|
||||
}
|
||||
|
||||
// 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 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) {
|
||||
const std::string full = "printf '%s\\n' " + shellQuote(password)
|
||||
+ " | sudo -S " + pacmanCmd + " 2>&1";
|
||||
return runWithProgress(full, 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();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_queryMutex);
|
||||
if (slot.valid && now - slot.fetched < kQueryTtl) return slot.output;
|
||||
}
|
||||
|
||||
// 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;
|
||||
}
|
||||
}
|
||||
|
||||
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";
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
return parseUpdatesOutput(cachedQuery(m_updatesQuery, "pacman -Qu 2>&1"));
|
||||
}
|
||||
|
||||
// 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.
|
||||
return parseCleanupOutput(exec("pacman -Qdt 2>/dev/null"),
|
||||
exec("pacman -Qm 2>/dev/null"));
|
||||
}
|
||||
|
||||
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 {
|
||||
std::string full = command;
|
||||
if (withSudo) {
|
||||
full = "printf '%s\\n' " + shellQuote(m_password) + " | sudo -S " + 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 the session password can reach it.
|
||||
return hasPassword() && 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 hasPassword() && 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);
|
||||
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.
|
||||
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::hasPassword() const {
|
||||
return !m_password.empty();
|
||||
}
|
||||
@@ -1,253 +0,0 @@
|
||||
#include "plugin-manager.h"
|
||||
#include "app-logging.h"
|
||||
|
||||
#include <QDir>
|
||||
#include <QFileInfo>
|
||||
#include <QCoreApplication>
|
||||
|
||||
// Plugin directories, checked in order. Bundled plugins ship next to the
|
||||
// executable (<prefix>/bin/plugins after install); user plugins live under
|
||||
// the standard data directory so they survive application updates.
|
||||
static QStringList pluginSearchPaths() {
|
||||
QStringList paths;
|
||||
paths << QCoreApplication::applicationDirPath() + "/plugins";
|
||||
paths << QDir::homePath() + "/.local/share/PacManager/plugins";
|
||||
// System-wide plugins: <prefix>/lib/PacManager/plugins for installs to
|
||||
// /usr or /usr/local (covers both lib and lib64 layouts).
|
||||
const QString appDir = QCoreApplication::applicationDirPath();
|
||||
QDir prefix(appDir);
|
||||
if (prefix.dirName() == QLatin1String("bin") && prefix.cdUp()) {
|
||||
paths << prefix.absoluteFilePath("lib/PacManager/plugins");
|
||||
paths << prefix.absoluteFilePath("lib64/PacManager/plugins");
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
// Run a plugin's teardown and free what the host owns: the addon/provider
|
||||
// instance (after onUnload) and the library it was compiled into.
|
||||
static void unloadEntry(PluginManager::PluginEntry& entry) {
|
||||
if (entry.plugin) {
|
||||
entry.plugin->onUnload();
|
||||
delete entry.plugin;
|
||||
entry.plugin = nullptr;
|
||||
}
|
||||
if (entry.manager) {
|
||||
delete entry.manager;
|
||||
entry.manager = nullptr;
|
||||
}
|
||||
delete entry.library;
|
||||
entry.library = nullptr;
|
||||
}
|
||||
|
||||
PluginManager::PluginManager() = default;
|
||||
|
||||
PluginManager::~PluginManager() {
|
||||
// Unload plugins first (they may run code), then the libraries they were
|
||||
// compiled into.
|
||||
for (auto& entry : m_plugins) {
|
||||
unloadEntry(entry);
|
||||
}
|
||||
}
|
||||
|
||||
void PluginManager::registerBuiltin(PluginInfo info, IPackageManager* manager) {
|
||||
info.builtin = true;
|
||||
info.available = manager->isAvailable();
|
||||
m_plugins.push_back({std::move(info), nullptr, manager, nullptr});
|
||||
}
|
||||
|
||||
// Load a single shared library as a plugin. Returns false (without erroring)
|
||||
// when the file is not a plugin, so unrelated libraries in the directory are
|
||||
// skipped. The plugin's kind decides which create function is resolved:
|
||||
// "addon" -> IPlugin (see plugin.h), anything else -> IPackageManager.
|
||||
bool PluginManager::loadPluginFile(const QString& filePath) {
|
||||
typedef const char* (*MetaFn)();
|
||||
typedef IPackageManager* (*CreateProviderFn)();
|
||||
typedef IPlugin* (*CreatePluginFn)();
|
||||
|
||||
// Own the library for the lifetime of the plugin: it must stay loaded
|
||||
// as long as the addon/manager instance created from it exists.
|
||||
QLibrary* library = new QLibrary(filePath);
|
||||
if (!library->load()) {
|
||||
qCWarning(pacmgrPlugin) << "not a loadable plugin, skipping" << filePath
|
||||
<< library->errorString();
|
||||
delete library;
|
||||
return false;
|
||||
}
|
||||
|
||||
MetaFn idFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_id"));
|
||||
MetaFn nameFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_name"));
|
||||
MetaFn versionFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_version"));
|
||||
MetaFn descFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_description"));
|
||||
MetaFn authorFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_author"));
|
||||
MetaFn kindFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_kind"));
|
||||
CreateProviderFn createProviderFn =
|
||||
reinterpret_cast<CreateProviderFn>(library->resolve("fws_create_provider"));
|
||||
CreatePluginFn createPluginFn =
|
||||
reinterpret_cast<CreatePluginFn>(library->resolve("fws_create_plugin"));
|
||||
// Optional: only present when the plugin declares an install hint.
|
||||
MetaFn installHintFn = reinterpret_cast<MetaFn>(library->resolve("fws_plugin_install_hint"));
|
||||
|
||||
if (!idFn || !nameFn || !versionFn || !descFn || !authorFn) {
|
||||
library->unload();
|
||||
delete library;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Reject plugins whose id collides with an already registered plugin.
|
||||
const std::string id = idFn();
|
||||
for (const auto& entry : m_plugins) {
|
||||
if (entry.info.id == id) {
|
||||
library->unload();
|
||||
delete library;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Kind defaults to "provider" so legacy plugins without the symbol keep
|
||||
// loading; "addon" requires the matching create function.
|
||||
const std::string kind = kindFn ? kindFn() : "provider";
|
||||
const bool isAddon = (kind == "addon");
|
||||
if ((isAddon && !createPluginFn) || (!isAddon && !createProviderFn)) {
|
||||
library->unload();
|
||||
delete library;
|
||||
return false;
|
||||
}
|
||||
|
||||
PluginInfo info;
|
||||
info.id = id;
|
||||
info.name = nameFn();
|
||||
info.version = versionFn();
|
||||
info.description = descFn();
|
||||
info.author = authorFn();
|
||||
info.kind = isAddon ? PluginKind::Addon : PluginKind::Provider;
|
||||
info.path = filePath.toStdString();
|
||||
if (installHintFn && installHintFn() && *installHintFn()) {
|
||||
info.installHint = installHintFn();
|
||||
}
|
||||
|
||||
if (isAddon) {
|
||||
IPlugin* plugin = createPluginFn();
|
||||
plugin->onLoad();
|
||||
info.available = plugin->isAvailable();
|
||||
m_plugins.push_back({std::move(info), plugin, nullptr, library});
|
||||
} else {
|
||||
IPackageManager* manager = createProviderFn();
|
||||
info.available = manager->isAvailable();
|
||||
m_plugins.push_back({std::move(info), nullptr, manager, library});
|
||||
}
|
||||
qCDebug(pacmgrPlugin) << "loaded" << (isAddon ? "addon" : "provider")
|
||||
<< filePath << "available" << m_plugins.back().info.available;
|
||||
return true;
|
||||
}
|
||||
|
||||
void PluginManager::scanDirectory(const QString& dir) {
|
||||
QDir directory(dir);
|
||||
if (!directory.exists()) return;
|
||||
|
||||
const QStringList filters = {
|
||||
#ifdef Q_OS_WIN
|
||||
"*.dll"
|
||||
#elif defined(Q_OS_MACOS)
|
||||
"*.dylib"
|
||||
#else
|
||||
"*.so"
|
||||
#endif
|
||||
};
|
||||
|
||||
const QStringList files = directory.entryList(filters, QDir::Files);
|
||||
for (const QString& file : files) {
|
||||
loadPluginFile(directory.absoluteFilePath(file));
|
||||
}
|
||||
}
|
||||
|
||||
void PluginManager::unloadExternal() {
|
||||
for (auto it = m_plugins.begin(); it != m_plugins.end();) {
|
||||
if (!it->info.builtin) {
|
||||
unloadEntry(*it);
|
||||
it = m_plugins.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void PluginManager::discoverExternal() {
|
||||
for (const QString& dir : pluginSearchPaths()) {
|
||||
scanDirectory(dir);
|
||||
}
|
||||
}
|
||||
|
||||
void PluginManager::reload() {
|
||||
unloadExternal();
|
||||
discoverExternal();
|
||||
}
|
||||
|
||||
void PluginManager::refreshAvailability() {
|
||||
for (auto& entry : m_plugins) {
|
||||
if (entry.plugin) {
|
||||
entry.info.available = entry.plugin->isAvailable();
|
||||
} else {
|
||||
entry.info.available = entry.manager->isAvailable();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const std::vector<PluginManager::PluginEntry>& PluginManager::plugins() const {
|
||||
return m_plugins;
|
||||
}
|
||||
|
||||
std::vector<const PluginManager::PluginEntry*> PluginManager::availableProviders() const {
|
||||
std::vector<const PluginEntry*> result;
|
||||
for (const auto& entry : m_plugins) {
|
||||
if (entry.manager && entry.info.available && isEnabled(entry.info.id)) {
|
||||
result.push_back(&entry);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
std::vector<IPackageManager*> PluginManager::availableManagers() const {
|
||||
std::vector<IPackageManager*> result;
|
||||
for (const auto& entry : m_plugins) {
|
||||
if (entry.manager && entry.info.available && isEnabled(entry.info.id)) {
|
||||
result.push_back(entry.manager);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
const PluginManager::PluginEntry* PluginManager::findAvailable(const std::string& id) const {
|
||||
for (const auto& entry : m_plugins) {
|
||||
if (entry.info.id == id && entry.manager && entry.info.available
|
||||
&& isEnabled(entry.info.id)) {
|
||||
return &entry;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
std::vector<IPlugin*> PluginManager::availableAddons() const {
|
||||
std::vector<IPlugin*> result;
|
||||
for (const auto& entry : m_plugins) {
|
||||
if (entry.plugin && entry.info.available && isEnabled(entry.info.id)) {
|
||||
result.push_back(entry.plugin);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
bool PluginManager::isEnabled(const std::string& id) const {
|
||||
return m_settings.value(QString("plugins/%1/enabled").arg(QString::fromStdString(id)),
|
||||
true).toBool();
|
||||
}
|
||||
|
||||
void PluginManager::setEnabled(const std::string& id, bool enabled) {
|
||||
m_settings.setValue(QString("plugins/%1/enabled").arg(QString::fromStdString(id)), enabled);
|
||||
}
|
||||
|
||||
IPackageManager* PluginManager::managerFor(const std::string& id) const {
|
||||
for (const auto& entry : m_plugins) {
|
||||
if (entry.info.id == id) return entry.manager;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
@@ -1,329 +0,0 @@
|
||||
#include "plugin-package.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QSaveFile>
|
||||
#include <QSettings>
|
||||
|
||||
#include "app-logging.h"
|
||||
|
||||
// The per-user plugin directory, shared with PluginManager's search paths: what
|
||||
// a package installs lands exactly where a hand-copied library would, so the
|
||||
// registry needs nothing else to pick it up.
|
||||
static const char* kUserPluginDir = "/.local/share/PacManager/plugins";
|
||||
|
||||
// The manifest a package must carry, and the name the format is versioned
|
||||
// under. A package declaring another version is refused rather than guessed at.
|
||||
static const char* kManifestName = "plugin.json";
|
||||
|
||||
PluginPackage::PluginPackage(QObject* parent) : QObject(parent) {}
|
||||
|
||||
QString PluginPackage::suffix() {
|
||||
return QStringLiteral(".fwspacm");
|
||||
}
|
||||
|
||||
bool PluginPackage::isPackagePath(const QString& path) {
|
||||
return path.trimmed().endsWith(suffix(), Qt::CaseInsensitive);
|
||||
}
|
||||
|
||||
QString PluginPackage::librarySuffix() {
|
||||
#ifdef Q_OS_WIN
|
||||
return QStringLiteral(".dll");
|
||||
#elif defined(Q_OS_MACOS)
|
||||
return QStringLiteral(".dylib");
|
||||
#else
|
||||
return QStringLiteral(".so");
|
||||
#endif
|
||||
}
|
||||
|
||||
QString PluginPackage::installDirectory() const {
|
||||
if (!m_installDirectory.isEmpty()) return m_installDirectory;
|
||||
return QDir::homePath() + QLatin1String(kUserPluginDir);
|
||||
}
|
||||
|
||||
void PluginPackage::setInstallDirectory(const QString& path) {
|
||||
m_installDirectory = path;
|
||||
}
|
||||
|
||||
QString PluginPackage::installedKey(const QString& id) {
|
||||
return QStringLiteral("packages/installed/%1").arg(id);
|
||||
}
|
||||
|
||||
QString PluginPackage::installedKeyPrefix() {
|
||||
return QStringLiteral("packages/installed/");
|
||||
}
|
||||
|
||||
bool PluginPackage::isInstalled(const QString& id) const {
|
||||
return !installedPath(id).isEmpty();
|
||||
}
|
||||
|
||||
QString PluginPackage::installedPath(const QString& id) const {
|
||||
QSettings settings;
|
||||
const QString path = settings.value(installedKey(id)).toString();
|
||||
// A file deleted behind our back is not installed any more: the state
|
||||
// follows the disk, which is also what makes an uninstall of a missing
|
||||
// library a no-op rather than a failure.
|
||||
if (path.isEmpty() || !QFile::exists(path)) return QString();
|
||||
return path;
|
||||
}
|
||||
|
||||
QStringList PluginPackage::installedIds() const {
|
||||
QSettings settings;
|
||||
QStringList ids;
|
||||
const QString prefix = installedKeyPrefix();
|
||||
// allKeys(), not childKeys(): the ids sit one level below the prefix, and
|
||||
// childKeys() would only report the "installed" group itself.
|
||||
for (const QString& key : settings.allKeys()) {
|
||||
if (!key.startsWith(prefix)) continue;
|
||||
const QString id = key.mid(prefix.size());
|
||||
if (id.isEmpty() || !isInstalled(id)) continue;
|
||||
ids << id;
|
||||
}
|
||||
ids.sort();
|
||||
return ids;
|
||||
}
|
||||
|
||||
QString PluginPackage::targetFileName(const Manifest& manifest, const ZipArchive& archive,
|
||||
QString* error) {
|
||||
auto fail = [error](const QString& message) {
|
||||
if (error) *error = message;
|
||||
return QString();
|
||||
};
|
||||
|
||||
const QString suffix = librarySuffix();
|
||||
|
||||
// A manifest naming its library is trusted, but only as far as a name that
|
||||
// is safe to write: the entry is looked up in the archive, and what lands
|
||||
// in the plugin directory is a bare file name, never a path.
|
||||
if (!manifest.library.isEmpty()) {
|
||||
if (!ZipArchive::isSafeEntryName(manifest.library)
|
||||
|| manifest.library.contains(QLatin1Char('/'))
|
||||
|| manifest.library.contains(QLatin1Char('\\'))) {
|
||||
return fail(QStringLiteral("Nom de bibliothèque refusé : %1.")
|
||||
.arg(manifest.library));
|
||||
}
|
||||
if (!archive.contains(manifest.library)) {
|
||||
return fail(QStringLiteral("L'archive ne contient pas %1.")
|
||||
.arg(manifest.library));
|
||||
}
|
||||
// The directory is scanned for shared libraries, so an entry that is
|
||||
// not one would be written and then ignored.
|
||||
if (!manifest.library.endsWith(suffix, Qt::CaseInsensitive)) {
|
||||
return fail(QStringLiteral("%1 n'est pas une bibliothèque partagée (%2).")
|
||||
.arg(manifest.library, suffix));
|
||||
}
|
||||
return manifest.library;
|
||||
}
|
||||
|
||||
// Otherwise the library is the archive's single shared-library entry. More
|
||||
// than one would be ambiguous: picking one silently is how the wrong file
|
||||
// gets installed.
|
||||
QStringList candidates;
|
||||
for (const QString& name : archive.fileNames()) {
|
||||
if (name.endsWith(suffix, Qt::CaseInsensitive)) candidates << name;
|
||||
}
|
||||
if (candidates.isEmpty()) {
|
||||
return fail(QStringLiteral("L'archive ne contient aucune bibliothèque partagée (%1).")
|
||||
.arg(suffix));
|
||||
}
|
||||
if (candidates.size() > 1) {
|
||||
return fail(QStringLiteral("L'archive contient plusieurs bibliothèques : %1. "
|
||||
"Nommez celle à installer avec \"library\".")
|
||||
.arg(candidates.join(QStringLiteral(", "))));
|
||||
}
|
||||
return candidates.first();
|
||||
}
|
||||
|
||||
PluginPackage::Manifest PluginPackage::parseManifest(const QByteArray& json,
|
||||
const ZipArchive& archive, QString* error) {
|
||||
Manifest manifest;
|
||||
|
||||
auto fail = [error](const QString& message) {
|
||||
if (error) *error = message;
|
||||
return Manifest{};
|
||||
};
|
||||
|
||||
QJsonParseError parseError{};
|
||||
const QJsonDocument document = QJsonDocument::fromJson(json, &parseError);
|
||||
if (parseError.error != QJsonParseError::NoError) {
|
||||
return fail(QStringLiteral("Manifeste illisible : %1").arg(parseError.errorString()));
|
||||
}
|
||||
if (!document.isObject()) {
|
||||
return fail(QStringLiteral("Manifeste illisible : objet JSON attendu."));
|
||||
}
|
||||
|
||||
const QJsonObject root = document.object();
|
||||
manifest.format = root.value(QStringLiteral("format")).toInt(0);
|
||||
manifest.id = root.value(QStringLiteral("id")).toString().trimmed();
|
||||
manifest.name = root.value(QStringLiteral("name")).toString().trimmed();
|
||||
manifest.description = root.value(QStringLiteral("description")).toString().trimmed();
|
||||
manifest.version = root.value(QStringLiteral("version")).toString().trimmed();
|
||||
manifest.author = root.value(QStringLiteral("author")).toString().trimmed();
|
||||
manifest.kind = root.value(QStringLiteral("kind")).toString().trimmed().toLower();
|
||||
manifest.library = root.value(QStringLiteral("library")).toString().trimmed();
|
||||
manifest.sha256 = root.value(QStringLiteral("sha256")).toString().trimmed().toLower();
|
||||
|
||||
// The format is versioned so a future layout can be told apart from this
|
||||
// one; guessing would mean reading a package as something it is not.
|
||||
if (manifest.format != 1) {
|
||||
return fail(QStringLiteral("Format de paquet non pris en charge (%1).")
|
||||
.arg(manifest.format));
|
||||
}
|
||||
if (manifest.id.isEmpty()) {
|
||||
return fail(QStringLiteral("Manifeste sans \"id\"."));
|
||||
}
|
||||
// The id becomes a settings key, so the characters that would need quoting
|
||||
// there (a slash among them) are refused rather than sanitised into
|
||||
// something that would later mismatch.
|
||||
static const QString kForbidden = QStringLiteral("/\\\"");
|
||||
for (const QChar c : kForbidden) {
|
||||
if (manifest.id.contains(c)) {
|
||||
return fail(QStringLiteral("Identifiant refusé : %1").arg(manifest.id));
|
||||
}
|
||||
}
|
||||
// An unstated kind stays empty: the real kind is the one the library
|
||||
// declares once the registry loads it.
|
||||
if (manifest.kind != QLatin1String("provider") && manifest.kind != QLatin1String("addon")) {
|
||||
manifest.kind.clear();
|
||||
}
|
||||
|
||||
// Refused here rather than at write time, so an unusable package is
|
||||
// reported before anything is extracted.
|
||||
QString nameError;
|
||||
const QString target = targetFileName(manifest, archive, &nameError);
|
||||
if (target.isEmpty()) return fail(nameError);
|
||||
manifest.library = target;
|
||||
|
||||
if (error) error->clear();
|
||||
return manifest;
|
||||
}
|
||||
|
||||
PluginPackage::Contents PluginPackage::read(const QString& path, QString* error) {
|
||||
auto fail = [error](const QString& message) {
|
||||
if (error) *error = message;
|
||||
return Contents{};
|
||||
};
|
||||
|
||||
ZipArchive archive;
|
||||
if (!archive.open(path, error)) return fail(error ? *error : QString());
|
||||
|
||||
// The manifest is matched case-insensitively, so a package zipped on
|
||||
// Windows (where the name may have been uppercased) still installs.
|
||||
int manifestIndex = archive.indexOf(QLatin1String(kManifestName));
|
||||
if (manifestIndex < 0) {
|
||||
for (const QString& name : archive.fileNames()) {
|
||||
if (name.compare(QLatin1String(kManifestName), Qt::CaseInsensitive) == 0) {
|
||||
manifestIndex = archive.indexOf(name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (manifestIndex < 0) {
|
||||
return fail(QStringLiteral("Paquet invalide : %1 est introuvable.")
|
||||
.arg(QLatin1String(kManifestName)));
|
||||
}
|
||||
|
||||
const QByteArray manifestJson = archive.read(archive.entries()[static_cast<size_t>(manifestIndex)].name, error);
|
||||
if (error && !error->isEmpty()) return fail(*error);
|
||||
|
||||
Manifest manifest = parseManifest(manifestJson, archive, error);
|
||||
if (error && !error->isEmpty()) return fail(*error);
|
||||
|
||||
QByteArray library = archive.read(manifest.library, error);
|
||||
if (error && !error->isEmpty()) return fail(*error);
|
||||
if (library.isEmpty()) {
|
||||
return fail(QStringLiteral("La bibliothèque %1 est vide.").arg(manifest.library));
|
||||
}
|
||||
|
||||
// The checksum is the one guarantee about *which* bytes run: a package whose
|
||||
// library does not match what its manifest announces is never written.
|
||||
if (!manifest.sha256.isEmpty()) {
|
||||
const QString digest = QString::fromLatin1(
|
||||
QCryptographicHash::hash(library, QCryptographicHash::Sha256).toHex());
|
||||
if (digest.compare(manifest.sha256, Qt::CaseInsensitive) != 0) {
|
||||
return fail(QStringLiteral("Somme de contrôle invalide (attendu %1).")
|
||||
.arg(manifest.sha256));
|
||||
}
|
||||
}
|
||||
|
||||
Contents contents;
|
||||
contents.manifest = manifest;
|
||||
contents.library = library;
|
||||
contents.libraryName = manifest.library;
|
||||
if (error) error->clear();
|
||||
return contents;
|
||||
}
|
||||
|
||||
void PluginPackage::install(const QString& path) {
|
||||
const QString trimmed = path.trimmed();
|
||||
if (trimmed.isEmpty()) {
|
||||
emit installFinished(QString(), false, QStringLiteral("Aucun paquet à installer."));
|
||||
return;
|
||||
}
|
||||
if (!isPackagePath(trimmed)) {
|
||||
emit installFinished(QFileInfo(trimmed).completeBaseName(), false,
|
||||
QStringLiteral("Ce fichier n'est pas un paquet %1.")
|
||||
.arg(suffix()));
|
||||
return;
|
||||
}
|
||||
|
||||
QString error;
|
||||
const Contents contents = read(trimmed, &error);
|
||||
if (contents.library.isEmpty()) {
|
||||
const QString id = contents.manifest.id.isEmpty()
|
||||
? QFileInfo(trimmed).completeBaseName()
|
||||
: contents.manifest.id;
|
||||
emit installFinished(id, false, error);
|
||||
return;
|
||||
}
|
||||
|
||||
const QString directory = installDirectory();
|
||||
if (!QDir().mkpath(directory)) {
|
||||
emit installFinished(contents.manifest.id, false,
|
||||
QStringLiteral("Impossible de créer %1.").arg(directory));
|
||||
return;
|
||||
}
|
||||
|
||||
const QString target = QDir(directory).filePath(contents.libraryName);
|
||||
// Written through QSaveFile so the library only ever appears in the scanned
|
||||
// directory complete, under its final name. A rejected commit (a read-only
|
||||
// home, a full disk) leaves the previous version in place rather than a
|
||||
// truncated file.
|
||||
QSaveFile file(target);
|
||||
if (!file.open(QIODevice::WriteOnly) || file.write(contents.library) != contents.library.size()
|
||||
|| !file.commit()) {
|
||||
emit installFinished(contents.manifest.id, false,
|
||||
QStringLiteral("Impossible d'écrire %1.").arg(target));
|
||||
return;
|
||||
}
|
||||
|
||||
QSettings settings;
|
||||
settings.setValue(installedKey(contents.manifest.id), target);
|
||||
qCInfo(pacmgrPlugin) << "plugin package installed:" << contents.manifest.id << target;
|
||||
emit installFinished(contents.manifest.id, true, target);
|
||||
}
|
||||
|
||||
void PluginPackage::remove(const QString& id) {
|
||||
// Only a library this class wrote is removed: a plugin the user copied into
|
||||
// the directory by hand is not ours to delete.
|
||||
const QString path = installedPath(id);
|
||||
if (path.isEmpty()) {
|
||||
emit removeFinished(id, false,
|
||||
QStringLiteral("Ce plugin n'a pas été installé depuis un paquet."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (QFile::exists(path) && !QFile::remove(path)) {
|
||||
emit removeFinished(id, false, QStringLiteral("Impossible de supprimer %1.").arg(path));
|
||||
return;
|
||||
}
|
||||
|
||||
QSettings settings;
|
||||
settings.remove(installedKey(id));
|
||||
qCInfo(pacmgrPlugin) << "plugin package removed:" << id << path;
|
||||
emit removeFinished(id, true, path);
|
||||
}
|
||||
Reference in new issue
Block a user