// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // KOutNet - Network & Audio core #pragma once #include #include #include #include #include #include #include #include #include #include "Protocol.h" #include "core/backend/ChatBackend.h" #include "network/AvatarExchange.h" #include "network/BannerExchange.h" #include "network/FileTransferSender.h" #include "network/FrameRouter.h" #include "network/GroupKeyStore.h" #include "network/PresenceService.h" #include "network/SessionTransport.h" #include "network/StunClient.h" #include "network/VoiceTransport.h" namespace koutnet { class CryptoManager; class AppSettings; // unit tests reach into the peer/unce plumbing (m_presence) and the datagram // decoder, so the harness class is a friend; the forward declaration is enough. class NetworkManagerTest; class NetworkManager : public ChatBackend { Q_OBJECT // the primary local address changes under us when a VPN adapter comes up, // so the status bar needs a notify rather than a one-shot read. Q_PROPERTY(QString hostIp READ hostIp NOTIFY hostIpChanged) public: // the LAN/VPN transport, registered with ChatBackendRegistry in main.cpp. // Everything a chat can ask goes through the registry; the // datagram calls below are this transport's own vocabulary (calls, // receipts, edits), used by Main.qml only where the backend is this one. // LanOrVpn: broadcast, mDNS and ARP discovery, no server. KServer: a // K-Server, wherever it is. A relay mode used to sit here too; it is gone, // and there is no relay host to ship. Three K-Server entries once sat // here - self-hosted, somebody else's and the maintainer's VDS - with one // protocol behind them; only the address differed, and that is kServerHost. // The values are persisted as ints, so reordering them moves everyone to // a different mode; see AppSettings::migrateConnectionModes(). enum class ConnectionMode { LanOrVpn = 0, KServer = 1, }; Q_ENUM(ConnectionMode) // CryptoManager is owned by the application and injected here, never created // internally - identity keys and session state must stay single-sourced. explicit NetworkManager(CryptoManager *crypto, QObject *parent = nullptr); ~NetworkManager() override; // Aggressive while no peers are known, then backs off: discovery has already // worked, and the noise costs battery. The presence side of these intervals // lives on PresenceService. Max addresses per message: four covers LAN + VPN. static constexpr int kMaxDeliveryAddresses = 4; bool start(); void stop(); Q_INVOKABLE bool isRunning() const { return m_running; } // whether a verified TLS channel to this identity id is up. The id is the // one its certificate's CN carries, the same string the handshake signs // with; presence dials, and the TOFU pins gate who may open. Q_INVOKABLE bool hasTlsPeer(const QString &peerId) const { return m_session.hasPeer(peerId); } // whether a pinned TLS channel to the identity owning this address is up: // what the peer details page asks to answer "is this conversation protected". Q_INVOKABLE bool hasTlsPeerByAddress(const QString &address) const { const QString peerId = m_session.identityForAddress(address); return !peerId.isEmpty() && hasTlsPeer(peerId); } // the identity the TLS channel authenticated from this address, empty until // one passes the pin gate. Only from the certificate, never from a packet. Q_INVOKABLE QString peerIdForAddress(const QString &address) const { return m_session.identityForAddress(address); } // the pinned identity fingerprint (SPKI SHA-256, hex) behind this address, // empty when none is pinned - what two people read to each other. Q_INVOKABLE QString fingerprintForAddress(const QString &address) const { return m_session.pinnedFingerprint(m_session.identityForAddress(address)); } // every address this identity has authenticated from, newest first, for the // peer details page. What a peer advertises is not in here. Q_INVOKABLE QStringList addressesForPeer(const QString &peerId) const; // Forget a pinned peer identity so the next contact is trusted on first use // again. Use this only after confirming the key change out of band. Q_INVOKABLE bool forgetTrustedPeer(const QString &peerId); Q_INVOKABLE QString trustPinFile() const { return m_session.pinFile(); } Q_INVOKABLE QString hostIp() const { return m_hostIp; } quint16 udpPort() const { return m_udpPort; } quint16 tcpPort() const { return m_voice.port(); } // The observed peer table and its staleness live in the presence service; // this is the read the UI and the other transport layers query it through. const QMap &peers() const { return m_presence.peers(); } // Newest observed first, never more than kMaxDeliveryAddresses. Public // so a test can read the cap back. QVector deliveryAddresses(const QString &toIp) const; // Safe before start(), or while running, where it raises or drops the tunnel. Q_INVOKABLE void setConnectionMode(ConnectionMode mode); Q_INVOKABLE ConnectionMode connectionMode() const { return m_mode; } // STUN is only consulted in KServer mode (see start()); main.cpp feeds the // configured server in here, the tests keep the Google default. void setStunServer(const QString &host, quint16 port); // whether a mode has anything behind it. The settings page asks rather than // hardcoding it, so landing a K-Server changes this function and nothing in QML. Q_INVOKABLE bool modeAvailable(int mode) const; // revision is a short digest of everything in the profile, images included, so a // peer can tell it needs to re-fetch without being sent the files. Q_INVOKABLE void setProfile(const QString &handle, const QString &displayName, const QString &bio, const QString &revision); // The local file this station's avatar is read from, "" meaning none. // AvatarExchange pushes it to every TLS-authenticated peer and dedups by // sha; main.cpp feeds it from AppSettings and re-fires on avatarPathChanged. Q_INVOKABLE void setAvatar(const QString &avatarPath); // The local file this station's banner is read from, "" meaning none. // BannerExchange does the same over the same seams; main.cpp feeds it from // AppSettings and re-fires on bannerPathChanged. Q_INVOKABLE void setBanner(const QString &bannerPath); // what the user says they are, and the one emoji they say it with. Kept out // of the profile digest: going busy must not ask peers to refetch. Q_INVOKABLE void setStatus(int presence, const QString &statusEmoji); // Broadcast has no single peer to hold an ECDH session with, so a passphrase // everyone knows is the only thing that can protect it. Empty means cleartext. void setGroupPassphrase(const QString &passphrase); // one key per group, so one group's traffic says nothing about the next. // A key is made only when it will be handed out - the LAN path makes one on // the first invite and seals it under the session with the invitee. A group // predating per-group keys keeps the shared passphrase; both directions fall // back the same way: pinned key, shared passphrase, never the clear. An // invite proposing a different key for a pinned group is refused and raises // groupKeyConfirmationRequired. Q_INVOKABLE void setGroupKey(const QString &gid, const QString &key); Q_INVOKABLE void removeGroupKey(const QString &gid); // Addresses to unicast presence to every cycle until they answer. main.cpp // feeds it from AppSettings; the settings page applies edits the same way. Q_INVOKABLE void setStaticPeers(const QStringList &ips); // Split out of onUdpReadyRead() because everything below this line is // attacker-controlled, and a test needing two live UDP sockets never gets written. void handleDatagram(const QString &host, const QByteArray &data); Q_INVOKABLE bool sendPrivate(const QString &text, const QString &toIp); Q_INVOKABLE void sendGroupMessage(const QString &gid, const QString &text, const QVector &members); Q_INVOKABLE void sendTyping(const QString &chatId, const QString &targetIp); Q_INVOKABLE void sendCallRequest(const QString &toIp); Q_INVOKABLE void sendCallAccept(const QString &toIp); Q_INVOKABLE void sendCallReject(const QString &toIp); Q_INVOKABLE void sendCallEnd(const QString &toIp); Q_INVOKABLE void sendCallBusy(const QString &toIp); // the peers currently in a live call with us, either direction. main.cpp // keeps it in sync with VoiceCallManager::activeCalls(), and the call // signalling gates on it: accept only for a call we asked for, end only for // a live call or ring, busy for a request while one is live. void setActiveCalls(const QSet &ips); Q_INVOKABLE bool sendMessageEdit(const QString &toIp, const QString &chatId, const QVariant &identifier, const QString &newText); Q_INVOKABLE bool sendMessageDelete(const QString &toIp, const QString &chatId, const QVariant &identifier); Q_INVOKABLE void sendReadReceipt(const QString &toIp, const QString &chatId, double upToTs = 0.0); Q_INVOKABLE void sendGroupInvite(const QString &gid, const QString &gname, const QString &toIp); bool sendFileInternal(const QString &toIp, const QString &filePath, const QByteArray &rawBytes = {}, const QString &filename = QStringLiteral("file")); // ChatBackend interface, registered in main.cpp; the window routes every // chat action through chatTransport and reads these flags for LAN furniture. chatid::Transport transport() const override; bool canHandle(const QString &chatId) const override; bool serverOwnsTimeline(const QString &chatId) const override; bool hasRooms(const QString &chatId) const override; bool supportsCalls(const QString &chatId) const override; bool supportsTyping(const QString &chatId) const override; bool supportsEdits(const QString &chatId) const override; bool supportsReactions(const QString &chatId) const override; bool sendText(const QString &chatId, const QString &text) override; bool sendFile(const QString &chatId, const QString &localFilePath) override; void markRead(const QString &chatId) override; void sendReaction(const QString &chatId, const QVariant &identifier, const QString &emoji, bool added) override; void sendTyping(const QString &chatId) override; // ChatBackend's ts-keyed edit and unsend, which the window routes through // the registry; both resolve to the protocol packets below. bool sendEdit(const QString &chatId, const QVariant &identifier, const QString &newText) override; bool sendDelete(const QString &chatId, const QVariant &identifier) override; bool leaveChat(const QString &chatId) override; QVariantMap roomInfo(const QString &chatId) const override; QVariantList roomMembers(const QString &chatId) const override; QVariantMap memberInfo(const QString &chatId, const QString &userId) const override; // Returns straight away: true means an attempt is in flight, false that // there is nothing to connect to. The outcome arrives as signals. bool connectVoice(const QString &ip); // Peer dialed over several candidates in parallel, the first to connect wins // and the rest are torn down. Candidates are "ip" or "ip:port"; a Matrix // caller dials back at the same time, so a NAT pair meets as one connection. bool dialVoiceCandidates(const QString &peer, const QStringList &candidates); // "ip:port" of the reflexive address a STUN server saw for this station, // empty until one answers. Matrix room calls fold it into their offer. QString stunReflexive() const; bool sendVoice(const QString &ip, const QByteArray &data); void disconnectVoice(const QString &ip); Q_SIGNALS: void hostIpChanged(); void userOnline(QJsonObject peerInfo); // userOnline() fires once, on the first packet, so without this the interface idea // of when a peer was last around would freeze at its first appearance. void peerRefreshed(QString ip, double lastSeen); void userOffline(QString ip); void message(QJsonObject msg); void callRequest(QString username, QString ip); void callAccepted(QString username, QString ip); void callRejected(QString ip); void callEnded(QString ip); void voiceDataFrom(QString ip, QByteArray raw); // host is the address the frame arrived on, which for a TLS frame is the // pinned peer; carried through so the transfer binds to one sender. void fileMeta(QString host, QJsonObject meta); void fileChunkBytes(QString host, QString tid, int idx, int total, QByteArray chunk); // file_data -> FileTransferHandler void groupInvite(QString groupId, QString name, QString fromIp); // an invite proposed a different key for a pinned group; nothing rewrote // it, since only the UI can confirm a rotation. void groupKeyConfirmationRequired(QString groupId, QString name, QString fromIp); void errorOccurred(QString message); // a peer's profile picture landed, or went away with an empty source. fromIp // is the chat id; the source is a local file URL the UI can load offline. void peerAvatar(QString fromIp, QString avatarSource); // a peer's profile banner landed, AvatarExchange's sibling signal: same // keying, same local-file-URL rule, one channel up the header. void peerBanner(QString fromIp, QString bannerSource); // fromIp is the address the packet arrived on, conversations are keyed by address. void typing(QString username, QString chatId, QString fromIp); void voiceConnected(QString ip); void voiceDisconnected(QString ip); // a peer's identity passed the TLS pin gate, so the peer details page can // refresh what depends on the pin (fingerprint, encrypted state). void tlsPeerAuthenticated(QString peerId, QString address); private Q_SLOTS: void onUdpReadyRead(); void refreshLocalIps(); void scanArpTable(); private: friend class NetworkManagerTest; // the routing of one decoded frame - the seam the tests drive. Split out of // SessionTransport because messages, calls and group keys live here. void dispatch(const QString &host, QJsonObject msg); // a peer's identity passed the TLS pin gate: correct the observed seat and // push the avatar, as the one moment a peer can miss our picture. void onTlsPeerAuthenticated(const QString &peerId, const QString &address); // a socket wearing the peer's identity id presented a different key. void onTlsPeerRejected(const QString &peerId, const QString &address, const QByteArray &expectedPin, const QByteArray &actualFingerprint); // a file_meta arrived: note the tid's owner before anything routes on it, // which is what makes it unstealable by a second peer sending chunks. void onFileMeta(const QString &host, const QJsonObject &meta); // file chunk arrives for the reassembler, from the datagram path or the // TLS channel; when a transfer completes this acks it back the same way. void onFileChunkFrom(const QString &host, const QString &tid, int idx, int total, const QByteArray &chunk); // a file_ack from either transport closes the outgoing transfer. void onFileAck(const QString &tid); // true when chat/group/call signalling for this address can ride TLS: a // live channel to the identity the address belongs to. bool canUseTls(const QString &targetAddress) const; // place a protocol frame on the TLS channel to this address's identity; // no-ops when nobody is there (the UDP sender should not call it). bool sendPeerFrame(const QString &targetAddress, const QJsonObject &payload); bool sendPeerFrame(const QString &targetAddress, const QCborMap &payload); CryptoManager *m_crypto = nullptr; QUdpSocket *m_udp = nullptr; // The authenticated session plane (see SessionTransport): TLS channel, // station identity, pin table and dial-on-advertise. Built from the identity // seed, so a degraded first run has no channel and announces no TLS port. SessionTransport m_session; // The routing of decoded frames (see FrameRouter): echo and presence, // message/meta/invite/typing signals, call buckets and the busy reply. // Owns no sockets and no crypto. FrameRouter m_router; // true when voice should carry TLS: identity present and the chat channel // up. Voice is then admitted only from identities already pinned. void updateVoiceTransport(); // The voice media plane (see VoiceTransport): sockets, dials, channels, // framing and TLS wrap, with seams back to the pin table and identity. VoiceTransport m_voice; // The STUN endpoint is configured by main.cpp and the reflexive result // (its own cache and re-query) lives in the client; see StunClient. StunClient m_stun; // Peer discovery on its own (see PresenceService): beacon, rate/replay // guards and observed table, relaying arrivals onto the signals here. PresenceService m_presence; // The avatar half of the peer table: the channel writer resolves a seat to // its pinned identity, the seats are pin table keys, the recorder files it. AvatarExchange m_avatar; // The banner exchange, the avatar's sibling on the same seams: bytes over // the pinned channel, sha-deduped per seat. BannerExchange m_banner; QString m_hostIp; QSet m_localIps; bool m_running = false; quint16 m_udpPort = 0; QTimer m_ipRefreshTimer; // The outgoing file transfer (see FileTransferSender): reads the file and // places the meta and chunks on the pinned channel. The incoming half stays // on fileChunkBytes and m_incomingTransfers below. FileTransferSender m_fileSender; // Incoming file transfers: tid -> received indices, total and sender. struct IncomingTransfer { QSet received; int total = 0; QString fromIp; bool offered = false; // a meta for this tid has been seen, so fromIp is the owner }; QHash m_incomingTransfers; ConnectionMode m_mode = ConnectionMode::LanOrVpn; // The shared group passphrase and the per-group keys live in here, plus the // rule for which one seals a conversation; see GroupKeyStore. GroupKeyStore m_groupKeyStore; }; } // namespace koutnet