strawberry/app/app_controller.cpp
trvon ca9350f0fa
Build on macOS: portable syscalls, sockets and tray
The tree now compiles on macOS. Each Linux-only call gets a Darwin
branch, and the Linux branch stays as it was:

- io::fdatasync uses fcntl(F_FULLFSYNC): fsync alone only reaches the
  drive cache on APFS, and the store's crash atomicity relies on it.
- Control socket: FD_CLOEXEC set after socket/accept/recvmsg (no
  SOCK_CLOEXEC, accept4 or MSG_CMSG_CLOEXEC), SO_NOSIGPIPE, peer
  credentials from LOCAL_PEERCRED + LOCAL_PEERPID, getgrouplist with
  int groups and a growing buffer. launchd has no RuntimeDirectory, so
  the socket directory is created (0750, access group) when missing.
  Default socket path is /var/run/strawberry/control.sock.
- CRC32C detects ARMv8 CRC with hw.optional.armv8_crc32 (no auxv).
- stat mtime via st_mtimespec; the BPF shared header uses stdint
  typedefs off Linux.
- Background threads join the PRIO_DARWIN_BG band (lower CPU and I/O);
  crash safety zeroes RLIMIT_CORE in place of PR_SET_DUMPABLE.
- The desktop app drops Qt DBus off Linux and shows notifications as
  tray messages (app/notifier_tray.cpp).
- make setup passes Homebrew's keg-only libarchive to meson.

Tests: behavior_live (Linux ptrace API) builds on Linux only, the
control-server fd count reads /dev/fd, the crash test checks the core
limit on macOS, and the runtime pipeline test no longer references a
YARA-only helper when YARA is absent (that also broke Linux builds
without libyara).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 20:52:39 -06:00

291 lines
13 KiB
C++

#include "app_controller.hpp"
#include "daemon_client.hpp"
#include "main_window.hpp"
#include "notifier.hpp"
#include "tray.hpp"
#include <QApplication>
#include <QJsonArray>
#include <QTimer>
#include <QVariantMap>
namespace strawberry::app {
namespace {
const QString kSeenKey = QStringLiteral("findings/seen");
const QString kNotifiedKey = QStringLiteral("findings/notified");
const QString kDefaultDbPath = QStringLiteral("/var/lib/strawberry/database.db");
}
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);
notifier_->attach_tray_icon(tray_->system_icon());
}
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::start() {
store_.set_path((options_.db_path_override.isEmpty() ? kDefaultDbPath : options_.db_path_override).toStdString());
if (tray_) {
tray_->show();
}
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() {
client_->send(QStringLiteral("status"));
client_->send(QStringLiteral("policy"));
}
void AppController::on_reply(const QString& verb, bool ok, const QJsonObject& data, const QString& error) {
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