A slow daemon (17-22 s per request during the 2026-11-14 hang) made every 3 s poll open new status + policy requests on top of the unanswered ones. Now each verb has at most one request in flight, and failed status polls back off 2x per failure up to 30 s, restoring the normal rate on success. (The tray's ~1 core of CPU at the time is not yet root-caused: profiling it needs root here; see the Tracy setup follow-up.) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
368 lines
16 KiB
C++
368 lines
16 KiB
C++
#include "app_controller.hpp"
|
|
|
|
#include <QCoreApplication>
|
|
|
|
#include <QStandardPaths>
|
|
|
|
#include "daemon_client.hpp"
|
|
#include "strawberry/config.hpp"
|
|
#include "main_window.hpp"
|
|
#include "notifier.hpp"
|
|
#include "tray.hpp"
|
|
|
|
#include <QApplication>
|
|
#include <QCoreApplication>
|
|
#include <QJsonArray>
|
|
#include <QStandardPaths>
|
|
#include <QSystemTrayIcon>
|
|
#include <QTimer>
|
|
|
|
#include <algorithm>
|
|
#include <QVariantMap>
|
|
|
|
namespace strawberry::app {
|
|
|
|
namespace {
|
|
const QString kSeenKey = QStringLiteral("findings/seen");
|
|
const QString kNotifiedKey = QStringLiteral("findings/notified");
|
|
const QString kDefaultDbPath = QString::fromUtf8(strawberry::kSystemStorePath);
|
|
}
|
|
|
|
AppController::AppController(AppOptions options, QObject* parent)
|
|
: QObject(parent),
|
|
options_(std::move(options)),
|
|
settings_(QStringLiteral("strawberry"), QStringLiteral("strawberry-tray")) {
|
|
seen_ = load_map(settings_, kSeenKey);
|
|
notified_ = load_map(settings_, kNotifiedKey);
|
|
|
|
client_ = new DaemonClient(options_.socket_path, this);
|
|
notifier_ = new Notifier(this);
|
|
window_ = new MainWindow(store_);
|
|
window_->setWindowIcon(Tray::icon_for(TrayLevel::ok));
|
|
|
|
if (options_.tray) {
|
|
tray_ = new Tray(this);
|
|
connect(tray_, &Tray::open_requested, this, &AppController::show_window);
|
|
connect(tray_, &Tray::command_requested, client_, &DaemonClient::send);
|
|
connect(tray_, &Tray::mark_all_seen_requested, this, &AppController::mark_all_seen);
|
|
connect(tray_, &Tray::quit_requested, qApp, &QApplication::quit);
|
|
connect(tray_, &Tray::autostart_toggled, this, &AppController::set_autostart);
|
|
notifier_->attach_tray_icon(tray_->system_icon());
|
|
}
|
|
connect(window_, &MainWindow::autostart_toggled, this, &AppController::set_autostart);
|
|
|
|
// The autostart entry points at the installed binary when there is one,
|
|
// so starting the app from a build tree does not autostart that build.
|
|
autostart_env_ = autostart_env_from_process();
|
|
tray_exec_ = QStandardPaths::findExecutable(QStringLiteral("strawberry-tray"));
|
|
if (tray_exec_.isEmpty()) {
|
|
tray_exec_ = QCoreApplication::applicationFilePath();
|
|
}
|
|
|
|
connect(client_, &DaemonClient::replied, this, &AppController::on_reply);
|
|
connect(notifier_, &Notifier::activated, this, [this](const QString& finding_id) {
|
|
show_window();
|
|
window_->show_finding(finding_id);
|
|
});
|
|
connect(window_, &MainWindow::command_requested, client_, &DaemonClient::send);
|
|
connect(window_, &MainWindow::policy_change_requested, client_, &DaemonClient::send_with_payload);
|
|
connect(window_, &MainWindow::mark_all_seen_requested, this, &AppController::mark_all_seen);
|
|
connect(window_, &MainWindow::finding_viewed, this, &AppController::mark_seen);
|
|
|
|
timer_ = new QTimer(this);
|
|
timer_->setInterval(options_.poll_ms);
|
|
connect(timer_, &QTimer::timeout, this, &AppController::poll);
|
|
}
|
|
|
|
AppController::~AppController() {
|
|
delete window_;
|
|
}
|
|
|
|
void AppController::set_autostart(bool enable) {
|
|
std::string error;
|
|
if (!app::set_autostart(autostart_env_, enable, tray_exec_.toStdString(), error)) {
|
|
show_autostart_state(QString::fromStdString(error));
|
|
return;
|
|
}
|
|
show_autostart_state();
|
|
}
|
|
|
|
void AppController::show_autostart_state(const QString& error) {
|
|
const bool enabled = autostart_enabled(autostart_env_);
|
|
QString note = error;
|
|
if (note.isEmpty() && enabled) {
|
|
note = QString::fromStdString(session_hint(autostart_env_, tray_exec_.toStdString()));
|
|
}
|
|
if (tray_) {
|
|
tray_->set_autostart_checked(enabled);
|
|
}
|
|
window_->set_autostart_state(enabled, note);
|
|
}
|
|
|
|
void AppController::start() {
|
|
show_autostart_state();
|
|
store_.set_path((options_.db_path_override.isEmpty() ? kDefaultDbPath : options_.db_path_override).toStdString());
|
|
if (tray_) {
|
|
tray_->show();
|
|
if (!QSystemTrayIcon::isSystemTrayAvailable()) {
|
|
// Tray host not up yet (sway/waybar autostart race). Retry
|
|
// registration when it appears; fall back to the window only if no
|
|
// tray shows up within the grace period.
|
|
auto* retry = new QTimer(this);
|
|
retry->setInterval(1500);
|
|
connect(retry, &QTimer::timeout, this, [this, retry, ticks = 0]() mutable {
|
|
if (QSystemTrayIcon::isSystemTrayAvailable()) {
|
|
tray_->system_icon()->hide(); // force (re)registration with the new host
|
|
tray_->show();
|
|
retry->stop();
|
|
retry->deleteLater();
|
|
} else if (++ticks >= 10) { // ~15 s: no tray host; show the window instead
|
|
retry->stop();
|
|
retry->deleteLater();
|
|
if (!options_.show_window) show_window();
|
|
}
|
|
});
|
|
retry->start();
|
|
}
|
|
}
|
|
if (!options_.initial_tab.isEmpty()) {
|
|
window_->select_tab(options_.initial_tab);
|
|
}
|
|
if (options_.show_window || !tray_) {
|
|
show_window();
|
|
}
|
|
poll();
|
|
timer_->start();
|
|
}
|
|
|
|
void AppController::show_window() {
|
|
window_->show();
|
|
window_->raise();
|
|
window_->activateWindow();
|
|
}
|
|
|
|
void AppController::poll() {
|
|
if (!status_in_flight_) {
|
|
status_in_flight_ = true;
|
|
client_->send(QStringLiteral("status"));
|
|
}
|
|
if (!policy_in_flight_) {
|
|
policy_in_flight_ = true;
|
|
client_->send(QStringLiteral("policy"));
|
|
}
|
|
}
|
|
|
|
void AppController::on_reply(const QString& verb, bool ok, const QJsonObject& data, const QString& error) {
|
|
if (verb == QStringLiteral("status")) {
|
|
status_in_flight_ = false;
|
|
// Back off 2x per failed status poll (3 s -> max 30 s); one success restores the normal rate.
|
|
failed_polls_ = ok ? 0 : std::min(failed_polls_ + 1, 4);
|
|
const int interval = std::min(30000, options_.poll_ms << failed_polls_);
|
|
if (timer_ && timer_->interval() != interval) timer_->setInterval(interval);
|
|
} else if (verb == QStringLiteral("policy")) {
|
|
policy_in_flight_ = false;
|
|
}
|
|
if (verb == QStringLiteral("policy")) {
|
|
window_->update_policy(data, ok ? QString() : error);
|
|
if (ok) {
|
|
// Tell the user when Strawberry blocked something on its own.
|
|
const auto list = data.value(QStringLiteral("policy")).toObject().value(QStringLiteral("containment")).toArray();
|
|
QSet<QString> current;
|
|
for (const auto& value : list) {
|
|
const auto c = value.toObject();
|
|
const auto id = c.value(QStringLiteral("id")).toString();
|
|
current.insert(id);
|
|
if (containments_seeded_ && !known_containments_.contains(id) && c.value(QStringLiteral("automatic")).toBool()) {
|
|
notifier_->notify(QStringLiteral("Network blocked automatically"),
|
|
QStringLiteral("%1 (%2, %3)").arg(c.value(QStringLiteral("path")).toString(),
|
|
c.value(QStringLiteral("reason")).toString(),
|
|
c.value(QStringLiteral("severity")).toString()),
|
|
Notifier::Urgency::critical);
|
|
}
|
|
}
|
|
known_containments_ = current;
|
|
containments_seeded_ = true;
|
|
}
|
|
return;
|
|
}
|
|
if (verb.startsWith(QStringLiteral("allowlist-")) || verb.startsWith(QStringLiteral("feed-"))
|
|
|| verb.startsWith(QStringLiteral("contain-")) || verb == QStringLiteral("protection-set")
|
|
|| verb.startsWith(QStringLiteral("quarantine")) || verb.startsWith(QStringLiteral("process-"))
|
|
|| verb == QStringLiteral("scan-memory")) {
|
|
QString message = error;
|
|
if (ok) {
|
|
if (verb == QStringLiteral("allowlist-add")) {
|
|
message = QStringLiteral("Allowlisted. Matching detections will no longer be recorded.");
|
|
} else if (verb == QStringLiteral("allowlist-remove")) {
|
|
message = QStringLiteral("Allowlist entry removed.");
|
|
} else if (verb == QStringLiteral("feed-add")) {
|
|
message = QStringLiteral("Feed added; the updater is downloading it now.");
|
|
} else if (verb == QStringLiteral("contain-add")) {
|
|
const auto c = data.value(QStringLiteral("containment")).toObject();
|
|
message = QStringLiteral("Network blocked for %1%2").arg(c.value(QStringLiteral("path")).toString(),
|
|
c.value(QStringLiteral("hash_pinned")).toBool() ? QString() : QStringLiteral(" (path only)"));
|
|
notifier_->notify(QStringLiteral("Network blocked"), message, Notifier::Urgency::normal);
|
|
} else if (verb == QStringLiteral("contain-remove")) {
|
|
message = QStringLiteral("Containment removed; network allowed again.");
|
|
} else if (verb == QStringLiteral("quarantine")) {
|
|
message = QStringLiteral("Quarantined %1: execution %2, network %3.")
|
|
.arg(data.value(QStringLiteral("path")).toString(),
|
|
data.value(QStringLiteral("execution_blocked")).toBool() ? QStringLiteral("blocked")
|
|
: QStringLiteral("NOT blocked (") + data.value(QStringLiteral("note")).toString() + QStringLiteral(")"),
|
|
data.value(QStringLiteral("network_contained")).toBool() ? QStringLiteral("blocked")
|
|
: QStringLiteral("not blocked (") + data.value(QStringLiteral("network_error")).toString() + QStringLiteral(")"));
|
|
} else if (verb == QStringLiteral("quarantine-remove")) {
|
|
message = QStringLiteral("Released from quarantine; the binary can run and connect again.");
|
|
} else if (verb == QStringLiteral("scan-memory")) {
|
|
message = QStringLiteral("Memory scan started for PID %1; any match appears as a finding.")
|
|
.arg(data.value(QStringLiteral("pid")).toInt());
|
|
} else if (verb.startsWith(QStringLiteral("process-"))) {
|
|
const auto what = verb == QStringLiteral("process-kill") ? QStringLiteral("Killed")
|
|
: verb == QStringLiteral("process-suspend") ? QStringLiteral("Suspended") : QStringLiteral("Resumed");
|
|
message = QStringLiteral("%1 PID %2 (%3).").arg(what).arg(data.value(QStringLiteral("pid")).toInt())
|
|
.arg(data.value(QStringLiteral("path")).toString());
|
|
} else if (verb == QStringLiteral("protection-set")) {
|
|
message = QStringLiteral("Protection settings saved.");
|
|
} else if (verb == QStringLiteral("feed-remove")) {
|
|
message = QStringLiteral("Feed removed; rules reloaded.");
|
|
} else {
|
|
message = QStringLiteral("Feed updated; rules reloaded.");
|
|
}
|
|
}
|
|
window_->show_policy_result(verb, ok, message);
|
|
client_->send(QStringLiteral("policy"));
|
|
return;
|
|
}
|
|
if (verb != QStringLiteral("status")) {
|
|
QString message;
|
|
if (!ok) {
|
|
message = error;
|
|
} else if (verb == QStringLiteral("reload-rules")) {
|
|
ok = data.value(QStringLiteral("reloaded")).toBool();
|
|
message = ok ? QStringLiteral("rules reloaded")
|
|
: QStringLiteral("failed: %1 (previous rules still active)").arg(data.value(QStringLiteral("error")).toString());
|
|
} else if (verb == QStringLiteral("update-rules")) {
|
|
message = QStringLiteral("update requested; the updater runs in the background (see the Rules tab)");
|
|
} else {
|
|
message = QStringLiteral("rescan of running processes queued");
|
|
}
|
|
window_->show_command_result(verb, ok, message);
|
|
notifier_->notify(verb == QStringLiteral("rescan") ? QStringLiteral("Rescan")
|
|
: verb == QStringLiteral("update-rules") ? QStringLiteral("Rule update")
|
|
: QStringLiteral("Rule reload"),
|
|
message, ok ? Notifier::Urgency::low : Notifier::Urgency::normal);
|
|
poll();
|
|
return;
|
|
}
|
|
|
|
if (ok) {
|
|
snapshot_ = DaemonClient::snapshot_from_status(data);
|
|
status_ = data;
|
|
status_error_.clear();
|
|
const auto reported = data.value(QStringLiteral("db_path")).toString();
|
|
if (options_.db_path_override.isEmpty() && !reported.isEmpty()) {
|
|
store_.set_path(reported.toStdString());
|
|
}
|
|
} else {
|
|
snapshot_ = DaemonSnapshot{};
|
|
snapshot_.unreachable_reason = error.toStdString();
|
|
status_ = {};
|
|
status_error_ = error;
|
|
}
|
|
if (tray_) {
|
|
tray_->set_controls_enabled(ok);
|
|
}
|
|
|
|
refresh_evidence(false);
|
|
update_tray();
|
|
window_->update_status(status_, status_error_, tray_state_);
|
|
previous_scan_errors_ = snapshot_.scan_errors;
|
|
}
|
|
|
|
void AppController::refresh_evidence(bool force_view_refresh) {
|
|
const bool changed = store_.reload_if_changed();
|
|
if (changed || force_view_refresh || first_evidence_load_) {
|
|
window_->refresh_findings(seen_);
|
|
notify_new_findings();
|
|
first_evidence_load_ = false;
|
|
}
|
|
}
|
|
|
|
std::vector<FindingSummary> AppController::finding_summaries() const {
|
|
std::vector<FindingSummary> summaries;
|
|
for (const auto& finding : store_.findings()) {
|
|
summaries.push_back({finding.id, finding.title, finding.severity, finding.last_seen});
|
|
}
|
|
return summaries;
|
|
}
|
|
|
|
void AppController::update_tray() {
|
|
tray_state_ = evaluate_tray(snapshot_, finding_summaries(), seen_, previous_scan_errors_);
|
|
if (tray_) {
|
|
tray_->apply(tray_state_);
|
|
}
|
|
}
|
|
|
|
void AppController::notify_new_findings() {
|
|
const auto pending = findings_to_notify(finding_summaries(), seen_, notified_);
|
|
if (pending.empty()) {
|
|
return;
|
|
}
|
|
|
|
// Avoid a burst on first start with a backlog: summarise instead.
|
|
if (pending.size() > 3) {
|
|
notifier_->notify(QStringLiteral("%1 new high-severity findings").arg(pending.size()),
|
|
QStringLiteral("Open Strawberry to review them."), Notifier::Urgency::critical,
|
|
QString::fromStdString(pending.front().id));
|
|
} else {
|
|
for (const auto& finding : pending) {
|
|
const auto stored = store_.finding(finding.id);
|
|
notifier_->notify(QStringLiteral("[%1] %2").arg(QString::fromStdString(finding.severity).toUpper(),
|
|
QString::fromStdString(finding.title)),
|
|
stored ? QString::fromStdString(stored->summary) : QString(),
|
|
Notifier::Urgency::critical, QString::fromStdString(finding.id));
|
|
}
|
|
}
|
|
for (const auto& finding : pending) {
|
|
notified_[finding.id] = finding.last_seen;
|
|
}
|
|
save_map(settings_, kNotifiedKey, notified_);
|
|
}
|
|
|
|
void AppController::mark_seen(const QString& id, qint64 last_seen) {
|
|
const auto key = id.toStdString();
|
|
if (const auto it = seen_.find(key); it != seen_.end() && it->second >= last_seen) {
|
|
return;
|
|
}
|
|
seen_[key] = last_seen;
|
|
save_map(settings_, kSeenKey, seen_);
|
|
update_tray();
|
|
}
|
|
|
|
void AppController::mark_all_seen() {
|
|
for (const auto& finding : finding_summaries()) {
|
|
seen_[finding.id] = finding.last_seen;
|
|
}
|
|
save_map(settings_, kSeenKey, seen_);
|
|
window_->refresh_findings(seen_);
|
|
update_tray();
|
|
}
|
|
|
|
AckMap AppController::load_map(const QSettings& settings, const QString& key) {
|
|
AckMap map;
|
|
const auto stored = settings.value(key).toMap();
|
|
for (auto it = stored.cbegin(); it != stored.cend(); ++it) {
|
|
map[it.key().toStdString()] = it.value().toLongLong();
|
|
}
|
|
return map;
|
|
}
|
|
|
|
void AppController::save_map(QSettings& settings, const QString& key, const AckMap& map) {
|
|
QVariantMap stored;
|
|
for (const auto& [id, last_seen] : map) {
|
|
stored.insert(QString::fromStdString(id), QVariant::fromValue<qlonglong>(last_seen));
|
|
}
|
|
settings.setValue(key, stored);
|
|
}
|
|
|
|
} // namespace strawberry::app
|