// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // KOutNet - Network & Audio core #include "NetworkManager.h" #include "../core/media/OutgoingFile.h" #include "../core/security/CryptoManager.h" #include "../core/security/IdentityCertificate.h" #include "AddressUtils.h" #include "Protocol.h" #include "StunClient.h" #include #include #include #include #include #include #include #include #include #include #include #include "koutnet_network_debug.h" #include #ifdef Q_OS_WIN // winsock2 must come first: iphlpapi.h reaches the SDK's net tables through it, // and parsing them without that context lost the IFTYPE. GetIpNetTable2 and // FreeMibTable are in iphlpapi.lib. // clang-format off #include #include #include // clang-format on #endif namespace koutnet { namespace { // How many announced transfers are remembered. Small enough that a peer // announcing metas and never sending chunks cannot grow it forever. constexpr int kMaxTrackedFileTransfers = 64; bool isLoopbackAddress(const QString &addr) { return addr == QLatin1String("127.0.0.1") || addr == QLatin1String("::1") || addr == QLatin1String("0.0.0.0") || addr == QLatin1String("::"); } bool isLinkLocal(const QString &addr) { return addr.startsWith(QLatin1String("169.254.")) || addr.startsWith(QLatin1String("fe80:")); } QString localIpFallback() { // Prefer an IPv4 address for the primary host ip: the LAN protocol's /24 // sweep and subnet broadcast are IPv4-only, and most LAN peers are IPv4. const auto addrs = QNetworkInterface::allAddresses(); for (const auto &addr : addrs) { if (addr.protocol() == QAbstractSocket::IPv4Protocol && !addr.isLoopback()) return normaliseAddress(addr); } // Fall back to any non-loopback address (IPv6 included). for (const auto &addr : addrs) { if (!addr.isLoopback()) return normaliseAddress(addr); } return QStringLiteral("127.0.0.1"); } QSet allLocalIpsFallback() { QSet result; const auto addrs = QNetworkInterface::allAddresses(); for (const auto &addr : addrs) { if (!addr.isLoopback()) result.insert(normaliseAddress(addr)); } return result; } } // namespace NetworkManager::NetworkManager(CryptoManager *crypto, QObject *parent) : ChatBackend(parent) , m_crypto(crypto) // The avatar exchange owns the bytes and the dedup, not the transport: it // writes through lambdas into the pin table and the channel. , m_avatar( [this](const QString &targetAddress, const QJsonObject &payload) { return m_session.sendFrame(targetAddress, payload); }, [this]() { const auto seats = m_session.seats().keys(); return QSet(seats.cbegin(), seats.cend()); }, [this](const QString &host, const QString &avatarSource) { m_presence.setAvatarSource(host, avatarSource); }, this) // The banner exchange is the avatar's sibling with the same three seams: // channel, seats, and the peer info map beside the avatar. , m_banner( [this](const QString &targetAddress, const QJsonObject &payload) { return m_session.sendFrame(targetAddress, payload); }, [this]() { const auto seats = m_session.seats().keys(); return QSet(seats.cbegin(), seats.cend()); }, [this](const QString &host, const QString &bannerSource) { m_presence.setBannerSource(host, bannerSource); }, this) { m_hostIp = localIpFallback(); // The presence service owns the beacon, guards and observed table; what it // names about this station is read back through this one seam. m_presence.setStation([this] { PresenceService::StationInfo info; info.primaryAddress = m_hostIp; info.localAddresses = m_localIps; info.tlsPort = m_session.active() ? m_session.listenPort() : 0; info.identityId = m_crypto ? m_crypto->ownIdentityId() : QString(); return info; }); m_presence.setDatagramSink([this](const QByteArray &data, const QHostAddress &to, quint16 port) { if (m_udp) m_udp->writeDatagram(data, to, port); }); m_presence.setLocalPort([this] { return m_udpPort; }); // The only identity→address association routing trusts, and it is filled // from the pinned certificate, never from anything a packet claimed. m_presence.setTrustedIdentity([this](const QString &address) { return m_session.identityForAddress(address); }); // A presence may only ask for a dial, never order one: channel state, pins // and in-flight attempts are all the pin table's business. m_presence.setAdvertisedTlsDial([this](const QString &peerId, const QString &address, quint16 port) { m_session.dial(peerId, address, port); }); // The e2e field only exists on a station with a crypto manager; with none // there is nothing a peer's presence could have vouched for. if (m_crypto) { m_presence.setE2eVouch([this](const QString &peerId) { return m_session.hasPeer(peerId); }); } connect(&m_presence, &PresenceService::userOnline, this, &NetworkManager::userOnline); connect(&m_presence, &PresenceService::peerRefreshed, this, &NetworkManager::peerRefreshed); connect(&m_presence, &PresenceService::userOffline, this, &NetworkManager::userOffline); // The address a channel frame is stamped with is the observed seat, not the // pin: the pin says which identity a socket is. An authenticated socket with // no filed seat is dropped before it routes. m_session.setSeatLookup([this](const QString &peerId) { return m_presence.keyForIdentity(peerId); }); // Decoded frames off an authenticated channel route through the router; the // running guard keeps a teardown from feeding the UI one last frame. connect(&m_session, &SessionTransport::frame, this, [this](const QString &host, const QJsonObject &msg) { if (!m_running) return; m_router.route(host, msg); }); connect(&m_session, &SessionTransport::fileChunk, this, [this](const QString &host, const QString &tid, int idx, int total, const QByteArray &chunk) { if (!m_running) return; onFileChunkFrom(host, tid, idx, total, chunk); }); connect(&m_session, &SessionTransport::fileAck, this, [this](const QString &tid) { if (!m_running) return; onFileAck(tid); }); connect(&m_session, &SessionTransport::avatarFrame, this, [this](const QString &host, const QJsonObject &msg) { if (!m_running) return; m_avatar.onFrame(host, msg); }); connect(&m_session, &SessionTransport::bannerFrame, this, [this](const QString &host, const QJsonObject &msg) { if (!m_running) return; m_banner.onFrame(host, msg); }); connect(&m_session, &SessionTransport::peerAuthenticated, this, &NetworkManager::onTlsPeerAuthenticated); connect(&m_session, &SessionTransport::peerRejected, this, &NetworkManager::onTlsPeerRejected); connect(&m_ipRefreshTimer, &QTimer::timeout, this, &NetworkManager::refreshLocalIps); m_ipRefreshTimer.start(30'000); // refresh local IPs every 30s (VPN adapters etc.) // The router answers presence, messages, call signalling and group invites // through seams, and relays its decided events onto this class's signals. m_router.setRateGate([this](const QString &host) { return !m_crypto || m_crypto->checkRate(host); }); m_router.setOwnNetwork([this] { return m_localIps.isEmpty() ? QSet{m_hostIp} : m_localIps; }); m_router.setPresenceSink([this](const QString &host, const QJsonObject &msg) { m_presence.acceptPresence(host, msg); }); m_router.setBusyReply([this](const QString &toIp) { sendCallBusy(toIp); }); m_router.setKeySeams( [this](const QString &gid) { return m_groupKeyStore.cipherKeyFor(gid); }, [this](const QString &gid) { return m_groupKeyStore.keyFor(gid); }, [this](const QString &gid, const QString &key) { m_groupKeyStore.setKey(gid, key); }); m_router.setCrypto( [this] { return m_crypto != nullptr; }, [this](const QString &cipher, const QString &key, const std::function &done) { m_crypto->decryptAsync(cipher, key, done); }); connect(&m_router, &FrameRouter::message, this, &NetworkManager::message); connect(&m_router, &FrameRouter::callRequest, this, &NetworkManager::callRequest); connect(&m_router, &FrameRouter::callAccepted, this, &NetworkManager::callAccepted); connect(&m_router, &FrameRouter::callRejected, this, &NetworkManager::callRejected); connect(&m_router, &FrameRouter::callEnded, this, &NetworkManager::callEnded); connect(&m_router, &FrameRouter::fileMeta, this, &NetworkManager::onFileMeta); connect(&m_router, &FrameRouter::groupInvite, this, &NetworkManager::groupInvite); connect(&m_router, &FrameRouter::groupKeyConfirmationRequired, this, &NetworkManager::groupKeyConfirmationRequired); connect(&m_router, &FrameRouter::typing, this, &NetworkManager::typing); // a landed picture is one more thing the window repaints; the peer info map // is kept in sync by the recorder lambda above. connect(&m_avatar, &AvatarExchange::peerAvatar, this, &NetworkManager::peerAvatar); // a landed banner is the same kind of repaint, one channel up the header. connect(&m_banner, &BannerExchange::peerBanner, this, &NetworkManager::peerBanner); // The voice transport talks through seams: pinned identity, the address an // identity is filed under, and the filing of one back after a voice // handshake. Its call-layer signals relay onto this class's own. m_voice.setPinGate([this](const QString &peerId) { return m_session.hasPeer(peerId); }); m_voice.setSeatLookup([this](const QString &peerId) { return m_presence.keyForIdentity(peerId); }); m_voice.setSeatFiler([this](const QString &filed, const QString &peerId) { m_session.seatFromVoice(filed, peerId); }); connect(&m_voice, &VoiceTransport::voiceConnected, this, &NetworkManager::voiceConnected); connect(&m_voice, &VoiceTransport::voiceDisconnected, this, &NetworkManager::voiceDisconnected); connect(&m_voice, &VoiceTransport::callEnded, this, &NetworkManager::callEnded); connect(&m_voice, &VoiceTransport::media, this, &NetworkManager::voiceDataFrom); connect(&m_voice, &VoiceTransport::errorOccurred, this, &NetworkManager::errorOccurred); // The outgoing file transfer rides the pinned channel: whether the peer has // one, and where each frame goes. Identity and address are read fresh on // every send, since the primary address can change under a session. m_fileSender.setRouter( [this](const QString &toIp) { return canUseTls(toIp); }, [this](const QString &toIp, const QCborMap &frame) { sendPeerFrame(toIp, frame); }); m_fileSender.setLocalIdentity( [this] { return m_crypto ? m_crypto->ownIdentityId() : QString(); }, [this] { return m_hostIp; }); connect(&m_fileSender, &FileTransferSender::errorOccurred, this, &NetworkManager::errorOccurred); } NetworkManager::~NetworkManager() { stop(); } void NetworkManager::setActiveCalls(const QSet &ips) { m_router.setActiveCalls(ips); } void NetworkManager::setStaticPeers(const QStringList &ips) { m_presence.setStaticPeers(ips); } void NetworkManager::setProfile(const QString &handle, const QString &displayName, const QString &bio, const QString &revision) { // trimming, compare and the immediate re-beacon are the service's. m_presence.setProfile(handle, displayName, bio, revision); } void NetworkManager::setStatus(int presence, const QString &statusEmoji) { m_presence.setStatus(presence, statusEmoji); } void NetworkManager::setAvatar(const QString &avatarPath) { // comparison, hashing and push are all the exchange's business now. m_avatar.setAvatar(avatarPath); } void NetworkManager::setBanner(const QString &bannerPath) { m_banner.setBanner(bannerPath); } void NetworkManager::setGroupPassphrase(const QString &passphrase) { m_groupKeyStore.setPassphrase(passphrase); } // One key per group, so opening one group's traffic says nothing about the // next; the store below owns the cache and the SecretStore persistence. void NetworkManager::setGroupKey(const QString &gid, const QString &key) { m_groupKeyStore.setKey(gid, key); } void NetworkManager::removeGroupKey(const QString &gid) { m_groupKeyStore.setKey(gid, QString()); } void NetworkManager::setConnectionMode(ConnectionMode mode) { m_mode = mode; if (!m_running) return; // applied on next start() } void NetworkManager::setStunServer(const QString &host, quint16 port) { m_stun.setServer(host, port); // the new server is read on the next refresh(); a flight already in the air, // and the reflexive address it earned, outlive this call. Dropping a live // client would tear down a call room for nothing. } bool NetworkManager::modeAvailable(int mode) const { switch (static_cast(mode)) { case ConnectionMode::LanOrVpn: return true; case ConnectionMode::KServer: // KServer mode is Matrix. The Matrix transport lives in matrix/ and // registers with the chat transport registry on its own; this class // answers for LAN only. return true; } // Telegram is a separate transport/backend (not a NetworkManager mode), but // the UI may use this value for rail selection. if (mode == 2) return true; return false; } void NetworkManager::refreshLocalIps() { m_localIps = allLocalIpsFallback(); m_localIps.insert(m_hostIp); const QString newPrimary = localIpFallback(); if (newPrimary != m_hostIp) { m_hostIp = newPrimary; Q_EMIT hostIpChanged(); } } bool NetworkManager::start() { const quint16 udpPort = protocol::kUdpPortDefault; const quint16 tcpPort = protocol::kTcpPortDefault; m_udp = new QUdpSocket(this); // an IPv4 socket on purpose: joining the mDNS group on a dual-stack bind is // refused, so AnyIPv4 is the only bind the sweep hears v4 replies on. bool bound = m_udp->bind(QHostAddress::AnyIPv4, udpPort, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint); if (!bound) { bound = m_udp->bind(QHostAddress::AnyIPv4, udpPort + 1, QUdpSocket::ShareAddress | QUdpSocket::ReuseAddressHint); } if (!bound) { // int(): KLocalizedString has no quint16 substitution overload. Q_EMIT errorOccurred(i18nc("@info:status %1 is a port number", "UDP bind failed on port %1.", int(udpPort))); return false; } m_udpPort = m_udp->localPort(); connect(m_udp, &QUdpSocket::readyRead, this, &NetworkManager::onUdpReadyRead); // mDNS multicast over 224.0.0.251, v4 of course m_udp->joinMulticastGroup(QHostAddress(QStringLiteral("224.0.0.251"))); // The voice media plane binds its own listener (its accepted descriptors // become plain or TLS sockets depending on the seam state pushed below). if (!m_voice.listen(tcpPort)) { // do not leave a bound UDP socket behind for the next attempt if (m_udp) { m_udp->close(); m_udp->deleteLater(); m_udp = nullptr; m_udpPort = 0; } return false; // VoiceTransport already reported both attempts } // The TLS channel is THE transport now: sessions, chats, groups, calls and // files all ride length-prefixed TLS 1.3 frames, and its TOFU pins decide // who may open one. It is built from the identity seed, so both sides pin // to their KOutNet identity, and presence announces its port. A first run // whose store failed has no keys and announces no TLS port. m_session.start(m_crypto); // voice media rides the identity-made socket only when that channel is // alive: the accept side then gates on pins the chat channel already holds. updateVoiceTransport(); m_running = true; // the mode is applied by main.cpp from AppSettings before start() is called. m_localIps = allLocalIpsFallback(); m_localIps.insert(m_hostIp); // Presence: rehydrates its nonce counter, starts the beacon on the // aggressive interval and fires the first one immediately. m_presence.start(); // A STUN server is where the outside world finds this station, which is // Matrix-call furniture: only KServer mode publishes a reflexive candidate, // so LAN-only builds need not contact a public server on every start. // Offline or missing, calls simply reach LAN/VPN addresses. if (m_mode == ConnectionMode::KServer) m_stun.refresh(); QTimer::singleShot(3000, this, &NetworkManager::scanArpTable); return true; } void NetworkManager::stop() { m_running = false; m_presence.stop(); // The voice plane tears its sockets, dials, watchdogs and listener down as // one, disconnecting each before closing so no teardown handler fires. The // relays to this class's signals stay for the next start(). m_voice.stop(); if (m_udp) { m_udp->close(); m_udp->deleteLater(); m_udp = nullptr; m_udpPort = 0; } m_session.stop(); } void NetworkManager::scanArpTable() { // Send presence packets to neighbours in the system ARP/NDP cache. if (!m_running) return; QSet ips; #ifdef Q_OS_LINUX // IPv4 ARP table. QFile arpFile(QStringLiteral("/proc/net/arp")); if (arpFile.open(QIODevice::ReadOnly | QIODevice::Text)) { const auto lines = QString::fromUtf8(arpFile.readAll()).split(QLatin1Char('\n')); for (int i = 1; i < lines.size(); ++i) { const auto parts = lines[i].split(QLatin1Char(' '), Qt::SkipEmptyParts); if (parts.size() >= 4 && parts[2] != QLatin1String("0x0")) ips.insert(parts[0]); } } // IPv6 neighbour table. QFile ndpFile(QStringLiteral("/proc/net/neighbour")); if (ndpFile.open(QIODevice::ReadOnly | QIODevice::Text)) { const auto lines = QString::fromUtf8(ndpFile.readAll()).split(QLatin1Char('\n')); for (int i = 1; i < lines.size(); ++i) { const auto parts = lines[i].split(QLatin1Char(' '), Qt::SkipEmptyParts); // Column 0 is IP, column 3 is state (0x2 = REACHABLE, 0x4 = STALE, etc.) if (parts.size() >= 4 && parts[3] != QLatin1String("0x0")) ips.insert(parts[0]); } } #elif defined(Q_OS_WIN) // AF_UNSPEC includes both IPv4 and IPv6 neighbours. PMIB_IPNET_TABLE2 netTable = nullptr; DWORD result = GetIpNetTable2(AF_UNSPEC, &netTable); if (result == NO_ERROR && netTable) { for (ULONG i = 0; i < netTable->NumEntries; ++i) { const auto &row = netTable->Table[i]; if (row.State == NlnsUnreachable || row.State == NlnsIncomplete) continue; QHostAddress addr; if (row.Address.si_family == AF_INET) { addr.setAddress(ntohl(row.Address.Ipv4.sin_addr.s_addr)); } else if (row.Address.si_family == AF_INET6) { Q_IPV6ADDR ipv6; memcpy(&ipv6, row.Address.Ipv6.sin6_addr.s6_addr, 16); addr.setAddress(ipv6); } if (!addr.isNull()) ips.insert(addr.toString()); } FreeMibTable(netTable); } #endif if (ips.isEmpty()) { QTimer::singleShot(60'000, this, &NetworkManager::scanArpTable); return; } const QByteArray data = m_presence.beaconFrame(); int sent = 0; for (const auto &ip : std::as_const(ips)) { if (ip == m_hostIp || isLinkLocal(ip) || isLoopbackAddress(ip)) continue; m_udp->writeDatagram(data, QHostAddress(ip), protocol::kUdpPortDefault); if (m_udpPort != protocol::kUdpPortDefault) m_udp->writeDatagram(data, QHostAddress(ip), m_udpPort); ++sent; } if (sent > 0) qCDebug(KOUTNET_LOG_NETWORK) << "ARP/NDP scan: pinged" << sent << "neighbour(s)"; QTimer::singleShot(60'000, this, &NetworkManager::scanArpTable); } void NetworkManager::onUdpReadyRead() { while (m_udp && m_udp->hasPendingDatagrams()) { const QNetworkDatagram dg = m_udp->receiveDatagram(); const QString host = normaliseAddress(dg.senderAddress()); handleDatagram(host, dg.data()); } } // UDP is discovery only: an incoming datagram is expected to be a presence // beacon, and nothing else is trusted from it. Chats, groups, calls and files // travel TLS frames on the pinned channel. void NetworkManager::handleDatagram(const QString &host, const QByteArray &data) { // Attacker-supplied bytes: decode defensively. QString type; QCborMap map; if (!protocol::decodeFrame(data, type, map)) { // Keep invalid datagrams in the debug log rather than the UI. qCDebug(KOUTNET_LOG_NETWORK) << "unreadable datagram from" << host << "size" << data.size(); return; } // the header type is the one every branch keys on, so the payload's // "type" field must match it. const QString payloadType = map.value(QStringLiteral("type")).toString(); if (payloadType != type) { qCDebug(KOUTNET_LOG_NETWORK) << "mismatched frame from" << host << "header" << type << "payload" << payloadType; return; } if (type != protocol::kMsgPresence) { // Only presence is accepted over unauthenticated UDP. qCDebug(KOUTNET_LOG_NETWORK) << "dropping datagram" << type << "from" << host << "- traffic rides the TLS channel"; return; } dispatch(host, protocol::qjsonFromCbor(map)); } void NetworkManager::onFileMeta(const QString &host, const QJsonObject &meta) { const QString tid = meta.value(QStringLiteral("tid")).toString(); if (!tid.isEmpty()) { // Claim the tid for the peer that announced it. A tid nobody announced is // not tracked: a chunk with no meta has nothing to reassemble into, and // the first sender must not win someone else's transfer. auto it = m_incomingTransfers.find(tid); if (it == m_incomingTransfers.end()) { if (m_incomingTransfers.size() >= kMaxTrackedFileTransfers) return; // table full: the offer is simply not honoured it = m_incomingTransfers.insert(tid, IncomingTransfer()); it->fromIp = host; it->offered = true; } else if (it->offered && it->fromIp != host) { // the same id offered by somebody else: the first announcement owns it return; } } Q_EMIT fileMeta(host, meta); } void NetworkManager::onFileChunkFrom(const QString &host, const QString &tid, int idx, int total, const QByteArray &chunk) { if (tid.isEmpty() || total <= 0 || idx < 0 || idx >= total) return; const auto known = m_incomingTransfers.constFind(tid); if (known == m_incomingTransfers.constEnd()) return; // no meta announced this transfer - nothing to reassemble into IncomingTransfer &inc = m_incomingTransfers[tid]; // Before the emit, not after: once the chunk is handed to the reassembler it // is already part of the file, so a later sender check protects nothing. if (inc.fromIp != host) { qCDebug(KOUTNET_LOG_NETWORK) << "chunk for transfer" << tid << "from" << host << "which does not own it - dropped"; return; } if (inc.total == 0) inc.total = total; if (inc.total != total) { m_incomingTransfers.remove(tid); return; } Q_EMIT fileChunkBytes(host, tid, idx, total, chunk); inc.received.insert(idx); if (inc.received.size() >= inc.total) { QJsonObject ack; ack[QStringLiteral("type")] = protocol::kMsgFileAck; ack[QStringLiteral("tid")] = tid; if (canUseTls(inc.fromIp)) sendPeerFrame(inc.fromIp, ack); m_incomingTransfers.remove(tid); } } void NetworkManager::onFileAck(const QString &tid) { // file_ack confirms frame receipt, not successful validation or saving. // The sender has no retransmission state to release. Q_UNUSED(tid) } void NetworkManager::dispatch(const QString &host, QJsonObject msg) { m_router.route(host, std::move(msg)); } void NetworkManager::onTlsPeerAuthenticated(const QString &peerId, const QString &address) { // The session transport already filed the pin: the only identity->address // association routing trusts, taken from the certificate. // Correct a seat an unsigned presence id planted: if this identity // authenticated from an address filed under another id, give it to the // certificate's holder. m_presence.authenticatedSeat(peerId, address); // Channel-up is the one moment a peer can miss our picture, so the avatar // exchange pushes it right here (deduped by its own per-seat sha table). m_avatar.onPeerAuthenticated(address); // the banner rides the same moment: a peer that has never seen it stays // unadorned until its next change otherwise. m_banner.onPeerAuthenticated(address); Q_EMIT tlsPeerAuthenticated(peerId, address); } void NetworkManager::onTlsPeerRejected(const QString &peerId, const QString &address, const QByteArray &expectedPin, const QByteArray &actualFingerprint) { // A socket wearing the peer's identity id presented a different key: an // impostor or a reset store. The TLS layer refused it before traffic moved. const QString expected = QString::fromLatin1(expectedPin.toHex()); const QString actual = QString::fromLatin1(actualFingerprint.toHex()); Q_EMIT errorOccurred( i18nc("@info:status %1 is an identity id, %2 a host address, %3 the previously pinned fingerprint, %4 the new fingerprint, %5 a file path", "Rejected a connection claiming to be %1 from %2: its TLS key changed (pinned %3, now %4). " "Only if you verified this change, remove the line for %1 in %5 or use the trust reset action, then reconnect.", peerId, address, expected, actual, m_session.pinFile())); } bool NetworkManager::forgetTrustedPeer(const QString &peerId) { if (peerId.isEmpty()) return false; return m_session.forgetPin(peerId); } bool NetworkManager::canUseTls(const QString &targetAddress) const { return m_session.canUse(targetAddress); } bool NetworkManager::sendPeerFrame(const QString &targetAddress, const QJsonObject &payload) { return m_session.sendFrame(targetAddress, payload); } bool NetworkManager::sendPeerFrame(const QString &targetAddress, const QCborMap &payload) { return m_session.sendFrame(targetAddress, payload); } void NetworkManager::updateVoiceTransport() { // voice media rides the identity-made socket only when the chat channel is // alive; the accept side gates on pins it already holds. The identity // certificate itself stays inside the session transport for TLS handshakes. const IdentityCertificate &ident = m_session.identity(); m_voice.setCredentials(ident, ident.isValid() && m_session.active()); } QVector NetworkManager::deliveryAddresses(const QString &toIp) const { // One peer, one pinned channel: the TLS channel replaced the old sweep of // every address a datagram pair once answered on. QVector targets; if (!toIp.isEmpty()) targets.append(toIp); return targets; } QStringList NetworkManager::addressesForPeer(const QString &peerId) const { QStringList out; if (peerId.isEmpty()) return out; const auto seats = m_session.seats(); for (auto it = seats.cbegin(); it != seats.cend(); ++it) { if (it.value() == peerId) out.append(it.key()); } // Newest first, so the top one is where a message would be sent. The stamp // is presence's local observation, not anything the peer claimed. std::sort(out.begin(), out.end(), [this](const QString &a, const QString &b) { const double ta = m_presence.lastSeen(a); const double tb = m_presence.lastSeen(b); return ta > tb; }); return out; } bool NetworkManager::sendPrivate(const QString &text, const QString &toIp) { if (!canUseTls(toIp)) { Q_EMIT errorOccurred(i18nc("@info:status", "No live TLS channel to this peer - message not sent.")); return false; } // The pinned channel already authenticated the other end and TLS carried // this plaintext over a fresh 1.3 session, so the body rides untouched. QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgPrivate; payload[QStringLiteral("to")] = toIp; payload[QStringLiteral("from_ip")] = m_hostIp; payload[QStringLiteral("from_id")] = m_crypto ? m_crypto->ownIdentityId() : QString(); payload[QStringLiteral("text")] = text; sendPeerFrame(toIp, payload); return true; } void NetworkManager::sendGroupMessage(const QString &gid, const QString &text, const QVector &members) { // Mirror the receive path: a pinned per-group key seals the traffic, and a // group without one falls back to the shared passphrase. Without either // there is nothing safe to send in the clear. QString passphrase = m_groupKeyStore.cipherKeyFor(gid); if (!m_crypto || passphrase.isEmpty()) { Q_EMIT errorOccurred(i18nc("@info:status", "No group key and no shared passphrase - refusing to send in the clear.")); return; } const QString cipherText = m_crypto->encrypt(text, passphrase); if (cipherText.isEmpty() || cipherText == text) { // encrypt() returns plaintext on failure; sending that would leak the // message the user thinks is protected. Q_EMIT errorOccurred(i18nc("@info:status", "Failed to encrypt the group message - not sent.")); return; } QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgGroup; payload[QStringLiteral("gid")] = gid; payload[QStringLiteral("text")] = cipherText; payload[QStringLiteral("from_ip")] = m_hostIp; payload[QStringLiteral("from_id")] = m_crypto ? m_crypto->ownIdentityId() : QString(); for (const auto &ip : members) { if (ip != m_hostIp && canUseTls(ip)) sendPeerFrame(ip, payload); } } void NetworkManager::sendTyping(const QString &chatId, const QString &targetIp) { if (!canUseTls(targetIp)) return; // typing is cosmetic; a missing channel is not worth an error QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgTyping; payload[QStringLiteral("chat_id")] = chatId; payload[QStringLiteral("from_id")] = m_crypto ? m_crypto->ownIdentityId() : QString(); sendPeerFrame(targetIp, payload); } void NetworkManager::sendCallRequest(const QString &toIp) { // the accept/reject/busy/end for this ring only counts against a request // that was actually sent. if (!canUseTls(toIp)) { Q_EMIT errorOccurred(i18nc("@info:status", "No live TLS channel to this peer - call not placed.")); return; } m_router.openRequest(toIp); QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgCallReq; payload[QStringLiteral("from_id")] = m_crypto ? m_crypto->ownIdentityId() : QString(); sendPeerFrame(toIp, payload); } void NetworkManager::sendCallAccept(const QString &toIp) { m_router.resolveRing(toIp); // the ring is resolved either way QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgCallAccept; payload[QStringLiteral("from_id")] = m_crypto ? m_crypto->ownIdentityId() : QString(); if (canUseTls(toIp)) sendPeerFrame(toIp, payload); connectVoice(toIp); } void NetworkManager::sendCallReject(const QString &toIp) { m_router.resolveRing(toIp); QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgCallReject; payload[QStringLiteral("from_id")] = m_crypto ? m_crypto->ownIdentityId() : QString(); if (canUseTls(toIp)) sendPeerFrame(toIp, payload); } void NetworkManager::sendCallBusy(const QString &toIp) { QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgCallBusy; payload[QStringLiteral("from_id")] = m_crypto ? m_crypto->ownIdentityId() : QString(); if (canUseTls(toIp)) sendPeerFrame(toIp, payload); } void NetworkManager::sendCallEnd(const QString &toIp) { // the remote's end of the ring no longer needs an answer. m_router.cancelRequest(toIp); m_router.resolveRing(toIp); QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgCallEnd; payload[QStringLiteral("from_id")] = m_crypto ? m_crypto->ownIdentityId() : QString(); if (canUseTls(toIp)) sendPeerFrame(toIp, payload); } void NetworkManager::sendReaction(const QString &chatId, const QVariant &identifier, const QString &emoji, bool added) { if (!canUseTls(chatId)) return; // emoji on a stalled channel is not worth an error const double ts = identifier.toDouble(); QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgReaction; payload[QStringLiteral("from_ip")] = m_hostIp; payload[QStringLiteral("chat_id")] = chatId; payload[QStringLiteral("msg_ts")] = ts; payload[QStringLiteral("emoji")] = emoji; payload[QStringLiteral("added")] = added; // the channel keeps the emoji off the wire in the clear; the peer's pin // guarantees who reads it. payload[QStringLiteral("from_id")] = m_crypto ? m_crypto->ownIdentityId() : QString(); sendPeerFrame(chatId, payload); } bool NetworkManager::sendMessageEdit(const QString &toIp, const QString &chatId, const QVariant &identifier, const QString &newText) { if (!canUseTls(toIp)) { Q_EMIT errorOccurred(i18nc("@info:status", "No live TLS channel to this peer - edit not sent.")); return false; } const double ts = identifier.toDouble(); QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgEdit; payload[QStringLiteral("from_ip")] = m_hostIp; payload[QStringLiteral("chat_id")] = chatId; payload[QStringLiteral("msg_ts")] = ts; payload[QStringLiteral("new_text")] = newText; payload[QStringLiteral("from_id")] = m_crypto ? m_crypto->ownIdentityId() : QString(); // like sendPrivate: the transport is the cipher here. return sendPeerFrame(toIp, payload); } bool NetworkManager::sendMessageDelete(const QString &toIp, const QString &chatId, const QVariant &identifier) { if (!canUseTls(toIp)) return false; const double ts = identifier.toDouble(); QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgDelete; payload[QStringLiteral("from_ip")] = m_hostIp; payload[QStringLiteral("chat_id")] = chatId; payload[QStringLiteral("msg_ts")] = ts; payload[QStringLiteral("from_id")] = m_crypto ? m_crypto->ownIdentityId() : QString(); return sendPeerFrame(toIp, payload); } void NetworkManager::sendReadReceipt(const QString &toIp, const QString &chatId, double upToTs) { if (!canUseTls(toIp)) return; QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgRead; payload[QStringLiteral("from_ip")] = m_hostIp; payload[QStringLiteral("chat_id")] = chatId; payload[QStringLiteral("from_id")] = m_crypto ? m_crypto->ownIdentityId() : QString(); // The position the receipt claims: everything of ours up to this stamp was // on the reader's screen. Zero still means "read the chat" to an old peer. if (upToTs > 0.0) payload[QStringLiteral("up_to_ts")] = upToTs; // the channel reaches the one peer the receipt is for. sendPeerFrame(toIp, payload); } void NetworkManager::sendGroupInvite(const QString &gid, const QString &gname, const QString &toIp) { if (!canUseTls(toIp)) return; // no channel, no inviting - the invite would never arrive anyway QJsonObject payload; payload[QStringLiteral("type")] = protocol::kMsgGroupInv; payload[QStringLiteral("gid")] = gid; payload[QStringLiteral("gname")] = gname; payload[QStringLiteral("from_ip")] = m_hostIp; payload[QStringLiteral("from_id")] = m_crypto ? m_crypto->ownIdentityId() : QString(); // Inviting someone is what gives a new group its key: one is created when // none is pinned and rides the invitee's channel, whose pin proved the peer. const QString key = m_groupKeyStore.ensureKey(gid); payload[QStringLiteral("key")] = key; sendPeerFrame(toIp, payload); } bool NetworkManager::sendFileInternal(const QString &toIp, const QString &filePath, const QByteArray &rawBytes, const QString &filename) { // the file half and the bytes half both live in the sender; it reads fresh // identity and address through the seams the constructor pushed in. if (!rawBytes.isEmpty()) return m_fileSender.sendBytes(toIp, rawBytes, filename); return m_fileSender.send(toIp, filePath); } QString NetworkManager::stunReflexive() const { return m_stun.reflexiveAddress(); } bool NetworkManager::connectVoice(const QString &ip) { return dialVoiceCandidates(ip, QStringList{ip}); } bool NetworkManager::dialVoiceCandidates(const QString &peer, const QStringList &candidates) { // "Returns straight away": a channel already up or an attempt already in // flight reads as an in-flight attempt, so the caller never double-dials. if (m_voice.isCallUp(peer)) return true; if (m_voice.isDialing(peer)) return true; return m_voice.connectTo(peer, candidates); } bool NetworkManager::sendVoice(const QString &peer, const QByteArray &data) { // same cap the receiver enforces. return m_voice.sendMedia(peer, data); } void NetworkManager::disconnectVoice(const QString &peer) { m_voice.hangUp(peer); } // LAN chat id is a datagram destination, not a room. chatid::Transport NetworkManager::transport() const { return chatid::Transport::Lan; } bool NetworkManager::canHandle(const QString &chatId) const { // everything without a foreign prefix is ours. return chatid::transportOf(chatId) == chatid::Transport::Lan; } bool NetworkManager::serverOwnsTimeline(const QString &) const { return false; } bool NetworkManager::hasRooms(const QString &) const { return false; } bool NetworkManager::supportsCalls(const QString &) const { return true; } bool NetworkManager::supportsTyping(const QString &) const { return true; } bool NetworkManager::supportsEdits(const QString &) const { return true; } bool NetworkManager::supportsReactions(const QString &) const { return true; } bool NetworkManager::sendText(const QString &chatId, const QString &text) { if (chatId.isEmpty()) return false; return sendPrivate(text, chatId); } bool NetworkManager::sendFile(const QString &chatId, const QString &localFilePath) { if (chatId.isEmpty()) return false; // A picture goes onto the wire shrunk, the same as over Matrix: the frame is // built in memory, and a twelve-megapixel photograph is otherwise copied // out in full. A file that cannot be shrunk is sent as it is. const QString path = localFilePath.startsWith(QStringLiteral("file://")) ? QUrl(localFilePath).toLocalFile() : localFilePath; return sendFileInternal(chatId, OutgoingFile::preparedPath(path), QByteArray(), QStringLiteral("file")); } void NetworkManager::markRead(const QString &chatId) { // the chat id of a LAN chat is the peer address. sendReadReceipt(chatId, QStringLiteral("dm")); } void NetworkManager::sendTyping(const QString &chatId) { NetworkManager::sendTyping(chatId, chatId); } bool NetworkManager::leaveChat(const QString &) { return false; // there is nothing to leave: a LAN chat is an address } bool NetworkManager::sendEdit(const QString &chatId, const QVariant &identifier, const QString &newText) { // A LAN chat's identifier is its address, so both ends are the same string. return sendMessageEdit(chatId, chatId, identifier, newText); } bool NetworkManager::sendDelete(const QString &chatId, const QVariant &identifier) { return sendMessageDelete(chatId, chatId, identifier); } QVariantMap NetworkManager::roomInfo(const QString &) const { return {}; } QVariantList NetworkManager::roomMembers(const QString &) const { return {}; } QVariantMap NetworkManager::memberInfo(const QString &, const QString &) const { return {}; } } // namespace koutnet