// SPDX-FileCopyrightText: 2026 Matvey Shcherbinin // SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-KDE-Accepted-GPL // KOutNet - RFC 8489 STUN binding-request client over TCP #include "StunClient.h" #include "koutnet_network_debug.h" #include #include #include namespace koutnet { namespace { constexpr quint32 kMagicCookie = 0x2112A442u; constexpr quint16 kBindingRequest = 0x0001; constexpr quint16 kBindingSuccess = 0x0101; constexpr quint16 kAttrMappedAddress = 0x0001; constexpr quint16 kAttrXorMappedAddress = 0x0020; // how long the server has to answer before a reflexive candidate is given up on. constexpr int kStunTimeoutMs = 5000; quint16 be16(const QByteArray &bytes, int offset) { return quint16((quint16(quint8(bytes.at(offset))) << 8) | quint8(bytes.at(offset + 1))); } quint32 be32(const QByteArray &bytes, int offset) { return (quint32(be16(bytes, offset)) << 16) | be16(bytes, offset + 2); } // The raw bytes of the mapped address, in network order either way. Qt6's // QHostAddress no longer takes a QByteArray, so the four (or sixteen) bytes go // through the numeric constructor and back. QHostAddress ipv4FromBytes(const QByteArray &bytes) { if (bytes.size() < 4) return QHostAddress(); quint32 net = 0; for (int i = 0; i < 4; ++i) net = (net << 8) | quint8(bytes.at(i)); return QHostAddress(net); } QHostAddress ipv6FromBytes(const QByteArray &bytes) { if (bytes.size() < 16) return QHostAddress(); return QHostAddress(reinterpret_cast(bytes.constData())); } // The X-Port of an XOR-MAPPED-ADDRESS value: the port travels network order // and xored with the top half of the cookie, so reading the big-endian word // back after the xor yields the host-order port directly. quint16 decodeXorPort(const QByteArray &value) { return be16(value, 2) ^ quint16(kMagicCookie >> 16); } } // namespace QByteArray encodeStunBindingRequest(const QByteArray &transactionId) { QByteArray message; if (transactionId.size() != 12) return message; message.resize(20); message[0] = char(kBindingRequest >> 8); message[1] = char(kBindingRequest & 0xff); message[2] = 0; // no attributes in a bare binding request message[3] = 0; message[4] = char(kMagicCookie >> 24); message[5] = char((kMagicCookie >> 16) & 0xff); message[6] = char((kMagicCookie >> 8) & 0xff); message[7] = char(kMagicCookie & 0xff); for (int i = 0; i < transactionId.size(); ++i) message[8 + i] = transactionId.at(i); return message; } bool parseStunBindingResponse(const QByteArray &message, const QByteArray &transactionId, QHostAddress *address, quint16 *port) { if (message.size() < 20 || transactionId.size() != 12) return false; if (be16(message, 0) != kBindingSuccess) return false; if (be32(message, 4) != kMagicCookie) return false; if (message.mid(8, 12) != transactionId) return false; const int payloadEnd = 20 + int(be16(message, 2)); if (payloadEnd > message.size() || payloadEnd < 20) return false; bool haveXor = false; QHostAddress xorAddress; quint16 xorPort = 0; bool havePlain = false; QHostAddress plainAddress; quint16 plainPort = 0; int offset = 20; while (offset + 4 <= payloadEnd) { const quint16 type = be16(message, offset); const int length = int(be16(message, offset + 2)); const int valueOffset = offset + 4; if (valueOffset + length > message.size()) return false; // truncated attribute: not a tied response const QByteArray value = message.mid(valueOffset, length); if (type == kAttrXorMappedAddress) { const int family = value.size() >= 2 ? quint8(value.at(1)) : 0; if (family == 1 && value.size() >= 8 && !haveXor) { xorPort = decodeXorPort(value); QByteArray ip(4, 0); for (int i = 0; i < 4; ++i) ip[i] = char(quint8(value.at(4 + i)) ^ quint8(kMagicCookie >> (24 - 8 * i))); xorAddress = ipv4FromBytes(ip); haveXor = true; } else if (family == 2 && value.size() >= 20 && !haveXor) { xorPort = decodeXorPort(value); QByteArray ip(16, 0); for (int i = 0; i < 16; ++i) { const char key = i < 4 ? char(kMagicCookie >> (24 - 8 * i)) : transactionId.at(i - 4); ip[i] = char(quint8(value.at(4 + i)) ^ quint8(key)); } xorAddress = ipv6FromBytes(ip); haveXor = true; } } else if (type == kAttrMappedAddress && value.size() >= 8) { const int family = quint8(value.at(1)); if (family == 1 && !havePlain) { plainPort = be16(value, 2); plainAddress = ipv4FromBytes(value.mid(4, 4)); havePlain = true; } else if (family == 2 && value.size() >= 20 && !havePlain) { plainPort = be16(value, 2); plainAddress = ipv6FromBytes(value.mid(4, 16)); havePlain = true; } } offset = valueOffset + length; if (length & 3) offset += 4 - (length & 3); // attributes pad to a 32-bit boundary } if (haveXor) { *address = xorAddress; *port = xorPort; return true; } if (havePlain) { *address = plainAddress; *port = plainPort; return true; } return false; } StunClient::StunClient(const QString &server, quint16 port, QObject *parent) : QObject(parent) , m_server(server) , m_port(port) { } void StunClient::setServer(const QString &host, quint16 port) { m_server = host; m_port = port; } QString StunClient::server() const { return m_server; } quint16 StunClient::port() const { return m_port; } QString StunClient::reflexiveAddress() const { return m_reflexive; } void StunClient::setReflexive(const QString &address, quint16 port) { m_reflexive = QStringLiteral("%1:%2").arg(address).arg(port); Q_EMIT reflexiveChanged(m_reflexive); } void StunClient::clearReflexive() { if (m_reflexive.isEmpty()) return; m_reflexive.clear(); Q_EMIT reflexiveChanged(m_reflexive); } void StunClient::refresh() { if (m_socket != nullptr) finish(); m_rx.clear(); m_transactionId.resize(12); QRandomGenerator::system()->fillRange(reinterpret_cast(m_transactionId.data()), m_transactionId.size() / int(sizeof(quint32))); auto *sock = new QTcpSocket(this); m_socket = sock; if (m_timeout == nullptr) { m_timeout = new QTimer(this); m_timeout->setSingleShot(true); connect(m_timeout, &QTimer::timeout, this, &StunClient::onDeadline); } m_timeout->start(kStunTimeoutMs); connect(sock, &QTcpSocket::connected, this, [this, sock] { sock->write(encodeStunBindingRequest(m_transactionId)); }); connect(sock, &QTcpSocket::readyRead, this, &StunClient::onSocketReady); // A refused or black-holed connection is a missing candidate, not an error // to ring on: the call still goes on to the host address. connect(sock, &QTcpSocket::errorOccurred, this, &StunClient::onDeadline); sock->connectToHost(m_server, m_port); } void StunClient::onSocketReady() { auto *sock = m_socket; if (sock == nullptr) return; m_rx += sock->readAll(); QHostAddress address; quint16 port = 0; if (!parseStunBindingResponse(m_rx, m_transactionId, &address, &port) || address.isNull() || port == 0) return; // the rest of the reply may still be in flight; the deadline guards qCInfo(KOUTNET_LOG_NETWORK) << "STUN reflexive address" << address.toString() << ":" << port; if (m_timeout != nullptr) m_timeout->stop(); m_rx.clear(); m_transactionId.clear(); finish(); setReflexive(address.toString(), port); } void StunClient::onDeadline() { if (m_socket == nullptr) return; finish(); qCInfo(KOUTNET_LOG_NETWORK) << "no STUN reflexive address, room calls will dial the host address only"; clearReflexive(); } void StunClient::finish() { if (m_socket != nullptr) { m_socket->disconnect(this); m_socket->abort(); m_socket->deleteLater(); m_socket = nullptr; } if (m_timeout != nullptr) m_timeout->stop(); } } // namespace koutnet