LCOV - code coverage report
Current view: top level - source/network - NetServer.cpp (source / functions) Hit Total Coverage
Test: 0 A.D. test coverage report Lines: 0 818 0.0 %
Date: 2026-12-03 01:19:39 Functions: 0 66 0.0 %

          Line data    Source code
       1             : /* Copyright (C) 2026 Wildfire Games.
       2             :  * This file is part of 0 A.D.
       3             :  *
       4             :  * 0 A.D. is free software: you can redistribute it and/or modify
       5             :  * it under the terms of the GNU General Public License as published by
       6             :  * the Free Software Foundation, either version 2 of the License, or
       7             :  * (at your option) any later version.
       8             :  *
       9             :  * 0 A.D. is distributed in the hope that it will be useful,
      10             :  * but WITHOUT ANY WARRANTY; without even the implied warranty of
      11             :  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
      12             :  * GNU General Public License for more details.
      13             :  *
      14             :  * You should have received a copy of the GNU General Public License
      15             :  * along with 0 A.D.  If not, see <http://www.gnu.org/licenses/>.
      16             :  */
      17             : 
      18             : #include "precompiled.h"
      19             : 
      20             : #include "NetServer.h"
      21             : 
      22             : #include "lib/code_generation.h"
      23             : #include "lib/debug.h"
      24             : #include "lib/external_libraries/enet.h"
      25             : #include "lib/secure_crt.h"
      26             : #include "lib/status.h"
      27             : #include "lib/utf8.h"
      28             : #include "network/FSM.h"
      29             : #include "network/NetEnet.h"
      30             : #include "network/NetFileTransfer.h"
      31             : #include "network/NetHost.h"
      32             : #include "network/NetMessage.h"
      33             : #include "network/NetProtocol.h"
      34             : #include "network/NetServerTurnManager.h"
      35             : #include "network/NetServerSession.h"
      36             : #include "network/NetStats.h"
      37             : #include "network/StunClient.h"
      38             : #include "ps/CLogger.h"
      39             : #include "ps/ConfigDB.h"
      40             : #include "ps/GUID.h"
      41             : #include "ps/Hashing.h"
      42             : #include "ps/ProfileViewer.h"
      43             : #include "ps/Profiler2.h"
      44             : #include "ps/Threading.h"
      45             : #include "ps/algorithm.h"
      46             : #include "scriptinterface/JSON.h"
      47             : #include "scriptinterface/Object.h"
      48             : #include "scriptinterface/Context.h"
      49             : #include "scriptinterface/Interface.h"
      50             : #include "scriptinterface/Request.h"
      51             : #include "simulation2/helpers/SimulationCommand.h"
      52             : #include "simulation2/system/TurnManager.h"
      53             : 
      54             : #include <algorithm>
      55             : #include <cstring>
      56             : #include <fmt/format.h>
      57             : #include <functional>
      58             : #include <iterator>
      59             : #include <memory>
      60             : #include <set>
      61             : #include <sstream>
      62             : #include <string>
      63             : #include <utility>
      64             : 
      65             : #if CONFIG2_MINIUPNPC
      66             : #include <miniupnpc/igd_desc_parse.h>
      67             : #include <miniupnpc/miniupnpc.h>
      68             : #include <miniupnpc/upnpcommands.h>
      69             : #include <miniupnpc/upnpdev.h>
      70             : #include <miniupnpc/upnperrors.h>
      71             : #endif
      72             : 
      73             : #if FMT_VERSION >= 80000
      74             : #include <fmt/xchar.h>
      75             : #endif
      76             : 
      77             : /**
      78             :  * Number of peers to allocate for the enet host.
      79             :  * Limited by ENET_PROTOCOL_MAXIMUM_PEER_ID (4096).
      80             :  *
      81             :  * At most 8 players, 32 observers and 1 temporary connection to send the "server full" disconnect-reason.
      82             :  */
      83             : #define MAX_CLIENTS 41
      84             : 
      85             : constexpr int CHANNEL_COUNT = 1;
      86             : constexpr int FAILED_PASSWORD_TRIES_BEFORE_BAN = 3;
      87             : 
      88             : /**
      89             :  * enet_host_service timeout (msecs).
      90             :  * Smaller numbers may hurt performance; larger numbers will
      91             :  * hurt latency responding to messages from game thread.
      92             :  */
      93             : static const int HOST_SERVICE_TIMEOUT = 50;
      94             : 
      95             : /**
      96             :  * Once ping goes above turn length * command delay,
      97             :  * the game will start 'freezing' for other clients while we catch up.
      98             :  * Since commands are sent client -> server -> client, divide by 2.
      99             :  * (duplicated in NetServer.cpp to avoid having to fetch the constants in a header file)
     100             :  */
     101             : constexpr std::uint32_t NETWORK_BAD_PING = DEFAULT_TURN_LENGTH * COMMAND_DELAY_MP / 2;
     102             : 
     103             : /**
     104             :  * Legitimate clients only send commands for turns up to about ready turn + COMMAND_DELAY_MP.
     105             :  * Commands further ahead than MAX_COMMAND_TURN_FACTOR * COMMAND_DELAY_MP are treated as an attack.
     106             :  */
     107             : constexpr std::int32_t MAX_COMMAND_TURN_FACTOR = 5;
     108             : 
     109             : CNetServer* g_NetServer = NULL;
     110             : 
     111           0 : static CStr DebugName(CNetServerSession* session)
     112             : {
     113           0 :     if (session == NULL)
     114           0 :         return "[unknown host]";
     115           0 :     if (session->GetGUID().empty())
     116           0 :         return "[unauthed host]";
     117           0 :     return "[" + session->GetGUID().substr(0, 8) + "...]";
     118             : }
     119             : 
     120             : /*
     121             :  * XXX: We use some non-threadsafe functions from the worker thread.
     122             :  * See https://gitea.wildfiregames.com/0ad/0ad/issues/654
     123             :  */
     124             : 
     125           0 : CNetServerWorker::CNetServerWorker(const bool continueSavedGame, std::uint16_t port,
     126             :     const bool useLobbyAuth, std::string password, std::string controllerSecret,
     127           0 :     std::string initAttributes, std::set<std::string> buddies) :
     128           0 :     m_ContinuesSavedGame{continueSavedGame},
     129           0 :     m_LobbyAuth{useLobbyAuth},
     130           0 :     m_Buddies{std::move(buddies)},
     131           0 :     m_ControllerSecret{std::move(controllerSecret)},
     132           0 :     m_Password{std::move(password)}
     133             : {
     134             :     // Bind to default host
     135           0 :     ENetAddress addr;
     136           0 :     addr.host = ENET_HOST_ANY;
     137           0 :     addr.port = port;
     138             : 
     139             :     // Create ENet server
     140           0 :     m_Host.reset(PS::Enet::CreateHost(&addr, MAX_CLIENTS, CHANNEL_COUNT));
     141           0 :     if (!m_Host)
     142             :     {
     143           0 :         LOGERROR("Net server: enet_host_create failed");
     144           0 :         throw std::runtime_error{"Failed to start server"};
     145             :     }
     146             : 
     147           0 :     m_Stats = std::make_unique<CNetStatsTable>();
     148           0 :     if (CProfileViewer::IsInitialised())
     149           0 :         g_ProfileViewer.AddRootTable(m_Stats.get());
     150             : 
     151           0 :     m_State = SERVER_STATE_PREGAME;
     152             : 
     153             :     // Launch the worker thread
     154           0 :     m_WorkerThread = std::thread(Threading::HandleExceptions<RunThread>::Wrapper, this,
     155           0 :         std::move(initAttributes));
     156             : 
     157             : #if CONFIG2_MINIUPNPC
     158             :     // Launch the UPnP thread
     159           0 :     m_UPnPThread = std::thread(Threading::HandleExceptions<SetupUPnP>::Wrapper, port);
     160             : #endif
     161           0 : }
     162             : 
     163           0 : CNetServerWorker::~CNetServerWorker()
     164             : {
     165             :     // Tell the thread to shut down
     166           0 :     {
     167           0 :         std::lock_guard<std::mutex> lock(m_WorkerMutex);
     168           0 :         m_Shutdown = true;
     169           0 :     }
     170             : 
     171             :     // Wait for it to shut down cleanly
     172           0 :     m_WorkerThread.join();
     173             : 
     174             : #if CONFIG2_MINIUPNPC
     175           0 :     if (m_UPnPThread.joinable())
     176           0 :         m_UPnPThread.detach();
     177             : #endif
     178             : 
     179             :     // Clean up resources
     180           0 :     for (const auto& session : m_Sessions)
     181           0 :         session->DisconnectNow(NDR_SERVER_SHUTDOWN);
     182           0 : }
     183             : 
     184             : 
     185           0 : bool CNetServerWorker::CheckPassword(const std::string& password, const std::string& salt) const
     186             : {
     187           0 :     return HashCryptographically(m_Password, salt) == password;
     188             : }
     189             : 
     190             : #if CONFIG2_MINIUPNPC
     191           0 : void CNetServerWorker::SetupUPnP(const std::uint16_t port)
     192             : {
     193           0 :     debug_SetThreadName("UPnP");
     194             : 
     195             :     // Values we want to set.
     196           0 :     char psPort[6];
     197           0 :     sprintf_s(psPort, ARRAY_SIZE(psPort), "%d", port);
     198           0 :     const char* leaseDuration = "0"; // Indefinite/permanent lease duration.
     199           0 :     const char* description = "0AD Multiplayer";
     200           0 :     const char* protocall = "UDP";
     201           0 :     char internalIPAddress[64];
     202           0 :     char externalIPAddress[40];
     203             : 
     204             :     // Variables to hold the values that actually get set.
     205           0 :     char intClient[40];
     206           0 :     char intPort[6];
     207           0 :     char duration[16];
     208             : 
     209             :     // Intermediate variables.
     210           0 :     bool allocatedUrls = false;
     211           0 :     struct UPNPUrls urls;
     212           0 :     struct IGDdatas data;
     213           0 :     struct UPNPDev* devlist = NULL;
     214             : 
     215             :     // Make sure everything is properly freed.
     216           0 :     std::function<void()> freeUPnP = [&allocatedUrls, &urls, &devlist]()
     217             :     {
     218           0 :         if (allocatedUrls)
     219           0 :             FreeUPNPUrls(&urls);
     220           0 :         freeUPNPDevlist(devlist);
     221             :         // IGDdatas does not need to be freed according to UPNP_GetIGDFromUrl
     222           0 :     };
     223             : 
     224             :     // Cached root descriptor URL.
     225           0 :     const std::string rootDescURL{g_ConfigDB.Get("network.upnprootdescurl", std::string{})};
     226           0 :     if (!rootDescURL.empty())
     227           0 :         LOGMESSAGE("Net server: attempting to use cached root descriptor URL: {}", rootDescURL);
     228             : 
     229           0 :     int ret = 0;
     230             : 
     231             :     // Try a cached URL first
     232           0 :     if (!rootDescURL.empty() && UPNP_GetIGDFromUrl(rootDescURL.c_str(), &urls, &data, internalIPAddress, sizeof(internalIPAddress)) && strlen(data.first.controlurl) != 0)
     233             :     {
     234           0 :         LOGMESSAGE("Net server: using cached IGD = {}", urls.controlURL);
     235           0 :         ret = 1;
     236             :     }
     237             :     // No cached URL, or it did not respond. Try discovering the UPnP IGD for 2 seconds.
     238             : #if defined(MINIUPNPC_API_VERSION) && MINIUPNPC_API_VERSION >= 14
     239           0 :     else if ((devlist = upnpDiscover(2000, 0, 0, 0, 0, 2, 0)) != NULL)
     240             : #else
     241             :     else if ((devlist = upnpDiscover(2000, 0, 0, 0, 0, 0)) != NULL)
     242             : #endif
     243             :     {
     244             : #if defined(MINIUPNPC_API_VERSION) && MINIUPNPC_API_VERSION >= 18
     245             :         ret = UPNP_GetValidIGD(devlist, &urls, &data, internalIPAddress, sizeof(internalIPAddress), nullptr, 0);
     246             : #else
     247           0 :         ret = UPNP_GetValidIGD(devlist, &urls, &data, internalIPAddress, sizeof(internalIPAddress));
     248             : #endif
     249           0 :         allocatedUrls = ret != 0; // urls is allocated on non-zero return values
     250             :     }
     251             :     else
     252             :     {
     253           0 :         LOGMESSAGE("Net server: upnpDiscover failed and no working cached URL.");
     254           0 :         freeUPnP();
     255             :         return;
     256             :     }
     257             : 
     258           0 :     switch (ret)
     259             :     {
     260           0 :     case 0:
     261           0 :         LOGMESSAGE("Net server: No IGD found");
     262           0 :         break;
     263           0 :     case 1:
     264           0 :         LOGMESSAGE("Net server: found valid IGD = {}", urls.controlURL);
     265           0 :         break;
     266             : #if defined(MINIUPNPC_API_VERSION) && MINIUPNPC_API_VERSION >= 18
     267             :     case 2:
     268             :         LOGMESSAGE("Net server: found IGD with reserved IP = {}, will try to continue anyway",
     269             :             urls.controlURL);
     270             :         break;
     271             :     case 3:
     272             : #else
     273           0 :     case 2:
     274             : #endif
     275           0 :         LOGMESSAGE("Net server: found a valid, not connected IGD = {}, will try to continue anyway",
     276             :             urls.controlURL);
     277           0 :         break;
     278             : #if defined(MINIUPNPC_API_VERSION) && MINIUPNPC_API_VERSION >= 18
     279             :     case 4:
     280             : #else
     281           0 :     case 3:
     282             : #endif
     283           0 :         LOGMESSAGE("Net server: found a UPnP device unrecognized as IGD = {}, will try to continue "
     284             :             "anyway", urls.controlURL);
     285           0 :         break;
     286           0 :     default:
     287           0 :         debug_warn(L"Unrecognized return value from UPNP_GetValidIGD");
     288             :     }
     289             : 
     290             :     // Try getting our external/internet facing IP. TODO: Display this on the game-setup page for convenience.
     291           0 :     ret = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
     292           0 :     if (ret != UPNPCOMMAND_SUCCESS)
     293             :     {
     294           0 :         LOGMESSAGE("Net server: GetExternalIPAddress failed with code {} ({})", ret,
     295             :             strupnperror(ret));
     296           0 :         freeUPnP();
     297             :         return;
     298             :     }
     299           0 :     LOGMESSAGE("Net server: ExternalIPAddress = {}", externalIPAddress);
     300             : 
     301             :     // Try to setup port forwarding.
     302           0 :     ret = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, psPort, psPort,
     303             :                             internalIPAddress, description, protocall, 0, leaseDuration);
     304           0 :     if (ret != UPNPCOMMAND_SUCCESS)
     305             :     {
     306           0 :         LOGMESSAGE("Net server: AddPortMapping({}, {}, {}) failed with code {} ({})",
     307             :             psPort, psPort, internalIPAddress, ret, strupnperror(ret));
     308           0 :         freeUPnP();
     309             :         return;
     310             :     }
     311             : 
     312             :     // Check that the port was actually forwarded.
     313           0 :     ret = UPNP_GetSpecificPortMappingEntry(urls.controlURL,
     314             :                                      data.first.servicetype,
     315             :                                      psPort, protocall,
     316             : #if defined(MINIUPNPC_API_VERSION) && MINIUPNPC_API_VERSION >= 10
     317             :                                      NULL/*remoteHost*/,
     318             : #endif
     319             :                                      intClient, intPort, NULL/*desc*/,
     320             :                                      NULL/*enabled*/, duration);
     321             : 
     322           0 :     if (ret != UPNPCOMMAND_SUCCESS)
     323             :     {
     324           0 :         LOGMESSAGE("Net server: GetSpecificPortMappingEntry() failed with code {} ({})", ret,
     325             :             strupnperror(ret));
     326           0 :         freeUPnP();
     327             :         return;
     328             :     }
     329             : 
     330           0 :     LOGMESSAGE("Net server: External {}:{} {} is redirected to internal {}:{} (duration={})",
     331             :         externalIPAddress, psPort, protocall, intClient, intPort, duration);
     332             : 
     333             :     // Cache root descriptor URL to try to avoid discovery next time.
     334           0 :     g_ConfigDB.SetValueString(CFG_USER, "network.upnprootdescurl", urls.rootdescURL);
     335           0 :     g_ConfigDB.WriteValueToFile(CFG_USER, "network.upnprootdescurl", urls.rootdescURL);
     336           0 :     LOGMESSAGE("Net server: cached UPnP root descriptor URL as {}", urls.rootdescURL);
     337             : 
     338           0 :     freeUPnP();
     339           0 : }
     340             : #endif // CONFIG2_MINIUPNPC
     341             : 
     342           0 : bool CNetServerWorker::SendMessage(ENetPeer* peer, const CNetMessage* message)
     343             : {
     344           0 :     ENSURE(m_Host);
     345             : 
     346           0 :     CNetServerSession* session = static_cast<CNetServerSession*>(peer->data);
     347             : 
     348           0 :     return CNetHost::SendMessage(message, peer, DebugName(session).c_str());
     349             : }
     350             : 
     351           0 : bool CNetServerWorker::Multicast(const CNetMessage* message,
     352             :     const std::vector<NetServerSessionState>& targetStates,
     353             :     const std::optional<std::vector<std::string>>& receivers /* = std::nullopt */)
     354             : {
     355           0 :     ENSURE(m_Host);
     356             : 
     357           0 :     const auto isReceiver = [&](const CNetServerSession& session)
     358             :         {
     359           0 :             if (!PS::contains(targetStates,
     360           0 :                 static_cast<NetServerSessionState>(session.GetCurrState())))
     361             :             {
     362             :                 return false;
     363             :             }
     364           0 :             if (!receivers)
     365             :                 return true;
     366           0 :             return PS::contains(*receivers, session.GetGUID());
     367           0 :         };
     368             : 
     369           0 :     bool ok = true;
     370             : 
     371             :     // TODO: this does lots of repeated message serialisation if we have lots
     372             :     // of remote peers; could do it more efficiently if that's a real problem
     373             : 
     374           0 :     for (const auto& session : m_Sessions)
     375           0 :         if (isReceiver(*session) && !session->SendMessage(message))
     376             :             ok = false;
     377             : 
     378           0 :     return ok;
     379             : }
     380             : 
     381           0 : void CNetServerWorker::RunThread(CNetServerWorker* data, const std::string& initAttributes)
     382             : {
     383           0 :     debug_SetThreadName("NetServer");
     384             : 
     385           0 :     data->Run(initAttributes);
     386           0 : }
     387             : 
     388           0 : void CNetServerWorker::Run(const std::string& initAttributes)
     389             : {
     390             :     // The script context uses the profiler and therefore the thread must be registered before the context is created
     391           0 :     g_Profiler2.RegisterCurrentThread("Net server");
     392             : 
     393             :     // We create a new Script::Context for this network thread, with a single Script::Interface.
     394           0 :     Script::Context netServerContext;
     395           0 :     m_ScriptInterface = new Script::Interface("Engine", "Net server", netServerContext);
     396           0 :     m_InitAttributes.init(m_ScriptInterface->GetGeneralJSContext(), JS::UndefinedValue());
     397             : 
     398           0 :     if (!initAttributes.empty())
     399             :     {
     400           0 :         Script::Request rq(m_ScriptInterface);
     401           0 :         JS::RootedValue gameAttributesVal(rq.cx);
     402           0 :         Script::ParseJSON(rq, std::move(initAttributes), &gameAttributesVal);
     403           0 :         m_InitAttributes = gameAttributesVal;
     404           0 :     }
     405             : 
     406           0 :     while (true)
     407             :     {
     408           0 :         if (!RunStep())
     409             :             break;
     410             : 
     411             :         // Update profiler stats
     412           0 :         m_Stats->LatchHostState(*m_Host);
     413             :     }
     414             : 
     415             :     // Clear roots before deleting their context
     416           0 :     m_SavedCommands.clear();
     417             : 
     418           0 :     SAFE_DELETE(m_ScriptInterface);
     419           0 : }
     420             : 
     421           0 : bool CNetServerWorker::RunStep()
     422             : {
     423             :     // Check for messages from the game thread.
     424             :     // (Do as little work as possible while the mutex is held open,
     425             :     // to avoid performance problems and deadlocks.)
     426             : 
     427           0 :     m_ScriptInterface->GetContext().MaybeIncrementalGC();
     428             : 
     429           0 :     Script::Request rq(m_ScriptInterface);
     430             : 
     431           0 :     std::vector<bool> newStartGame;
     432           0 :     std::vector<std::pair<CStr, CStr>> newLobbyAuths;
     433           0 :     std::vector<std::uint32_t> newTurnLength;
     434             : 
     435           0 :     {
     436           0 :         std::lock_guard<std::mutex> lock(m_WorkerMutex);
     437             : 
     438           0 :         if (m_Shutdown)
     439           0 :             return false;
     440             : 
     441           0 :         newStartGame.swap(m_StartGameQueue);
     442           0 :         newLobbyAuths.swap(m_LobbyAuthQueue);
     443           0 :         newTurnLength.swap(m_TurnLengthQueue);
     444           0 :     }
     445             : 
     446           0 :     if (!newTurnLength.empty())
     447           0 :         SetTurnLength(newTurnLength.back());
     448             : 
     449           0 :     while (!newLobbyAuths.empty())
     450             :     {
     451           0 :         const std::pair<CStr, CStr>& auth = newLobbyAuths.back();
     452           0 :         ProcessLobbyAuth(auth.first, auth.second);
     453           0 :         newLobbyAuths.pop_back();
     454             :     }
     455             : 
     456             :     // Perform file transfers
     457           0 :     for (const auto& session : m_Sessions)
     458           0 :         session->GetFileTransferer().Poll();
     459             : 
     460           0 :     CheckClientConnections();
     461             : 
     462             :     // Process network events:
     463             : 
     464           0 :     ENetEvent event;
     465           0 :     int status = enet_host_service(m_Host.get(), &event, HOST_SERVICE_TIMEOUT);
     466           0 :     if (status < 0)
     467             :     {
     468           0 :         LOGERROR("CNetServerWorker: enet_host_service failed ({})", status);
     469             :         // TODO: notify game that the server has shut down
     470           0 :         return false;
     471             :     }
     472             : 
     473           0 :     if (status == 0)
     474             :     {
     475             :         // Reached timeout with no events - try again
     476             :         return true;
     477             :     }
     478             : 
     479             :     // Process the event:
     480             : 
     481           0 :     switch (event.type)
     482             :     {
     483           0 :     case ENET_EVENT_TYPE_CONNECT:
     484           0 :     {
     485             :         // Report the client address
     486           0 :         char hostname[256] = "(error)";
     487           0 :         enet_address_get_host_ip(&event.peer->address, hostname, ARRAY_SIZE(hostname));
     488           0 :         LOGMESSAGE("Net server: Received connection from {}:{}", hostname,
     489             :             event.peer->address.port);
     490             : 
     491             :         // Set up a session object for this peer
     492             : 
     493           0 :         const std::unique_ptr<CNetServerSession>& session{m_Sessions.emplace_back(
     494           0 :             std::make_unique<CNetServerSession>(*this, event.peer))};
     495             : 
     496           0 :         SetupSession(session.get());
     497             : 
     498           0 :         ENSURE(event.peer->data == NULL);
     499           0 :         event.peer->data = session.get();
     500             : 
     501           0 :         HandleConnect(session.get());
     502             : 
     503           0 :         break;
     504             :     }
     505             : 
     506           0 :     case ENET_EVENT_TYPE_DISCONNECT:
     507           0 :     {
     508             :         // If there is an active session with this peer, then reset and delete it
     509             : 
     510           0 :         CNetServerSession* session = static_cast<CNetServerSession*>(event.peer->data);
     511           0 :         if (session)
     512             :         {
     513           0 :             LOGMESSAGE("Net server: Disconnected {}", DebugName(session));
     514             : 
     515             :             // Remove the session first, so we won't send player-update messages to it
     516             :             // when updating the FSM
     517           0 :             const auto iter = std::ranges::find(m_Sessions, session,
     518             :                 &std::unique_ptr<CNetServerSession>::get);
     519           0 :             const std::unique_ptr<CNetServerSession> _ = std::move(*iter);
     520           0 :             m_Sessions.erase(iter);
     521             : 
     522           0 :             session->Update(static_cast<unsigned int>(NMT_CONNECTION_LOST), nullptr);
     523             : 
     524           0 :             event.peer->data = NULL;
     525           0 :         }
     526             : 
     527           0 :         if (m_State == SERVER_STATE_LOADING)
     528           0 :             CheckGameLoadStatus(NULL);
     529             : 
     530           0 :         break;
     531             :     }
     532             : 
     533           0 :     case ENET_EVENT_TYPE_RECEIVE:
     534           0 :     {
     535             :         // If there is an active session with this peer, then process the message
     536             : 
     537           0 :         CNetServerSession* session = static_cast<CNetServerSession*>(event.peer->data);
     538           0 :         if (session)
     539             :         {
     540             :             // Create message from raw data
     541           0 :             CNetMessage* msg = CNetMessageFactory::CreateMessage(event.packet->data, event.packet->dataLength, GetScriptInterface());
     542           0 :             if (msg)
     543             :             {
     544           0 :                 LOGMESSAGE("Net server: Received message {} of size {} from {}",
     545             :                     msg->ToString(), msg->GetSerializedLength(), DebugName(session));
     546             : 
     547           0 :                 HandleMessageReceive(msg, session);
     548             : 
     549           0 :                 delete msg;
     550             :             }
     551             :         }
     552             : 
     553             :         // Done using the packet
     554           0 :         enet_packet_destroy(event.packet);
     555             : 
     556             :         break;
     557             :     }
     558             : 
     559             :     case ENET_EVENT_TYPE_NONE:
     560             :         break;
     561             :     }
     562             : 
     563             :     return true;
     564           0 : }
     565             : 
     566           0 : void CNetServerWorker::CheckClientConnections()
     567             : {
     568             :     // Send messages at most once per second
     569           0 :     std::time_t now = std::time(nullptr);
     570           0 :     if (now <= m_LastConnectionCheck)
     571             :         return;
     572             : 
     573           0 :     m_LastConnectionCheck = now;
     574             : 
     575           0 :     for (size_t i = 0; i < m_Sessions.size(); ++i)
     576             :     {
     577           0 :         std::uint32_t lastReceived = m_Sessions[i]->GetLastReceivedTime();
     578           0 :         std::uint32_t meanRTT = m_Sessions[i]->GetMeanRTT();
     579             : 
     580           0 :         CNetMessage* message = nullptr;
     581             : 
     582             :         // Report if we didn't hear from the client since few seconds
     583           0 :         if (lastReceived > NETWORK_WARNING_TIMEOUT)
     584             :         {
     585           0 :             CClientTimeoutMessage* msg = new CClientTimeoutMessage();
     586           0 :             msg->m_GUID = m_Sessions[i]->GetGUID();
     587           0 :             msg->m_LastReceivedTime = lastReceived;
     588           0 :             message = msg;
     589             :         }
     590             :         // Report if the client has bad ping
     591           0 :         else if (meanRTT > NETWORK_BAD_PING)
     592             :         {
     593           0 :             CClientPerformanceMessage* msg = new CClientPerformanceMessage();
     594           0 :             CClientPerformanceMessage::S_m_Clients client;
     595           0 :             client.m_GUID = m_Sessions[i]->GetGUID();
     596           0 :             client.m_MeanRTT = meanRTT;
     597           0 :             msg->m_Clients.push_back(client);
     598           0 :             message = msg;
     599           0 :         }
     600             : 
     601             :         // Send to all clients except the affected one
     602             :         // (since that will show the locally triggered warning instead).
     603             :         // Also send it to clients that finished the loading screen while
     604             :         // the game is still waiting for other clients to finish the loading screen.
     605           0 :         if (message)
     606           0 :             for (size_t j = 0; j < m_Sessions.size(); ++j)
     607             :             {
     608           0 :                 if (i != j && (
     609           0 :                     (m_Sessions[j]->GetCurrState() == NSS_PREGAME && m_State == SERVER_STATE_PREGAME) ||
     610           0 :                     m_Sessions[j]->GetCurrState() == NSS_INGAME))
     611             :                 {
     612           0 :                     m_Sessions[j]->SendMessage(message);
     613             :                 }
     614             :             }
     615             : 
     616           0 :         SAFE_DELETE(message);
     617             :     }
     618             : }
     619             : 
     620           0 : void CNetServerWorker::HandleMessageReceive(CNetMessage* message, CNetServerSession* session)
     621             : {
     622             :     // Handle non-FSM messages first
     623           0 :     Status status = session->GetFileTransferer().HandleMessageReceive(*message);
     624           0 :     if (status != INFO::SKIPPED)
     625             :         return;
     626             : 
     627           0 :     if (message->GetType() == NMT_FILE_TRANSFER_REQUEST)
     628             :     {
     629           0 :         CFileTransferRequestMessage* reqMessage = (CFileTransferRequestMessage*)message;
     630             : 
     631             :         // A client requested the gamestate. Clients only request the gamestate when we sent them a
     632             :         // JoinSyncStart or a GameSavedStart message. We only send those messages after we received the
     633             :         // gamestate.
     634             :         // For joins and loads the gamestate is in a different format. Send the respective one.
     635             : 
     636           0 :         session->GetFileTransferer().StartResponse(reqMessage->m_RequestID,
     637           0 :             static_cast<CNetFileTransferer::RequestType>(reqMessage->m_RequestType) ==
     638             :                 CNetFileTransferer::RequestType::LOADGAME ? m_SavedState : m_JoinSyncFile);
     639             : 
     640           0 :         return;
     641             :     }
     642             : 
     643             :     // Update FSM
     644           0 :     if (!session->Update(message->GetType(), message))
     645           0 :         LOGERROR("Net server: Error running FSM update (type={} state={})",
     646             :             static_cast<int>(message->GetType()), static_cast<int>(session->GetCurrState()));
     647             : }
     648             : 
     649           0 : void CNetServerWorker::SetupSession(CNetServerSession* session)
     650             : {
     651             :     // Set up transitions for session
     652             : 
     653           0 :     session->AddTransition(NSS_UNCONNECTED, static_cast<unsigned int>(NMT_CONNECTION_LOST),
     654             :         NSS_UNCONNECTED);
     655             : 
     656           0 :     session->AddTransition(NSS_HANDSHAKE, static_cast<unsigned int>(NMT_CONNECTION_LOST),
     657             :         NSS_UNCONNECTED);
     658           0 :     session->AddTransition(NSS_HANDSHAKE, static_cast<unsigned int>(NMT_CLIENT_HANDSHAKE),
     659             :         NSS_AUTHENTICATE, &OnClientHandshake, session);
     660             : 
     661           0 :     session->AddTransition(NSS_LOBBY_AUTHENTICATE, static_cast<unsigned int>(NMT_CONNECTION_LOST),
     662             :         NSS_UNCONNECTED);
     663           0 :     session->AddTransition(NSS_LOBBY_AUTHENTICATE, static_cast<unsigned int>(NMT_AUTHENTICATE),
     664             :         NSS_PREGAME, &OnAuthenticate, session);
     665             : 
     666           0 :     session->AddTransition(NSS_AUTHENTICATE, static_cast<unsigned int>(NMT_CONNECTION_LOST),
     667             :         NSS_UNCONNECTED);
     668           0 :     session->AddTransition(NSS_AUTHENTICATE, static_cast<unsigned int>(NMT_AUTHENTICATE), NSS_PREGAME,
     669             :         &OnAuthenticate, session);
     670             : 
     671           0 :     session->AddTransition(NSS_PREGAME, static_cast<unsigned int>(NMT_CONNECTION_LOST), NSS_UNCONNECTED,
     672             :         &OnDisconnect, session);
     673           0 :     session->AddTransition(NSS_PREGAME, static_cast<unsigned int>(NMT_CHAT), NSS_PREGAME, &OnChat,
     674             :         session);
     675           0 :     session->AddTransition(NSS_PREGAME, static_cast<unsigned int>(NMT_READY), NSS_PREGAME, &OnReady,
     676             :         session);
     677           0 :     session->AddTransition(NSS_PREGAME, static_cast<unsigned int>(NMT_CLEAR_ALL_READY), NSS_PREGAME,
     678             :         &OnClearAllReady, session);
     679           0 :     session->AddTransition(NSS_PREGAME, static_cast<unsigned int>(NMT_GAME_SETUP), NSS_PREGAME,
     680             :         &OnGameSetup, session);
     681           0 :     session->AddTransition(NSS_PREGAME, static_cast<unsigned int>(NMT_ASSIGN_PLAYER), NSS_PREGAME,
     682             :         &OnAssignPlayer, session);
     683           0 :     session->AddTransition(NSS_PREGAME, static_cast<unsigned int>(NMT_KICKED), NSS_PREGAME,
     684             :         &OnKickPlayer, session);
     685           0 :     session->AddTransition(NSS_PREGAME, static_cast<unsigned int>(NMT_GAME_START), NSS_PREGAME,
     686             :         &OnGameStart, session);
     687           0 :     session->AddTransition(NSS_PREGAME, static_cast<unsigned int>(NMT_SAVED_GAME_START), NSS_PREGAME,
     688             :         &OnSavedGameStart, session);
     689           0 :     session->AddTransition(NSS_PREGAME, static_cast<unsigned int>(NMT_LOADED_GAME), NSS_INGAME,
     690             :         &OnLoadedGame, session);
     691             : 
     692           0 :     session->AddTransition(NSS_JOIN_SYNCING, static_cast<unsigned int>(NMT_KICKED), NSS_JOIN_SYNCING,
     693             :         &OnKickPlayer, session);
     694           0 :     session->AddTransition(NSS_JOIN_SYNCING, static_cast<unsigned int>(NMT_CONNECTION_LOST),
     695             :         NSS_UNCONNECTED, &OnDisconnect, session);
     696           0 :     session->AddTransition(NSS_JOIN_SYNCING, static_cast<unsigned int>(NMT_LOADED_GAME), NSS_INGAME,
     697             :         &OnJoinSyncingLoadedGame, session);
     698             : 
     699           0 :     session->AddTransition(NSS_INGAME, static_cast<unsigned int>(NMT_REJOINED), NSS_INGAME, &OnRejoined,
     700             :         session);
     701           0 :     session->AddTransition(NSS_INGAME, static_cast<unsigned int>(NMT_KICKED), NSS_INGAME, &OnKickPlayer,
     702             :         session);
     703           0 :     session->AddTransition(NSS_INGAME, static_cast<unsigned int>(NMT_CLIENT_PAUSED), NSS_INGAME,
     704             :         &OnClientPaused, session);
     705           0 :     session->AddTransition(NSS_INGAME, static_cast<unsigned int>(NMT_CONNECTION_LOST), NSS_UNCONNECTED,
     706             :         &OnDisconnect, session);
     707           0 :     session->AddTransition(NSS_INGAME, static_cast<unsigned int>(NMT_CHAT), NSS_INGAME, &OnChat,
     708             :         session);
     709           0 :     session->AddTransition(NSS_INGAME, static_cast<unsigned int>(NMT_SIMULATION_COMMAND), NSS_INGAME,
     710             :         &OnSimulationCommand, session);
     711           0 :     session->AddTransition(NSS_INGAME, static_cast<unsigned int>(NMT_FLARE), NSS_INGAME, &OnFlare,
     712             :         session);
     713           0 :     session->AddTransition(NSS_INGAME, static_cast<unsigned int>(NMT_SYNC_CHECK), NSS_INGAME,
     714             :         &OnSyncCheck, session);
     715           0 :     session->AddTransition(NSS_INGAME, static_cast<unsigned int>(NMT_END_COMMAND_BATCH), NSS_INGAME,
     716             :         &OnEndCommandBatch, session);
     717             : 
     718             :     // Set first state
     719           0 :     session->SetFirstState(NSS_HANDSHAKE);
     720           0 : }
     721             : 
     722           0 : bool CNetServerWorker::HandleConnect(CNetServerSession* session)
     723             : {
     724           0 :     if (std::find(m_BannedIPs.begin(), m_BannedIPs.end(), session->GetIPAddress()) != m_BannedIPs.end())
     725             :     {
     726           0 :         session->Disconnect(NDR_BANNED);
     727           0 :         return false;
     728             :     }
     729             : 
     730           0 :     const CSrvHandshakeMessage handshake(CreateHandshake<CSrvHandshakeMessage>());
     731           0 :     return session->SendMessage(&handshake);
     732           0 : }
     733             : 
     734           0 : void CNetServerWorker::OnUserJoin(CNetServerSession* session)
     735             : {
     736           0 :     AddPlayer(session->GetGUID(), session->GetUserName());
     737             : 
     738           0 :     CPlayerAssignmentMessage assignMessage;
     739           0 :     ConstructPlayerAssignmentMessage(assignMessage);
     740           0 :     session->SendMessage(&assignMessage);
     741           0 : }
     742             : 
     743           0 : void CNetServerWorker::OnUserLeave(CNetServerSession* session)
     744             : {
     745           0 :     std::vector<CStr>::iterator pausing = std::find(m_PausingPlayers.begin(), m_PausingPlayers.end(), session->GetGUID());
     746           0 :     if (pausing != m_PausingPlayers.end())
     747           0 :         m_PausingPlayers.erase(pausing);
     748             : 
     749           0 :     RemovePlayer(session->GetGUID());
     750             : 
     751           0 :     if (m_ServerTurnManager && session->GetCurrState() != NSS_JOIN_SYNCING)
     752           0 :         m_ServerTurnManager->UninitialiseClient(session->GetHostID());
     753             : 
     754             :     // TODO: ought to switch the player controlled by that client
     755             :     // back to AI control, or something?
     756           0 : }
     757             : 
     758           0 : void CNetServerWorker::AddPlayer(const CStr& guid, const CStrW& name)
     759             : {
     760             :     // Find all player IDs in active use; we mustn't give them to a second player (excluding the unassigned ID: -1)
     761           0 :     std::set<std::int32_t> usedIDs;
     762           0 :     for (const std::pair<const CStr, PlayerAssignment>& p : m_PlayerAssignments)
     763           0 :         if (p.second.m_Enabled && p.second.m_PlayerID != -1)
     764           0 :             usedIDs.insert(p.second.m_PlayerID);
     765             : 
     766             :     // If the player is rejoining after disconnecting, try to give them
     767             :     // back their old player ID. Don't do this in pregame however,
     768             :     // as that ID might be invalid for various reasons.
     769             : 
     770           0 :     std::int32_t playerID = -1;
     771             : 
     772           0 :     if (m_State != SERVER_STATE_PREGAME)
     773             :     {
     774             :         // Try to match GUID first
     775           0 :         for (PlayerAssignmentMap::iterator it = m_PlayerAssignments.begin(); it != m_PlayerAssignments.end(); ++it)
     776             :         {
     777           0 :             if (!it->second.m_Enabled && it->first == guid && usedIDs.find(it->second.m_PlayerID) == usedIDs.end())
     778             :             {
     779           0 :                 playerID = it->second.m_PlayerID;
     780           0 :                 m_PlayerAssignments.erase(it); // delete the old mapping, since we've got a new one now
     781           0 :                 goto found;
     782             :             }
     783             :         }
     784             : 
     785             :         // Try to match username next
     786           0 :         for (PlayerAssignmentMap::iterator it = m_PlayerAssignments.begin(); it != m_PlayerAssignments.end(); ++it)
     787             :         {
     788           0 :             if (!it->second.m_Enabled && it->second.m_Name == name && usedIDs.find(it->second.m_PlayerID) == usedIDs.end())
     789             :             {
     790           0 :                 playerID = it->second.m_PlayerID;
     791           0 :                 m_PlayerAssignments.erase(it); // delete the old mapping, since we've got a new one now
     792           0 :                 goto found;
     793             :             }
     794             :         }
     795             :     }
     796             : 
     797           0 : found:
     798           0 :     PlayerAssignment assignment;
     799           0 :     assignment.m_Enabled = true;
     800           0 :     assignment.m_Name = name;
     801           0 :     assignment.m_PlayerID = playerID;
     802           0 :     assignment.m_Status = 0;
     803           0 :     m_PlayerAssignments[guid] = assignment;
     804             : 
     805             :     // Send the new assignments to all currently active players
     806             :     // (which does not include the one that's just joining)
     807           0 :     SendPlayerAssignments();
     808           0 : }
     809             : 
     810           0 : void CNetServerWorker::RemovePlayer(const CStr& guid)
     811             : {
     812           0 :     m_PlayerAssignments[guid].m_Enabled = false;
     813             : 
     814           0 :     SendPlayerAssignments();
     815           0 : }
     816             : 
     817           0 : void CNetServerWorker::ClearAllPlayerReady()
     818             : {
     819           0 :     for (std::pair<const CStr, PlayerAssignment>& p : m_PlayerAssignments)
     820           0 :         if (p.second.m_Status != 2)
     821           0 :             p.second.m_Status = 0;
     822             : 
     823           0 :     SendPlayerAssignments();
     824           0 : }
     825             : 
     826           0 : void CNetServerWorker::KickPlayer(const CStrW& playerName, const bool ban)
     827             : {
     828             :     // Find the user with that name
     829           0 :     const auto it = std::find_if(m_Sessions.begin(), m_Sessions.end(),
     830           0 :         [&](const auto& session) { return session->GetUserName() == playerName; });
     831             : 
     832             :     // and return if no one or the host has that name
     833           0 :     if (it == m_Sessions.end() || (*it)->GetGUID() == m_ControllerGUID)
     834           0 :         return;
     835             : 
     836           0 :     if (ban)
     837             :     {
     838             :         // Remember name
     839           0 :         if (std::find(m_BannedPlayers.begin(), m_BannedPlayers.end(), playerName) == m_BannedPlayers.end())
     840           0 :             m_BannedPlayers.push_back(m_LobbyAuth ? CStrW(playerName.substr(0, playerName.find(L" ("))) : playerName);
     841             : 
     842             :         // Remember IP address
     843           0 :         std::uint32_t ipAddress = (*it)->GetIPAddress();
     844           0 :         if (std::find(m_BannedIPs.begin(), m_BannedIPs.end(), ipAddress) == m_BannedIPs.end())
     845           0 :             m_BannedIPs.push_back(ipAddress);
     846             :     }
     847             : 
     848             :     // Disconnect that user
     849           0 :     (*it)->Disconnect(ban ? NDR_BANNED : NDR_KICKED);
     850             : 
     851             :     // Send message notifying other clients
     852           0 :     CKickedMessage kickedMessage;
     853           0 :     kickedMessage.m_Name = playerName;
     854           0 :     kickedMessage.m_Ban = ban;
     855           0 :     Multicast(&kickedMessage, { NSS_PREGAME, NSS_JOIN_SYNCING, NSS_INGAME });
     856           0 : }
     857             : 
     858           0 : void CNetServerWorker::AssignPlayer(int playerID, const CStr& guid)
     859             : {
     860             :     // Remove anyone who's already assigned to this player
     861           0 :     for (std::pair<const CStr, PlayerAssignment>& p : m_PlayerAssignments)
     862             :     {
     863           0 :         if (p.second.m_PlayerID == playerID)
     864           0 :             p.second.m_PlayerID = -1;
     865             :     }
     866             : 
     867             :     // Update this host's assignment if it exists
     868           0 :     if (m_PlayerAssignments.find(guid) != m_PlayerAssignments.end())
     869           0 :         m_PlayerAssignments[guid].m_PlayerID = playerID;
     870             : 
     871           0 :     SendPlayerAssignments();
     872           0 : }
     873             : 
     874           0 : void CNetServerWorker::ConstructPlayerAssignmentMessage(CPlayerAssignmentMessage& message)
     875             : {
     876           0 :     for (const std::pair<const CStr, PlayerAssignment>& p : m_PlayerAssignments)
     877             :     {
     878           0 :         if (!p.second.m_Enabled)
     879           0 :             continue;
     880             : 
     881           0 :         CPlayerAssignmentMessage::S_m_Hosts h;
     882           0 :         h.m_GUID = p.first;
     883           0 :         h.m_Name = p.second.m_Name;
     884           0 :         h.m_PlayerID = p.second.m_PlayerID;
     885           0 :         h.m_Status = p.second.m_Status;
     886           0 :         message.m_Hosts.push_back(h);
     887           0 :     }
     888           0 : }
     889             : 
     890           0 : void CNetServerWorker::SendPlayerAssignments()
     891             : {
     892           0 :     CPlayerAssignmentMessage message;
     893           0 :     ConstructPlayerAssignmentMessage(message);
     894           0 :     Multicast(&message, { NSS_PREGAME, NSS_JOIN_SYNCING, NSS_INGAME });
     895           0 : }
     896             : 
     897           0 : const Script::Interface& CNetServerWorker::GetScriptInterface()
     898             : {
     899           0 :     return *m_ScriptInterface;
     900             : }
     901             : 
     902           0 : void CNetServerWorker::SetTurnLength(std::uint32_t msecs)
     903             : {
     904           0 :     if (m_ServerTurnManager)
     905           0 :         m_ServerTurnManager->SetTurnLength(msecs);
     906           0 : }
     907             : 
     908           0 : void CNetServerWorker::ProcessLobbyAuth(const CStr& name, const CStr& token)
     909             : {
     910           0 :     LOGMESSAGE("Net Server: Received lobby auth message from {} with {}", name, token);
     911             :     // Find the user with that guid
     912           0 :     const auto it = std::find_if(m_Sessions.begin(), m_Sessions.end(),
     913           0 :         [&](const auto& session) { return session->GetGUID() == token; });
     914             : 
     915           0 :     if (it == m_Sessions.end())
     916           0 :         return;
     917             : 
     918           0 :     (*it)->SetUserName(name.FromUTF8());
     919             :     // Send an empty message to request the authentication message from the client
     920             :     // after its identity has been confirmed via the lobby
     921           0 :     CAuthenticateMessage emptyMessage;
     922           0 :     (*it)->SendMessage(&emptyMessage);
     923           0 : }
     924             : 
     925           0 : bool CNetServerWorker::OnClientHandshake(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
     926             : {
     927           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_CLIENT_HANDSHAKE));
     928             : 
     929           0 :     CNetServerWorker& server = session->GetServer();
     930             : 
     931           0 :     CCliHandshakeMessage* message = (CCliHandshakeMessage*)event->GetParamRef();
     932           0 :     if (message->m_ProtocolVersion != PS_PROTOCOL_VERSION)
     933             :     {
     934           0 :         session->Disconnect(NDR_INCORRECT_PROTOCOL_VERSION);
     935           0 :         return false;
     936             :     }
     937             : 
     938           0 :     if (CheckHandshake(CreateHandshake<CSrvHandshakeMessage>(), *message))
     939             :     {
     940           0 :         session->Disconnect(NDR_INCORRECT_SOFTWARE_VERSION);
     941           0 :         return false;
     942             :     }
     943             : 
     944           0 :     CStr guid = ps_generate_guid();
     945             :     int count = 0;
     946             :     // Ensure unique GUID
     947           0 :     while(std::find_if(
     948             :         server.m_Sessions.begin(), server.m_Sessions.end(),
     949           0 :         [&guid] (const auto& session)
     950           0 :         { return session->GetGUID() == guid; }) != server.m_Sessions.end())
     951             :     {
     952           0 :         if (++count > 100)
     953             :         {
     954           0 :             session->Disconnect(NDR_GUID_FAILED);
     955             :             return true;
     956             :         }
     957           0 :         guid = ps_generate_guid();
     958             :     }
     959             : 
     960           0 :     session->SetGUID(guid);
     961             : 
     962           0 :     CSrvHandshakeResponseMessage handshakeResponse;
     963           0 :     handshakeResponse.m_UseProtocolVersion = PS_PROTOCOL_VERSION;
     964           0 :     handshakeResponse.m_GUID = guid;
     965           0 :     handshakeResponse.m_Flags = 0;
     966             : 
     967           0 :     if (server.m_LobbyAuth)
     968             :     {
     969           0 :         handshakeResponse.m_Flags |= PS_NETWORK_FLAG_REQUIRE_LOBBYAUTH;
     970           0 :         session->SetNextState(NSS_LOBBY_AUTHENTICATE);
     971             :     }
     972             : 
     973           0 :     session->SendMessage(&handshakeResponse);
     974             : 
     975           0 :     return true;
     976             : }
     977             : 
     978           0 : bool CNetServerWorker::OnAuthenticate(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
     979             : {
     980           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_AUTHENTICATE));
     981             : 
     982           0 :     CNetServerWorker& server = session->GetServer();
     983             : 
     984             :     // Prohibit joins while the game is loading
     985           0 :     if (server.m_State == SERVER_STATE_LOADING)
     986             :     {
     987           0 :         LOGMESSAGE("Refused connection while the game is loading");
     988           0 :         session->Disconnect(NDR_SERVER_LOADING);
     989           0 :         return true;
     990             :     }
     991             : 
     992           0 :     CAuthenticateMessage* message = (CAuthenticateMessage*)event->GetParamRef();
     993           0 :     CStrW username = SanitisePlayerName(message->m_Name);
     994           0 :     CStrW usernameWithoutRating(username.substr(0, username.find(L" (")));
     995             : 
     996             :     // Compare the lowercase names as specified by https://xmpp.org/extensions/xep-0029.html#sect-idm139493404168176
     997             :     // "[...] comparisons will be made in case-normalized canonical form."
     998           0 :     if (server.m_LobbyAuth && usernameWithoutRating.LowerCase() != session->GetUserName().LowerCase())
     999             :     {
    1000           0 :         LOGERROR("Net server: lobby auth: {} tried joining as {}", session->GetUserName().ToUTF8(),
    1001             :             usernameWithoutRating.ToUTF8());
    1002           0 :         session->Disconnect(NDR_LOBBY_AUTH_FAILED);
    1003             :         return true;
    1004             :     }
    1005             : 
    1006             :     // Check the password before anything else.
    1007             :     // NB: m_Name must match the client's salt, @see CNetClient::SetGamePassword
    1008           0 :     if (!server.CheckPassword(message->m_Password, message->m_Name.ToUTF8()))
    1009             :     {
    1010             :         // Noisy logerror because players are not supposed to be able to get the IP,
    1011             :         // so this might be someone targeting the host for some reason
    1012             :         // (or TODO a dedicated server and we do want to log anyways)
    1013           0 :         LOGERROR("Net server: user {} tried joining with the wrong password",
    1014             :             session->GetUserName().ToUTF8());
    1015           0 :         session->Disconnect(NDR_SERVER_REFUSED);
    1016             :         return true;
    1017             :     }
    1018             : 
    1019             :     // If lobby authentication is enabled, the clients playername has already been registered.
    1020             :     // There also can't be any duplicated names.
    1021             :     // Either deduplicate or prohibit join if name is in use
    1022           0 :     if (!server.m_LobbyAuth && g_ConfigDB.Get("network.duplicateplayernames", false))
    1023           0 :         username = server.DeduplicatePlayerName(username);
    1024             :     else
    1025             :     {
    1026           0 :         const auto it = std::find_if(
    1027             :             server.m_Sessions.begin(), server.m_Sessions.end(),
    1028           0 :             [&username](const auto& session) { return session->GetUserName() == username; });
    1029             : 
    1030           0 :         if (it != server.m_Sessions.end() && it->get() != session)
    1031             :         {
    1032           0 :             session->Disconnect(NDR_PLAYERNAME_IN_USE);
    1033           0 :             return true;
    1034             :         }
    1035             :     }
    1036             : 
    1037             :     // Disconnect banned usernames
    1038           0 :     if (std::find(server.m_BannedPlayers.begin(), server.m_BannedPlayers.end(), server.m_LobbyAuth ? usernameWithoutRating : username) != server.m_BannedPlayers.end())
    1039             :     {
    1040           0 :         session->Disconnect(NDR_BANNED);
    1041             :         return true;
    1042             :     }
    1043             : 
    1044           0 :     bool isRejoining = false;
    1045           0 :     bool serverFull = false;
    1046           0 :     if (server.m_State == SERVER_STATE_PREGAME)
    1047             :     {
    1048             :         // Don't check for maxObservers in the gamesetup, as we don't know yet who will be assigned
    1049           0 :         serverFull = server.m_Sessions.size() >= MAX_CLIENTS;
    1050             :     }
    1051             :     else
    1052             :     {
    1053           0 :         bool isObserver = true;
    1054           0 :         int disconnectedPlayers = 0;
    1055           0 :         int connectedPlayers = 0;
    1056             :         // (TODO: if GUIDs were stable, we should use them instead)
    1057           0 :         for (const std::pair<const CStr, PlayerAssignment>& p : server.m_PlayerAssignments)
    1058             :         {
    1059           0 :             const PlayerAssignment& assignment = p.second;
    1060             : 
    1061           0 :             if (!assignment.m_Enabled && assignment.m_Name == username)
    1062             :             {
    1063           0 :                 isObserver = assignment.m_PlayerID == -1;
    1064           0 :                 isRejoining = true;
    1065             :             }
    1066             : 
    1067           0 :             if (assignment.m_PlayerID == -1)
    1068           0 :                 continue;
    1069             : 
    1070           0 :             if (assignment.m_Enabled)
    1071           0 :                 ++connectedPlayers;
    1072             :             else
    1073           0 :                 ++disconnectedPlayers;
    1074             :         }
    1075             : 
    1076             :         // Optionally allow everyone or only buddies to join after the game has started
    1077           0 :         if (!isRejoining)
    1078             :         {
    1079           0 :             const std::string observerLateJoin{
    1080           0 :                 g_ConfigDB.Get("network.lateobservers", std::string{})};
    1081             : 
    1082           0 :             if (observerLateJoin == "everyone")
    1083             :             {
    1084             :                 isRejoining = true;
    1085             :             }
    1086           0 :             else if (observerLateJoin == "buddies")
    1087             :             {
    1088           0 :                 const std::string name{usernameWithoutRating.ToUTF8().LowerCase()};
    1089           0 :                 if (server.m_Buddies.count(name) > 0)
    1090             :                     isRejoining = true;
    1091           0 :             }
    1092           0 :         }
    1093             : 
    1094           0 :         if (!isRejoining)
    1095             :         {
    1096           0 :             LOGMESSAGE("Refused connection after game start from not-previously-known user \"{}\"",
    1097             :                 utf8_from_wstring(username));
    1098           0 :             session->Disconnect(NDR_SERVER_ALREADY_IN_GAME);
    1099             :             return true;
    1100             :         }
    1101             : 
    1102             :         // Ensure all players will be able to rejoin
    1103           0 :         serverFull = isObserver && (
    1104           0 :             (int) server.m_Sessions.size() - connectedPlayers >
    1105           0 :                 g_ConfigDB.Get("network.observerlimit", 0) ||
    1106           0 :             (int) server.m_Sessions.size() + disconnectedPlayers >= MAX_CLIENTS);
    1107             :     }
    1108             : 
    1109           0 :     if (serverFull)
    1110             :     {
    1111           0 :         session->Disconnect(NDR_SERVER_FULL);
    1112             :         return true;
    1113             :     }
    1114             : 
    1115           0 :     std::uint32_t newHostID = server.m_NextHostID++;
    1116             : 
    1117           0 :     session->SetUserName(username);
    1118           0 :     session->SetHostID(newHostID);
    1119             : 
    1120           0 :     CAuthenticateResultMessage authenticateResult;
    1121           0 :     authenticateResult.m_Code = isRejoining ? ARC_OK_REJOINING :
    1122           0 :         server.m_ContinuesSavedGame ? ARC_OK_SAVED_GAME : ARC_OK;
    1123           0 :     authenticateResult.m_HostID = newHostID;
    1124           0 :     authenticateResult.m_Message = L"Logged in";
    1125           0 :     authenticateResult.m_IsController = 0;
    1126             : 
    1127           0 :     if (message->m_ControllerSecret == server.m_ControllerSecret)
    1128             :     {
    1129           0 :         if (server.m_ControllerGUID.empty())
    1130             :         {
    1131           0 :             server.m_ControllerGUID = session->GetGUID();
    1132           0 :             authenticateResult.m_IsController = 1;
    1133             :         }
    1134             :         // TODO: we could probably handle having several controllers, or swapping?
    1135             :     }
    1136             : 
    1137           0 :     session->SendMessage(&authenticateResult);
    1138             : 
    1139           0 :     server.OnUserJoin(session);
    1140             : 
    1141           0 :     if (!isRejoining)
    1142             :         return true;
    1143             : 
    1144           0 :     ENSURE(server.m_State != SERVER_STATE_PREGAME);
    1145             : 
    1146             :     // Request a copy of the current game state from an existing player, so we can send it on to the new
    1147             :     // player.
    1148             : 
    1149             :     // Assume session 0 is most likely the local player, so they're the most efficient client to request a
    1150             :     // copy from.
    1151           0 :     server.m_Sessions.at(0)->GetFileTransferer().StartTask(CNetFileTransferer::RequestType::REJOIN,
    1152           0 :         [&server, newHostID](std::string buffer)
    1153             :         {
    1154             :             // We've received the game state from an existing player - now we need to send it onwards
    1155             :             // to the newly rejoining player.
    1156             : 
    1157           0 :             const auto sessionIt = std::find_if(server.m_Sessions.begin(), server.m_Sessions.end(),
    1158           0 :                 [newHostID](const auto& serverSession)
    1159             :                 {
    1160           0 :                     return serverSession->GetHostID() == newHostID;
    1161             :                 });
    1162             : 
    1163           0 :             if (sessionIt == server.m_Sessions.end())
    1164             :             {
    1165           0 :                 LOGMESSAGE("Net server: rejoining client disconnected before we sent to it");
    1166           0 :                 return;
    1167             :             }
    1168             : 
    1169             :             // Store the received state file, and tell the client to stant downloading it from us.
    1170             :             // TODO: The server will get kind of confused if there's multiple clients downloading in
    1171             :             // parallel; they'll race and get whichever happens to be the latest received by the
    1172             :             // server, which should still work but isn't great.
    1173           0 :             server.m_JoinSyncFile = std::move(buffer);
    1174             : 
    1175             :             // Send the init attributes alongside - these should be correct since the game should be
    1176             :             // started.
    1177           0 :             CJoinSyncStartMessage message;
    1178           0 :             message.m_InitAttributes = Script::StringifyJSON(
    1179           0 :                 Script::Request{server.GetScriptInterface()}, &server.m_InitAttributes);
    1180           0 :             (*sessionIt)->SendMessage(&message);
    1181           0 :         });
    1182             : 
    1183           0 :     session->SetNextState(NSS_JOIN_SYNCING);
    1184           0 :     return true;
    1185             : }
    1186             : 
    1187           0 : bool CNetServerWorker::OnSimulationCommand(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1188             : {
    1189           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_SIMULATION_COMMAND));
    1190             : 
    1191           0 :     CNetServerWorker& server = session->GetServer();
    1192             : 
    1193           0 :     CSimulationMessage* message = (CSimulationMessage*)event->GetParamRef();
    1194             : 
    1195             :     // Ignore messages sent by one player on behalf of another player
    1196             :     // unless cheating is enabled
    1197           0 :     bool cheatsEnabled = false;
    1198           0 :     const Script::Interface& scriptInterface = server.GetScriptInterface();
    1199           0 :     Script::Request rq(scriptInterface);
    1200           0 :     JS::RootedValue settings(rq.cx);
    1201           0 :     Script::GetProperty(rq, server.m_InitAttributes, "settings", &settings);
    1202           0 :     if (Script::HasProperty(rq, settings, "CheatsEnabled"))
    1203           0 :         Script::GetProperty(rq, settings, "CheatsEnabled", cheatsEnabled);
    1204             : 
    1205           0 :     PlayerAssignmentMap::iterator it = server.m_PlayerAssignments.find(session->GetGUID());
    1206             :     // When cheating is disabled, fail if the player the message claims to
    1207             :     // represent does not exist or does not match the sender's player name
    1208           0 :     if (!cheatsEnabled && (it == server.m_PlayerAssignments.end() || it->second.m_PlayerID != message->m_Player))
    1209             :         return true;
    1210             : 
    1211             :     // Prevent high turn attack that will cause OOM.
    1212             :     // The command is always dropped; the sender is kicked unless it is the host.
    1213           0 :     const turn_id_t readyTurn = server.m_ServerTurnManager->GetReadyTurn();
    1214           0 :     if (message->m_Turn < 0 ||
    1215           0 :         message->m_Turn > readyTurn + MAX_COMMAND_TURN_FACTOR * static_cast<std::int32_t>(COMMAND_DELAY_MP))
    1216             :     {
    1217           0 :         LOGMESSAGERENDER("Net server: %s sent a command for invalid turn %d (ready turn is %d)",
    1218             :             utf8_from_wstring(session->GetUserName()), message->m_Turn, readyTurn);
    1219             : 
    1220           0 :         server.KickPlayer(session->GetUserName(), false);
    1221             :         return true;
    1222             :     }
    1223             : 
    1224             :     // Send it back to all clients that have finished
    1225             :     // the loading screen (and the synchronization when rejoining)
    1226           0 :     server.Multicast(message, { NSS_INGAME });
    1227             : 
    1228             :     // Save all the received commands
    1229           0 :     if (server.m_SavedCommands.size() < static_cast<size_t>(message->m_Turn) + 1)
    1230           0 :         server.m_SavedCommands.resize(static_cast<size_t>(message->m_Turn) + 1);
    1231           0 :     server.m_SavedCommands[static_cast<size_t>(message->m_Turn)].push_back(*message);
    1232             : 
    1233             :     // TODO: we shouldn't send the message back to the client that first sent it
    1234             :     return true;
    1235             : }
    1236             : 
    1237           0 : bool CNetServerWorker::OnFlare(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1238             : {
    1239           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_FLARE));
    1240             : 
    1241           0 :     CNetServerWorker& server = session->GetServer();
    1242           0 :     CFlareMessage* message = (CFlareMessage*)event->GetParamRef();
    1243           0 :     message->m_GUID = session->GetGUID();
    1244           0 :     server.Multicast(message, { NSS_INGAME });
    1245             : 
    1246           0 :     return true;
    1247             : }
    1248             : 
    1249           0 : bool CNetServerWorker::OnSyncCheck(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1250             : {
    1251           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_SYNC_CHECK));
    1252             : 
    1253           0 :     CNetServerWorker& server = session->GetServer();
    1254             : 
    1255           0 :     CSyncCheckMessage* message = (CSyncCheckMessage*)event->GetParamRef();
    1256             : 
    1257           0 :     server.m_ServerTurnManager->NotifyFinishedClientUpdate(*session, message->m_Turn, message->m_Hash);
    1258           0 :     return true;
    1259             : }
    1260             : 
    1261           0 : bool CNetServerWorker::OnEndCommandBatch(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1262             : {
    1263           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_END_COMMAND_BATCH));
    1264             : 
    1265           0 :     CNetServerWorker& server = session->GetServer();
    1266             : 
    1267           0 :     CEndCommandBatchMessage* message = (CEndCommandBatchMessage*)event->GetParamRef();
    1268             : 
    1269             :     // The turn-length field is ignored
    1270           0 :     server.m_ServerTurnManager->NotifyFinishedClientCommands(*session, message->m_Turn);
    1271           0 :     return true;
    1272             : }
    1273             : 
    1274           0 : bool CNetServerWorker::OnChat(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1275             : {
    1276           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_CHAT));
    1277             : 
    1278           0 :     CNetServerWorker& server = session->GetServer();
    1279             : 
    1280           0 :     CChatMessage* message = (CChatMessage*)event->GetParamRef();
    1281             : 
    1282           0 :     message->m_SenderGUID = session->GetGUID();
    1283             : 
    1284           0 :     const std::vector<NetServerSessionState> receivingStates{NSS_PREGAME, NSS_INGAME};
    1285           0 :     const std::vector messageReceivers{std::exchange(message->m_Receivers, {})};
    1286             : 
    1287           0 :     if (messageReceivers.empty())
    1288           0 :         server.Multicast(message, receivingStates);
    1289             :     else
    1290             :     {
    1291           0 :         auto receivers = std::make_optional<std::vector<std::string>>();
    1292           0 :         std::transform(messageReceivers.begin(), messageReceivers.end(), std::back_inserter(*receivers),
    1293             :             std::mem_fn(&CChatMessage::S_m_Receivers::m_ReceiverGUID));
    1294           0 :         server.Multicast(message, receivingStates, std::move(receivers));
    1295           0 :     }
    1296             : 
    1297           0 :     return true;
    1298             : }
    1299             : 
    1300           0 : bool CNetServerWorker::OnReady(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1301             : {
    1302           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_READY));
    1303             : 
    1304           0 :     CNetServerWorker& server = session->GetServer();
    1305             : 
    1306             :     // Occurs if a client presses not-ready
    1307             :     // in the very last moment before the hosts starts the game
    1308           0 :     if (server.m_State == SERVER_STATE_LOADING)
    1309             :         return true;
    1310             : 
    1311           0 :     CReadyMessage* message = (CReadyMessage*)event->GetParamRef();
    1312           0 :     message->m_GUID = session->GetGUID();
    1313           0 :     server.Multicast(message, { NSS_PREGAME });
    1314             : 
    1315           0 :     server.m_PlayerAssignments[message->m_GUID].m_Status = message->m_Status;
    1316             : 
    1317           0 :     return true;
    1318             : }
    1319             : 
    1320           0 : bool CNetServerWorker::OnClearAllReady(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1321             : {
    1322           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_CLEAR_ALL_READY));
    1323             : 
    1324           0 :     CNetServerWorker& server = session->GetServer();
    1325             : 
    1326           0 :     if (session->GetGUID() == server.m_ControllerGUID)
    1327           0 :         server.ClearAllPlayerReady();
    1328             : 
    1329           0 :     return true;
    1330             : }
    1331             : 
    1332           0 : bool CNetServerWorker::OnGameSetup(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1333             : {
    1334           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_GAME_SETUP));
    1335             : 
    1336           0 :     CNetServerWorker& server = session->GetServer();
    1337             : 
    1338             :     // Changing the settings after gamestart is not implemented and would cause an Out-of-sync error.
    1339             :     // This happened when doubleclicking on the startgame button.
    1340           0 :     if (server.m_State != SERVER_STATE_PREGAME)
    1341             :         return true;
    1342             : 
    1343             :     // Only the controller is allowed to send game setup updates.
    1344             :     // TODO: it would be good to allow other players to request changes to some settings,
    1345             :     // e.g. their civilisation.
    1346             :     // Possibly this should use another message, to enforce a single source of truth.
    1347           0 :     if (session->GetGUID() == server.m_ControllerGUID)
    1348             :     {
    1349           0 :         CGameSetupMessage* message = (CGameSetupMessage*)event->GetParamRef();
    1350           0 :         server.Multicast(message, { NSS_PREGAME });
    1351             :     }
    1352             :     return true;
    1353             : }
    1354             : 
    1355           0 : bool CNetServerWorker::OnAssignPlayer(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1356             : {
    1357           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_ASSIGN_PLAYER));
    1358           0 :     CNetServerWorker& server = session->GetServer();
    1359             : 
    1360           0 :     if (session->GetGUID() == server.m_ControllerGUID)
    1361             :     {
    1362           0 :         CAssignPlayerMessage* message = (CAssignPlayerMessage*)event->GetParamRef();
    1363           0 :         server.AssignPlayer(message->m_PlayerID, message->m_GUID);
    1364             :     }
    1365           0 :     return true;
    1366             : }
    1367             : 
    1368           0 : bool CNetServerWorker::OnGameStart(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1369             : {
    1370           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_GAME_START));
    1371           0 :     CNetServerWorker& server = session->GetServer();
    1372             : 
    1373           0 :     if (session->GetGUID() != server.m_ControllerGUID)
    1374             :         return true;
    1375             : 
    1376           0 :     CGameStartMessage* message = (CGameStartMessage*)event->GetParamRef();
    1377           0 :     server.StartGame(message->m_InitAttributes);
    1378           0 :     return true;
    1379             : }
    1380             : 
    1381           0 : bool CNetServerWorker::OnSavedGameStart(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1382             : {
    1383           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_SAVED_GAME_START));
    1384           0 :     CNetServerWorker& server{session->GetServer()};
    1385             : 
    1386           0 :     if (session->GetGUID() != server.m_ControllerGUID)
    1387             :         return true;
    1388             : 
    1389           0 :     CGameSavedStartMessage* message = static_cast<CGameSavedStartMessage*>(event->GetParamRef());
    1390           0 :     session->GetFileTransferer().StartTask(CNetFileTransferer::RequestType::LOADGAME,
    1391           0 :         [&server, initAttributes = std::move(message->m_InitAttributes)](std::string buffer)
    1392             :         {
    1393           0 :             server.m_SavedState = std::move(buffer);
    1394             : 
    1395           0 :             server.StartSavedGame(initAttributes);
    1396           0 :         });
    1397           0 :     return true;
    1398           0 : }
    1399             : 
    1400           0 : bool CNetServerWorker::OnLoadedGame(CNetServerSession* loadedSession, CFsmEvent<CNetMessage*>* event)
    1401             : {
    1402           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_LOADED_GAME));
    1403             : 
    1404           0 :     CNetServerWorker& server = loadedSession->GetServer();
    1405             : 
    1406             :     // We're in the loading state, so wait until every client has loaded
    1407             :     // before starting the game
    1408           0 :     ENSURE(server.m_State == SERVER_STATE_LOADING);
    1409           0 :     if (server.CheckGameLoadStatus(loadedSession))
    1410             :         return true;
    1411             : 
    1412           0 :     CClientsLoadingMessage message;
    1413             :     // We always send all GUIDs of clients in the loading state
    1414             :     // so that we don't have to bother about switching GUI pages
    1415           0 :     for (const auto& session : server.m_Sessions)
    1416           0 :         if (session->GetCurrState() != NSS_INGAME && loadedSession->GetGUID() != session->GetGUID())
    1417             :         {
    1418           0 :             CClientsLoadingMessage::S_m_Clients client;
    1419           0 :             client.m_GUID = session->GetGUID();
    1420           0 :             message.m_Clients.push_back(client);
    1421           0 :         }
    1422             : 
    1423             :     // If no other player is loading the server can clear the savestate
    1424           0 :     if (message.m_Clients.empty())
    1425           0 :         server.m_SavedState.clear();
    1426             : 
    1427             :     // Send to the client who has loaded the game but did not reach the NSS_INGAME state yet
    1428           0 :     loadedSession->SendMessage(&message);
    1429           0 :     server.Multicast(&message, { NSS_INGAME });
    1430             : 
    1431           0 :     return true;
    1432             : }
    1433             : 
    1434           0 : bool CNetServerWorker::OnJoinSyncingLoadedGame(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1435             : {
    1436             :     // A client rejoining an in-progress game has now finished loading the
    1437             :     // map and deserialized the initial state.
    1438             :     // The simulation may have progressed since then, so send any subsequent
    1439             :     // commands to them and set them as an active player so they can participate
    1440             :     // in all future turns.
    1441             :     //
    1442             :     // (TODO: if it takes a long time for them to receive and execute all these
    1443             :     // commands, the other players will get frozen for that time and may be unhappy;
    1444             :     // we could try repeating this process a few times until the client converges
    1445             :     // on the up-to-date state, before setting them as active.)
    1446             : 
    1447           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_LOADED_GAME));
    1448             : 
    1449           0 :     CNetServerWorker& server = session->GetServer();
    1450             : 
    1451           0 :     CLoadedGameMessage* message = (CLoadedGameMessage*)event->GetParamRef();
    1452             : 
    1453           0 :     turn_id_t turn = message->m_CurrentTurn;
    1454           0 :     turn_id_t readyTurn = server.m_ServerTurnManager->GetReadyTurn();
    1455             : 
    1456             :     // Send them all commands received since their saved state,
    1457             :     // and turn-ended messages for any turns that have already been processed
    1458           0 :     for (turn_id_t i = turn + 1; i < std::max(readyTurn + 1, static_cast<turn_id_t>(server.m_SavedCommands.size())); ++i)
    1459             :     {
    1460           0 :         if (static_cast<size_t>(i) < server.m_SavedCommands.size())
    1461           0 :             for (size_t j = 0; j < server.m_SavedCommands[i].size(); ++j)
    1462           0 :                 session->SendMessage(&server.m_SavedCommands[i][j]);
    1463             : 
    1464           0 :         if (i <= readyTurn)
    1465             :         {
    1466           0 :             CEndCommandBatchMessage endMessage;
    1467           0 :             endMessage.m_Turn = i;
    1468           0 :             endMessage.m_TurnLength = server.m_ServerTurnManager->GetSavedTurnLength(i);
    1469           0 :             session->SendMessage(&endMessage);
    1470           0 :         }
    1471             :     }
    1472             : 
    1473             :     // Tell the turn manager to expect commands from this new client
    1474             :     // Special case: the controller shouldn't be treated as an observer in any case.
    1475           0 :     bool isObserver = server.m_PlayerAssignments[session->GetGUID()].m_PlayerID == -1 && server.m_ControllerGUID != session->GetGUID();
    1476           0 :     server.m_ServerTurnManager->InitialiseClient(session->GetHostID(), readyTurn, isObserver);
    1477             : 
    1478             :     // Tell the client that everything has finished loading and it should start now
    1479           0 :     CLoadedGameMessage loaded;
    1480           0 :     loaded.m_CurrentTurn = readyTurn;
    1481           0 :     session->SendMessage(&loaded);
    1482             : 
    1483           0 :     return true;
    1484             : }
    1485             : 
    1486           0 : bool CNetServerWorker::OnRejoined(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1487             : {
    1488             :     // A client has finished rejoining and the loading screen disappeared.
    1489           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_REJOINED));
    1490             : 
    1491           0 :     CNetServerWorker& server = session->GetServer();
    1492             : 
    1493             :     // Inform everyone of the client having rejoined
    1494           0 :     CRejoinedMessage* message = (CRejoinedMessage*)event->GetParamRef();
    1495           0 :     message->m_GUID = session->GetGUID();
    1496           0 :     server.Multicast(message, { NSS_INGAME });
    1497             : 
    1498             :     // Send all pausing players to the rejoined client.
    1499           0 :     for (const CStr& guid : server.m_PausingPlayers)
    1500             :     {
    1501           0 :         CClientPausedMessage pausedMessage;
    1502           0 :         pausedMessage.m_GUID = guid;
    1503           0 :         pausedMessage.m_Pause = true;
    1504           0 :         session->SendMessage(&pausedMessage);
    1505           0 :     }
    1506             : 
    1507           0 :     return true;
    1508             : }
    1509             : 
    1510           0 : bool CNetServerWorker::OnKickPlayer(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1511             : {
    1512           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_KICKED));
    1513             : 
    1514           0 :     CNetServerWorker& server = session->GetServer();
    1515             : 
    1516           0 :     if (session->GetGUID() == server.m_ControllerGUID)
    1517             :     {
    1518           0 :         CKickedMessage* message = (CKickedMessage*)event->GetParamRef();
    1519           0 :         server.KickPlayer(message->m_Name, message->m_Ban);
    1520             :     }
    1521           0 :     return true;
    1522             : }
    1523             : 
    1524           0 : bool CNetServerWorker::OnDisconnect(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1525             : {
    1526           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_CONNECTION_LOST));
    1527             : 
    1528           0 :     CNetServerWorker& server = session->GetServer();
    1529             : 
    1530           0 :     server.OnUserLeave(session);
    1531             : 
    1532           0 :     return true;
    1533             : }
    1534             : 
    1535           0 : bool CNetServerWorker::OnClientPaused(CNetServerSession* session, CFsmEvent<CNetMessage*>* event)
    1536             : {
    1537           0 :     ENSURE(event->GetType() == static_cast<unsigned int>(NMT_CLIENT_PAUSED));
    1538             : 
    1539           0 :     CNetServerWorker& server = session->GetServer();
    1540             : 
    1541           0 :     CClientPausedMessage* message = (CClientPausedMessage*)event->GetParamRef();
    1542             : 
    1543           0 :     message->m_GUID = session->GetGUID();
    1544             : 
    1545             :     // Update the list of pausing players.
    1546           0 :     std::vector<CStr>::iterator player = std::find(server.m_PausingPlayers.begin(), server.m_PausingPlayers.end(), session->GetGUID());
    1547             : 
    1548           0 :     if (message->m_Pause)
    1549             :     {
    1550           0 :         if (player != server.m_PausingPlayers.end())
    1551             :             return true;
    1552             : 
    1553           0 :         server.m_PausingPlayers.push_back(session->GetGUID());
    1554             :     }
    1555             :     else
    1556             :     {
    1557           0 :         if (player == server.m_PausingPlayers.end())
    1558             :             return true;
    1559             : 
    1560           0 :         server.m_PausingPlayers.erase(player);
    1561             :     }
    1562             : 
    1563             :     // Send messages to clients that are in game, and are not the client who paused.
    1564           0 :     for (const auto& netSession : server.m_Sessions)
    1565           0 :         if (netSession->GetCurrState() == NSS_INGAME && message->m_GUID != netSession->GetGUID())
    1566           0 :             netSession->SendMessage(message);
    1567             : 
    1568             :     return true;
    1569             : }
    1570             : 
    1571           0 : bool CNetServerWorker::CheckGameLoadStatus(CNetServerSession* changedSession)
    1572             : {
    1573           0 :     for (const auto& session : m_Sessions)
    1574           0 :         if (session.get() != changedSession && session->GetCurrState() != NSS_INGAME)
    1575           0 :             return false;
    1576             : 
    1577             :     // Inform clients that everyone has loaded the map and that the game can start
    1578           0 :     CLoadedGameMessage loaded;
    1579           0 :     loaded.m_CurrentTurn = 0;
    1580             : 
    1581             :     // Notice the changedSession is still in the NSS_PREGAME state
    1582           0 :     Multicast(&loaded, { NSS_PREGAME, NSS_INGAME });
    1583             : 
    1584           0 :     m_State = SERVER_STATE_INGAME;
    1585           0 :     return true;
    1586           0 : }
    1587             : 
    1588           0 : void CNetServerWorker::PreStartGame(const CStr& initAttribs)
    1589             : {
    1590           0 :     for (std::pair<const CStr, PlayerAssignment>& player : m_PlayerAssignments)
    1591           0 :         if (player.second.m_Enabled && player.second.m_PlayerID != -1 && player.second.m_Status == 0)
    1592             :         {
    1593           0 :             LOGERROR("Tried to start the game without player \"{}\" being ready!",
    1594             :                 utf8_from_wstring(player.second.m_Name).c_str());
    1595           0 :             return;
    1596             :         }
    1597             : 
    1598           0 :     m_ServerTurnManager = std::make_unique<CNetServerTurnManager>(*this);
    1599             : 
    1600           0 :     for (const auto& session : m_Sessions)
    1601             :     {
    1602             :         // InitialiseClient makes the NetServerTurnManager wait for this client.
    1603             :         // But we only want to wait for clients who have passed authentication, i.e. who have the correct password.
    1604             :         // Therefore we may not call InitialiseClient for unauthenticated clients.
    1605           0 :         if (session->GetCurrState() != NSS_PREGAME)
    1606             :         {
    1607             :             // We only support clients joining before or after, not during the loading screen.
    1608             :             // Therefore we have to disconnect clients who did not complete the authentication yet.
    1609           0 :             LOGMESSAGE("Dropping client ({} / {} / {}) not in NSS_PREGAME when starting the game",
    1610             :                 session->GetUserName().ToUTF8(), session->GetGUID(), session->GetHostID());
    1611           0 :             session->Disconnect(NDR_SERVER_LOADING);
    1612           0 :             continue;
    1613           0 :         }
    1614             : 
    1615             :         // Special case: the controller shouldn't be treated as an observer in any case.
    1616           0 :         bool isObserver = m_PlayerAssignments[session->GetGUID()].m_PlayerID == -1 && m_ControllerGUID != session->GetGUID();
    1617           0 :         m_ServerTurnManager->InitialiseClient(session->GetHostID(), 0, isObserver);
    1618             :     }
    1619             : 
    1620           0 :     m_State = SERVER_STATE_LOADING;
    1621             : 
    1622             :     // Remove players and observers that are not present when the game starts
    1623           0 :     for (PlayerAssignmentMap::iterator it = m_PlayerAssignments.begin(); it != m_PlayerAssignments.end();)
    1624           0 :         if (it->second.m_Enabled)
    1625           0 :             ++it;
    1626             :         else
    1627           0 :             it = m_PlayerAssignments.erase(it);
    1628             : 
    1629           0 :     SendPlayerAssignments();
    1630             : 
    1631             :     // Update init attributes. They should no longer change.
    1632           0 :     Script::ParseJSON(Script::Request(m_ScriptInterface), initAttribs, &m_InitAttributes);
    1633             : }
    1634             : 
    1635           0 : void CNetServerWorker::StartGame(const CStr& initAttribs)
    1636             : {
    1637           0 :     PreStartGame(initAttribs);
    1638             : 
    1639           0 :     CGameStartMessage gameStart;
    1640           0 :     gameStart.m_InitAttributes = initAttribs;
    1641           0 :     Multicast(&gameStart, { NSS_PREGAME });
    1642           0 : }
    1643             : 
    1644           0 : void CNetServerWorker::StartSavedGame(const CStr& initAttribs)
    1645             : {
    1646           0 :     PreStartGame(initAttribs);
    1647             : 
    1648           0 :     CGameSavedStartMessage gameSavedStart;
    1649           0 :     gameSavedStart.m_InitAttributes = initAttribs;
    1650           0 :     Multicast(&gameSavedStart, { NSS_PREGAME });
    1651           0 : }
    1652             : 
    1653           0 : CStrW CNetServerWorker::SanitisePlayerName(const CStrW& original)
    1654             : {
    1655           0 :     const size_t MAX_LENGTH = 32;
    1656             : 
    1657           0 :     CStrW name = original;
    1658           0 :     PS::ReplaceSubrange(name, L"[", L"{"); // remove GUI tags
    1659           0 :     PS::ReplaceSubrange(name, L"]", L"}"); // remove for symmetry
    1660             : 
    1661             :     // Restrict the length
    1662           0 :     if (name.length() > MAX_LENGTH)
    1663           0 :         name = name.substr(0, MAX_LENGTH);
    1664             : 
    1665             :     // Don't allow surrounding whitespace
    1666           0 :     name.Trim(PS_TRIM_BOTH);
    1667             : 
    1668             :     // Don't allow empty name
    1669           0 :     if (name.empty())
    1670           0 :         name = L"Anonymous";
    1671             : 
    1672           0 :     return name;
    1673           0 : }
    1674             : 
    1675           0 : CStrW CNetServerWorker::DeduplicatePlayerName(const CStrW& original)
    1676             : {
    1677           0 :     CStrW name = original;
    1678             : 
    1679             :     // Try names "Foo", "Foo (2)", "Foo (3)", etc
    1680           0 :     size_t id = 2;
    1681           0 :     while (true)
    1682             :     {
    1683           0 :         bool unique = true;
    1684           0 :         for (const auto& session : m_Sessions)
    1685             :         {
    1686           0 :             if (session->GetUserName() == name)
    1687             :             {
    1688             :                 unique = false;
    1689             :                 break;
    1690             :             }
    1691             :         }
    1692             : 
    1693           0 :         if (unique)
    1694           0 :             return name;
    1695             : 
    1696           0 :         name = fmt::format(L"{} ({})", original, id++);
    1697           0 :     }
    1698           0 : }
    1699             : 
    1700           0 : void CNetServerWorker::SendHolePunchingMessage(const CStr& ipStr, std::uint16_t port)
    1701             : {
    1702           0 :     if (m_Host)
    1703           0 :         StunClient::SendHolePunchingMessages(*m_Host, ipStr, port);
    1704           0 : }
    1705             : 
    1706             : 
    1707             : 
    1708             : 
    1709           0 : CNetServer::CNetServer(const bool continueSavedGame, std::uint16_t port, const bool useLobbyAuth,
    1710             :     std::string password, std::string controllerSecret, std::string initAttributes,
    1711           0 :     std::set<std::string> buddies) :
    1712           0 :     m_Worker{continueSavedGame, port, useLobbyAuth, password, std::move(controllerSecret),
    1713             :         std::move(initAttributes), std::move(buddies)},
    1714           0 :     m_LobbyAuth{useLobbyAuth},
    1715           0 :     m_Password{std::move(password)}
    1716             : {
    1717           0 :     if (!useLobbyAuth)
    1718           0 :         return;
    1719             : 
    1720             :     // In lobby, we send our public ip and port on request to the players who want to connect.
    1721             :     // Thus we need to know our public IP and use STUN to get it.
    1722           0 :     std::lock_guard<std::mutex> lock(m_Worker.m_WorkerMutex);
    1723           0 :     if (!m_Worker.m_Host || !StunClient::FindPublicIP(*m_Worker.m_Host, m_PublicIp, m_PublicPort))
    1724           0 :         throw std::runtime_error{"Failed to resolve public IP-address."};
    1725           0 : }
    1726             : 
    1727           0 : bool CNetServer::UseLobbyAuth() const
    1728             : {
    1729           0 :     return m_LobbyAuth;
    1730             : }
    1731             : 
    1732           0 : CStr CNetServer::GetPublicIp() const
    1733             : {
    1734           0 :     return m_PublicIp;
    1735             : }
    1736             : 
    1737           0 : std::uint16_t CNetServer::GetPublicPort() const
    1738             : {
    1739           0 :     return m_PublicPort;
    1740             : }
    1741             : 
    1742           0 : std::uint16_t CNetServer::GetLocalPort() const
    1743             : {
    1744           0 :     std::lock_guard<std::mutex> lock(m_Worker.m_WorkerMutex);
    1745           0 :     if (!m_Worker.m_Host)
    1746             :         return 0;
    1747           0 :     return m_Worker.m_Host->address.port;
    1748           0 : }
    1749             : 
    1750           0 : bool CNetServer::CheckPasswordAndIncrement(const std::string& username, const std::string& password, const std::string& salt)
    1751             : {
    1752           0 :     std::unordered_map<std::string, int>::iterator it = m_FailedAttempts.find(username);
    1753           0 :     if (m_Worker.CheckPassword(password, salt))
    1754             :     {
    1755           0 :         if (it != m_FailedAttempts.end())
    1756           0 :             it->second = 0;
    1757           0 :         return true;
    1758             :     }
    1759           0 :     if (it == m_FailedAttempts.end())
    1760           0 :         m_FailedAttempts.emplace(username, 1);
    1761             :     else
    1762           0 :         it->second++;
    1763             :     return false;
    1764             : }
    1765             : 
    1766           0 : bool CNetServer::IsBanned(const std::string& username) const
    1767             : {
    1768           0 :     std::unordered_map<std::string, int>::const_iterator it = m_FailedAttempts.find(username);
    1769           0 :     return it != m_FailedAttempts.end() && it->second >= FAILED_PASSWORD_TRIES_BEFORE_BAN;
    1770             : }
    1771             : 
    1772           0 : void CNetServer::StartGame()
    1773             : {
    1774           0 :     std::lock_guard<std::mutex> lock(m_Worker.m_WorkerMutex);
    1775           0 :     m_Worker.m_StartGameQueue.push_back(true);
    1776           0 : }
    1777             : 
    1778           0 : void CNetServer::OnLobbyAuth(const CStr& name, const CStr& token)
    1779             : {
    1780           0 :     std::lock_guard<std::mutex> lock(m_Worker.m_WorkerMutex);
    1781           0 :     m_Worker.m_LobbyAuthQueue.push_back(std::make_pair(name, token));
    1782           0 : }
    1783             : 
    1784           0 : void CNetServer::SetTurnLength(std::uint32_t msecs)
    1785             : {
    1786           0 :     std::lock_guard<std::mutex> lock(m_Worker.m_WorkerMutex);
    1787           0 :     m_Worker.m_TurnLengthQueue.push_back(msecs);
    1788           0 : }
    1789             : 
    1790           0 : void CNetServer::SendHolePunchingMessage(const CStr& ip, std::uint16_t port)
    1791             : {
    1792           0 :     m_Worker.SendHolePunchingMessage(ip, port);
    1793           0 : }

Generated by: LCOV version 1.16