diff --git a/include/main-window.h b/include/main-window.h index 206ce66..691685d 100644 --- a/include/main-window.h +++ b/include/main-window.h @@ -9,6 +9,7 @@ #include #include #include +#include #include #include @@ -24,6 +25,7 @@ class QListWidget; class QListWidgetItem; class QButtonGroup; class QFrame; +class QAction; // Runs a package search off the UI thread. class SearchWorker : public QThread { @@ -94,6 +96,14 @@ private slots: private: enum BrowseMode { ModeSearch, ModeInstalled, ModeUpdates }; + // When the sudo password is requested: once per session (at launch) or + // before every privileged operation. + enum class CredentialMode { AtLaunch, EachTime }; + + void applyCredentialMode(CredentialMode mode); + bool ensureCredentials(); + void clearCredentialsAfterUse(); + void setupUI(); void setupSidebar(); void setupHeader(); @@ -174,6 +184,12 @@ private: HistoryManager* m_historyManager = nullptr; BrowseMode m_browseMode = ModeSearch; + // Settings + QSettings m_settings; + CredentialMode m_credentialMode = CredentialMode::EachTime; + QAction* m_credLaunchAction = nullptr; + QAction* m_credEachTimeAction = nullptr; + std::vector m_currentResults; std::vector m_installedPackages; PackageInfo m_selectedPackage; diff --git a/include/pacman-manager.h b/include/pacman-manager.h index 10a340c..90014d4 100644 --- a/include/pacman-manager.h +++ b/include/pacman-manager.h @@ -34,6 +34,18 @@ public: // Exposed as static so the parsing can be unit-tested without invoking pacman. static std::map parseSyncRepos(const std::string& output); + // Detect a sudo authentication failure (wrong or missing password) in the + // output of a privileged command. Exposed as static so it can be + // unit-tested without invoking sudo. + static bool authFailed(const std::string& output); + + // Credential handling for privileged (sudo) operations. The password is + // kept in memory only for the session (never persisted) and piped to + // `sudo -S` for each privileged command. + void setPassword(const std::string& password); + void clearPassword(); + bool hasPassword() const; + std::vector search(const std::string& query) override; bool install(const std::string& packageName, std::function progressCallback) override; @@ -47,4 +59,6 @@ public: private: bool isPackageInstalled(const std::string& name); + + std::string m_password; }; diff --git a/src/main-window.cpp b/src/main-window.cpp index 20617d6..22fd578 100644 --- a/src/main-window.cpp +++ b/src/main-window.cpp @@ -20,6 +20,9 @@ #include #include #include +#include +#include +#include #include @@ -97,6 +100,16 @@ MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent) { setupUI(); setupMenuBar(); + // With per-session credentials, ask for the sudo password once, right + // after the window is shown (so the dialog has a visible parent). + if (m_pacman->isAvailable()) { + QTimer::singleShot(0, this, [this]() { + if (m_credentialMode == CredentialMode::AtLaunch) { + ensureCredentials(); + } + }); + } + if (!m_pacman->isAvailable()) { statusBar()->showMessage("pacman n'est pas disponible sur ce système."); m_searchBar->setEnabled(false); @@ -805,6 +818,35 @@ void MainWindow::setupMenuBar() { toolsMenu->addSeparator(); toolsMenu->addAction("Rafraîchir les sources", this, &MainWindow::onRefresh); + QMenu* settingsMenu = menuBar->addMenu("Paramètres"); + + QActionGroup* credGroup = new QActionGroup(this); + credGroup->setExclusive(true); + + QAction* credTitle = settingsMenu->addAction("Identifiants sudo"); + credTitle->setEnabled(false); + + m_credEachTimeAction = settingsMenu->addAction("Demander à chaque fois"); + m_credEachTimeAction->setCheckable(true); + m_credEachTimeAction->setToolTip("Demande le mot de passe avant chaque opération"); + credGroup->addAction(m_credEachTimeAction); + + m_credLaunchAction = settingsMenu->addAction("Demander au lancement"); + m_credLaunchAction->setCheckable(true); + m_credLaunchAction->setToolTip("Demande le mot de passe une seule fois, au lancement"); + credGroup->addAction(m_credLaunchAction); + + m_credentialMode = (m_settings.value("credentials/mode", "each").toString() == "launch") + ? CredentialMode::AtLaunch + : CredentialMode::EachTime; + (m_credentialMode == CredentialMode::AtLaunch ? m_credLaunchAction + : m_credEachTimeAction)->setChecked(true); + + connect(m_credEachTimeAction, &QAction::triggered, this, + [this]() { applyCredentialMode(CredentialMode::EachTime); }); + connect(m_credLaunchAction, &QAction::triggered, this, + [this]() { applyCredentialMode(CredentialMode::AtLaunch); }); + QMenu* helpMenu = menuBar->addMenu("Aide"); helpMenu->addAction("À propos", [this]() { QMessageBox::about(this, "PacManager", @@ -814,6 +856,59 @@ void MainWindow::setupMenuBar() { }); } +void MainWindow::applyCredentialMode(CredentialMode mode) { + m_credentialMode = mode; + m_settings.setValue("credentials/mode", + mode == CredentialMode::AtLaunch ? "launch" : "each"); + + if (mode == CredentialMode::EachTime) { + // Each operation must re-authenticate: never keep the password around. + m_pacman->clearPassword(); + statusBar()->showMessage("Identifiants demandés à chaque opération."); + } else { + // Per-session credentials: prompt once now so operations don't re-ask. + ensureCredentials(); + statusBar()->showMessage("Identifiants enregistrés pour la session."); + } +} + +// Makes sure a sudo password is available before a privileged operation, +// prompting the user on the UI thread when needed. Returns false if the user +// cancelled, in which case the operation must not start. +bool MainWindow::ensureCredentials() { + if (!m_pacman->isAvailable()) return false; + if (system("which sudo > /dev/null 2>&1") != 0) { + statusBar()->showMessage("sudo n'est pas installé sur ce système."); + return false; + } + + // Per-session mode: reuse the password captured at launch. + if (m_credentialMode == CredentialMode::AtLaunch && m_pacman->hasPassword()) { + return true; + } + + bool ok = false; + QString password = QInputDialog::getText( + this, "Authentification", + "Mot de passe administrateur (sudo) :", + QLineEdit::Password, QString(), &ok); + if (!ok) { + statusBar()->showMessage("Opération annulée : identifiants requis."); + return false; + } + + m_pacman->setPassword(password.toStdString()); + return true; +} + +void MainWindow::clearCredentialsAfterUse() { + // In per-operation mode the password is single-use: drop it once the + // command ran so the next operation prompts again. + if (m_credentialMode == CredentialMode::EachTime) { + m_pacman->clearPassword(); + } +} + QFrame* MainWindow::makeCard() { QFrame* card = new QFrame(); card->setObjectName("card"); @@ -935,13 +1030,15 @@ void MainWindow::resetDetailsPanel() { void MainWindow::onSearch() { if (!m_pacman->isAvailable()) { - QMessageBox::warning(this, "Erreur", "pacman n'est pas disponible."); + statusBar()->showMessage("pacman n'est pas disponible."); return; } std::string query = m_searchBar->text().toStdString(); if (query.empty()) { - QMessageBox::information(this, "Info", "Entrez un terme de recherche."); + // Refocus the search field instead of interrupting with a dialog. + m_searchBar->setFocus(); + statusBar()->showMessage("Entrez un terme de recherche."); return; } @@ -951,7 +1048,7 @@ void MainWindow::onSearch() { SearchWorker* worker = new SearchWorker(m_pacman, query); connect(worker, &SearchWorker::finished, this, &MainWindow::onSearchFinished); - connect(worker, &SearchWorker::finished, worker, &QObject::deleteLater); + connect(worker, &SearchWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); worker->start(); } @@ -962,7 +1059,7 @@ void MainWindow::loadInstalled() { ListWorker* worker = new ListWorker(m_pacman, ListWorker::Installed); connect(worker, &ListWorker::finished, this, &MainWindow::onListFinished); - connect(worker, &ListWorker::finished, worker, &QObject::deleteLater); + connect(worker, &ListWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); worker->start(); } @@ -973,7 +1070,7 @@ void MainWindow::loadUpdates() { ListWorker* worker = new ListWorker(m_pacman, ListWorker::Updates); connect(worker, &ListWorker::finished, this, &MainWindow::onListFinished); - connect(worker, &ListWorker::finished, worker, &QObject::deleteLater); + connect(worker, &ListWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); worker->start(); } @@ -1150,16 +1247,17 @@ void MainWindow::onRemove() { void MainWindow::onUpdate() { if (m_selectedPackage.name.empty()) return; + if (!ensureCredentials()) return; setBusy(true); statusBar()->showMessage( QString("Mise à jour de %1...").arg(QString::fromStdString(m_selectedPackage.name))); auto* worker = new InstallWorker(m_pacman, InstallWorker::Op::Update, m_selectedPackage.name); - connect(worker, &InstallWorker::progress, [this](const QString& msg) { + connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { statusBar()->showMessage(msg); }); - connect(worker, &InstallWorker::finished, [this](bool success) { + connect(worker, &InstallWorker::finished, this, [this](bool success) { setBusy(false); if (success) { statusBar()->showMessage("Mise à jour terminée"); @@ -1168,75 +1266,82 @@ void MainWindow::onUpdate() { } m_historyManager->record({"", "update", m_selectedPackage.name, m_pacman->getName(), success}); + clearCredentialsAfterUse(); reloadCurrentView(); }); - connect(worker, &InstallWorker::finished, worker, &QObject::deleteLater); + connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); worker->start(); } void MainWindow::onUpdateAll() { if (!m_pacman->isAvailable()) { - QMessageBox::warning(this, "Erreur", "pacman n'est pas disponible."); + statusBar()->showMessage("pacman n'est pas disponible."); return; } + if (!ensureCredentials()) return; setBusy(true); statusBar()->showMessage("Mise à jour de tous les paquets..."); auto* worker = new InstallWorker(m_pacman, InstallWorker::Op::UpdateAll, ""); - connect(worker, &InstallWorker::progress, [this](const QString& msg) { + connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { statusBar()->showMessage(msg); }); - connect(worker, &InstallWorker::finished, [this](bool success) { + connect(worker, &InstallWorker::finished, this, [this](bool success) { setBusy(false); if (success) { statusBar()->showMessage("Tous les paquets sont à jour"); } else { statusBar()->showMessage("Erreur lors de la mise à jour globale"); } + clearCredentialsAfterUse(); reloadCurrentView(); refreshDashboard(); }); - connect(worker, &InstallWorker::finished, worker, &QObject::deleteLater); + connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); worker->start(); } void MainWindow::onRefresh() { if (!m_pacman->isAvailable()) { - QMessageBox::warning(this, "Erreur", "pacman n'est pas disponible."); + statusBar()->showMessage("pacman n'est pas disponible."); return; } + if (!ensureCredentials()) return; setBusy(true); statusBar()->showMessage("Rafraîchissement des sources..."); auto* worker = new InstallWorker(m_pacman, InstallWorker::Op::Refresh, ""); - connect(worker, &InstallWorker::progress, [this](const QString& msg) { + connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { statusBar()->showMessage(msg); }); - connect(worker, &InstallWorker::finished, [this](bool success) { + connect(worker, &InstallWorker::finished, this, [this](bool success) { setBusy(false); if (success) { statusBar()->showMessage("Sources rafraîchies"); } else { statusBar()->showMessage("Erreur lors du rafraîchissement"); } + clearCredentialsAfterUse(); refreshDashboard(); }); - connect(worker, &InstallWorker::finished, worker, &QObject::deleteLater); + connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); worker->start(); } void MainWindow::performInstall(const std::string& package) { + if (!ensureCredentials()) return; + setBusy(true); statusBar()->showMessage( QString("Installation de %1...").arg(QString::fromStdString(package))); auto* worker = new InstallWorker(m_pacman, InstallWorker::Op::Install, package); - connect(worker, &InstallWorker::progress, [this](const QString& msg) { + connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { statusBar()->showMessage(msg); }); - connect(worker, &InstallWorker::finished, [this](bool success) { + connect(worker, &InstallWorker::finished, this, [this](bool success) { setBusy(false); if (success) { statusBar()->showMessage( @@ -1249,31 +1354,26 @@ void MainWindow::performInstall(const std::string& package) { } m_historyManager->record({"", "install", m_selectedPackage.name, m_pacman->getName(), success}); + clearCredentialsAfterUse(); reloadCurrentView(); refreshDashboard(); }); - connect(worker, &InstallWorker::finished, worker, &QObject::deleteLater); + connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); worker->start(); } void MainWindow::performRemove(const std::string& package) { - QMessageBox::StandardButton reply = QMessageBox::question(this, - "Confirmation", - QString("Voulez-vous vraiment supprimer %1 ?").arg( - QString::fromStdString(package)), - QMessageBox::Yes | QMessageBox::No); - - if (reply != QMessageBox::Yes) return; + if (!ensureCredentials()) return; setBusy(true); statusBar()->showMessage( QString("Suppression de %1...").arg(QString::fromStdString(package))); auto* worker = new InstallWorker(m_pacman, InstallWorker::Op::Remove, package); - connect(worker, &InstallWorker::progress, [this](const QString& msg) { + connect(worker, &InstallWorker::progress, this, [this](const QString& msg) { statusBar()->showMessage(msg); }); - connect(worker, &InstallWorker::finished, [this](bool success) { + connect(worker, &InstallWorker::finished, this, [this](bool success) { setBusy(false); if (success) { statusBar()->showMessage( @@ -1286,10 +1386,11 @@ void MainWindow::performRemove(const std::string& package) { } m_historyManager->record({"", "remove", m_selectedPackage.name, m_pacman->getName(), success}); + clearCredentialsAfterUse(); reloadCurrentView(); refreshDashboard(); }); - connect(worker, &InstallWorker::finished, worker, &QObject::deleteLater); + connect(worker, &InstallWorker::finished, this, [worker] { worker->wait(); worker->deleteLater(); }); worker->start(); } @@ -1407,7 +1508,7 @@ void MainWindow::refreshDashboard() { connect(inst, &ListWorker::finished, this, [this](std::vector r) { m_statInstalled->setText(QString::number(r.size())); }); - connect(inst, &ListWorker::finished, inst, &QObject::deleteLater); + connect(inst, &ListWorker::finished, this, [inst] { inst->wait(); inst->deleteLater(); }); inst->start(); auto* upd = new ListWorker(m_pacman, ListWorker::Updates); @@ -1417,7 +1518,7 @@ void MainWindow::refreshDashboard() { ? QString() : QString("color: #e0af68;")); }); - connect(upd, &ListWorker::finished, upd, &QObject::deleteLater); + connect(upd, &ListWorker::finished, this, [upd] { upd->wait(); upd->deleteLater(); }); upd->start(); } diff --git a/src/pacman-manager.cpp b/src/pacman-manager.cpp index c6defdf..f3aa401 100644 --- a/src/pacman-manager.cpp +++ b/src/pacman-manager.cpp @@ -19,6 +19,38 @@ static std::string exec(const char* cmd) { 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; +} + +// Run a privileged pacman command as root, piping the password to `sudo -S` +// on stdin and returning the combined stdout+stderr. +static std::string execPrivileged(const std::string& pacmanCmd, + const std::string& password) { + std::string full = "printf '%s\\n' " + shellQuote(password) + + " | sudo -S " + pacmanCmd + " 2>&1"; + return exec(full.c_str()); +} + +// Stream the lines of a command's output to the progress callback, if any. +static void streamOutput(const std::string& output, + std::function progressCallback) { + if (!progressCallback) return; + std::istringstream iss(output); + std::string line; + while (std::getline(iss, line)) { + if (!line.empty()) progressCallback(line); + } +} + std::vector PacmanManager::search(const std::string& query) { std::vector results; @@ -68,52 +100,53 @@ std::vector PacmanManager::search(const std::string& query) { bool PacmanManager::install(const std::string& packageName, std::function progressCallback) { if (progressCallback) progressCallback("Installation de " + packageName + "..."); - - std::string cmd = "pkexec pacman -S --noconfirm " + packageName + " 2>&1"; - std::string output = exec(cmd.c_str()); - - if (progressCallback) { - std::istringstream iss(output); - std::string line; - while (std::getline(iss, line)) { - if (!line.empty()) progressCallback(line); - } + + std::string output = execPrivileged("pacman -S --noconfirm " + packageName, m_password); + streamOutput(output, progressCallback); + + // A wrong/expired password must not be silently reused: drop it so the + // next attempt prompts again. + if (authFailed(output)) { + clearPassword(); + return false; } - + return isPackageInstalled(packageName); } bool PacmanManager::remove(const std::string& packageName, std::function progressCallback) { if (progressCallback) progressCallback("Suppression de " + packageName + "..."); - - std::string cmd = "pkexec pacman -R --noconfirm " + packageName + " 2>&1"; - std::string output = exec(cmd.c_str()); - - if (progressCallback) { - std::istringstream iss(output); - std::string line; - while (std::getline(iss, line)) { - if (!line.empty()) progressCallback(line); - } + + std::string output = execPrivileged("pacman -R --noconfirm " + packageName, m_password); + streamOutput(output, progressCallback); + + if (authFailed(output)) { + clearPassword(); + return false; } - + return !isPackageInstalled(packageName); } bool PacmanManager::update(const std::string& packageName, std::function progressCallback) { + std::string output; if (packageName.empty()) { if (progressCallback) progressCallback("Mise à jour de tous les paquets..."); - std::string cmd = "pkexec pacman -Syu --noconfirm 2>&1"; - exec(cmd.c_str()); - return true; + output = execPrivileged("pacman -Syu --noconfirm", m_password); } else { if (progressCallback) progressCallback("Mise à jour de " + packageName + "..."); - std::string cmd = "pkexec pacman -S --noconfirm " + packageName + " 2>&1"; - exec(cmd.c_str()); - return true; + output = execPrivileged("pacman -S --noconfirm " + packageName, m_password); } + streamOutput(output, progressCallback); + + if (authFailed(output)) { + clearPassword(); + return false; + } + + return true; } std::vector PacmanManager::listInstalled() { @@ -175,15 +208,12 @@ std::vector PacmanManager::listUpdates() { bool PacmanManager::refresh(std::function progressCallback) { if (progressCallback) progressCallback("Rafraîchissement des bases de données..."); - std::string cmd = "pkexec pacman -Sy --noconfirm 2>&1"; - std::string output = exec(cmd.c_str()); + std::string output = execPrivileged("pacman -Sy --noconfirm", m_password); + streamOutput(output, progressCallback); - if (progressCallback) { - std::istringstream iss(output); - std::string line; - while (std::getline(iss, line)) { - if (!line.empty()) progressCallback(line); - } + if (authFailed(output)) { + clearPassword(); + return false; } // `pacman -Sy` has no easy success code; treat a completed run as success @@ -285,3 +315,21 @@ std::map PacmanManager::parseSyncRepos( return repos; } + +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; +} + +void PacmanManager::setPassword(const std::string& password) { + m_password = password; +} + +void PacmanManager::clearPassword() { + m_password.clear(); +} + +bool PacmanManager::hasPassword() const { + return !m_password.empty(); +} diff --git a/tests/pacman-manager.test.cpp b/tests/pacman-manager.test.cpp index eab1ea9..64a9237 100644 --- a/tests/pacman-manager.test.cpp +++ b/tests/pacman-manager.test.cpp @@ -76,6 +76,20 @@ static void testParseSyncRepos_emptyInput() { assert(PacmanManager::parseSyncRepos("").empty()); } +static void testAuthFailed_detectsWrongPassword() { + assert(PacmanManager::authFailed( + "[sudo] password for alice: Sorry, try again.\nsudo: 1 incorrect password attempt")); +} + +static void testAuthFailed_detectsMissingPassword() { + assert(PacmanManager::authFailed("sudo: a password is required")); +} + +static void testAuthFailed_ignoresPacmanErrors() { + assert(!PacmanManager::authFailed("error: target not found: firefox")); + assert(!PacmanManager::authFailed("warning: firefox is up to date")); +} + int main() { testParseInstalledOutput_parsesSimpleLines(); testParseInstalledOutput_keepsHyphensInNames(); @@ -87,6 +101,10 @@ int main() { testParseSyncRepos_skipsHeader(); testParseSyncRepos_emptyInput(); + testAuthFailed_detectsWrongPassword(); + testAuthFailed_detectsMissingPassword(); + testAuthFailed_ignoresPacmanErrors(); + std::cout << "All pacman-manager tests passed." << std::endl; return 0; }