| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | // Copyright 2019 Juan Palacios <[email protected]> |
| 3 | |
| 4 | #include "helperkiller.h" |
| 5 | |
| 6 | #include "helperids.h" |
| 7 | #include "polkit.h" |
| 8 | #include <QCoreApplication> |
| 9 | #include <QDBusConnection> |
| 10 | #include <QDBusMessage> |
| 11 | #include <QProcess> |
| 12 | #include <QString> |
| 13 | #include <QStringList> |
| 14 | #include <QTimer> |
| 15 | #include <exception> |
| 16 | #include <signal.h> |
| 17 | #include <string> |
| 18 | |
| 19 | HelperKiller::HelperKiller(QObject *parent) noexcept |
| 20 | : QDBusAbstractAdaptor(parent) |
| 21 | { |
| 22 | } |
| 23 | |
| 24 | HelperKiller::~HelperKiller() = default; |
| 25 | |
| 26 | bool HelperKiller::start(QDBusMessage const &message) const |
| 27 | { |
| 28 | if (!isAuthorized(message)) |
| 29 | return false; |
| 30 | |
| 31 | QProcess cmd; |
| 32 | cmd.start(QStringLiteral("pidof"), QStringList(HELPER_EXE)); |
| 33 | |
| 34 | bool result = cmd.waitForFinished(); |
| 35 | if (result) { |
| 36 | try { |
| 37 | auto output = cmd.readAllStandardOutput().toStdString(); |
| 38 | int pid = std::stoi(output); |
| 39 | result = kill(pid, SIGKILL) == 0; |
| 40 | } |
| 41 | catch (std::exception const &) { |
| 42 | result = false; |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | QTimer::singleShot(0, QCoreApplication::instance(), &QCoreApplication::quit); |
| 47 | |
| 48 | return result; |
| 49 | } |
| 50 | |
| 51 | bool HelperKiller::isAuthorized(QDBusMessage const &message) const |
| 52 | { |
| 53 | auto subject = Polkit::BusNameSubject{message.service().toStdString()}; |
| 54 | return Polkit::checkAuthorizationSync(POLKIT_HELPER_KILLER_ACTION, subject) == |
| 55 | Polkit::AuthResult::Yes; |
| 56 | } |
| 57 | |
| 58 | bool initDBusForHelperKillerService(QObject *obj) |
| 59 | { |
| 60 | QDBusConnection bus = QDBusConnection::systemBus(); |
| 61 | return bus.isConnected() && |
| 62 | bus.registerObject(QStringLiteral(DBUS_HELPER_KILLER_PATH), obj) && |
| 63 | bus.registerService(QStringLiteral(DBUS_HELPER_KILLER_SERVICE)); |
| 64 | } |
| 65 | |
| 66 | bool endDBusForHelperKillerService() |
| 67 | { |
| 68 | QDBusConnection bus = QDBusConnection::systemBus(); |
| 69 | bus.unregisterObject(QStringLiteral(DBUS_HELPER_KILLER_PATH)); |
| 70 | return bus.unregisterService(QStringLiteral(DBUS_HELPER_KILLER_SERVICE)); |
| 71 | } |
| 72 | |
| 73 | int main(int argc, char **argv) |
| 74 | { |
| 75 | QCoreApplication app(argc, argv); |
| 76 | new HelperKiller(&app); |
| 77 | |
| 78 | if (!initDBusForHelperKillerService(&app)) |
| 79 | exit(1); |
| 80 | |
| 81 | app.exec(); |
| 82 | |
| 83 | if (!endDBusForHelperKillerService()) |
| 84 | exit(1); |
| 85 | |
| 86 | return 0; |
| 87 | } |