// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // KOutNet - Peer discovery: presence beacon, guards and the observed peer table #pragma once #include #include #include #include #include #include #include #include #include #include class QTimer; namespace koutnet { // The presence half of discovery, stood up out of NetworkManager: the beacon // (multicast, broadcast, the backoff'd /24 sweep, static targets), the guards // (per-address rate cap, replay gate and durable nonce counter) and the observed // peer table. All of it is unsigned observation; identity only becomes real when // the pinned TLS channel proves it, and routing never consults this table. // // It owns no sockets: the owner's UDP socket and station state arrive as seams, // wired once. The TLS-advertised dial goes through another seam, because whether // a dial may happen is a decision about the pin table the owner holds. class PresenceService : public QObject { Q_OBJECT public: // Aggressive while no peers are known, then backs off: discovery has already // worked, and the noise costs battery and CPU on laptops. static constexpr int kActiveBroadcastMs = 2000; static constexpr int kIdleBroadcastMs = 8000; // /24 sweep backoff: starts loud for a quick first find, then doubles with // jitter up to the cap so an empty network is not hammered forever. static constexpr int kSweepMinMs = 2000; static constexpr int kSweepMaxMs = 120000; // Cap on the observed peer table: spoofed presences must not grow it without // bound, so the oldest entry gives way to a newcomer. static constexpr int kMaxPeers = 512; // Presence is unsigned (handshake rides inside), so cap at 5/s per address. static constexpr int kMaxPresencePerSec = 5; // Everything a beacon names about this station and every address a peer must // not be filed under. Read fresh on each beacon and accepted presence, since // the primary address can change under a running session. struct StationInfo { QString primaryAddress; // this station's primary local address QSet localAddresses; // every local address, for all_ips and the echo checks quint16 tlsPort = 0; // where the TLS channel listens, 0 when it is down QString identityId; // our own identity id, empty without crypto }; explicit PresenceService(QObject *parent = nullptr); // The seams, wired once by the owning NetworkManager. void setStation(std::function readStation); // Place one beacon datagram; the owner holds the socket, so it is this // lambda that decides whether a socket exists at all. void setDatagramSink(std::function sink); // The local UDP port this station is bound on, read at each beacon (a // rebind changes it without the service being told). void setLocalPort(std::function port); // identity the pinned channel authenticated from an address, empty when // nothing passed the pin gate. Where the pin vouched, its identity wins. void setTrustedIdentity(std::function trustedIdentity); // A peer advertising a TLS port gets dialed for the transport channel; // whether the dial may happen is all the owner's call. void setAdvertisedTlsDial(std::function dial); // The pinned-channel check that decides the peer table's e2e field, or unset // to omit the field (a station with no crypto has nothing to vouch for). void setE2eVouch(std::function vouch); // Profile and status the beacon announces; setting these while running fires // a beacon immediately, so a status change is heard at once. void setProfile(const QString &handle, const QString &displayName, const QString &bio, const QString &revision); void setStatus(int presence, const QString &statusEmoji); void setStaticPeers(const QStringList &ips); // Beacon lifecycle. start() rehydrates the nonce counter, starts the timer and // fires a beacon immediately; stop() only silences it - the table is kept. void start(); void stop(); bool isRunning() const; void announceNow(); // One incoming presence beacon from host. The frame is already decoded; // everything below is attacker-controlled, so the guards run first. void acceptPresence(const QString &host, QJsonObject msg); // Peer-table access for the other layers. The table is observation: routing // never consults it, only the UI and seat resolution do. const QMap &peers() const; // the address (peer-table key) a known identity is filed under, empty // until presence has vouched for the identity in any form. QString keyForIdentity(const QString &peerId) const; // The avatar exchange records a landed picture (or, empty, its removal) // into the peer info this table keeps. void setAvatarSource(const QString &key, const QString &source); // The banner exchange records a landed header picture the same way, one // field beside the avatar's. void setBannerSource(const QString &key, const QString &source); // The pinned channel authenticated peerId from address: if unsigned presence // parked the identity under a different empty seat, hand it to the certificate. void authenticatedSeat(const QString &peerId, const QString &address); // the locally observed last-seen stamp of an address, 0 when unknown. double lastSeen(const QString &address) const; // The encoded beacon frame (payload + nonce + framing). The owner's ARP // sweep unicasts the same bytes, so they are built in one place. QByteArray beaconFrame(); // The durable nonce counter the beacon ix built on, public because the // restart test drives it directly. QString nonceCounterPath() const; void reloadCounter(); quint64 takeNonce(); // Configured addresses minus our own and ones already heard from. // Static so the decision can be tested without sockets. static QStringList staticUnicastTargets(const QStringList &configured, const QMap &knownPeers, const QString &hostIp); // Drops entries nobody has refreshed in 25 seconds, announcing each departure. // now is explicit so a test can age a peer; the beacon tick passes the clock. void pruneStalePeers(double now); Q_SIGNALS: void userOnline(QJsonObject peerInfo); // userOnline() fires once, on the first packet, so without this the interface's // last-seen would freeze at a peer's first appearance. void peerRefreshed(QString ip, double lastSeen); void userOffline(QString ip); private Q_SLOTS: void tick(); private: QJsonObject presencePayload(quint64 nonce) const; void evictOldestPeer(); // park the durable counter; every beacon calls it so a restart resumes // strictly past the last value a peer saw. stop() flushes once more. void saveCounter(quint64 nonce) const; std::function m_readStation; std::function m_sink; std::function m_localPort; std::function m_trustedIdentity; std::function m_dial; std::function m_e2eVouch; QTimer *m_timer = nullptr; bool m_running = false; // observed address -> peer info. last_seen is stamped from the local clock // on arrival, never read off the wire, and is what staleness is judged by. QMap m_peers; // observed address -> peer info QHash m_peerKeyById; // announced identity id -> its key in m_peers // Per-address presence rate limiter: address -> timestamps of recent arrivals. QHash> m_presenceRate; // Counter-based replay guard: source address -> last accepted nonce counter. // Separate from CryptoManager's counters because presence has no session. QHash m_lastPresenceNonce; // Monotonic counter for outgoing presence nonces, incremented per broadcast, // so receivers do O(1) replay detection. Rehydrated on start(). mutable quint64 m_presenceNonceCounter = 0; // the station's announced profile and status (see setProfile/setStatus). QString m_profileHandle; QString m_profileDisplayName; QString m_profileBio; QString m_profileRevision; QString m_statusEmoji; int m_presence = 0; QStringList m_staticPeers; // set via setStaticPeers() double m_lastScan = 0.0; double m_sweepIntervalMs = double(kSweepMinMs); // current /24 sweep gap, grows with backoff }; } // namespace koutnet