// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // KOutNet - The voice media plane: listener, dial, channels, framing, TLS wrap #include "VoiceTransport.h" #include "AddressUtils.h" #include "Protocol.h" #include #include #include #include #include #include #include #include #include "koutnet_network_debug.h" namespace koutnet { namespace { QByteArray lengthPrefix(quint32 len) { QByteArray header(protocol::kFrameHeaderBytes, 0); header[0] = char((len >> 24) & 0xFF); header[1] = char((len >> 16) & 0xFF); header[2] = char((len >> 8) & 0xFF); header[3] = char(len & 0xFF); return header; } quint32 readLengthPrefix(const QByteArray &buf) { return (quint32(quint8(buf.at(0))) << 24) | (quint32(quint8(buf.at(1))) << 16) | (quint32(quint8(buf.at(2))) << 8) | quint32(quint8(buf.at(3))); } // The voice listener. QTcpServer cannot start TLS by itself, and the accepted // QTcpSocket it hands over would fight the QSslSocket for the descriptor, so // the accept event is surfaced as a bare descriptor - each side then builds // exactly the socket it wants (see VoiceTransport::acceptDescriptor). class VoiceServer final : public QTcpServer { public: explicit VoiceServer(QObject *parent = nullptr) : QTcpServer(parent) { } std::function onSocket; protected: void incomingConnection(qintptr socketDescriptor) override { if (onSocket) onSocket(socketDescriptor); } }; } // namespace VoiceTransport::VoiceTransport(QObject *parent) : QObject(parent) { } void VoiceTransport::setCredentials(const IdentityCertificate &identity, bool overTls) { m_identity = identity; m_overTls = overTls; } bool VoiceTransport::overTls() const { return m_overTls; } void VoiceTransport::setPinGate(std::function trusted) { m_trusted = std::move(trusted); } void VoiceTransport::setSeatLookup(std::function filedSeat) { m_seatFor = std::move(filedSeat); } void VoiceTransport::setSeatFiler(std::function fileSeat) { m_fileSeat = std::move(fileSeat); } bool VoiceTransport::listen(quint16 preferredPort) { auto *server = new VoiceServer(this); m_listener = server; if (!server->listen(QHostAddress::Any, preferredPort)) { if (!server->listen(QHostAddress::Any, 0)) { Q_EMIT errorOccurred(i18nc("@info:status %1 is a port number", "TCP listen failed on port %1.", int(preferredPort))); server->deleteLater(); m_listener = nullptr; return false; } } m_port = server->serverPort(); server->onSocket = [this](qintptr descriptor) { acceptDescriptor(descriptor); }; return true; } quint16 VoiceTransport::port() const { return m_port; } bool VoiceTransport::isCallUp(const QString &peer) const { return !m_channels.value(peer).isEmpty(); } bool VoiceTransport::isDialing(const QString &peer) const { return m_pending.contains(peer); } void VoiceTransport::acceptDescriptor(qintptr socketDescriptor) { if (!m_overTls) { // no identity, so no certificate to ride: a plain socket whose media // the LAN itself defends. The moment identity is available the channel // flips to the TLS path below. auto *sock = new QTcpSocket(this); if (!sock->setSocketDescriptor(socketDescriptor)) { sock->deleteLater(); return; } const QString ip = normaliseAddress(sock->peerAddress()); // A peer that dials and gets dialed joins back on the same call: the // second channel carries the mirror of the first. Nothing here decides // which flow the audio rides, because every socket is full-duplex and // the call only ends when all of them close. addChannel(ip, sock); return; } // TLS path: hand the accepted descriptor to a QSslSocket, refuse early TCP // probes with a silent abort, and admit the connection only once its // certificate has been seen and its identity is one the chat channel // already pinned. Voice trusts the same pins chat does - a stranger that // never authenticated there gets no microphone. auto *ssl = new QSslSocket(this); if (!ssl->setSocketDescriptor(socketDescriptor)) { ssl->deleteLater(); return; } ssl->setSslConfiguration(tlsConfig(/*server=*/true)); auto *handshakeFailure = new QTimer(this); handshakeFailure->setSingleShot(true); const QPointer handshakeGuard = handshakeFailure; // A dial that never completes is not a peer: the watchdog's timeout and // any transport error both land here. An adopted socket is none of its // business - onSocketDisconnected owns that teardown, and the guard // pointer keeps a late error from freeing an already-gone timer. const auto giveUp = [this, ssl, handshakeGuard] { for (auto it = m_channels.cbegin(); it != m_channels.cend(); ++it) if (it->contains(ssl)) return; // adopted and live: normal teardown handles it if (m_rx.contains(ssl)) return; // mid-frame: let the reassembler finish ssl->disconnect(this); ssl->abort(); ssl->deleteLater(); if (handshakeGuard) handshakeGuard->deleteLater(); }; connect(ssl, &QSslSocket::encrypted, this, [this, ssl, handshakeGuard] { const QStringList cn = ssl->peerCertificate().subjectInfo(QSslCertificate::CommonName); const QString id = cn.isEmpty() ? QString() : cn.first(); const QString filed = m_seatFor ? m_seatFor(id) : QString(); const bool trusted = !id.isEmpty() && !filed.isEmpty() && m_trusted && m_trusted(id); if (!trusted) { // somebody on the wire, but not a pinned peer: no seat, no call. ssl->disconnectFromHost(); ssl->deleteLater(); if (handshakeGuard) handshakeGuard->deleteLater(); return; } if (handshakeGuard) { handshakeGuard->stop(); // adopted: the dial timer is done handshakeGuard->deleteLater(); } if (m_fileSeat) m_fileSeat(filed, id); // the voice handshake authenticates too addChannel(filed, ssl); }); connect(ssl, &QSslSocket::errorOccurred, this, [giveUp](QAbstractSocket::SocketError) { giveUp(); }); // The peer's self-signed certificate trips peerVerifyError whatever the // verify mode: we do not verify chains, we decide the peer's fate from the // pinned chat channel in the encrypted() handler above, so this signal is // informational noise and must not abort the handshake. connect(handshakeFailure, &QTimer::timeout, this, giveUp); handshakeFailure->start(kConnectTimeoutMs); ssl->startServerEncryption(); } void VoiceTransport::addChannel(const QString &peer, QAbstractSocket *sock) { QVector &channels = m_channels[peer]; const bool first = channels.isEmpty(); channels.append(sock); connect(sock, &QAbstractSocket::readyRead, this, [this, sock, peer] { onSocketReady(sock, peer); }); connect(sock, &QAbstractSocket::disconnected, this, [this, sock, peer] { onSocketDisconnected(sock, peer); }); // a speaker joining a call that already has a channel is not a new call. if (first) Q_EMIT voiceConnected(peer); } void VoiceTransport::onSocketReady(QAbstractSocket *sock, const QString &ip) { // Reassemble whole frames; TCP may split one frame across reads. QByteArray buf = m_rx.value(sock) + sock->readAll(); QVector frames; while (buf.size() >= protocol::kFrameHeaderBytes) { const quint32 len = readLengthPrefix(buf); if (len == 0 || len > protocol::kMaxVoiceFrameBytes) { // peer-supplied length: a silly one asks us to allocate a gigabyte Q_EMIT errorOccurred( i18nc("@info:status %1 is a host address, %2 a byte count", "Voice frame from %1 declared %2 bytes - dropping the connection.", ip, len)); // the same teardown a real disconnect runs: abort() alone does not // guarantee disconnected(), which would leave the socket in m_channels. onSocketDisconnected(sock, ip); return; } if (quint32(buf.size() - protocol::kFrameHeaderBytes) < len) break; // the rest of this frame is still in flight frames.append(buf.mid(protocol::kFrameHeaderBytes, int(len))); buf.remove(0, protocol::kFrameHeaderBytes + int(len)); } // Remainder goes back before anything is emitted: a listener may hang up // and erase this socket's buffer underneath us. m_rx[sock] = buf; for (const auto &frame : std::as_const(frames)) { Q_EMIT media(ip, frame); } } void VoiceTransport::onSocketDisconnected(QAbstractSocket *sock, const QString &peer) { m_rx.remove(sock); auto it = m_channels.find(peer); if (it != m_channels.end()) { it->removeAll(sock); // Another channel (the peer's dial-back) may still be up: that peer is not // gone. The call ends with the last channel, so a flapping spare socket // cannot tear a working call out from under both sides. if (it->isEmpty()) { m_channels.erase(it); Q_EMIT voiceDisconnected(peer); Q_EMIT callEnded(peer); } } sock->deleteLater(); } QSslConfiguration VoiceTransport::tlsConfig(bool server) const { QSslConfiguration cfg = QSslConfiguration::defaultConfiguration(); // match the chat channel: TLS 1.3 and the identity-derived certificate. cfg.setProtocol(QSsl::TlsV1_3OrLater); cfg.setLocalCertificate(m_identity.cert); cfg.setPrivateKey(m_identity.key); // the server asks for the client certificate and decides from its CN; the // client does not verify the server's - it dialed the address itself and // the voice media on a TLS socket is protected by that same session. cfg.setPeerVerifyMode(server ? QSslSocket::QueryPeer : QSslSocket::VerifyNone); return cfg; } void VoiceTransport::adoptDial(const QString &peer, QAbstractSocket *sock, QTimer *watchdog) { if (!m_pending.value(peer).contains(sock)) return; // superseded, or the call was already torn down if (!m_channels.value(peer).isEmpty()) { // another candidate, or the peer's own dial, already won: spare m_pending[peer].removeAll(sock); sock->abort(); sock->deleteLater(); return; } QList dialsLeft = m_pending.take(peer); dialsLeft.removeAll(sock); m_watchdogs.remove(peer); for (auto *other : std::as_const(dialsLeft)) { other->disconnect(this); other->abort(); other->deleteLater(); } if (watchdog) watchdog->deleteLater(); addChannel(peer, sock); } bool VoiceTransport::connectTo(const QString &peer, const QStringList &candidates) { // a peer already on a call, or whose dial is still in flight, is not dialed // a second time: collateral dials only breed spare sockets, and the caller // reads a true return as "already in flight". if (isCallUp(peer) || isDialing(peer)) return true; // A peer can be reachable on several links: the host address it announced, // plus a STUN-reflexive address for the NAT it sits behind. Every candidate // is dialed at once and the first to connect opens the call; the far side // dials this side's set back, so over a NAT pair the two dials meet as one // connection. "ip:port" names its own port, a bare "ip" (the LAN path) // lands on the well-known voice port. QVector> targets; QStringList seen; for (const QString &candidate : candidates) { if (seen.contains(candidate)) continue; seen.append(candidate); QHostAddress host(candidate); quint16 port = m_port; if (host.isNull()) { // a candidate with a port: the trailing part is the port, the rest // the address. IPv6 literals are never enclosed in brackets here, // so only an address that is not one whole valid IP gets split. const int colon = candidate.lastIndexOf(QLatin1Char(':')); if (colon <= 0) continue; const QString hostText = candidate.left(colon); host = QHostAddress(hostText); if (host.isNull()) continue; bool portOk = false; const int given = candidate.mid(colon + 1).toInt(&portOk); if (!portOk || given <= 0 || given > 65535) continue; port = quint16(given); } targets.append(QPair(host, port)); } if (targets.isEmpty()) return false; auto *watchdog = new QTimer(this); watchdog->setSingleShot(true); m_watchdogs[peer] = watchdog; // a shared "the dial did not end well" path: report it, tear the window // down, and free the sockets. callEnded is what the call UI listens for, so // an unanswered dial has to emit it or the window pretends to be a call. const auto fail = [this, peer, watchdog](const QString &message) { // contains() and not isEmpty(): the last candidate's error already // removed its socket, leaving the key in the map with an empty list, // and that is still "an attempt that is ending" - exactly the state we // are here to close and report. A hangUp or an adopted dial take() the // key away, and a dial that never got that far never calls fail. if (!m_pending.contains(peer)) return; if (!m_channels.value(peer).isEmpty()) return; // the peer's own dial already put a channel up - nothing failed const QList dials = m_pending.take(peer); m_watchdogs.remove(peer); for (auto *sock : dials) { sock->disconnect(this); sock->abort(); sock->deleteLater(); } watchdog->deleteLater(); Q_EMIT errorOccurred(message); Q_EMIT voiceDisconnected(peer); Q_EMIT callEnded(peer); }; // Over the TLS transport the dial is a handshake, not a bare TCP connect: // the server keeps the connection only once it has seen and pinned our // certificate, so "the dial won" is the encrypted signal. Plain sockets // still use connected() as before. const bool tlsDial = m_overTls; QList dials; for (const auto &target : std::as_const(targets)) { auto *sock = tlsDial ? static_cast(new QSslSocket(this)) : new QTcpSocket(this); dials.append(sock); const QHostAddress targetHost = target.first; const quint16 targetPort = target.second; if (tlsDial) { auto *ssl = static_cast(sock); ssl->setSslConfiguration(tlsConfig(/*server=*/false)); connect(ssl, &QSslSocket::encrypted, this, [this, ssl, peer, watchdog, fail] { // The dial must land on the pinned identity too. The address was // a delivery hint from presence, not proof of who answers, so // the client runs the same CN + pin gate as the accepted side; // otherwise any host that owns the address gets our audio. const QStringList cn = ssl->peerCertificate().subjectInfo(QSslCertificate::CommonName); const QString id = cn.isEmpty() ? QString() : cn.first(); const QString filed = m_seatFor ? m_seatFor(id) : QString(); const bool trusted = !id.isEmpty() && !filed.isEmpty() && m_trusted && m_trusted(id); if (!trusted) { if (m_pending.value(peer).contains(ssl)) m_pending[peer].removeAll(ssl); ssl->disconnect(this); ssl->abort(); ssl->deleteLater(); if (m_pending.value(peer).isEmpty() && m_channels.value(peer).isEmpty()) fail(i18nc("@info:status %1 is a host address", "Voice connect to %1 failed: the peer's TLS identity is not pinned.", peer)); return; } adoptDial(peer, ssl, watchdog); }); ssl->connectToHostEncrypted(targetHost.toString(), targetPort); } else { connect(sock, &QTcpSocket::connected, this, [this, sock, peer, watchdog] { adoptDial(peer, sock, watchdog); }); sock->connectToHost(targetHost, targetPort); } connect(sock, &QAbstractSocket::errorOccurred, this, [this, sock, peer, watchdog, fail](QAbstractSocket::SocketError) { if (!m_pending.value(peer).contains(sock)) return; m_pending[peer].removeAll(sock); const QString message = sock->errorString(); sock->abort(); sock->deleteLater(); // only the last candidate failing is a failed dial: one dead link // must not cut a peer whose other candidate is still in the air. if (m_pending.value(peer).isEmpty() && m_channels.value(peer).isEmpty()) fail(i18nc("@info:status %1 is a host address, %2 a socket error message", "Voice connect to %1 failed: %2", peer, message)); }); } m_pending[peer] = dials; watchdog->start(kConnectTimeoutMs); connect(watchdog, &QTimer::timeout, this, [peer, watch = watchdog, fail] { fail(i18nc("@info:status %1 is a host address", "Voice connect to %1 timed out - the peer never answered the dial.", peer)); }); return true; } bool VoiceTransport::sendMedia(const QString &peer, const QByteArray &data) { // same cap the receiver enforces. if (data.isEmpty() || quint32(data.size()) > protocol::kMaxVoiceFrameBytes) return false; for (QAbstractSocket *sock : m_channels.value(peer)) { if (sock->state() == QAbstractSocket::ConnectedState) { sock->write(lengthPrefix(quint32(data.size())) + data); return true; } } return false; } void VoiceTransport::hangUp(const QString &peer) { // a call hung up while the sockets are still connecting has to stop too if (auto *watchdog = m_watchdogs.take(peer)) watchdog->deleteLater(); const QList pending = m_pending.take(peer); for (auto *sock : pending) { sock->disconnect(this); sock->abort(); sock->deleteLater(); } if (m_channels.contains(peer)) { const QVector channels = m_channels.take(peer); for (auto *sock : channels) { m_rx.remove(sock); sock->disconnect(this); sock->abort(); sock->deleteLater(); } Q_EMIT voiceDisconnected(peer); Q_EMIT callEnded(peer); } } void VoiceTransport::stop() { QSet allVoice; for (auto &channels : std::as_const(m_channels)) { for (QAbstractSocket *sock : channels) { allVoice.insert(sock); sock->disconnect(this); sock->close(); } } for (auto &dials : std::as_const(m_pending)) { for (QAbstractSocket *sock : dials) { allVoice.insert(sock); sock->disconnect(this); sock->abort(); } } for (QAbstractSocket *sock : std::as_const(allVoice)) sock->deleteLater(); m_channels.clear(); m_rx.clear(); m_pending.clear(); for (auto *t : std::as_const(m_watchdogs)) t->deleteLater(); m_watchdogs.clear(); if (m_listener) { m_listener->close(); m_listener->deleteLater(); m_listener = nullptr; } m_port = 0; m_overTls = false; m_identity = IdentityCertificate(); } } // namespace koutnet