Merge branch 'feat/fwspacm-plugin-packages' into release-1.6.0
This commit is contained in:
29 files changed
+2107
-1047
No files matched your search
+22
-24
@@ -14,7 +14,7 @@
|
||||
|
||||
#include "app-logging.h"
|
||||
#include "log-manager.h"
|
||||
#include "plugin-shop.h"
|
||||
#include "plugin-package.h"
|
||||
#include "workers.h"
|
||||
|
||||
namespace {
|
||||
@@ -111,20 +111,20 @@ AppCore::AppCore(QObject* parent) : QObject(parent) {
|
||||
// Non-owning handle kept for sudo credentials and the database lock.
|
||||
m_pacman = dynamic_cast<PacmanManager*>(m_plugins->managerFor("pacman"));
|
||||
|
||||
// Plugin shop: the catalogue, the downloads and the bookkeeping of what it
|
||||
// installed. What it fetches lands in the directory the registry scans, so
|
||||
// a successful install only needs that registry reloaded.
|
||||
m_shop = new PluginShop(this);
|
||||
connect(m_shop, &PluginShop::catalogChanged, this, &AppCore::pluginCatalogChanged);
|
||||
connect(m_shop, &PluginShop::installFinished, this,
|
||||
// Plugin packages: a .fwspacm archive dropped on the window, and the
|
||||
// bookkeeping of what was installed from one. What a package carries lands
|
||||
// in the directory the registry scans, so a successful install only needs
|
||||
// that registry reloaded.
|
||||
m_packages = new PluginPackage(this);
|
||||
connect(m_packages, &PluginPackage::installFinished, this,
|
||||
[this](const QString& id, bool success, const QString& message) {
|
||||
if (success) reloadPlugins();
|
||||
emit shopInstallFinished(id, success, message);
|
||||
emit pluginPackageInstalled(id, success, message);
|
||||
});
|
||||
connect(m_shop, &PluginShop::removeFinished, this,
|
||||
connect(m_packages, &PluginPackage::removeFinished, this,
|
||||
[this](const QString& id, bool success, const QString& message) {
|
||||
if (success) reloadPlugins();
|
||||
emit shopInstallFinished(id, success, message);
|
||||
emit pluginPackageRemoved(id, success, message);
|
||||
});
|
||||
|
||||
m_history = new HistoryManager();
|
||||
@@ -524,6 +524,10 @@ bool AppCore::canInstallFile(const QString& path) const {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool AppCore::isPluginPackage(const QString& path) const {
|
||||
return PluginPackage::isPackagePath(path);
|
||||
}
|
||||
|
||||
AppCore::StartResult AppCore::removePackages(const std::vector<PackageInfo>& packages,
|
||||
const QString& description) { Request request;
|
||||
request.action = QStringLiteral("cleanup");
|
||||
@@ -1084,26 +1088,20 @@ void AppCore::reloadPlugins() {
|
||||
emit statusMessage(QStringLiteral("Plugins rechargés."));
|
||||
}
|
||||
|
||||
void AppCore::loadPluginCatalog() {
|
||||
LogManager::instance().logEvent(QStringLiteral("plugin"),
|
||||
QStringLiteral("chargement du catalogue"));
|
||||
emit statusMessage(QStringLiteral("Chargement du catalogue de plugins..."));
|
||||
m_shop->refresh();
|
||||
}
|
||||
|
||||
void AppCore::installShopPlugin(const QString& id) {
|
||||
void AppCore::installPluginPackage(const QString& path) {
|
||||
LogManager::instance().logEvent(
|
||||
QStringLiteral("plugin"),
|
||||
QStringLiteral("installation depuis la boutique : %1").arg(id));
|
||||
emit statusMessage(QStringLiteral("Téléchargement du plugin %1...").arg(id));
|
||||
m_shop->install(id);
|
||||
QStringLiteral("installation du paquet : %1").arg(QFileInfo(path).fileName()));
|
||||
emit statusMessage(
|
||||
QStringLiteral("Installation du paquet %1...").arg(QFileInfo(path).fileName()));
|
||||
m_packages->install(path);
|
||||
}
|
||||
|
||||
void AppCore::removeShopPlugin(const QString& id) {
|
||||
void AppCore::removePluginPackage(const QString& id) {
|
||||
LogManager::instance().logEvent(
|
||||
QStringLiteral("plugin"),
|
||||
QStringLiteral("suppression depuis la boutique : %1").arg(id));
|
||||
m_shop->remove(id);
|
||||
QStringLiteral("suppression du paquet : %1").arg(id));
|
||||
m_packages->remove(id);
|
||||
}
|
||||
|
||||
void AppCore::clearHistory() {
|
||||
|
||||
+10
-2
@@ -1031,7 +1031,7 @@ QStringList MainWindow::installableDroppedFiles(const QMimeData* mimeData) const
|
||||
// first, and a remote .flatpakref is better opened from a browser.
|
||||
if (!url.isLocalFile()) continue;
|
||||
const QString path = url.toLocalFile();
|
||||
if (m_core->canInstallFile(path)) files << path;
|
||||
if (m_core->canInstallFile(path) || m_core->isPluginPackage(path)) files << path;
|
||||
}
|
||||
return files;
|
||||
}
|
||||
@@ -1075,6 +1075,13 @@ void MainWindow::installLocalFiles(const QStringList& paths) {
|
||||
QStringList files;
|
||||
QStringList rejected;
|
||||
for (const QString& path : paths) {
|
||||
// A plugin package is installed by the core straight away: it needs no
|
||||
// provider, no password and no queue, and the registry is reloaded when
|
||||
// it lands (see AppCore::installPluginPackage).
|
||||
if (m_core->isPluginPackage(path)) {
|
||||
m_core->installPluginPackage(path);
|
||||
continue;
|
||||
}
|
||||
if (m_core->canInstallFile(path)) files << path;
|
||||
else rejected << path;
|
||||
}
|
||||
@@ -1084,7 +1091,8 @@ void MainWindow::installLocalFiles(const QStringList& paths) {
|
||||
if (!rejected.isEmpty()) {
|
||||
statusBar()->showMessage(
|
||||
QStringLiteral("%1 : format non reconnu (PacManager installe les fichiers "
|
||||
".flatpakref, .flatpakrepo et .flatpak).")
|
||||
".flatpakref, .flatpakrepo, .flatpak et les paquets de plugin "
|
||||
".fwspacm).")
|
||||
.arg(QFileInfo(rejected.first()).fileName()));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
#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);
|
||||
}
|
||||
@@ -1,283 +0,0 @@
|
||||
#include "plugin-shop.h"
|
||||
|
||||
#include <QCryptographicHash>
|
||||
#include <QDir>
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
#include <QJsonArray>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QNetworkReply>
|
||||
#include <QNetworkRequest>
|
||||
#include <QSaveFile>
|
||||
#include <QSettings>
|
||||
#include <QUrl>
|
||||
|
||||
#include "app-logging.h"
|
||||
|
||||
// Catalogue shipped with the project: publishing a plugin to the shop means
|
||||
// adding an entry to this file (see doc/plugin-shop.md for the format).
|
||||
static const char* kDefaultCatalogUrl =
|
||||
"https://gitea.nocode-var.tech/FWS/FWS-PacManage/raw/branch/main/plugins/catalog.json";
|
||||
|
||||
// The per-user plugin directory, shared with PluginManager's search paths.
|
||||
static const char* kUserPluginDir = "/.local/share/PacManager/plugins";
|
||||
|
||||
PluginShop::PluginShop(QObject* parent) : QObject(parent) {}
|
||||
|
||||
QString PluginShop::installDirectory() const {
|
||||
if (!m_installDirectory.isEmpty()) return m_installDirectory;
|
||||
return QDir::homePath() + QLatin1String(kUserPluginDir);
|
||||
}
|
||||
|
||||
void PluginShop::setInstallDirectory(const QString& path) {
|
||||
m_installDirectory = path;
|
||||
}
|
||||
|
||||
QString PluginShop::catalogUrl() const {
|
||||
QSettings settings;
|
||||
const QString configured = settings.value(QStringLiteral("shop/catalogUrl")).toString().trimmed();
|
||||
// An empty setting means "the catalogue this build ships with": the key is
|
||||
// only written once someone actually points the shop elsewhere.
|
||||
return configured.isEmpty() ? QString::fromLatin1(kDefaultCatalogUrl) : configured;
|
||||
}
|
||||
|
||||
void PluginShop::setCatalogUrl(const QString& url) {
|
||||
QSettings settings;
|
||||
const QString trimmed = url.trimmed();
|
||||
if (trimmed.isEmpty() || trimmed == QLatin1String(kDefaultCatalogUrl)) {
|
||||
settings.remove(QStringLiteral("shop/catalogUrl"));
|
||||
return;
|
||||
}
|
||||
settings.setValue(QStringLiteral("shop/catalogUrl"), trimmed);
|
||||
}
|
||||
|
||||
void PluginShop::refresh() {
|
||||
QNetworkRequest request{QUrl(catalogUrl())};
|
||||
request.setHeader(QNetworkRequest::UserAgentHeader,
|
||||
QStringLiteral("PacManager-plugin-shop"));
|
||||
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
|
||||
QNetworkRequest::NoLessSafeRedirectPolicy);
|
||||
|
||||
QNetworkReply* reply = m_network.get(request);
|
||||
connect(reply, &QNetworkReply::finished, this, [this, reply]() {
|
||||
reply->deleteLater();
|
||||
|
||||
if (reply->error() != QNetworkReply::NoError) {
|
||||
m_catalogLoaded = false;
|
||||
m_lastError = QStringLiteral("Catalogue indisponible : %1").arg(reply->errorString());
|
||||
qCWarning(pacmgrPlugin) << "plugin catalog fetch failed:" << reply->errorString();
|
||||
emit catalogChanged();
|
||||
return;
|
||||
}
|
||||
|
||||
QString error;
|
||||
std::vector<CatalogEntry> entries = parseCatalog(reply->readAll(), &error);
|
||||
if (!error.isEmpty()) {
|
||||
m_catalogLoaded = false;
|
||||
m_lastError = error;
|
||||
qCWarning(pacmgrPlugin) << "plugin catalog rejected:" << error;
|
||||
emit catalogChanged();
|
||||
return;
|
||||
}
|
||||
|
||||
m_catalog = std::move(entries);
|
||||
m_catalogLoaded = true;
|
||||
m_lastError.clear();
|
||||
qCInfo(pacmgrPlugin) << "plugin catalog loaded,"
|
||||
<< static_cast<int>(m_catalog.size()) << "entrie(s)";
|
||||
emit catalogChanged();
|
||||
});
|
||||
}
|
||||
|
||||
std::vector<PluginShop::CatalogEntry> PluginShop::parseCatalog(const QByteArray& json,
|
||||
QString* error) {
|
||||
auto fail = [error](const QString& message) {
|
||||
if (error) *error = message;
|
||||
return std::vector<CatalogEntry>{};
|
||||
};
|
||||
|
||||
QJsonParseError parseError{};
|
||||
const QJsonDocument document = QJsonDocument::fromJson(json, &parseError);
|
||||
if (parseError.error != QJsonParseError::NoError) {
|
||||
return fail(QStringLiteral("Catalogue illisible : %1").arg(parseError.errorString()));
|
||||
}
|
||||
if (!document.isObject()) {
|
||||
return fail(QStringLiteral("Catalogue illisible : document JSON attendu."));
|
||||
}
|
||||
|
||||
const QJsonObject root = document.object();
|
||||
if (!root.value(QStringLiteral("plugins")).isArray()) {
|
||||
return fail(QStringLiteral("Catalogue invalide : tableau « plugins » manquant."));
|
||||
}
|
||||
|
||||
std::vector<CatalogEntry> entries;
|
||||
const QJsonArray plugins = root.value(QStringLiteral("plugins")).toArray();
|
||||
for (const QJsonValue& value : plugins) {
|
||||
if (!value.isObject()) continue;
|
||||
const QJsonObject object = value.toObject();
|
||||
|
||||
CatalogEntry entry;
|
||||
entry.id = object.value(QStringLiteral("id")).toString().trimmed();
|
||||
entry.name = object.value(QStringLiteral("name")).toString().trimmed();
|
||||
entry.description = object.value(QStringLiteral("description")).toString().trimmed();
|
||||
entry.version = object.value(QStringLiteral("version")).toString().trimmed();
|
||||
entry.author = object.value(QStringLiteral("author")).toString().trimmed();
|
||||
entry.kind = object.value(QStringLiteral("kind")).toString().trimmed().toLower();
|
||||
entry.url = object.value(QStringLiteral("url")).toString().trimmed();
|
||||
entry.sha256 = object.value(QStringLiteral("sha256")).toString().trimmed().toLower();
|
||||
entry.fileName = object.value(QStringLiteral("file")).toString().trimmed();
|
||||
|
||||
// Without an id and a download URL an entry cannot be installed; the
|
||||
// rest of the catalogue stays usable instead of failing as a whole.
|
||||
if (entry.id.isEmpty() || entry.name.isEmpty() || entry.url.isEmpty()) continue;
|
||||
// Any other kind is left empty on purpose: the real kind is the one the
|
||||
// library declares when the registry loads it.
|
||||
if (entry.kind != QLatin1String("provider") && entry.kind != QLatin1String("addon")) {
|
||||
entry.kind.clear();
|
||||
}
|
||||
entries.push_back(entry);
|
||||
}
|
||||
|
||||
if (error) error->clear();
|
||||
return entries;
|
||||
}
|
||||
|
||||
QString PluginShop::librarySuffix() {
|
||||
#ifdef Q_OS_WIN
|
||||
return QStringLiteral(".dll");
|
||||
#elif defined(Q_OS_MACOS)
|
||||
return QStringLiteral(".dylib");
|
||||
#else
|
||||
return QStringLiteral(".so");
|
||||
#endif
|
||||
}
|
||||
|
||||
QString PluginShop::targetFileName(const CatalogEntry& entry) {
|
||||
if (!entry.fileName.isEmpty()) return entry.fileName;
|
||||
|
||||
QString name = QFileInfo(QUrl(entry.url).fileName()).fileName();
|
||||
if (name.isEmpty()) name = entry.id;
|
||||
// The plugin directory is scanned for shared libraries only, so a URL that
|
||||
// points at something else still lands as one.
|
||||
if (!name.endsWith(librarySuffix(), Qt::CaseInsensitive)) name += librarySuffix();
|
||||
return name;
|
||||
}
|
||||
|
||||
QString PluginShop::targetPath(const CatalogEntry& entry) const {
|
||||
return QDir(installDirectory()).filePath(targetFileName(entry));
|
||||
}
|
||||
|
||||
QString PluginShop::installedKey(const QString& id) {
|
||||
return QStringLiteral("shop/installed/%1").arg(id);
|
||||
}
|
||||
|
||||
const PluginShop::CatalogEntry* PluginShop::entry(const QString& id) const {
|
||||
for (const CatalogEntry& candidate : m_catalog) {
|
||||
if (candidate.id == id) return &candidate;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
QString PluginShop::installedPath(const QString& id) const {
|
||||
QSettings settings;
|
||||
const QString path = settings.value(installedKey(id)).toString();
|
||||
// A recorded file that was deleted by hand is not installed any more.
|
||||
if (path.isEmpty() || !QFile::exists(path)) return QString();
|
||||
return path;
|
||||
}
|
||||
|
||||
bool PluginShop::isInstalled(const QString& id) const {
|
||||
return !installedPath(id).isEmpty();
|
||||
}
|
||||
|
||||
void PluginShop::install(const QString& id) {
|
||||
const CatalogEntry* found = entry(id);
|
||||
if (!found) {
|
||||
emit installFinished(id, false, QStringLiteral("Plugin absent du catalogue."));
|
||||
return;
|
||||
}
|
||||
// Copied: the catalogue can be refreshed while the download is running.
|
||||
const CatalogEntry selected = *found;
|
||||
|
||||
QNetworkRequest request{QUrl(selected.url)};
|
||||
request.setHeader(QNetworkRequest::UserAgentHeader,
|
||||
QStringLiteral("PacManager-plugin-shop"));
|
||||
request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
|
||||
QNetworkRequest::NoLessSafeRedirectPolicy);
|
||||
|
||||
QNetworkReply* reply = m_network.get(request);
|
||||
connect(reply, &QNetworkReply::finished, this, [this, reply, selected]() {
|
||||
reply->deleteLater();
|
||||
|
||||
if (reply->error() != QNetworkReply::NoError) {
|
||||
emit installFinished(selected.id, false,
|
||||
QStringLiteral("Téléchargement impossible : %1").arg(reply->errorString()));
|
||||
return;
|
||||
}
|
||||
|
||||
const QByteArray payload = reply->readAll();
|
||||
if (payload.isEmpty()) {
|
||||
emit installFinished(selected.id, false,
|
||||
QStringLiteral("Fichier téléchargé vide."));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!selected.sha256.isEmpty()) {
|
||||
const QString digest = QString::fromLatin1(
|
||||
QCryptographicHash::hash(payload, QCryptographicHash::Sha256).toHex());
|
||||
if (digest.compare(selected.sha256, Qt::CaseInsensitive) != 0) {
|
||||
// The whole point of the checksum: a library that is not the one
|
||||
// the catalogue announced never reaches the plugin directory.
|
||||
emit installFinished(selected.id, false,
|
||||
QStringLiteral("Somme de contrôle invalide (attendu %1).")
|
||||
.arg(selected.sha256));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const QString directory = installDirectory();
|
||||
if (!QDir().mkpath(directory)) {
|
||||
emit installFinished(selected.id, false,
|
||||
QStringLiteral("Impossible de créer %1.").arg(directory));
|
||||
return;
|
||||
}
|
||||
|
||||
const QString path = targetPath(selected);
|
||||
// Written through QSaveFile so the shared library only ever appears in
|
||||
// the scanned directory complete, under its final name.
|
||||
QSaveFile file(path);
|
||||
if (!file.open(QIODevice::WriteOnly) || file.write(payload) != payload.size()
|
||||
|| !file.commit()) {
|
||||
emit installFinished(selected.id, false,
|
||||
QStringLiteral("Impossible d'écrire %1.").arg(path));
|
||||
return;
|
||||
}
|
||||
|
||||
QSettings settings;
|
||||
settings.setValue(installedKey(selected.id), path);
|
||||
qCInfo(pacmgrPlugin) << "plugin installed from the shop:" << selected.id << path;
|
||||
emit installFinished(selected.id, true, path);
|
||||
});
|
||||
}
|
||||
|
||||
void PluginShop::remove(const QString& id) {
|
||||
// Only a file the shop wrote is removed: a plugin the user dropped into the
|
||||
// directory by hand is not the shop's to delete.
|
||||
const QString path = installedPath(id);
|
||||
if (path.isEmpty()) {
|
||||
emit removeFinished(id, false,
|
||||
QStringLiteral("Ce plugin n'a pas été installé par le magasin."));
|
||||
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 removed from the shop:" << id << path;
|
||||
emit removeFinished(id, true, path);
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
#include "zip-archive.h"
|
||||
|
||||
#include <QFile>
|
||||
#include <QFileInfo>
|
||||
|
||||
#include <zlib.h>
|
||||
|
||||
namespace {
|
||||
|
||||
// ZIP signatures, little-endian on disk whatever the host is.
|
||||
constexpr quint32 kEndOfCentralDir = 0x06054b50;
|
||||
constexpr quint32 kCentralFileHeader = 0x02014b50;
|
||||
constexpr quint32 kLocalFileHeader = 0x04034b50;
|
||||
|
||||
// Marker of the ZIP64 extension: sizes and offsets of 0xffffffff are only valid
|
||||
// in the ZIP64 records, which are not read here.
|
||||
constexpr quint32 kZip64Marker = 0xffffffffu;
|
||||
|
||||
constexpr quint16 kMethodStored = 0;
|
||||
constexpr quint16 kMethodDeflated = 8;
|
||||
|
||||
// The largest comment a spec-compliant EOCD can carry. The record is searched
|
||||
// backwards from the end of the file over that window, which is how an archive
|
||||
// with trailing data is still found.
|
||||
constexpr int kMaxCommentLength = 0xffff;
|
||||
|
||||
// Reads a little-endian value out of a buffer. Every field of the format is
|
||||
// little-endian, on every platform, so this is byte order, not memcpy.
|
||||
quint16 readU16(const QByteArray& data, int offset) {
|
||||
return static_cast<quint16>(static_cast<quint8>(data[offset]))
|
||||
| (static_cast<quint16>(static_cast<quint8>(data[offset + 1])) << 8);
|
||||
}
|
||||
|
||||
quint32 readU32(const QByteArray& data, int offset) {
|
||||
return static_cast<quint32>(static_cast<quint8>(data[offset]))
|
||||
| (static_cast<quint32>(static_cast<quint8>(data[offset + 1])) << 8)
|
||||
| (static_cast<quint32>(static_cast<quint8>(data[offset + 2])) << 16)
|
||||
| (static_cast<quint32>(static_cast<quint8>(data[offset + 3])) << 24);
|
||||
}
|
||||
|
||||
// Inflates a raw deflate stream (no zlib header, hence the negative window
|
||||
// bits). The output size is known from the directory, so the buffer is sized
|
||||
// once and grown only if the stream turns out to be longer.
|
||||
bool inflateRaw(const QByteArray& input, quint32 expectedSize, QByteArray* out,
|
||||
QString* error) {
|
||||
if (expectedSize > ZipArchive::kMaxEntrySize) {
|
||||
if (error) *error = QStringLiteral("Entrée trop volumineuse.");
|
||||
return false;
|
||||
}
|
||||
|
||||
QByteArray result(static_cast<int>(expectedSize), Qt::Uninitialized);
|
||||
|
||||
z_stream stream{};
|
||||
// -MAX_WBITS selects the raw deflate that ZIP entries use, as opposed to
|
||||
// the zlib-wrapped stream inflateInit2() defaults to.
|
||||
if (inflateInit2(&stream, -MAX_WBITS) != Z_OK) {
|
||||
if (error) *error = QStringLiteral("Initialisation de la décompression impossible.");
|
||||
return false;
|
||||
}
|
||||
|
||||
stream.next_in = reinterpret_cast<Bytef*>(const_cast<char*>(input.constData()));
|
||||
stream.avail_in = static_cast<uInt>(input.size());
|
||||
stream.next_out = reinterpret_cast<Bytef*>(result.data());
|
||||
stream.avail_out = static_cast<uInt>(result.size());
|
||||
|
||||
int status = Z_OK;
|
||||
if (expectedSize > 0) status = inflate(&stream, Z_FINISH);
|
||||
|
||||
// A stream that produced nothing because the buffer was already the right
|
||||
// size returns Z_STREAM_END here; an empty entry is legitimate.
|
||||
if (expectedSize == 0) status = inflate(&stream, Z_FINISH);
|
||||
const uLong produced = stream.total_out;
|
||||
inflateEnd(&stream);
|
||||
|
||||
if (status != Z_STREAM_END) {
|
||||
if (error) {
|
||||
*error = QStringLiteral("Entrée compressée illisible (%1).")
|
||||
.arg(QString::fromLatin1(zError(status)));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if (produced != expectedSize) {
|
||||
if (error) {
|
||||
*error = QStringLiteral("Taille d'entrée incohérente (%1 octets lus, %2 annoncés).")
|
||||
.arg(static_cast<qulonglong>(produced))
|
||||
.arg(static_cast<qulonglong>(expectedSize));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
result.resize(static_cast<int>(produced));
|
||||
*out = result;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool ZipArchive::open(const QString& path, QString* error) {
|
||||
QFile file(path);
|
||||
if (!file.open(QIODevice::ReadOnly)) {
|
||||
if (error) *error = QStringLiteral("Impossible de lire %1.").arg(path);
|
||||
return false;
|
||||
}
|
||||
// Refused above rather than allocated: the declared size is a lie until the
|
||||
// central directory is parsed, and this file comes from the desktop.
|
||||
if (file.size() > static_cast<qint64>(kMaxEntrySize)) {
|
||||
if (error) *error = QStringLiteral("Archive trop volumineuse.");
|
||||
return false;
|
||||
}
|
||||
return openData(file.readAll(), error);
|
||||
}
|
||||
|
||||
bool ZipArchive::openData(const QByteArray& data, QString* error) {
|
||||
m_data = data;
|
||||
m_entries.clear();
|
||||
return parse(error);
|
||||
}
|
||||
|
||||
bool ZipArchive::parse(QString* error) {
|
||||
auto fail = [error](const QString& message) {
|
||||
if (error) *error = message;
|
||||
return false;
|
||||
};
|
||||
|
||||
if (m_data.size() < 22) return fail(QStringLiteral("Archive trop courte."));
|
||||
|
||||
// The end-of-central-directory record sits at the very end, after a
|
||||
// comment of up to 64 KiB, so it is searched backwards.
|
||||
int eocd = -1;
|
||||
const int searchStart = qMax(0, m_data.size() - 22 - kMaxCommentLength);
|
||||
for (int i = m_data.size() - 22; i >= searchStart; --i) {
|
||||
if (readU32(m_data, i) == kEndOfCentralDir) {
|
||||
eocd = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (eocd < 0) return fail(QStringLiteral("Archive ZIP illisible (répertoire introuvable)."));
|
||||
|
||||
const quint16 entryCount = readU16(m_data, eocd + 10);
|
||||
const quint32 directorySize = readU32(m_data, eocd + 12);
|
||||
const quint32 directoryOffset = readU32(m_data, eocd + 16);
|
||||
if (directoryOffset == kZip64Marker || directorySize == kZip64Marker
|
||||
|| entryCount == 0xffff) {
|
||||
// Nothing in a plugin package needs ZIP64, and guessing its record
|
||||
// layout would be guesswork: refusing says so instead.
|
||||
return fail(QStringLiteral("Archive ZIP64 non prise en charge."));
|
||||
}
|
||||
|
||||
const qint64 directoryEnd = static_cast<qint64>(directoryOffset) + directorySize;
|
||||
if (directoryOffset > static_cast<quint32>(m_data.size()) || directoryEnd > m_data.size()) {
|
||||
return fail(QStringLiteral("Répertoire de l'archive hors limites."));
|
||||
}
|
||||
|
||||
int cursor = static_cast<int>(directoryOffset);
|
||||
for (quint16 i = 0; i < entryCount; ++i) {
|
||||
if (cursor + 46 > m_data.size()) {
|
||||
return fail(QStringLiteral("Répertoire de l'archive tronqué."));
|
||||
}
|
||||
if (readU32(m_data, cursor) != kCentralFileHeader) {
|
||||
return fail(QStringLiteral("Entrée d'archive illisible."));
|
||||
}
|
||||
|
||||
const quint16 method = readU16(m_data, cursor + 10);
|
||||
const quint32 compressedSize = readU32(m_data, cursor + 20);
|
||||
const quint32 uncompressedSize = readU32(m_data, cursor + 24);
|
||||
const quint16 nameLength = readU16(m_data, cursor + 28);
|
||||
const quint16 extraLength = readU16(m_data, cursor + 30);
|
||||
const quint16 commentLength = readU16(m_data, cursor + 32);
|
||||
const quint32 localOffset = readU32(m_data, cursor + 42);
|
||||
|
||||
if (cursor + 46 + nameLength > m_data.size()) {
|
||||
return fail(QStringLiteral("Nom d'entrée tronqué."));
|
||||
}
|
||||
const QString name = QString::fromUtf8(m_data.constData() + cursor + 46, nameLength);
|
||||
|
||||
if (compressedSize == kZip64Marker || uncompressedSize == kZip64Marker
|
||||
|| localOffset == kZip64Marker) {
|
||||
return fail(QStringLiteral("Archive ZIP64 non prise en charge."));
|
||||
}
|
||||
if (uncompressedSize > kMaxEntrySize) {
|
||||
return fail(QStringLiteral("Entrée trop volumineuse : %1.").arg(name));
|
||||
}
|
||||
|
||||
Entry entry;
|
||||
entry.name = name;
|
||||
entry.compressedSize = compressedSize;
|
||||
entry.uncompressedSize = uncompressedSize;
|
||||
entry.localHeaderOffset = localOffset;
|
||||
entry.method = method;
|
||||
m_entries.push_back(entry);
|
||||
|
||||
cursor += 46 + nameLength + extraLength + commentLength;
|
||||
}
|
||||
|
||||
if (error) error->clear();
|
||||
return true;
|
||||
}
|
||||
|
||||
QStringList ZipArchive::fileNames() const {
|
||||
QStringList names;
|
||||
names.reserve(static_cast<int>(m_entries.size()));
|
||||
for (const Entry& entry : m_entries) {
|
||||
// A trailing '/' is the ZIP way of marking a directory.
|
||||
if (entry.name.endsWith(QLatin1Char('/'))) continue;
|
||||
names << entry.name;
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
int ZipArchive::indexOf(const QString& name) const {
|
||||
for (int i = 0; i < static_cast<int>(m_entries.size()); ++i) {
|
||||
if (m_entries[i].name.compare(name, Qt::CaseInsensitive) == 0) return i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
bool ZipArchive::contains(const QString& name) const {
|
||||
return indexOf(name) >= 0;
|
||||
}
|
||||
|
||||
const ZipArchive::Entry* ZipArchive::find(const QString& name) const {
|
||||
const int index = indexOf(name);
|
||||
return index < 0 ? nullptr : &m_entries[static_cast<size_t>(index)];
|
||||
}
|
||||
|
||||
bool ZipArchive::isSafeEntryName(const QString& name) {
|
||||
if (name.isEmpty()) return false;
|
||||
// A path is a path even on the other platform: both separators are refused
|
||||
// as a leading character, so the check does not depend on who reads it.
|
||||
if (name.startsWith(QLatin1Char('/')) || name.startsWith(QLatin1Char('\\'))) return false;
|
||||
if (name.size() > 1 && name.at(1) == QLatin1Char(':')) return false; // drive letter
|
||||
if (name.contains(QLatin1String(".."))) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
QByteArray ZipArchive::read(const QString& name, QString* error) const {
|
||||
const Entry* entry = find(name);
|
||||
if (!entry) {
|
||||
if (error) *error = QStringLiteral("Entrée absente de l'archive : %1.").arg(name);
|
||||
return {};
|
||||
}
|
||||
if (entry->name.endsWith(QLatin1Char('/'))) {
|
||||
if (error) *error = QStringLiteral("%1 est un dossier, pas un fichier.").arg(name);
|
||||
return {};
|
||||
}
|
||||
if (entry->uncompressedSize > kMaxEntrySize) {
|
||||
if (error) *error = QStringLiteral("Entrée trop volumineuse : %1.").arg(name);
|
||||
return {};
|
||||
}
|
||||
|
||||
// The local header repeats the name and the extra field, both of which can
|
||||
// differ in length from the central directory's copy: the payload starts
|
||||
// after the local header's own name and extra, never at a fixed offset.
|
||||
const int header = static_cast<int>(entry->localHeaderOffset);
|
||||
if (header < 0 || header + 30 > m_data.size()
|
||||
|| readU32(m_data, header) != kLocalFileHeader) {
|
||||
if (error) *error = QStringLiteral("En-tête local illisible pour %1.").arg(name);
|
||||
return {};
|
||||
}
|
||||
const int dataStart = header + 30 + readU16(m_data, header + 26) + readU16(m_data, header + 28);
|
||||
const qint64 dataEnd = static_cast<qint64>(dataStart) + entry->compressedSize;
|
||||
if (dataStart < 0 || dataEnd > m_data.size()) {
|
||||
if (error) *error = QStringLiteral("Données tronquées pour %1.").arg(name);
|
||||
return {};
|
||||
}
|
||||
|
||||
const QByteArray payload = m_data.mid(dataStart, static_cast<int>(entry->compressedSize));
|
||||
|
||||
if (entry->method == kMethodStored) {
|
||||
if (payload.size() != static_cast<int>(entry->uncompressedSize)) {
|
||||
if (error) {
|
||||
*error = QStringLiteral("Taille d'entrée incohérente pour %1.").arg(name);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
if (error) error->clear();
|
||||
return payload;
|
||||
}
|
||||
|
||||
if (entry->method != kMethodDeflated) {
|
||||
if (error) {
|
||||
*error = QStringLiteral("Méthode de compression non prise en charge (%1) pour %2.")
|
||||
.arg(entry->method)
|
||||
.arg(name);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
QByteArray result;
|
||||
if (!inflateRaw(payload, entry->uncompressedSize, &result, error)) return {};
|
||||
if (error) error->clear();
|
||||
return result;
|
||||
}
|
||||
Reference in new issue
Block a user