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 : #ifndef NETCLIENT_H
19 : #define NETCLIENT_H
20 :
21 : #include "lib/code_annotation.h"
22 : #include "lib/config2.h"
23 : #include "lib/external_libraries/enet.h"
24 : #include "network/FSM.h"
25 : #include "network/NetHost.h"
26 : #include "network/NetMessage.h"
27 : #include "ps/CStr.h"
28 : #include "scriptinterface/Object.h"
29 : #include "scriptinterface/Request.h"
30 : #include "scriptinterface/StructuredClone.h"
31 :
32 : #include <ctime>
33 : #include <deque>
34 : #include <js/RootingAPI.h>
35 : #include <js/TypeDecls.h>
36 : #include <js/Value.h>
37 : #include <optional>
38 : #include <string>
39 : #include <thread>
40 : #include <vector>
41 :
42 : class CGame;
43 : class CNetClientSession;
44 : class CNetClientTurnManager;
45 : class JSTracer;
46 : class XmppClient;
47 :
48 : namespace Script { class Interface; }
49 :
50 : typedef struct _ENetHost ENetHost;
51 :
52 : // NetClient session FSM states
53 : enum
54 : {
55 : NCS_UNCONNECTED,
56 : NCS_CONNECT,
57 : NCS_HANDSHAKE,
58 : NCS_AUTHENTICATE,
59 : NCS_PREGAME,
60 : NCS_LOADING,
61 : NCS_JOIN_SYNCING,
62 : NCS_INGAME
63 : };
64 :
65 : /**
66 : * Network client.
67 : * This code is run by every player (including the host, if they are not
68 : * a dedicated server).
69 : * It provides an interface between the GUI, the network (via CNetClientSession),
70 : * and the game (via CGame and CNetClientTurnManager).
71 : */
72 : class CNetClient : public CFsm<CNetClient, CNetMessage*>
73 : {
74 : NONCOPYABLE(CNetClient);
75 :
76 : public:
77 : /**
78 : * Construct a client associated with the given game object.
79 : * The game must exist for the lifetime of this object.
80 : * The user's name will be displayed to all players.
81 : * The JID of the host is needed for the secure lobby authentication.
82 : */
83 : CNetClient(CGame* game, std::string serverAddressOrHostname, std::uint16_t serverPont,
84 : const CStrW& username = L"anonymous", const CStr& hostJID = {},
85 : std::string hashedPassword = {}, std::string controllerSecret = {});
86 :
87 : /**
88 : * This constructor additionally requests connection information over the
89 : * lobby.
90 : */
91 : #if CONFIG2_LOBBY
92 : CNetClient(CGame* game, const CStrW& username, const CStr& hostJID,
93 : std::string hashedPassword, XmppClient& xmppClient);
94 : #endif
95 :
96 : virtual ~CNetClient();
97 :
98 0 : bool IsController() const { return m_IsController; }
99 :
100 : /**
101 : * Returns the GUID of the local client.
102 : * Used for distinguishing observers.
103 : */
104 0 : CStr GetGUID() const { return m_GUID; }
105 :
106 : /**
107 : * Connect to the remote networked server using lobby.
108 : * Push netstatus messages on failure.
109 : * @param localNetwork - if true, assume we are trying to connect on the local network.
110 : * @return true on success, false on connection failure
111 : */
112 : #if CONFIG2_LOBBY
113 : bool TryToConnectWithSTUN(std::string serverAddressOrHostname, std::uint16_t serverPort,
114 : const CStr& hostJID, bool localNetwork);
115 : #endif
116 :
117 : /**
118 : * Destroy the connection to the server.
119 : * This client probably cannot be used again.
120 : */
121 : void DestroyConnection();
122 :
123 : /**
124 : * Poll the connection for messages from the server and process them, and send
125 : * any queued messages.
126 : * This must be called frequently (i.e. once per frame).
127 : */
128 : void Poll();
129 :
130 : /**
131 : * Locally triggers a GUI message if the connection to the server is being lost or has bad latency.
132 : */
133 : void CheckServerConnection();
134 :
135 : /**
136 : * Retrieves the next queued GUI message, and removes it from the queue.
137 : * The returned value is in the JS context of the provided
138 : * @c Script::Interface.
139 : *
140 : * This is the only mechanism for the networking code to send messages to
141 : * the GUI.
142 : *
143 : * The structure of the messages is <code>{ "type": "...", ... }</code>.
144 : * The exact types and associated data are not specified anywhere - the
145 : * implementation and GUI scripts must make the same assumptions.
146 : *
147 : * @return a promise resolving to the next message.
148 : */
149 : JSObject* GetNextGUIMessage(const Script::Interface& guiInterface);
150 :
151 : /**
152 : * Has to be called bevore the @c Script::Interface gets destroied so that
153 : * no future messages are sent to it.
154 : */
155 : void Unregister(const Script::Interface* guiInterface);
156 :
157 : /**
158 : * Add a message to the queue, to be read by GuiPoll.
159 : * The script value must be in the GetScriptInterface() JS context.
160 : */
161 : template<typename... Args>
162 0 : void PushGuiMessage(Args const&... args)
163 : {
164 0 : Script::Request rq(GetScriptInterface());
165 :
166 0 : JS::RootedValue message(rq.cx);
167 0 : Script::CreateObject(rq, &message, args...);
168 0 : m_GuiMessageQueue.push_back(Script::WriteStructuredClone(rq, message));
169 0 : }
170 :
171 : /**
172 : * Return a concatenation of all messages in the GUI queue,
173 : * for test cases to easily verify the queue contents.
174 : */
175 : std::string TestReadGuiMessages();
176 :
177 : /**
178 : * Get the script interface associated with this network client,
179 : * which is equivalent to the one used by the CGame in the constructor.
180 : */
181 : const Script::Interface& GetScriptInterface();
182 :
183 : /**
184 : * Send a message to the server.
185 : * @param message message to send
186 : * @return true on success
187 : */
188 : bool SendMessage(const CNetMessage* message);
189 :
190 : /**
191 : * Call when the network connection has been successfully initiated.
192 : */
193 : void HandleConnect();
194 :
195 : /**
196 : * Call when the network connection has been lost.
197 : */
198 : void HandleDisconnect(std::uint32_t reason);
199 :
200 : /**
201 : * Call when a message has been received from the network.
202 : */
203 : bool HandleMessage(CNetMessage* message);
204 :
205 : /**
206 : * Call when the game has started and all data files have been loaded,
207 : * to signal to the server that we are ready to begin the game.
208 : */
209 : void LoadFinished();
210 :
211 : void SendGameSetupMessage(JS::MutableHandleValue attrs, const Script::Interface& scriptInterface);
212 :
213 : void SendAssignPlayerMessage(const int playerID, const CStr& guid);
214 :
215 : /**
216 : * @param text The message to send.
217 : * @param receivers The GUID of the receiving clients. If empty send it to
218 : * all clients.
219 : */
220 : void SendChatMessage(const std::wstring& text, std::optional<std::vector<std::string>> receivers);
221 :
222 : void SendReadyMessage(const int status);
223 :
224 : void SendClearAllReadyMessage();
225 :
226 : void SendStartGameMessage(const CStr& initAttribs);
227 :
228 : void SendStartSavedGameMessage(const CStr& initAttribs, const CStr& savedState);
229 :
230 : /**
231 : * Call when the client (player or observer) has sent a flare.
232 : */
233 : void SendFlareMessage(const CStr& positionX, const CStr& positionY, const CStr& positionZ);
234 :
235 : /**
236 : * Call when the client has rejoined a running match and finished
237 : * the loading screen.
238 : */
239 : void SendRejoinedMessage();
240 :
241 : /**
242 : * Call to kick/ban a client
243 : */
244 : void SendKickPlayerMessage(const CStrW& playerName, bool ban);
245 :
246 : /**
247 : * Call when the client has paused or unpaused the game.
248 : */
249 : void SendPausedMessage(bool pause);
250 :
251 : /**
252 : * @return Whether the NetClient is shutting down.
253 : */
254 : bool ShouldShutdown() const;
255 :
256 : /**
257 : * Called when fetching connection data from the host failed, to inform JS code.
258 : */
259 : void HandleGetServerDataFailed(const CStr& error);
260 : private:
261 : struct PrivateTag {};
262 : CNetClient(PrivateTag, CGame* game, std::string serverAddressOrHostname,
263 : std::uint16_t serverPont, const CStrW& username = L"anonymous", const CStr& hostJID = {},
264 : std::string hashedPassword = {}, std::string controllerSecret = {});
265 :
266 : void SendAuthenticateMessage();
267 :
268 : // Net message / FSM transition handlers
269 : static bool OnConnect(CNetClient* client, CFsmEvent<CNetMessage*>* event);
270 : static bool OnHandshake(CNetClient* client, CFsmEvent<CNetMessage*>* event);
271 : static bool OnHandshakeResponse(CNetClient* client, CFsmEvent<CNetMessage*>* event);
272 : static bool OnAuthenticateRequest(CNetClient* client, CFsmEvent<CNetMessage*>* event);
273 : static bool OnAuthenticate(CNetClient* client, CFsmEvent<CNetMessage*>* event);
274 : static bool OnChat(CNetClient* client, CFsmEvent<CNetMessage*>* event);
275 : static bool OnReady(CNetClient* client, CFsmEvent<CNetMessage*>* event);
276 : static bool OnGameSetup(CNetClient* client, CFsmEvent<CNetMessage*>* event);
277 : static bool OnPlayerAssignment(CNetClient* client, CFsmEvent<CNetMessage*>* event);
278 : static bool OnInGame(CNetClient* client, CFsmEvent<CNetMessage*>* event);
279 : static bool OnGameStart(CNetClient* client, CFsmEvent<CNetMessage*>* event);
280 : static bool OnSavedGameStart(CNetClient* client, CFsmEvent<CNetMessage*>* event);
281 : static bool OnJoinSyncStart(CNetClient* client, CFsmEvent<CNetMessage*>* event);
282 : static bool OnJoinSyncEndCommandBatch(CNetClient* client, CFsmEvent<CNetMessage*>* event);
283 : static bool OnFlare(CNetClient* client, CFsmEvent<CNetMessage*>* event);
284 : static bool OnRejoined(CNetClient* client, CFsmEvent<CNetMessage*>* event);
285 : static bool OnKicked(CNetClient* client, CFsmEvent<CNetMessage*>* event);
286 : static bool OnClientTimeout(CNetClient* client, CFsmEvent<CNetMessage*>* event);
287 : static bool OnClientPerformance(CNetClient* client, CFsmEvent<CNetMessage*>* event);
288 : static bool OnClientsLoading(CNetClient* client, CFsmEvent<CNetMessage*>* event);
289 : static bool OnClientPaused(CNetClient* client, CFsmEvent<CNetMessage*>* event);
290 : static bool OnLoadedGame(CNetClient* client, CFsmEvent<CNetMessage*>* event);
291 :
292 : /**
293 : * Set up a connection to the remote networked server.
294 : * @return true on success, false on connection failure
295 : */
296 : void SetupConnection(ENetHost* enetClient);
297 :
298 : /**
299 : * Take ownership of a session object, and use it for all network communication.
300 : */
301 : void SetAndOwnSession(CNetClientSession* session);
302 :
303 : /**
304 : * Starts a game with the specified init attributes and saved state. Called
305 : * by the start game and start saved game callbacks.
306 : */
307 : void StartGame(const JS::MutableHandleValue initAttributes, const std::string& savedState);
308 :
309 : /**
310 : * Push a message onto the GUI queue listing the current player assignments.
311 : */
312 : void PostPlayerAssignmentsToScript();
313 :
314 : void FetchMessage();
315 :
316 : CGame *m_Game;
317 : CStrW m_UserName;
318 :
319 : CStr m_HostJID;
320 : CStr m_ServerAddressOrHostname;
321 : std::uint16_t m_ServerPort{0};
322 :
323 : /**
324 : * Password to join the game.
325 : */
326 : CStr m_Password;
327 :
328 : /// The 'secret' used to identify the controller of the game.
329 : std::string m_ControllerSecret;
330 :
331 : /// Note that this is just a "gui hint" with no actual impact on being controller.
332 : bool m_IsController = false;
333 :
334 : /// Current network session (or nullptr if not connected)
335 : CNetClientSession* m_Session{nullptr};
336 :
337 : std::thread m_PollingThread;
338 :
339 : /// Turn manager associated with the current game (or nullptr if we haven't started the game yet)
340 : CNetClientTurnManager* m_ClientTurnManager{nullptr};
341 :
342 : /// Unique-per-game identifier of this client, used to identify the sender of simulation commands
343 : std::uint32_t m_HostID{static_cast<std::uint32_t>(-1)};
344 :
345 : /// True if the player is currently rejoining or has already rejoined the game.
346 : bool m_Rejoin{false};
347 :
348 : /// Latest copy of player assignments heard from the server
349 : PlayerAssignmentMap m_PlayerAssignments;
350 :
351 : /// Globally unique identifier to distinguish users beyond the lifetime of a single network session
352 : CStr m_GUID;
353 :
354 : /// Queue of messages for GuiPoll
355 : std::deque<Script::StructuredClone> m_GuiMessageQueue;
356 :
357 0 : struct GuiPollData
358 : {
359 : const Script::Interface& interface;
360 : /**
361 : * In the context of interface.
362 : * When the promise is pending @see Poll should fill it with a message.
363 : * When there it's fulfilled JavaScript code can take it.
364 : */
365 : JS::PersistentRootedObject promise;
366 : };
367 : std::optional<GuiPollData> m_GuiMessagePoll;
368 :
369 : /// Serialized game state received when joining an in-progress game
370 : std::string m_JoinSyncBuffer;
371 :
372 : std::string m_SavedState;
373 :
374 : /// Time when the server was last checked for timeouts and bad latency
375 : std::time_t m_LastConnectionCheck{0};
376 :
377 : /// Record of the server engine version and loaded mods
378 : CSrvHandshakeMessage m_ServerHandshake;
379 : };
380 :
381 : /// Global network client for the standard game
382 : extern CNetClient *g_NetClient;
383 :
384 : #endif // NETCLIENT_H
385 :
|