LCOV - code coverage report
Current view: top level - source/network - StunClient.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 12 148 8.1 %
Date: 2026-12-03 01:19:39 Functions: 1 10 10.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * Copyright (C) 2013-2016 SuperTuxKart-Team.
       3             :  * This file is part of 0 A.D.
       4             :  *
       5             :  * 0 A.D. is free software: you can redistribute it and/or modify
       6             :  * it under the terms of the GNU General Public License as published by
       7             :  * the Free Software Foundation, either version 2 of the License, or
       8             :  * (at your option) any later version.
       9             :  *
      10             :  * 0 A.D. is distributed in the hope that it will be useful,
      11             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      12             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      13             :  * GNU General Public License for more details.
      14             :  *
      15             :  * You should have received a copy of the GNU General Public License
      16             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      17             :  */
      18             : 
      19             : #include "precompiled.h"
      20             : 
      21             : #include "StunClient.h"
      22             : 
      23             : #include "lib/byte_order.h"
      24             : #include "lib/code_annotation.h"
      25             : #include "lib/external_libraries/enet.h"
      26             : #include "ps/CLogger.h"
      27             : #include "ps/CStr.h"
      28             : #include "ps/ConfigDB.h"
      29             : 
      30             : #include <bit>
      31             : #include <cerrno>
      32             : #include <chrono>
      33             : #include <concepts>
      34             : #include <cstddef>
      35             : #include <cstdlib>
      36             : #include <cstring>
      37             : #include <thread>
      38             : #include <type_traits>
      39             : #include <vector>
      40             : 
      41             : namespace StunClient
      42             : {
      43             : 
      44             : /**
      45             :  * These constants are defined in Section 6 of RFC 5389.
      46             :  */
      47             : const std::uint32_t m_MagicCookie = 0x2112A442;
      48             : const std::uint16_t m_MethodTypeBinding = 0x01;
      49             : const std::uint32_t m_BindingSuccessResponse = 0x0101;
      50             : 
      51             : /**
      52             :  * Bit determining whether comprehension of an attribute is optional.
      53             :  * Described in Section 15 of RFC 5389.
      54             :  */
      55             : const std::uint16_t m_ComprehensionOptional = 0x1 << 15;
      56             : 
      57             : /**
      58             :  * Bit determining whether the bit was assigned by IETF Review.
      59             :  * Described in section 18.1. of  RFC 5389.
      60             :  */
      61             : const std::uint16_t m_IETFReview = 0x1 << 14;
      62             : 
      63             : /**
      64             :  * These constants are defined in Section 15.1 of RFC 5389.
      65             :  */
      66             : const std::uint8_t m_IPAddressFamilyIPv4 = 0x01;
      67             : 
      68             : /**
      69             :  * These constants are defined in Section 18.2 of RFC 5389.
      70             :  */
      71             : const std::uint16_t m_AttrTypeMappedAddress = 0x001;
      72             : const std::uint16_t m_AttrTypeXORMappedAddress = 0x0020;
      73             : 
      74             : /**
      75             :  * Described in section 3 of RFC 5389.
      76             :  */
      77             : std::uint8_t m_TransactionID[12];
      78             : 
      79             : ENetAddress m_StunServer;
      80             : 
      81             : /**
      82             :  * Public IP + port discovered via the STUN transaction.
      83             :  */
      84             : ENetAddress m_PublicAddress;
      85             : 
      86             : /**
      87             :  * Push integral type to a network-byte-order buffer.
      88             :  */
      89             : template<std::integral T, size_t n = sizeof(T)>
      90           0 : void AddToBuffer(std::vector<std::uint8_t>& buffer, const T value)
      91             : {
      92           0 :     buffer.reserve(buffer.size() + n);
      93             :     // std::byte* can alias anything so this is legal.
      94           0 :     const std::byte* ptr = reinterpret_cast<const std::byte*>(&value);
      95           0 :     for (size_t a = 0; a < n; ++a)
      96             :     {
      97             :         if constexpr (std::endian::native == std::endian::little)
      98           0 :             buffer.push_back(static_cast<std::uint8_t>(*(ptr + n - 1 - a)));
      99             :         else
     100             :             buffer.push_back(static_cast<std::uint8_t>(*(ptr + a)));
     101             :     }
     102           0 : }
     103             : 
     104             : /**
     105             :  * Read integral type from a network-byte-order buffer.
     106             :  */
     107             : template<std::integral T, size_t n = sizeof(T)>
     108           0 : bool GetFromBuffer(const std::vector<std::uint8_t>& buffer, std::uint32_t& offset, T& result)
     109             : {
     110           0 :     if (offset + n > buffer.size())
     111             :         return false;
     112             : 
     113             :     // std::byte* can alias anything so this is legal.
     114             :     std::byte* ptr = reinterpret_cast<std::byte*>(&result);
     115           0 :     for (size_t a = 0; a < n; ++a)
     116             :     {
     117             :         if constexpr (std::endian::native == std::endian::little)
     118           0 :             *ptr++ = static_cast<std::byte>(buffer[offset + n - 1 - a]);
     119             :         else
     120             :             *ptr++ = static_cast<std::byte>(buffer[offset + a]);
     121             :     }
     122             : 
     123           0 :     offset += n;
     124           0 :     return true;
     125             : }
     126             : 
     127           0 : void SendStunRequest(ENetHost& transactionHost, ENetAddress addr)
     128             : {
     129           0 :     std::vector<std::uint8_t> buffer;
     130           0 :     AddToBuffer<std::uint16_t>(buffer, m_MethodTypeBinding);
     131           0 :     AddToBuffer<std::uint16_t>(buffer, 0); // length
     132           0 :     AddToBuffer<std::uint32_t>(buffer, m_MagicCookie);
     133             : 
     134           0 :     for (std::size_t i = 0; i < sizeof(m_TransactionID); ++i)
     135             :     {
     136           0 :         std::uint8_t random_byte = rand() % 256;
     137           0 :         buffer.push_back(random_byte);
     138           0 :         m_TransactionID[i] = random_byte;
     139             :     }
     140             : 
     141           0 :     ENetBuffer enetBuffer;
     142           0 :     enetBuffer.data = buffer.data();
     143           0 :     enetBuffer.dataLength = buffer.size();
     144           0 :     enet_socket_send(transactionHost.socket, &addr, &enetBuffer, 1);
     145           0 : }
     146             : 
     147             : /**
     148             :  * Creates a STUN request and sends it to a STUN server.
     149             :  * The request is sent through transactionHost, from which the answer
     150             :  * will be retrieved by ReceiveStunResponse and interpreted by ParseStunResponse.
     151             :  */
     152           0 : bool CreateStunRequest(ENetHost& transactionHost)
     153             : {
     154           0 :     const std::string server_name{g_ConfigDB.Get("lobby.stun.server", std::string{})};
     155           0 :     const int port{g_ConfigDB.Get("lobby.stun.port", 0)};
     156             : 
     157           0 :     LOGMESSAGE("StunClient: Using STUN server {}:{}\n", server_name, port);
     158             : 
     159           0 :     ENetAddress addr;
     160           0 :     addr.port = port;
     161           0 :     if (enet_address_set_host(&addr, server_name.c_str()) == -1)
     162             :         return false;
     163             : 
     164           0 :     m_StunServer = addr;
     165             : 
     166           0 :     StunClient::SendStunRequest(transactionHost, addr);
     167             : 
     168             :     return true;
     169           0 : }
     170             : 
     171             : /**
     172             :  * Gets the response from the STUN server and checks it for its validity.
     173             :  */
     174           0 : bool ReceiveStunResponse(ENetHost& transactionHost, std::vector<std::uint8_t>& buffer)
     175             : {
     176             :     // TransportAddress sender;
     177           0 :     const int LEN = 2048;
     178           0 :     char input_buffer[LEN];
     179             : 
     180           0 :     memset(input_buffer, 0, LEN);
     181             : 
     182           0 :     ENetBuffer enetBuffer;
     183           0 :     enetBuffer.data = input_buffer;
     184           0 :     enetBuffer.dataLength = LEN;
     185             : 
     186           0 :     ENetAddress sender = m_StunServer;
     187           0 :     int len = enet_socket_receive(transactionHost.socket, &sender, &enetBuffer, 1);
     188             : 
     189           0 :     const int delay{g_ConfigDB.Get("lobby.stun.delay", 10)};
     190           0 :     const int maxTries{g_ConfigDB.Get("lobby.stun.max_tries", 100)};
     191             : 
     192             :     // Wait to receive the message because enet sockets are non-blocking
     193           0 :     for (int count = 0; len <= 0 && (count < maxTries || maxTries == -1); ++count)
     194             :     {
     195           0 :         std::this_thread::sleep_for(std::chrono::milliseconds(delay));
     196           0 :         len = enet_socket_receive(transactionHost.socket, &sender, &enetBuffer, 1);
     197             :     }
     198             : 
     199           0 :     if (len <= 0)
     200             :     {
     201           0 :         LOGERROR("ReceiveStunResponse: recvfrom error ({}): {}", errno, strerror(errno));
     202           0 :         return false;
     203             :     }
     204             : 
     205           0 :     if (memcmp(&sender, &m_StunServer, sizeof(m_StunServer)) != 0)
     206           0 :         LOGERROR("ReceiveStunResponse: Received stun response from different address: {}.{}.{}.{}:{} "
     207             :             "{}",
     208             :             (sender.host >> 24) & 0xff,
     209             :             (sender.host >> 16) & 0xff,
     210             :             (sender.host >>  8) & 0xff,
     211             :             (sender.host >>  0) & 0xff,
     212             :             sender.port,
     213             :             input_buffer);
     214             : 
     215             :     // Convert to network string.
     216           0 :     buffer.resize(len);
     217           0 :     memcpy(buffer.data(), reinterpret_cast<std::uint8_t*>(input_buffer), len);
     218             : 
     219           0 :     return true;
     220             : }
     221             : 
     222           0 : bool ParseStunResponse(const std::vector<std::uint8_t>& buffer)
     223             : {
     224           0 :     std::uint32_t offset = 0;
     225             : 
     226           0 :     std::uint16_t responseType = 0;
     227           0 :     if (!GetFromBuffer(buffer, offset, responseType) || responseType != m_BindingSuccessResponse)
     228             :     {
     229           0 :         LOGERROR("STUN response isn't a binding success response");
     230           0 :         return false;
     231             :     }
     232             : 
     233             :     // Ignore message size
     234           0 :     offset += 2;
     235             : 
     236           0 :     std::uint32_t cookie = 0;
     237           0 :     if (!GetFromBuffer(buffer, offset, cookie) || cookie != m_MagicCookie)
     238             :     {
     239           0 :         LOGERROR("STUN response doesn't contain the magic cookie");
     240           0 :         return false;
     241             :     }
     242             : 
     243           0 :     for (std::size_t i = 0; i < sizeof(m_TransactionID); ++i)
     244             :     {
     245           0 :         std::uint8_t transactionChar = 0;
     246           0 :         if (!GetFromBuffer(buffer, offset, transactionChar) || transactionChar != m_TransactionID[i])
     247             :         {
     248           0 :             LOGERROR("STUN response doesn't contain the transaction ID");
     249           0 :             return false;
     250             :         }
     251             :     }
     252             : 
     253           0 :     while (offset < buffer.size())
     254             :     {
     255           0 :         std::uint16_t type = 0;
     256           0 :         std::uint16_t size = 0;
     257           0 :         if (!GetFromBuffer(buffer, offset, type) ||
     258           0 :             !GetFromBuffer(buffer, offset, size))
     259             :         {
     260           0 :             LOGERROR("STUN response contains invalid attribute");
     261           0 :             return false;
     262             :         }
     263             : 
     264             :         // The first two bits are irrelevant to the type
     265           0 :         type &= ~(m_ComprehensionOptional | m_IETFReview);
     266             : 
     267           0 :         switch (type)
     268             :         {
     269           0 :         case m_AttrTypeMappedAddress:
     270           0 :         case m_AttrTypeXORMappedAddress:
     271           0 :         {
     272           0 :             if (size != 8)
     273             :             {
     274           0 :                 LOGERROR("Invalid STUN Mapped Address length");
     275           0 :                 return false;
     276             :             }
     277             : 
     278             :             // Ignore the first byte as mentioned in Section 15.1 of RFC 5389.
     279           0 :             ++offset;
     280             : 
     281           0 :             std::uint8_t ipFamily = 0;
     282           0 :             if (!GetFromBuffer(buffer, offset, ipFamily) || ipFamily != m_IPAddressFamilyIPv4)
     283             :             {
     284           0 :                 LOGERROR("Unsupported address family, IPv4 is expected");
     285           0 :                 return false;
     286             :             }
     287             : 
     288           0 :             std::uint16_t port = 0;
     289           0 :             std::uint32_t ip = 0;
     290           0 :             if (!GetFromBuffer(buffer, offset, port) ||
     291           0 :                 !GetFromBuffer(buffer, offset, ip))
     292             :             {
     293           0 :                 LOGERROR("Mapped address doesn't contain IP and port");
     294           0 :                 return false;
     295             :             }
     296             : 
     297             :             // Obfuscation is described in Section 15.2 of RFC 5389.
     298           0 :             if (type == m_AttrTypeXORMappedAddress)
     299             :             {
     300           0 :                 port ^= m_MagicCookie >> 16;
     301           0 :                 ip ^= m_MagicCookie;
     302             :             }
     303             : 
     304             :             // ENetAddress takes a host byte-order port and network byte-order IP.
     305             :             // Network byte order is big endian, so convert appropriately.
     306           0 :             m_PublicAddress.host = to_be32(ip);
     307           0 :             m_PublicAddress.port = port;
     308             : 
     309           0 :             break;
     310             :         }
     311           0 :         default:
     312           0 :         {
     313             :             // We don't care about other attributes at all
     314             : 
     315             :             // Skip attribute
     316           0 :             offset += size;
     317             : 
     318             :             // Skip padding
     319           0 :             int padding = size % 4;
     320           0 :             if (padding)
     321           0 :                 offset += 4 - padding;
     322             :             break;
     323             :         }
     324             :         }
     325             :     }
     326             : 
     327             :     return true;
     328             : }
     329             : 
     330           0 : bool STUNRequestAndResponse(ENetHost& transactionHost)
     331             : {
     332           0 :     if (!CreateStunRequest(transactionHost))
     333             :         return false;
     334             : 
     335           0 :     std::vector<std::uint8_t> buffer;
     336           0 :     return ReceiveStunResponse(transactionHost, buffer) &&
     337           0 :            ParseStunResponse(buffer);
     338           0 : }
     339             : 
     340           0 : bool FindPublicIP(ENetHost& transactionHost, CStr& ip, std::uint16_t& port)
     341             : {
     342           0 :     if (!STUNRequestAndResponse(transactionHost))
     343             :         return false;
     344             : 
     345             :     // Convert m_IP to string
     346           0 :     char ipStr[256] = "(error)";
     347           0 :     enet_address_get_host_ip(&m_PublicAddress, ipStr, ARRAY_SIZE(ipStr));
     348             : 
     349           0 :     ip = ipStr;
     350           0 :     port = m_PublicAddress.port;
     351             : 
     352           0 :     LOGMESSAGE("StunClient: external IP address is {}:{}", ip, port);
     353             : 
     354           0 :     return true;
     355             : }
     356             : 
     357           0 : void SendHolePunchingMessages(ENetHost& enetClient, const std::string& serverAddress,
     358             :     std::uint16_t serverPort)
     359             : {
     360             :     // Convert ip string to int64
     361           0 :     ENetAddress addr;
     362           0 :     addr.port = serverPort;
     363           0 :     enet_address_set_host(&addr, serverAddress.c_str());
     364             : 
     365           0 :     const int delay{g_ConfigDB.Get("lobby.fw_punch.delay", 200)};
     366           0 :     const int numMsg{g_ConfigDB.Get("lobby.fw_punch.num_msg", 3)};
     367             : 
     368             :     // Send an UDP message from enet host to ip:port
     369           0 :     for (int i = 0; i < numMsg || numMsg == -1; ++i)
     370             :     {
     371           0 :         SendStunRequest(enetClient, addr);
     372           0 :         std::this_thread::sleep_for(std::chrono::milliseconds(delay));
     373             :     }
     374           0 : }
     375             : 
     376           1 : bool FindLocalIP(CStr& ip)
     377             : {
     378             :     // Open an UDP socket.
     379           1 :     ENetSocket socket = enet_socket_create(ENET_SOCKET_TYPE_DATAGRAM);
     380             : 
     381           1 :     ENetAddress addr;
     382           1 :     addr.port = 9; // Use the debug port (which we pick does not matter).
     383             :     // Connect to a random address. It does not need to be valid, only to not be the loopback address.
     384           1 :     if (enet_address_set_host(&addr, "100.0.100.0") == -1)
     385             :         return false;
     386             : 
     387             :     // Connect the socket. Being UDP, there is no actual outgoing traffic, this just binds it
     388             :     // to a valid port locally, allowing us to get the local IP of the machine.
     389           1 :     if (enet_socket_connect(socket, &addr) == -1)
     390             :         return false;
     391             : 
     392             :     // Fetch the local port & IP.
     393           1 :     if (enet_socket_get_address(socket, &addr) == -1)
     394             :         return false;
     395             : 
     396           1 :     enet_socket_destroy(socket);
     397             : 
     398             :     // Convert to a human readable string.
     399           1 :     char buf[50];
     400           1 :     if (enet_address_get_host_ip(&addr, buf, ARRAY_SIZE(buf)) == -1)
     401             :         return false;
     402             : 
     403           1 :     ip = buf;
     404             : 
     405           1 :     return true;
     406             : }
     407             : }

Generated by: LCOV version 1.16