// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // KOutNet - The authenticated session planner and pin table #include "SessionTransport.h" #include "../core/security/CryptoManager.h" #include "AddressUtils.h" #include "Protocol.h" #include #include #include #include #include "koutnet_network_debug.h" namespace koutnet { SessionTransport::SessionTransport(QObject *parent) : QObject(parent) { } void SessionTransport::start(const CryptoManager *crypto) { m_listenPort = 0; m_ident = IdentityCertificate(); if (m_tls) { m_tls->stop(); m_tls->deleteLater(); m_tls = nullptr; } m_dialing.clear(); m_seats.clear(); // The TLS channel is THE transport: sessions, chats, groups, calls and // files all ride length-prefixed frames over TLS 1.3, and its TOFU pins // decide who may open one. The channel is built from the identity seed, so // both sides present certificates that pin to their KOutNet identity, and // its port is what presence announces so a peer that sees this station // knows where to dial. A first run whose store failed has no keys and gets // no channel, which is exactly the degraded state the rest of the // transport already tolerates. if (crypto && crypto->isValid()) { const IdentityCertificate ident = buildIdentityCertificate(crypto->identitySeed(), crypto->ownIdentityId()); if (!ident.isValid()) { qCWarning(KOUTNET_LOG_NETWORK) << "could not build the identity certificate - the TLS channel stays down"; } else { m_ident = ident; m_tls = new TlsChannel(ident, this); if (!m_tls->listen(protocol::kTlsPortDefault)) { if (!m_tls->listen(0)) { qCWarning(KOUTNET_LOG_NETWORK) << "TLS listen failed on" << protocol::kTlsPortDefault << "- no session transport"; m_tls->deleteLater(); m_tls = nullptr; } } } } if (m_tls && m_tls->isListening()) { m_listenPort = m_tls->listenPort(); connect(m_tls, &TlsChannel::peerAuthenticated, this, &SessionTransport::onPeerAuthenticated); connect(m_tls, &TlsChannel::peerRejected, this, &SessionTransport::onPeerRejected); connect(m_tls, &TlsChannel::frameReceived, this, &SessionTransport::onFrame); connect(m_tls, &TlsChannel::connectionFailed, this, &SessionTransport::onDialFailure); qCDebug(KOUTNET_LOG_NETWORK) << "TLS transport up on port" << m_listenPort; } } void SessionTransport::stop() { m_listenPort = 0; m_ident = IdentityCertificate(); if (m_tls) { // closing the channel drops its sockets and its listening port; the // pins it wrote stay on disk so a restart welcomes the same peers. m_tls->stop(); m_tls->deleteLater(); m_tls = nullptr; } m_dialing.clear(); m_seats.clear(); } bool SessionTransport::active() const { return m_tls && m_tls->isListening(); } quint16 SessionTransport::listenPort() const { return m_listenPort; } const IdentityCertificate &SessionTransport::identity() const { return m_ident; } bool SessionTransport::hasPeer(const QString &peerId) const { return m_tls && m_tls->hasPeer(peerId); } QString SessionTransport::pinnedFingerprint(const QString &peerId) const { if (!m_tls) return {}; return m_tls->pinnedFingerprint(peerId); } QString SessionTransport::identityForAddress(const QString &address) const { return m_seats.value(address); } QHash SessionTransport::seats() const { return m_seats; } bool SessionTransport::forgetPin(const QString &peerId) { // Drop every address seat bound to the forgotten identity so a reconnect is // not routed as an already-known peer before it authenticates again. for (auto it = m_seats.begin(); it != m_seats.end();) { if (it.value() == peerId) it = m_seats.erase(it); else ++it; } return m_tls && m_tls->forgetPin(peerId); } QString SessionTransport::pinFile() const { return m_tls ? m_tls->pinFile() : QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QStringLiteral("/tofu-pins"); } void SessionTransport::seatFromVoice(const QString &address, const QString &peerId) { m_seats[address] = peerId; } void SessionTransport::setSeatLookup(std::function lookup) { m_seatLookup = std::move(lookup); } bool SessionTransport::canUse(const QString &targetAddress) const { if (!m_tls || !m_tls->isListening()) return false; const QString peerId = m_seats.value(targetAddress); // m_crypto is the owner's invariant and it made this channel in the first // place, so a live pipe is proof enough. return !peerId.isEmpty() && m_tls->hasPeer(peerId); } bool SessionTransport::sendFrame(const QString &targetAddress, const QJsonObject &payload) { return sendFrame(targetAddress, QCborValue::fromJsonValue(payload).toMap()); } bool SessionTransport::sendFrame(const QString &targetAddress, const QCborMap &payload) { if (!m_tls) return false; const QString peerId = m_seats.value(targetAddress); if (peerId.isEmpty() || !m_tls->hasPeer(peerId)) return false; const QByteArray frame = protocol::encodeFrame(payload); if (frame.isEmpty()) return false; m_tls->sendPeer(peerId, frame); return true; } bool SessionTransport::sendPeerFrame(const QString &peerId, const QJsonObject &payload) { if (!m_tls || !m_tls->hasPeer(peerId)) return false; const QByteArray frame = protocol::encodeFrame(payload); if (frame.isEmpty()) return false; m_tls->sendPeer(peerId, frame); return true; } void SessionTransport::dial(const QString &peerId, const QString &address, quint16 port) { // presence may only ask for a dial, never order one: whether the channel // is up, whether the identity is already pinned and whether an attempt is // already in flight are all the pin table's business. // The address is normalised before it becomes the dialing-set key: the // success/reject/failure paths all hand back a socket address, which may // carry the IPv4-mapped prefix or a zone id the caller's string lacked. const QString norm = normaliseAddress(QHostAddress(address)); if (norm.isEmpty()) return; // not an address at all if (!m_tls || !m_tls->isListening() || m_tls->hasPeer(peerId) || m_dialing.contains(norm)) return; // already dialed and waiting, or no channel to dial from m_dialing.insert(norm); if (!m_tls->connectTo(norm, port)) { m_dialing.remove(norm); } } void SessionTransport::onPeerAuthenticated(const QString &peerId, const QString &address) { m_dialing.remove(address); // The only identity→address association routing trusts, and it is filled // from the pinned certificate, never from anything a packet claimed. The // TLS layer already decided this peerId goes with this key. const QString norm = normaliseAddress(QHostAddress(address)); m_seats[norm] = peerId; Q_EMIT peerAuthenticated(peerId, norm); } void SessionTransport::onPeerRejected(const QString &peerId, const QString &address, const QByteArray &expectedPin, const QByteArray &actualFingerprint) { m_dialing.remove(normaliseAddress(QHostAddress(address))); Q_EMIT peerRejected(peerId, normaliseAddress(QHostAddress(address)), expectedPin, actualFingerprint); } void SessionTransport::onFrame(const QString &peerId, const QByteArray &rawFrame) { QString type; QCborMap raw; if (!protocol::decodeFrame(rawFrame, type, raw)) return; if (raw.value(QStringLiteral("type")).toString() != type) return; const QString host = m_seatLookup ? m_seatLookup(peerId) : QString(); if (host.isEmpty()) return; // an authenticated socket for whom we have no filed seat: no presence ever vouched for it // File chunks stay as CBOR byte strings: going through QJsonObject would // turn them into base64 text and back, wasting a third of the bandwidth. if (type == protocol::kMsgFileData) { const QString tid = raw.value(QStringLiteral("tid")).toString(); const int idx = int(raw.value(QStringLiteral("idx")).toInteger(-1)); const int total = int(raw.value(QStringLiteral("total")).toInteger(-1)); const QByteArray chunk = raw.value(QStringLiteral("data")).toByteArray(); Q_EMIT fileChunk(host, tid, idx, total, chunk); return; } QJsonObject msg = protocol::qjsonFromCbor(raw); // The TLS gate already settled identity and freshness: the payload is // cleartext the moment it leaves the pin. Mark it so the message decrypt // step downstream hands private chat to the UI unchanged. msg.insert(QStringLiteral("via_tls"), true); msg.insert(QStringLiteral("from_id"), peerId); msg.insert(QStringLiteral("from_ip"), host); if (type == protocol::kMsgFileAck) { Q_EMIT fileAck(msg.value(QStringLiteral("tid")).toString()); return; } if (type == protocol::kMsgAvatar) { Q_EMIT avatarFrame(host, msg); return; } if (type == protocol::kMsgBanner) { Q_EMIT bannerFrame(host, msg); return; } Q_EMIT frame(host, msg); } void SessionTransport::onDialFailure(const QString &address) { // an address we dialed went away; the next presence gets a retry. m_dialing.remove(normaliseAddress(QHostAddress(address))); } } // namespace koutnet