// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // KOutNet - The frame router and call-signalling state machine #include "FrameRouter.h" #include "Protocol.h" #include #include "koutnet_network_debug.h" namespace koutnet { FrameRouter::FrameRouter(QObject *parent) : QObject(parent) { } void FrameRouter::setRateGate(std::function gate) { m_rateGate = std::move(gate); } void FrameRouter::setOwnNetwork(std::function()> myIps) { m_ownNetwork = std::move(myIps); } void FrameRouter::setPresenceSink(std::function sink) { m_presenceSink = std::move(sink); } void FrameRouter::setBusyReply(std::function reply) { m_busyReply = std::move(reply); } void FrameRouter::setKeySeams(std::function cipherKey, std::function pinnedKey, std::function setKey) { m_cipherKey = std::move(cipherKey); m_pinnedKey = std::move(pinnedKey); m_setKey = std::move(setKey); } void FrameRouter::setCrypto( std::function hasCrypto, std::function &done)> decryptAsync) { m_hasCrypto = std::move(hasCrypto); m_decryptAsync = std::move(decryptAsync); } void FrameRouter::route(const QString &host, QJsonObject msg) { if (m_rateGate && !m_rateGate(host)) { return; // dropped - over rate limit } const QString msgFromIp = msg.value(QStringLiteral("from_ip")).toString(); const QSet myIps = m_ownNetwork ? m_ownNetwork() : QSet(); const QString type = msg.value(QStringLiteral("type")).toString(); if (type != protocol::kMsgPresence && !type.isEmpty()) { if (!msgFromIp.isEmpty() && myIps.contains(msgFromIp)) return; // own message echoed back if (myIps.contains(host)) return; // own broadcast echoed back } if (type == protocol::kMsgPresence) { if (m_presenceSink) m_presenceSink(host, msg); } else if (type == protocol::kMsgChat || type == protocol::kMsgGroup || type == protocol::kMsgReaction || type == protocol::kMsgEdit || type == protocol::kMsgDelete || type == protocol::kMsgRead) { decryptText(msg, [this](QJsonObject decrypted) { Q_EMIT message(decrypted); }); } else if (type == protocol::kMsgPrivate) { // Against every address of ours, not just the primary one: // comparing with m_hostIp alone dropped this on multi-homed machines. if (myIps.contains(msg.value(QStringLiteral("to")).toString())) { decryptText(msg, [this](QJsonObject decrypted) { Q_EMIT message(decrypted); }); } } else if (type == protocol::kMsgCallReq) { if (!m_activeCalls.isEmpty()) { // already on a call; busy is cheaper for the caller than ringing forever if (m_busyReply) m_busyReply(host); } else { m_ringingCalls.insert(host); Q_EMIT callRequest(msg.value(QStringLiteral("username")).toString(QStringLiteral("?")), host); } } else if (type == protocol::kMsgCallAccept) { // the whole point of the state machine: a call_accept from a peer we // never called is somebody with a channel trying to open our // microphone. Only an asked peer's accept lands. if (!m_pendingCalls.remove(host)) return; Q_EMIT callAccepted(msg.value(QStringLiteral("username")).toString(QStringLiteral("?")), host); } else if (type == protocol::kMsgCallBusy || type == protocol::kMsgCallReject) { if (!m_pendingCalls.remove(host)) return; Q_EMIT callRejected(host); } else if (type == protocol::kMsgCallEnd) { // call_end carries two meanings: "your ring was cancelled" to a caller // and "the call is over" to a connected peer. if (!m_pendingCalls.remove(host) && !m_ringingCalls.remove(host) && !m_activeCalls.contains(host)) return; Q_EMIT callEnded(host); } else if (type == protocol::kMsgFileMeta) { Q_EMIT fileMeta(host, msg); } else if (type == protocol::kMsgGroupInv) { // The invitation carries the group key in the clear of its own channel // - the one peer it is addressed to, over TLS the pin already // authenticated. Identity is the certificate, not a claimed from_id. const QString gid = msg.value(QStringLiteral("gid")).toString(); const QString key = msg.value(QStringLiteral("key")).toString(); if (!key.isEmpty()) { const QString existing = m_pinnedKey ? m_pinnedKey(gid) : QString(); if (existing.isEmpty()) { // first sight of the group pins the key; the invite is the // confirmation, and this channel was the one holding it. if (m_setKey) m_setKey(gid, key); } else if (existing != key) { // A pinned key is not replaced on an invite's say-so. A silent // overwrite would let a peer regress a whole group onto a key // of their choosing. The mismatch is surfaced and the UI // decides - rotation is confirmed, not hijacked. qCWarning(KOUTNET_LOG_NETWORK) << "group key for" << gid << "differs from the pinned one - not overwritten without confirmation"; Q_EMIT groupKeyConfirmationRequired(gid, msg.value(QStringLiteral("gname")).toString(), host); return; } // an identical key is an idempotent re-invite: nothing to do. } Q_EMIT groupInvite(msg.value(QStringLiteral("gid")).toString(), msg.value(QStringLiteral("gname")).toString(), host); } else if (type == protocol::kMsgTyping) { Q_EMIT typing(msg.value(QStringLiteral("username")).toString(), msg.value(QStringLiteral("chat_id")).toString(QStringLiteral("public")), host); } } void FrameRouter::openRequest(const QString &ip) { m_pendingCalls.insert(ip); } void FrameRouter::resolveRing(const QString &ip) { m_ringingCalls.remove(ip); } void FrameRouter::cancelRequest(const QString &ip) { m_pendingCalls.remove(ip); } void FrameRouter::setActiveCalls(const QSet &ips) { m_activeCalls = ips; } void FrameRouter::decryptText(QJsonObject msg, const std::function &done) { if (!m_hasCrypto || !m_hasCrypto() || !msg.contains(QStringLiteral("text"))) { done(msg); return; } // A private chat body off the TLS channel already arrived decrypted and // authenticated: the transport DID it, so the text is handed on as-is. // Group bodies stay sealed under the group's own key whatever transport // carried them, so they are opened below. const QVariant gid = msg.value(QStringLiteral("gid")); const bool isGroup = !gid.isNull() && !gid.toString().isEmpty(); if (msg.value(QStringLiteral("via_tls")).toBool() && !isGroup) { done(msg); return; } // A group message is sealed under its own key; anything without a gid falls // back to the shared passphrase, and to cleartext when none exists. QString passphrase = m_cipherKey ? m_cipherKey(isGroup ? gid.toString() : QString()) : QString(); if (passphrase.isEmpty()) { // A message that should have been sealed but has no key must not reach // the UI as raw ciphertext. Group traffic is always app-sealed; a lone // wire marker means a sealed payload with no key to open it. const QString text = msg.value(QStringLiteral("text")).toString(); if (isGroup || text.startsWith(QStringLiteral("KNC2:"))) { msg[QStringLiteral("text")] = i18nc("@info shown in place of a message body", "This message could not be decrypted."); msg[QStringLiteral("decrypt_failed")] = true; } done(msg); return; } const QString cipherText = msg.value(QStringLiteral("text")).toString(); // Async so an attacker's fresh-salt flood pays for the KDF on a worker // thread rather than in the GUI's event loop (CryptoManager::decryptAsync). m_decryptAsync(cipherText, passphrase, [msg, done](const QString &plain, bool delivered) mutable { if (!delivered) return; // the queue gate refused it: a flood is dropped, not rendered msg[QStringLiteral("text")] = plain; done(msg); }); } } // namespace koutnet