// 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 #include "PresenceService.h" #include "../network/DiscoverySweep.h" #include "../network/Protocol.h" #include #include #include #include #include #include #include #include #include #include #include namespace koutnet { namespace { double nowEpoch() { return QDateTime::currentMSecsSinceEpoch() / 1000.0; } } // namespace PresenceService::PresenceService(QObject *parent) : QObject(parent) , m_timer(new QTimer(this)) { connect(m_timer, &QTimer::timeout, this, &PresenceService::tick); } void PresenceService::setStation(std::function readStation) { m_readStation = std::move(readStation); } void PresenceService::setDatagramSink(std::function sink) { m_sink = std::move(sink); } void PresenceService::setLocalPort(std::function port) { m_localPort = std::move(port); } void PresenceService::setTrustedIdentity(std::function trustedIdentity) { m_trustedIdentity = std::move(trustedIdentity); } void PresenceService::setAdvertisedTlsDial(std::function dial) { m_dial = std::move(dial); } void PresenceService::setE2eVouch(std::function vouch) { m_e2eVouch = std::move(vouch); } void PresenceService::setProfile(const QString &handle, const QString &displayName, const QString &bio, const QString &revision) { // Presence goes out on a short timer, so anything in here is paid for repeatedly; a long bio gets cut. constexpr int kMaxBioChars = 280; const QString trimmedBio = bio.left(kMaxBioChars); if (m_profileHandle == handle && m_profileDisplayName == displayName && m_profileBio == trimmedBio && m_profileRevision == revision) { return; } m_profileHandle = handle; m_profileDisplayName = displayName; m_profileBio = trimmedBio; m_profileRevision = revision; announceNow(); } void PresenceService::setStatus(int presence, const QString &statusEmoji) { const QString trimmed = statusEmoji.left(8); if (m_presence == presence && m_statusEmoji == trimmed) return; m_presence = presence; m_statusEmoji = trimmed; announceNow(); } void PresenceService::setStaticPeers(const QStringList &ips) { // not re-read from AppSettings: main.cpp passes the value once. m_staticPeers = ips; } void PresenceService::start() { // Rehydrate before any beacon claims to be fresh: a restart must emit // strictly past the value a peer may already hold, or the whole meeting // history of that peer would be replayed-looking. reloadCounter(); m_running = true; m_timer->start(kActiveBroadcastMs); // fast discovery until peers are found tick(); // first broadcast immediately } void PresenceService::stop() { m_running = false; m_timer->stop(); // park the last value so a restart resumes strictly past it. takeNonce() // already wrote it; this is the belt-and-braces flush for a clean exit. if (m_presenceNonceCounter > 0) saveCounter(m_presenceNonceCounter - 1); } bool PresenceService::isRunning() const { return m_running; } void PresenceService::announceNow() { if (m_running) tick(); } void PresenceService::tick() { if (!m_running || !m_sink) return; const StationInfo station = m_readStation ? m_readStation() : StationInfo(); // Cheap, always-on beacon: multicast first, then the subnet broadcast. This // keeps us discoverable without ever touching the loud /24 sweep below. const int desiredInterval = m_peers.isEmpty() ? kActiveBroadcastMs : kIdleBroadcastMs; if (m_timer->interval() != desiredInterval) m_timer->setInterval(desiredInterval); const QByteArray data = beaconFrame(); const quint16 port = m_localPort ? m_localPort() : protocol::kUdpPortDefault; // mDNS multicast: IPv4 and IPv6. m_sink(data, QHostAddress(QStringLiteral("224.0.0.251")), port); m_sink(data, QHostAddress(QStringLiteral("ff02::fb")), port); if (port != protocol::kUdpPortDefault) { m_sink(data, QHostAddress(QStringLiteral("224.0.0.251")), protocol::kUdpPortDefault); m_sink(data, QHostAddress(QStringLiteral("ff02::fb")), protocol::kUdpPortDefault); } QSet sentBroadcasts; const auto interfaces = QNetworkInterface::allInterfaces(); for (const auto &iface : interfaces) { const auto flags = iface.flags(); if (!(flags & QNetworkInterface::IsUp) || (flags & QNetworkInterface::IsLoopBack)) continue; const QList entries = iface.addressEntries(); for (const auto &entry : std::as_const(entries)) { if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) { // IPv4: subnet broadcast (e.g. 192.168.1.255). const QString bcast = entry.broadcast().toString(); if (!bcast.isEmpty() && bcast != QLatin1String("0.0.0.0") && !sentBroadcasts.contains(bcast)) { m_sink(data, entry.broadcast(), port); if (port != protocol::kUdpPortDefault) m_sink(data, entry.broadcast(), protocol::kUdpPortDefault); sentBroadcasts.insert(bcast); } } else if (entry.ip().protocol() == QAbstractSocket::IPv6Protocol) { // IPv6 has no subnet broadcast; use the all-nodes multicast // (ff02::1) scoped to this interface's link. const QHostAddress allNodes(QStringLiteral("ff02::1")); const QString key = QStringLiteral("v6:%1").arg(iface.index()); if (!sentBroadcasts.contains(key)) { // Qt does not expose scope id on QNetworkAddressEntry in all // versions; the socket's outgoing interface index suffices for // link-local multicast on Linux. m_sink(data, allNodes, port); if (port != protocol::kUdpPortDefault) m_sink(data, allNodes, protocol::kUdpPortDefault); sentBroadcasts.insert(key); } } } } // Subnet sweep: only while no peer is known, with backoff + jitter. // Uses real prefix length, skips subnets wider than /20 (too many hosts). const double now = nowEpoch(); const double jitter = 0.85 + 0.30 * QRandomGenerator::global()->generateDouble(); if (koutnet::discovery::sweepTick(now, m_lastScan, m_sweepIntervalMs, m_peers.isEmpty(), kSweepMinMs, kSweepMaxMs, jitter)) { const QHostAddress hostAddr(station.primaryAddress); if (hostAddr.protocol() == QAbstractSocket::IPv4Protocol) { // find the interface entry that owns our primary IP so we get // the actual prefix length instead of guessing /24 int prefix = 24; const auto ifaces = QNetworkInterface::allInterfaces(); for (const auto &iface : ifaces) { for (const auto &entry : iface.addressEntries()) { if (entry.ip() == hostAddr && entry.prefixLength() > 0) { prefix = entry.prefixLength(); break; } } } // skip anything wider than /20, too many hosts to sweep if (prefix >= 20) { const quint32 ip = hostAddr.toIPv4Address(); const quint32 mask = prefix < 32 ? ~((1u << (32 - prefix)) - 1u) : 0xFFFFFFFFu; const quint32 net = ip & mask; const quint32 bcast = net | ~mask; // first usable host = net+1, last = bcast-1 for (quint32 addr = net + 1; addr < bcast; ++addr) { if (addr == ip) continue; m_sink(data, QHostAddress(addr), port); } } } } // Static peers: unicast each cycle to addresses that have not answered yet. // A silent one is not reminded every cycle. const QStringList targets = staticUnicastTargets(m_staticPeers, m_peers, station.primaryAddress); for (const QString &target : std::as_const(targets)) m_sink(data, QHostAddress(target), port); pruneStalePeers(nowEpoch()); } void PresenceService::acceptPresence(const QString &host, QJsonObject msg) { // only ever a delivery candidate: a host at one address can advertise any other. const StationInfo station = m_readStation ? m_readStation() : StationInfo(); const QSet myIps = station.localAddresses.isEmpty() ? QSet{station.primaryAddress} : station.localAddresses; const QString advertised = msg.value(QStringLiteral("ip")).toString(); if (myIps.contains(advertised) || myIps.contains(host)) return; if (host.isEmpty() || host == QLatin1String("0.0.0.0") || host == QLatin1String("::")) return; // nowhere to file it and nowhere to answer // Presence packets are unsigned - the certificate a TLS dial presents is // the identity, so until a dial happens nothing here is authenticated - // and therefore the cheapest packet to forge. A per-address cap of // kMaxPresencePerSec keeps normal operation unaffected while making a // spoofed flood pointless. { const double now = nowEpoch(); QVector &window = m_presenceRate[host]; QVector kept; kept.reserve(window.size()); for (double t : std::as_const(window)) { if (now - t < 1.0) kept.append(t); } window = kept; if (window.size() >= kMaxPresencePerSec) return; window.append(now); } // Replay guard on the source address: the counter must be strictly greater // than the last one we saw from it. A missing or malformed nonce is not a // zero nonce - accepting it would pin zero as this sender's high-water mark // and drop every real beacon after it. const QJsonValue nonceValue = msg.value(QStringLiteral("nonce")); if (!nonceValue.isString()) return; bool nonceOk = false; const quint64 nonceCounter = nonceValue.toString().toULongLong(&nonceOk, 16); if (!nonceOk) return; auto prevIt = m_lastPresenceNonce.constFind(host); if (prevIt != m_lastPresenceNonce.constEnd() && nonceCounter <= *prevIt) return; m_lastPresenceNonce[host] = nonceCounter; // The announced identity is provisional until a TLS dial proves it. Where // the pinned channel already vouched for this address, that identity wins. QString peerId = msg.value(QStringLiteral("from_id")).toString(); const QString trustedId = m_trustedIdentity ? m_trustedIdentity(host) : QString(); if (!trustedId.isEmpty()) peerId = trustedId; // one entry per identity, filed under the address first heard: two contacts // for one person is worse than a stale address. const QString key = m_peerKeyById.value(peerId, host); msg[QStringLiteral("ip")] = key; if (!advertised.isEmpty() && advertised != key) msg[protocol::kFieldAdvertisedIp] = advertised; if (!peerId.isEmpty()) msg[QStringLiteral("from_id")] = peerId; const bool isNew = !m_peers.contains(key); msg[protocol::kFieldLastSeen] = nowEpoch(); if (m_e2eVouch) msg[QStringLiteral("e2e")] = !peerId.isEmpty() && m_e2eVouch(peerId); if (isNew) { // Spoofed presences must not grow the peer table without bound: // the oldest entry makes room. if (m_peers.size() >= kMaxPeers) evictOldestPeer(); } m_peers[key] = msg; if (!peerId.isEmpty()) m_peerKeyById[peerId] = key; // A peer that advertises a TLS port is dialed for the transport channel; // the pinned certificate decides whether it really is who it claims. The // dial goes to the address this presence came from (or the one it // advertised), so a spoofed presence can only waste one harmless TCP // attempt: nothing a stranger could say here opens a channel, TLS tells us. // Whether the dial may happen at all is the owner's call (the dial seam // already checks the pin table, the dialing set and the listening state). const quint16 tlsPort = quint16(msg.value(QStringLiteral("tls_port")).toInt()); if (tlsPort != 0 && !peerId.isEmpty() && m_dial) { const QString advert = msg.value(protocol::kFieldAdvertisedIp).toString(); m_dial(peerId, advert.isEmpty() ? host : advert, tlsPort); } if (isNew) Q_EMIT userOnline(msg); else Q_EMIT peerRefreshed(key, msg.value(protocol::kFieldLastSeen).toDouble()); } const QMap &PresenceService::peers() const { return m_peers; } QString PresenceService::keyForIdentity(const QString &peerId) const { return m_peerKeyById.value(peerId); } void PresenceService::setAvatarSource(const QString &key, const QString &source) { if (source.isEmpty()) m_peers[key].remove(QStringLiteral("avatar")); else m_peers[key].insert(QStringLiteral("avatar"), source); } void PresenceService::setBannerSource(const QString &key, const QString &source) { if (source.isEmpty()) m_peers[key].remove(QStringLiteral("banner")); else m_peers[key].insert(QStringLiteral("banner"), source); } void PresenceService::authenticatedSeat(const QString &peerId, const QString &address) { // Correct a seat that an unsigned presence id planted: if the address this // identity authenticated from is in the peer table but was filed under a // different announced id, give it to the holder of the real certificate. if (!m_peers.contains(address)) return; const QString oldSeat = m_peerKeyById.value(peerId); // the old seat is already held by an authenticated identity: leave it. if (!oldSeat.isEmpty() && m_trustedIdentity && !m_trustedIdentity(oldSeat).isEmpty()) return; m_peerKeyById[peerId] = address; } double PresenceService::lastSeen(const QString &address) const { return m_peers.value(address).value(protocol::kFieldLastSeen).toDouble(); } QByteArray PresenceService::beaconFrame() { return protocol::encodeFrame(presencePayload(takeNonce())); } QString PresenceService::nonceCounterPath() const { const QString dir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation); return dir + QStringLiteral("/presence-nonce-counter"); } // Rehydrate the presence counter before any beacon claims to be fresh: a // restart must emit strictly past the value a peer may already hold, or the // whole meeting history of that peer would be replayed-looking. void PresenceService::reloadCounter() { QFile in(nonceCounterPath()); if (in.open(QIODevice::ReadOnly)) { bool ok = false; const quint64 lastSent = QString::fromLatin1(in.readAll().trimmed()).toULongLong(&ok, 16); in.close(); if (ok) m_presenceNonceCounter = m_presenceNonceCounter > lastSent ? m_presenceNonceCounter : lastSent + 1; } } // Bump the durable presence counter and park the new value, so a process that // restarts rehydrates it and keeps emitting strictly increasing nonces. // Without the park file a cycled peer starts at 0 and every peer that ever // met it drops its beacons as replays until it catches up - which it cannot. quint64 PresenceService::takeNonce() { const quint64 nonce = m_presenceNonceCounter++; // The replay guard is only as good as the durable high-water mark: a crash // right after a beacon must not let the next process reuse its nonce. So // every beacon parks the counter atomically, even though that is a write // every couple of seconds - correctness beats the saved I/O here. saveCounter(nonce); return nonce; } void PresenceService::saveCounter(quint64 nonce) const { const QString path = nonceCounterPath(); QDir().mkpath(QFileInfo(path).absolutePath()); QSaveFile file(path); if (file.open(QIODevice::WriteOnly)) { file.write(QString::number(nonce, 16).toLatin1()); file.commit(); // atomic: a torn write would corrupt the counter } } QJsonObject PresenceService::presencePayload(quint64 presenceNonce) const { const StationInfo station = m_readStation ? m_readStation() : StationInfo(); QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgPresence; payload[QStringLiteral("ip")] = station.primaryAddress; // Deliberately not here: the rest of the interface list, and the OS name. // A beacon goes out unencrypted to every peer on the LAN every few seconds, // so every extra field is a field the whole segment can read. "ip" and // "tls_port" are what a peer needs to place a call, and nothing else is. payload[QStringLiteral("version")] = QStringLiteral(KOUTNET_VERSION_STRING); payload[QStringLiteral("protocol_version")] = protocol::kProtocolVersion; payload[QStringLiteral("ts")] = nowEpoch(); // Counter-based nonce: a monotonic 64-bit counter that receivers check // against the last one they saw, an O(1) replay guard. Presence is // unsigned - the certificate a TLS dial presents is who this station // really is, so a signature here would not even be verifiable yet. payload[QStringLiteral("nonce")] = QString::number(presenceNonce, 16); // where this station listens for TLS sessions, when the channel is up. The // address to dial is the one this presence arrived on (or the advertised // ip), not an extra authority: identity is decided by the pinned // certificate, never by which IP claims the port. if (station.tlsPort != 0) payload[QStringLiteral("tls_port")] = station.tlsPort; if (!station.identityId.isEmpty()) payload[QStringLiteral("from_id")] = station.identityId; payload[QStringLiteral("username")] = m_profileHandle; payload[QStringLiteral("display_name")] = m_profileDisplayName; payload[QStringLiteral("bio")] = m_profileBio; payload[QStringLiteral("profile_rev")] = m_profileRevision; payload[QStringLiteral("presence")] = m_presence; payload[QStringLiteral("status_emoji")] = m_statusEmoji; return payload; } QStringList PresenceService::staticUnicastTargets(const QStringList &configured, const QMap &knownPeers, const QString &hostIp) { QStringList targets; for (const QString &target : configured) { if (target == hostIp || knownPeers.contains(target)) continue; if (QHostAddress(target).isNull()) continue; // settings field holds a non-address targets.append(target); } return targets; } void PresenceService::pruneStalePeers(double now) { QVector stale; for (auto it = m_peers.constBegin(); it != m_peers.constEnd(); ++it) { const double lastSeen = it.value().value(protocol::kFieldLastSeen).toDouble(); if (now - lastSeen > 25) stale.append(it.key()); } for (const auto &ip : stale) { const QString peerId = m_peers.value(ip).value(QStringLiteral("from_id")).toString(); // or the next presence packet from this peer would be filed under an address // no longer in the table, and it would never come back. if (!peerId.isEmpty() && m_peerKeyById.value(peerId) == ip) m_peerKeyById.remove(peerId); m_peers.remove(ip); m_presenceRate.remove(ip); m_lastPresenceNonce.remove(ip); Q_EMIT userOffline(ip); } // Presence is rate-gated per source address, but a host that stopped sending // must not leave its window in memory forever. for (auto it = m_presenceRate.begin(); it != m_presenceRate.end();) { const QVector &window = it.value(); if (window.isEmpty() || now - window.constLast() >= 1.0) it = m_presenceRate.erase(it); else ++it; } // Replay nonces carry no timestamp, so prune by the only bound we have: a // source that is neither a known peer nor worth keeping in an oversized table. if (m_lastPresenceNonce.size() > kMaxPeers * 4) { for (auto it = m_lastPresenceNonce.begin(); it != m_lastPresenceNonce.end();) { if (!m_peers.contains(it.key())) it = m_lastPresenceNonce.erase(it); else ++it; } } } void PresenceService::evictOldestPeer() { // one pass instead of a sort: under a flood this runs for every newcomer. auto oldest = m_peers.begin(); for (auto it = m_peers.begin(); it != m_peers.end(); ++it) { if (it.value().value(protocol::kFieldLastSeen).toDouble() < oldest.value().value(protocol::kFieldLastSeen).toDouble()) oldest = it; } const QString key = oldest.key(); const QString peerId = oldest.value().value(QStringLiteral("from_id")).toString(); m_peers.erase(oldest); m_presenceRate.remove(key); m_lastPresenceNonce.remove(key); if (!peerId.isEmpty() && m_peerKeyById.value(peerId) == key) m_peerKeyById.remove(peerId); Q_EMIT userOffline(key); } } // namespace koutnet