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 "JSInterface_Network.h"
21 :
22 : #include "lib/code_generation.h"
23 : #include "lib/config2.h"
24 : #include "lib/debug.h"
25 : #include "lib/utf8.h"
26 : #include "lobby/XmppClient.h"
27 : #include "network/NetClient.h"
28 : #include "network/NetMessage.h"
29 : #include "network/NetServer.h"
30 : #include "ps/CLogger.h"
31 : #include "ps/CStr.h"
32 : #include "ps/GUID.h"
33 : #include "ps/Game.h"
34 : #include "ps/Hashing.h"
35 : #include "ps/Pyrogenesis.h"
36 : #include "ps/SavedGame.h"
37 : #include "scriptinterface/FunctionWrapper.h"
38 : #include "scriptinterface/JSON.h"
39 : #include "scriptinterface/Conversions.h"
40 : #include "scriptinterface/Request.h"
41 : #include "scriptinterface/StructuredClone.h"
42 :
43 : #include <fmt/format.h>
44 : #include <js/PropertyAndElement.h>
45 : #include <js/RootingAPI.h>
46 : #include <js/TypeDecls.h>
47 : #include <js/Value.h>
48 : #include <optional>
49 : #include <set>
50 : #include <stdexcept>
51 : #include <string>
52 : #include <utility>
53 : #include <vector>
54 :
55 : namespace Script { class Interface; }
56 :
57 : namespace JSI_Network
58 : {
59 0 : std::uint16_t GetDefaultPort()
60 : {
61 0 : return PS_DEFAULT_PORT;
62 : }
63 :
64 0 : bool IsNetController()
65 : {
66 0 : return !!g_NetClient && g_NetClient->IsController();
67 : }
68 :
69 0 : bool HasNetServer()
70 : {
71 0 : return !!g_NetServer;
72 : }
73 :
74 0 : bool HasNetClient()
75 : {
76 0 : return !!g_NetClient;
77 : }
78 :
79 0 : void StartNetworkHost(const CStrW& playerName, const std::uint16_t serverPort, const CStr& password,
80 : const bool continueSavedGame, bool storeReplay)
81 : {
82 0 : ENSURE(!g_NetClient);
83 0 : ENSURE(!g_NetServer);
84 0 : ENSURE(!g_Game);
85 :
86 : // Always use lobby authentication for lobby matches to prevent impersonation and smurfing, in particular through mods that implemented an UI for arbitrary or other players nicknames.
87 0 : const bool hasLobby = !!g_XmppClient;
88 0 : std::string hostJID;
89 : #if CONFIG2_LOBBY
90 0 : if (hasLobby)
91 0 : hostJID = g_XmppClient->GetJID();
92 : #endif
93 :
94 : /**
95 : * Password security - we want 0 A.D. to protect players from malicious hosts. We assume that clients
96 : * might mistakenly send a personal password instead of the game password (e.g. enter their mail account's password on autopilot).
97 : * Malicious dedicated servers might be set up to farm these failed logins and possibly obtain user credentials.
98 : * Therefore, we hash the passwords on the client side before sending them to the server.
99 : * This still makes the passwords potentially recoverable, but makes it much harder at scale.
100 : * To prevent the creation of rainbow tables, hash with:
101 : * - the host name
102 : * - the client name (this makes rainbow tables completely unworkable unless a specific user is targeted,
103 : * but that would require both computing the matching rainbow table _and_ for that specific user to mistype a personal password,
104 : * at which point we assume the attacker would/could probably just rather use another means of obtaining the password).
105 : * - the password itself
106 : * - the engine version (so that the hashes change periodically)
107 : * TODO: it should be possible to implement SRP or something along those lines to completely protect from this,
108 : * but the cost/benefit ratio is probably not worth it.
109 : */
110 0 : std::string hashedPassword = hasLobby ?
111 0 : HashCryptographically(password, hostJID + password + PS_SERIALIZATION_VERSION) : "";
112 :
113 0 : const std::string secret = ps_generate_guid();
114 :
115 : // Snapshot the host's buddies from the roster of the lobby they are
116 : // connected to. Hosting without a lobby means there is no roster, so
117 : // nobody is a buddy.
118 0 : std::set<std::string> buddies;
119 : #if CONFIG2_LOBBY
120 0 : if (hasLobby)
121 0 : buddies = g_XmppClient->GetBuddies();
122 : #endif
123 :
124 0 : g_NetServer = new CNetServer(continueSavedGame, serverPort, hasLobby, hashedPassword, secret,
125 0 : {}, buddies);
126 :
127 : // Generate a secret to identify the host client.
128 :
129 0 : auto tempGame = std::make_unique<CGame>(storeReplay);
130 0 : g_NetClient = new CNetClient(tempGame.get(), "127.0.0.1", serverPort, playerName, hostJID,
131 0 : hashedPassword, secret);
132 0 : g_Game = tempGame.release();
133 0 : }
134 :
135 0 : void StartNetworkJoin(const CStrW& playerName, const CStr& serverAddress, std::uint16_t serverPort,
136 : bool storeReplay)
137 : {
138 0 : ENSURE(!g_NetClient);
139 0 : ENSURE(!g_NetServer);
140 0 : ENSURE(!g_Game);
141 :
142 0 : auto tempGame = std::make_unique<CGame>(storeReplay);
143 0 : g_NetClient = new CNetClient(tempGame.get(), serverAddress, serverPort, playerName);
144 0 : g_Game = tempGame.release();
145 0 : }
146 :
147 : #if CONFIG2_LOBBY
148 : /**
149 : * Requires XmppClient to send iq request to the server to get server's ip and port based on passed password.
150 : * This is needed to not force server to share it's public ip with all potential clients in the lobby.
151 : * XmppClient will also handle logic after receiving the answer.
152 : */
153 0 : void StartNetworkJoinLobby(const CStrW& playerName, const CStr& hostJID, const CStr& password)
154 : {
155 0 : ENSURE(!!g_XmppClient);
156 0 : ENSURE(!g_NetClient);
157 0 : ENSURE(!g_NetServer);
158 0 : ENSURE(!g_Game);
159 :
160 0 : CStr hashedPass = HashCryptographically(password, hostJID + password + PS_SERIALIZATION_VERSION);
161 0 : auto tempGame = std::make_unique<CGame>(true);
162 0 : g_NetClient = new CNetClient(tempGame.get(), playerName, hostJID, hashedPass, *g_XmppClient);
163 0 : g_Game = tempGame.release();
164 0 : }
165 : #endif // CONFIG2_LOBBY
166 :
167 0 : void DisconnectNetworkGame()
168 : {
169 : // TODO: we ought to do async reliable disconnections
170 :
171 0 : SAFE_DELETE(g_NetServer);
172 0 : SAFE_DELETE(g_NetClient);
173 0 : SAFE_DELETE(g_Game);
174 0 : }
175 :
176 0 : CStr GetPlayerGUID()
177 : {
178 0 : if (!g_NetClient)
179 0 : return "local";
180 :
181 0 : return g_NetClient->GetGUID();
182 : }
183 :
184 0 : JS::Value PollNetworkClient(const Script::Interface& guiInterface)
185 : {
186 0 : if (!g_NetClient)
187 0 : throw std::logic_error{"Network client not present"};
188 :
189 0 : return JS::ObjectValue(*g_NetClient->GetNextGUIMessage(guiInterface));
190 : }
191 :
192 0 : void SendGameSetupMessage(const Script::Interface& scriptInterface, JS::HandleValue attribs1)
193 : {
194 0 : ENSURE(g_NetClient);
195 :
196 : // TODO: This is a workaround because we need to pass a MutableHandle to a JSAPI functions somewhere (with no obvious reason).
197 0 : Script::Request rq(scriptInterface);
198 0 : JS::RootedValue attribs(rq.cx, attribs1);
199 :
200 0 : g_NetClient->SendGameSetupMessage(&attribs, scriptInterface);
201 0 : }
202 :
203 0 : void AssignNetworkPlayer(int playerID, const CStr& guid)
204 : {
205 0 : ENSURE(g_NetClient);
206 :
207 0 : g_NetClient->SendAssignPlayerMessage(playerID, guid);
208 0 : }
209 :
210 0 : void KickPlayer(const CStrW& playerName, bool ban)
211 : {
212 0 : if (!g_NetClient)
213 0 : throw std::logic_error{"g_NetClient is null."};
214 0 : g_NetClient->SendKickPlayerMessage(playerName, ban);
215 0 : }
216 :
217 0 : void SendNetworkChat(const Script::Request& rq, const CStrW& message, JS::HandleValue handle)
218 : {
219 0 : ENSURE(g_NetClient);
220 :
221 0 : if (handle.isNullOrUndefined())
222 : {
223 0 : g_NetClient->SendChatMessage(message, std::nullopt);
224 0 : return;
225 : }
226 :
227 0 : auto receivers = std::make_optional<std::vector<std::string>>();
228 0 : if (!Script::FromJSVal(rq, handle, *receivers))
229 : {
230 0 : throw std::invalid_argument{"The second argument to `SendNetworkChat` has to be either an "
231 0 : "Array or a nullish value."};
232 : return;
233 : }
234 :
235 0 : g_NetClient->SendChatMessage(message, std::move(receivers));
236 0 : }
237 :
238 0 : void SendNetworkReady(int message)
239 : {
240 0 : ENSURE(g_NetClient);
241 :
242 0 : g_NetClient->SendReadyMessage(message);
243 0 : }
244 :
245 0 : void ClearAllPlayerReady ()
246 : {
247 0 : ENSURE(g_NetClient);
248 :
249 0 : g_NetClient->SendClearAllReadyMessage();
250 0 : }
251 :
252 0 : void StartNetworkGame(const Script::Interface& scriptInterface, JS::HandleValue savegame, JS::HandleValue attribs1)
253 : {
254 0 : ENSURE(g_NetClient);
255 :
256 0 : Script::Request rq(scriptInterface);
257 :
258 0 : JS::RootedValue attribs(rq.cx, attribs1);
259 0 : std::string attributesAsString{Script::StringifyJSON(rq, &attribs)};
260 :
261 0 : if (savegame.isUndefined())
262 : {
263 0 : g_NetClient->SendStartGameMessage(attributesAsString);
264 0 : return;
265 : }
266 :
267 0 : std::wstring savegameID;
268 0 : Script::FromJSVal(rq, savegame, savegameID);
269 :
270 0 : const std::optional<SavedGames::LoadResult> loadResult{SavedGames::Load(scriptInterface, savegameID)};
271 0 : if (loadResult)
272 0 : g_NetClient->SendStartSavedGameMessage(attributesAsString, loadResult->savedState);
273 : else
274 : {
275 0 : throw std::runtime_error{fmt::format("Failed to load the saved game: \"{}\"",
276 0 : utf8_from_wstring(savegameID).c_str())};
277 : }
278 : }
279 :
280 0 : void SetTurnLength(int length)
281 : {
282 0 : if (g_NetServer)
283 0 : g_NetServer->SetTurnLength(length);
284 : else
285 0 : LOGERROR("Only network host can change turn length");
286 0 : }
287 :
288 0 : void SendNetworkFlare(JS::HandleValue position)
289 : {
290 0 : ENSURE(g_NetClient);
291 :
292 0 : Script::Request rq(g_NetClient->GetScriptInterface());
293 0 : ENSURE(position.isObject());
294 0 : JS::RootedObject positionObj(rq.cx, &position.toObject());
295 0 : JS::RootedValue positionX(rq.cx);
296 0 : JS::RootedValue positionY(rq.cx);
297 0 : JS::RootedValue positionZ(rq.cx);
298 0 : ENSURE(JS_GetProperty(rq.cx, positionObj, "x", &positionX));
299 0 : ENSURE(JS_GetProperty(rq.cx, positionObj, "y", &positionY));
300 0 : ENSURE(JS_GetProperty(rq.cx, positionObj, "z", &positionZ));
301 :
302 : // (TODO?): Converting the doubles into strings here is a workaround because direct (de)serialisation of floating point numbers is not supported.
303 : // It causes somewhat awkward message handling, but the resulting efficiency losses are negligible.
304 0 : g_NetClient->SendFlareMessage(
305 0 : fmt::format("{}", positionX.toNumber()),
306 0 : fmt::format("{}", positionY.toNumber()),
307 0 : fmt::format("{}", positionZ.toNumber())
308 : );
309 0 : }
310 :
311 26 : void RegisterScriptFunctions(const Script::Request& rq)
312 : {
313 26 : Script::Function::Register<&GetDefaultPort>(rq, "GetDefaultPort");
314 26 : Script::Function::Register<&IsNetController>(rq, "IsNetController");
315 26 : Script::Function::Register<&HasNetServer>(rq, "HasNetServer");
316 26 : Script::Function::Register<&HasNetClient>(rq, "HasNetClient");
317 26 : Script::Function::Register<&StartNetworkHost>(rq, "StartNetworkHost");
318 26 : Script::Function::Register<&StartNetworkJoin>(rq, "StartNetworkJoin");
319 : #if CONFIG2_LOBBY
320 26 : Script::Function::Register<&StartNetworkJoinLobby>(rq, "StartNetworkJoinLobby");
321 : #endif
322 26 : Script::Function::Register<&DisconnectNetworkGame>(rq, "DisconnectNetworkGame");
323 26 : Script::Function::Register<&GetPlayerGUID>(rq, "GetPlayerGUID");
324 26 : Script::Function::Register<&PollNetworkClient>(rq, "PollNetworkClient");
325 26 : Script::Function::Register<&SendGameSetupMessage>(rq, "SendGameSetupMessage");
326 26 : Script::Function::Register<&AssignNetworkPlayer>(rq, "AssignNetworkPlayer");
327 26 : Script::Function::Register<&KickPlayer>(rq, "KickPlayer");
328 26 : Script::Function::Register<&SendNetworkChat>(rq, "SendNetworkChat");
329 26 : Script::Function::Register<&SendNetworkReady>(rq, "SendNetworkReady");
330 26 : Script::Function::Register<&ClearAllPlayerReady>(rq, "ClearAllPlayerReady");
331 26 : Script::Function::Register<&StartNetworkGame>(rq, "StartNetworkGame");
332 26 : Script::Function::Register<&SetTurnLength>(rq, "SetTurnLength");
333 26 : Script::Function::Register<&SendNetworkFlare>(rq, "SendNetworkFlare");
334 26 : }
335 : }
|