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 "XmppClient.h"
21 :
22 : #include "StanzaExtensions.h"
23 : #include "i18n/L10n.h"
24 : #include "lib/code_annotation.h"
25 : #include "lib/external_libraries/gloox.h"
26 : #include "lib/utf8.h"
27 : #include "lobby/GlooxConversion.h"
28 : #include "network/NetClient.h"
29 : #include "network/NetServer.h"
30 : #include "network/StunClient.h"
31 : #include "ps/CLogger.h"
32 : #include "ps/CStr.h"
33 : #include "ps/ConfigDB.h"
34 : #include "ps/GUID.h"
35 : #include "ps/Pyrogenesis.h"
36 : #include "scriptinterface/Object.h"
37 : #include "scriptinterface/Conversions.h"
38 : #include "scriptinterface/Interface.h"
39 : #include "scriptinterface/Request.h"
40 : #include "scriptinterface/StructuredClone.h"
41 :
42 : #include <algorithm>
43 : #include <ctime>
44 : #include <deque>
45 : #include <iostream>
46 : #include <js/GCVector.h>
47 : #include <js/PropertyAndElement.h>
48 : #include <js/PropertyDescriptor.h>
49 : #include <js/TracingAPI.h>
50 : #include <js/TypeDecls.h>
51 : #include <js/Value.h>
52 : #include <js/Vector.h>
53 : #include <map>
54 : #include <optional>
55 : #include <set>
56 : #include <string>
57 : #include <tuple>
58 : #include <unicode/locid.h>
59 : #include <unicode/utypes.h>
60 : #include <utility>
61 : #include <vector>
62 :
63 : namespace
64 : {
65 : constexpr const char* ROSTER_GROUP_NAME_BUDDIES{"buddies"};
66 :
67 : //debug
68 : #if 1
69 : #define DbgXMPP(x)
70 : #else
71 : #define DbgXMPP(x) std::cout << "XMPP DEBUG: " << x << std::endl;
72 :
73 : std::string tag_xml(const gloox::IQ& iq)
74 : {
75 : return iq.tag()->xml();
76 : }
77 : #endif
78 :
79 0 : std::string tag_name(const gloox::IQ& iq)
80 : {
81 0 : return iq.tag()->name();
82 : }
83 :
84 : /**
85 : * Parse and return the timestamp of a historic chat message and return the current time for new chat messages.
86 : * Historic chat messages are implement as DelayedDelivers as specified in XEP-0203.
87 : * Hence, their timestamp MUST be in UTC and conform to the DateTime format XEP-0082.
88 : *
89 : * @returns Seconds since the epoch.
90 : */
91 0 : std::time_t ComputeTimestamp(const gloox::Message& msg)
92 : {
93 : // Only historic messages contain a timestamp!
94 0 : if (!msg.when())
95 0 : return std::time(nullptr);
96 :
97 : // The locale is irrelevant, because the XMPP date format doesn't contain written month names
98 0 : for (const std::string& format : std::vector<std::string>{ "Y-M-d'T'H:m:sZ", "Y-M-d'T'H:m:s.SZ" })
99 : {
100 0 : UDate dateTime = g_L10n.ParseDateTime(msg.when()->stamp(), format, icu::Locale::getUS());
101 0 : if (dateTime)
102 0 : return dateTime / 1000.0;
103 0 : }
104 :
105 0 : return std::time(nullptr);
106 0 : }
107 :
108 0 : gloox::Client CreateClient(const bool regOpt, const std::string& username, const std::string& servername,
109 : const std::string& password)
110 : {
111 : // If we are connecting, use the full jid and a password
112 : // If we are registering, only use the server name
113 0 : if (regOpt)
114 0 : return gloox::Client{servername};
115 :
116 : // Generate a unique, unpredictable resource to allow multiple 0 A.D. instances to connect to the lobby.
117 0 : static const CStr guid{ps_generate_guid()};
118 0 : gloox::JID clientJid(username + "@" + servername + "/0ad-" + guid);
119 0 : return gloox::Client{clientJid, password};
120 0 : }
121 :
122 0 : std::optional<gloox::MUCRoom> CreateMucRoom(gloox::MUCRoomHandler* handler, const bool regOpt, gloox::Client& client,
123 : const std::string& room, const std::string& servername, const std::string& nick)
124 : {
125 0 : if (regOpt)
126 0 : return std::nullopt;
127 :
128 : // Generate a unique, unpredictable resource to allow multiple 0 A.D. instances to connect to the lobby.
129 0 : gloox::JID roomJid(room + "@conference." + servername + "/" + nick);
130 0 : return std::make_optional<gloox::MUCRoom>(&client, roomJid, handler);
131 0 : }
132 : } // anonymous namespace
133 :
134 : class XmppClient::Impl : public gloox::ConnectionListener, public gloox::MUCRoomHandler,
135 : public gloox::IqHandler, public gloox::RegistrationHandler, public gloox::MessageHandler,
136 : public gloox::Jingle::SessionHandler, public gloox::LogHandler, public gloox::RosterListener
137 : {
138 : public:
139 : // Basic
140 : Impl(const Script::Interface* scriptInterface, const std::string& sUsername,
141 : const std::string& sPassword, const std::string& sRoom, const std::string& sNick,
142 : const int historyRequestSize, const bool regOpt);
143 :
144 : std::string m_server;
145 :
146 : // Components
147 : gloox::Client m_client;
148 : std::optional<gloox::MUCRoom> m_mucRoom;
149 : gloox::Registration m_registration;
150 : gloox::Jingle::SessionManager m_sessionManager;
151 :
152 : // Account infos
153 : std::string m_username;
154 : std::string m_password;
155 : std::string m_room;
156 : std::string m_nick;
157 : std::string m_xpartamuppId;
158 : std::string m_echelonId;
159 :
160 : // Security
161 : std::string m_connectionDataJid;
162 : std::string m_connectionDataIqId;
163 :
164 : // State
165 : gloox::CertStatus m_certStatus;
166 : bool m_initialLoadComplete;
167 : bool m_regOpt;
168 : std::set<std::string> m_Buddies;
169 :
170 : private:
171 : /* Xmpp handlers */
172 : /* MUC handlers */
173 : void handleMUCParticipantPresence(gloox::MUCRoom* room, gloox::MUCRoomParticipant,
174 : const gloox::Presence&) override;
175 : void handleMUCError(gloox::MUCRoom* room, gloox::StanzaError) override;
176 : void handleMUCMessage(gloox::MUCRoom* room, const gloox::Message& msg, bool priv) override;
177 : void handleMUCSubject(gloox::MUCRoom* room, const std::string& nick,
178 : const std::string& subject) override;
179 : // Currently unused, provide noop implemtation for pure virtual functions.
180 0 : bool handleMUCRoomCreation(gloox::MUCRoom*) override { return false; }
181 0 : void handleMUCInviteDecline(gloox::MUCRoom*, const gloox::JID&, const std::string&) override {}
182 0 : void handleMUCInfo(gloox::MUCRoom*, int, const std::string&, const gloox::DataForm*) override {}
183 0 : void handleMUCItems(gloox::MUCRoom*, const std::list<gloox::Disco::Item*,
184 0 : std::allocator<gloox::Disco::Item*>>&) override {}
185 :
186 : /* Log handler */
187 : void handleLog(gloox::LogLevel level, gloox::LogArea area, const std::string& message) override;
188 :
189 : /* ConnectionListener handlers*/
190 : void onConnect() override;
191 : void onDisconnect(gloox::ConnectionError e) override;
192 : bool onTLSConnect(const gloox::CertInfo& info) override;
193 :
194 : /* Iq Handlers */
195 : bool handleIq(const gloox::IQ& iq) override;
196 0 : void handleIqID(const gloox::IQ&, int) override {}
197 :
198 : /* Registration Handlers */
199 : void handleRegistrationFields(const gloox::JID& /*from*/, int fields,
200 : std::string instructions) override;
201 : #if GLOOXVERSION >= 0x010100
202 : void handleRegistrationResult(const gloox::JID& /*from*/, gloox::RegistrationResult result,
203 : const gloox::Error* /*error*/) override;
204 : #else
205 : void handleRegistrationResult(const gloox::JID& /*from*/, gloox::RegistrationResult result) override;
206 : #endif
207 : void handleAlreadyRegistered(const gloox::JID& /*from*/) override;
208 : void handleDataForm(const gloox::JID& /*from*/, const gloox::DataForm& /*form*/) override;
209 : void handleOOB(const gloox::JID& /*from*/, const gloox::OOB& oob) override;
210 :
211 : /* Message Handler */
212 : void handleMessage(const gloox::Message& msg, gloox::MessageSession* session) override;
213 :
214 : /* Session Handler */
215 : void handleSessionAction(gloox::Jingle::Action action, gloox::Jingle::Session* session,
216 : const gloox::Jingle::Session::Jingle* jingle) override;
217 0 : void handleSessionActionError(gloox::Jingle::Action /*action*/, gloox::Jingle::Session* /*session*/,
218 0 : const gloox::Error* /*error*/) override {}
219 0 : void handleIncomingSession(gloox::Jingle::Session* /*session*/) override {}
220 :
221 : void handleSessionInitiation(gloox::Jingle::Session* session,
222 : const gloox::Jingle::Session::Jingle* jingle);
223 :
224 : /**
225 : * Rebuild m_Buddies from the roster.
226 : */
227 : void UpdateBuddies();
228 :
229 : /**
230 : * Move a pre-roster buddy list from the config into the roster, then drop
231 : * it from the config. Does nothing once that migration has happened.
232 : *
233 : * Must only be called once the roster has been received, since an empty
234 : * roster cannot be distinguished from one without buddies.
235 : */
236 : void MigrateBuddyList();
237 :
238 : /* Roster */
239 : void handleItemAdded(const gloox::JID& jid) override;
240 0 : void handleItemSubscribed(const gloox::JID& /*jid*/) override {}
241 : void handleItemRemoved(const gloox::JID& jid) override;
242 : void handleItemUpdated(const gloox::JID& jid) override;
243 0 : void handleItemUnsubscribed(const gloox::JID& /*jid*/) override {}
244 : void handleRoster(const gloox::Roster& /*roster*/) override;
245 0 : void handleRosterPresence(const gloox::RosterItem& /*item*/, const std::string& /*resource*/, gloox::Presence::PresenceType /*presence*/, const std::string& /*msg*/) override {}
246 0 : void handleSelfPresence(const gloox::RosterItem& /*item*/, const std::string& /*resource*/, gloox::Presence::PresenceType /*presence*/, const std::string& /*msg*/) override {}
247 0 : bool handleSubscriptionRequest(const gloox::JID& /*jid*/, const std::string& /*msg*/) override { return false; }
248 0 : bool handleUnsubscriptionRequest(const gloox::JID& /*jid*/, const std::string& /*msg*/) override { return false; }
249 0 : void handleNonrosterPresence(const gloox::Presence& /*presence*/) override {}
250 : void handleRosterError(const gloox::IQ& iq) override;
251 : #if GLOOXVERSION >= 0x010100
252 : void handleRosterItemExchange(const gloox::JID& /*from*/, const gloox::RosterX* /*items*/) override {}
253 : #endif
254 :
255 : template<typename... Args>
256 : void CreateGUIMessage(
257 : const std::string& type,
258 : const std::string& level,
259 : const std::time_t time,
260 : Args const&... args);
261 :
262 : public:
263 : struct SPlayer {
264 0 : SPlayer(const gloox::Presence::PresenceType presence, const gloox::MUCRoomRole role,
265 : const std::string& bareJid, const std::string& rating)
266 0 : : m_Presence(presence), m_Role(role), m_BareJid(bareJid), m_Rating(rating)
267 : {
268 0 : }
269 : gloox::Presence::PresenceType m_Presence;
270 : gloox::MUCRoomRole m_Role;
271 : std::string m_BareJid;
272 : std::string m_Rating;
273 : };
274 : using PlayerMap = std::map<std::string, SPlayer>;
275 :
276 : public:
277 : /// Map of players
278 : PlayerMap m_PlayerMap;
279 : /// Whether or not the playermap has changed since the last time the GUI checked.
280 : bool m_PlayerMapUpdate;
281 : /// List of games
282 : std::vector<std::unique_ptr<const gloox::Tag>> m_GameList;
283 : /// List of rankings
284 : std::vector<std::unique_ptr<const gloox::Tag>> m_BoardList;
285 : /// Profile data
286 : std::vector<std::unique_ptr<const gloox::Tag>> m_Profile;
287 : /// Script::Interface to root the values
288 : const Script::Interface* m_ScriptInterface;
289 : /// Queue of messages for the GUI
290 : JS::PersistentRootedVector<JS::Value> m_GuiMessageQueue;
291 : /// Cache of all GUI messages received since the login
292 : JS::PersistentRootedVector<JS::Value> m_HistoricGuiMessages;
293 : /// Current room subject/topic.
294 : std::wstring m_Subject;
295 : };
296 :
297 :
298 : /**
299 : * Construct the XMPP client.
300 : *
301 : * @param scriptInterface - Script::Interface to be used for storing GUI messages.
302 : * Can be left blank for non-visual applications.
303 : * @param sUsername Username to login with of register.
304 : * @param sPassword Password to login with or register.
305 : * @param sRoom MUC room to join.
306 : * @param sNick Nick to join with.
307 : * @param historyRequestSize Number of stanzas of room history to request.
308 : * @param regOpt If we are just registering or not.
309 : */
310 0 : XmppClient::XmppClient(const Script::Interface* scriptInterface, const std::string& username,
311 : const std::string& password, const std::string& room, const std::string& nick,
312 0 : const int historyRequestSize, bool regOpt) :
313 0 : m_Impl{std::make_unique<Impl>(scriptInterface, username, password, room, nick, historyRequestSize,
314 : regOpt)}
315 0 : {}
316 :
317 0 : XmppClient::Impl::Impl(const Script::Interface* scriptInterface, const std::string& sUsername,
318 : const std::string& sPassword, const std::string& sRoom, const std::string& sNick,
319 0 : const int historyRequestSize, bool regOpt)
320 0 : : m_server{g_ConfigDB.Get("lobby.server", std::string{})},
321 : // If we are connecting, use the full jid and a password
322 : // If we are registering, only use the server name
323 0 : m_client{CreateClient(regOpt, sUsername, m_server, sPassword)},
324 0 : m_mucRoom{CreateMucRoom(this, regOpt, m_client, sRoom, m_server, sNick)},
325 0 : m_registration{&m_client},
326 0 : m_sessionManager{&m_client, this},
327 0 : m_regOpt(regOpt),
328 0 : m_username(sUsername),
329 0 : m_password(sPassword),
330 0 : m_room(sRoom),
331 0 : m_nick(sNick),
332 0 : m_xpartamuppId{g_ConfigDB.Get("lobby.xpartamupp", std::string{}) + "@" + m_server + "/CC"},
333 0 : m_echelonId{g_ConfigDB.Get("lobby.echelon", std::string{}) + "@" + m_server + "/CC"},
334 0 : m_initialLoadComplete(false),
335 0 : m_certStatus(gloox::CertStatus::CertOk),
336 0 : m_PlayerMapUpdate(false),
337 0 : m_connectionDataJid(),
338 0 : m_connectionDataIqId(),
339 0 : m_ScriptInterface(scriptInterface),
340 0 : m_GuiMessageQueue{m_ScriptInterface->GetGeneralJSContext()},
341 0 : m_HistoricGuiMessages{m_ScriptInterface->GetGeneralJSContext()}
342 : {
343 : // Optionally join without a TLS certificate, so a local server can be tested quickly.
344 : // Security risks from malicious JS mods can be mitigated if this option and also the hostname and login are shielded from JS access.
345 0 : m_client.setTls(g_ConfigDB.Get("lobby.tls", true) ? gloox::TLSRequired : gloox::TLSDisabled);
346 :
347 : // Disable use of the SASL PLAIN mechanism, to prevent leaking credentials
348 : // if the server doesn't list any supported SASL mechanism or the response
349 : // has been modified to exclude those.
350 0 : const int mechs = gloox::SaslMechAll ^ gloox::SaslMechPlain;
351 0 : m_client.setSASLMechanisms(mechs);
352 :
353 0 : m_client.registerConnectionListener(this);
354 0 : m_client.setPresence(gloox::Presence::Available, -1);
355 0 : m_client.disco()->setVersion("Pyrogenesis", PS_SERIALIZATION_VERSION);
356 0 : m_client.disco()->setIdentity("client", "bot");
357 0 : m_client.setCompression(false);
358 :
359 0 : m_client.registerStanzaExtension(new GameListQuery());
360 0 : m_client.registerIqHandler(this, EXTGAMELISTQUERY);
361 :
362 0 : m_client.registerStanzaExtension(new BoardListQuery());
363 0 : m_client.registerIqHandler(this, EXTBOARDLISTQUERY);
364 :
365 0 : m_client.registerStanzaExtension(new ProfileQuery());
366 0 : m_client.registerIqHandler(this, EXTPROFILEQUERY);
367 :
368 0 : m_client.registerStanzaExtension(new LobbyAuth());
369 0 : m_client.registerIqHandler(this, EXTLOBBYAUTH);
370 :
371 0 : m_client.registerStanzaExtension(new ConnectionData());
372 0 : m_client.registerIqHandler(this, EXTCONNECTIONDATA);
373 :
374 0 : m_client.registerMessageHandler(this);
375 :
376 0 : m_client.rosterManager()->registerRosterListener(this, false);
377 :
378 0 : m_registration.registerRegistrationHandler(this);
379 :
380 : // Uncomment to see the raw stanzas
381 : // m_client.logInstance().registerLogHandler(gloox::LogLevelDebug, gloox::LogAreaAll, this);
382 :
383 0 : if (!regOpt)
384 0 : m_mucRoom->setRequestHistory(historyRequestSize, gloox::MUCRoom::HistoryMaxStanzas);
385 :
386 : // Register plugins to allow gloox parse them in incoming sessions
387 0 : m_sessionManager.registerPlugin(new gloox::Jingle::Content());
388 0 : m_sessionManager.registerPlugin(new gloox::Jingle::ICEUDP());
389 0 : }
390 :
391 : /**
392 : * Destroy the xmpp client
393 : */
394 0 : XmppClient::~XmppClient()
395 : {
396 0 : this->disconnect();
397 :
398 0 : DbgXMPP("XmppClient destroyed");
399 :
400 : // Workaround for memory leak in gloox 1.0/1.0.1
401 0 : m_Impl->m_client.removePresenceExtension(gloox::ExtCaps);
402 0 : }
403 :
404 : /// Network
405 0 : void XmppClient::connect()
406 : {
407 0 : m_Impl->m_initialLoadComplete = false;
408 0 : m_Impl->m_client.connect(false);
409 0 : }
410 :
411 0 : void XmppClient::disconnect()
412 : {
413 0 : m_Impl->m_client.disconnect();
414 0 : }
415 :
416 0 : bool XmppClient::isConnected()
417 : {
418 0 : return m_Impl->m_client.state() == gloox::StateConnected;
419 : }
420 :
421 0 : void XmppClient::recv()
422 : {
423 0 : m_Impl->m_client.recv(1);
424 0 : }
425 :
426 : /**
427 : * Log (debug) Handler
428 : */
429 0 : void XmppClient::Impl::handleLog(gloox::LogLevel level, gloox::LogArea area, const std::string& message)
430 : {
431 0 : std::cout << "log: level: " << level << ", area: " << area << ", message: " << message << std::endl;
432 0 : }
433 :
434 : /*****************************************************
435 : * Connection handlers *
436 : *****************************************************/
437 :
438 : /**
439 : * Handle connection
440 : */
441 0 : void XmppClient::Impl::onConnect()
442 : {
443 0 : if (m_mucRoom)
444 : {
445 0 : CreateGUIMessage("system", "connected", std::time(nullptr));
446 0 : m_mucRoom->join();
447 : }
448 :
449 0 : if (m_regOpt)
450 0 : m_registration.fetchRegistrationFields();
451 0 : }
452 :
453 : /**
454 : * Handle disconnection
455 : */
456 0 : void XmppClient::Impl::onDisconnect(gloox::ConnectionError error)
457 : {
458 : // Make sure we properly leave the room so that
459 : // everything works if we decide to come back later
460 0 : if (m_mucRoom)
461 0 : m_mucRoom->leave();
462 :
463 : // Clear game, board and player lists.
464 0 : m_GameList.clear();
465 0 : m_BoardList.clear();
466 0 : m_Profile.clear();
467 :
468 0 : m_PlayerMap.clear();
469 0 : m_PlayerMapUpdate = true;
470 0 : m_HistoricGuiMessages.clear();
471 0 : m_Buddies.clear();
472 0 : m_initialLoadComplete = false;
473 :
474 0 : CreateGUIMessage(
475 : "system",
476 : "disconnected",
477 : std::time(nullptr),
478 : "reason", error,
479 0 : "certificate_status", m_certStatus);
480 0 : }
481 :
482 : /**
483 : * Handle TLS connection.
484 : */
485 0 : bool XmppClient::Impl::onTLSConnect(const gloox::CertInfo& info)
486 : {
487 : DbgXMPP("onTLSConnect:" <<
488 : " status: " << info.status <<
489 : ", issuer: " << info.issuer <<
490 : ", peer: " << info.server <<
491 : ", protocol: " << info.protocol <<
492 : ", mac: " << info.mac <<
493 : ", cipher: " << info.cipher <<
494 0 : ", compression: " << info.compression);
495 :
496 0 : m_certStatus = static_cast<gloox::CertStatus>(info.status);
497 :
498 : // Optionally accept invalid certificates, see require_tls option.
499 0 : return info.status == gloox::CertOk || !g_ConfigDB.Get("lobby.verify_certificate", true);
500 : }
501 :
502 : /**
503 : * Handle MUC room errors
504 : */
505 0 : void XmppClient::Impl::handleMUCError(gloox::MUCRoom*, gloox::StanzaError err)
506 : {
507 0 : DbgXMPP("MUC Error " << ": " << StanzaErrorToString(err));
508 0 : CreateGUIMessage("system", "error", std::time(nullptr), "text", err);
509 0 : }
510 :
511 : /*****************************************************
512 : * Requests to server *
513 : *****************************************************/
514 :
515 : /**
516 : * Request the leaderboard data from the server.
517 : */
518 0 : void XmppClient::SendIqGetBoardList()
519 : {
520 0 : gloox::JID echelonJid(m_Impl->m_echelonId);
521 :
522 : // Send IQ
523 0 : BoardListQuery* b = new BoardListQuery();
524 0 : b->m_Command = "getleaderboard";
525 0 : gloox::IQ iq(gloox::IQ::Get, echelonJid, m_Impl->m_client.getID());
526 0 : iq.addExtension(b);
527 0 : DbgXMPP("SendIqGetBoardList [" << tag_xml(iq) << "]");
528 0 : m_Impl->m_client.send(iq);
529 0 : }
530 :
531 : /**
532 : * Request the profile data from the server.
533 : */
534 0 : void XmppClient::SendIqGetProfile(const std::string& player)
535 : {
536 0 : gloox::JID echelonJid(m_Impl->m_echelonId);
537 :
538 : // Send IQ
539 0 : ProfileQuery* b = new ProfileQuery();
540 0 : b->m_Command = player;
541 0 : gloox::IQ iq(gloox::IQ::Get, echelonJid, m_Impl->m_client.getID());
542 0 : iq.addExtension(b);
543 0 : DbgXMPP("SendIqGetProfile [" << tag_xml(iq) << "]");
544 0 : m_Impl->m_client.send(iq);
545 0 : }
546 :
547 : /**
548 : * Request the Connection data (ip, port...) from the server.
549 : */
550 0 : void XmppClient::SendIqGetConnectionData(const std::string& jid, const std::string& password, const std::string& clientSalt, bool localIP)
551 : {
552 0 : gloox::JID targetJID(jid);
553 :
554 0 : ConnectionData* connectionData = new ConnectionData();
555 0 : connectionData->m_Password = password;
556 0 : connectionData->m_ClientSalt = clientSalt;
557 0 : connectionData->m_IsLocalIP = localIP ? "1" : "0";
558 0 : gloox::IQ iq(gloox::IQ::Get, targetJID, m_Impl->m_client.getID());
559 0 : iq.addExtension(connectionData);
560 0 : m_Impl->m_connectionDataJid = iq.to().full();
561 0 : m_Impl->m_connectionDataIqId = iq.id();
562 0 : DbgXMPP("SendIqGetConnectionData [" << tag_xml(iq) << "]");
563 0 : m_Impl->m_client.send(iq);
564 0 : }
565 :
566 : /**
567 : * Send game report containing numerous game properties to the server.
568 : *
569 : * @param data A JS array of game statistics
570 : */
571 0 : void XmppClient::SendIqGameReport(const Script::Request& rq, JS::HandleValue data)
572 : {
573 0 : gloox::JID echelonJid(m_Impl->m_echelonId);
574 :
575 : // Setup some base stanza attributes
576 0 : GameReport* game = new GameReport();
577 0 : gloox::Tag* report = new gloox::Tag("game");
578 :
579 : // Iterate through all the properties reported and add them to the stanza.
580 0 : std::vector<std::string> properties;
581 0 : Script::EnumeratePropertyNames(rq, data, true, properties);
582 :
583 : // https://gitea.wildfiregames.com/0ad/0ad/issues/8687
584 0 : const std::map<std::string, std::string> mappings{
585 : { "civilianUnitsLost", "femaleCitizenUnitsLost" },
586 : { "civilianUnitsTrained", "femaleCitizenUnitsTrained" },
587 : { "enemyCivilianUnitsKilled", "enemyFemaleCitizenUnitsKilled"}
588 0 : };
589 0 : for (const std::string& p : properties)
590 : {
591 0 : std::wstring value;
592 0 : Script::GetProperty(rq, data, p.c_str(), value);
593 0 : if (mappings.contains(p))
594 0 : report->addAttribute(mappings.at(p), utf8_from_wstring(value));
595 : else
596 0 : report->addAttribute(p, utf8_from_wstring(value));
597 0 : }
598 :
599 : // Add stanza to IQ
600 0 : game->m_GameReport.emplace_back(report);
601 :
602 : // Send IQ
603 0 : gloox::IQ iq(gloox::IQ::Set, echelonJid, m_Impl->m_client.getID());
604 0 : iq.addExtension(game);
605 0 : DbgXMPP("SendGameReport [" << tag_xml(iq) << "]");
606 0 : m_Impl->m_client.send(iq);
607 0 : };
608 :
609 : /**
610 : * Send a request to register a game to the server.
611 : *
612 : * @param data A JS array of game attributes
613 : */
614 0 : void XmppClient::SendIqRegisterGame(const Script::Request& rq, JS::HandleValue data)
615 : {
616 0 : gloox::JID xpartamuppJid(m_Impl->m_xpartamuppId);
617 :
618 : // Setup some base stanza attributes
619 0 : std::unique_ptr<GameListQuery> g = std::make_unique<GameListQuery>();
620 0 : g->m_Command = "register";
621 0 : gloox::Tag* game = new gloox::Tag("game");
622 :
623 : // Iterate through all the properties reported and add them to the stanza.
624 0 : std::vector<std::string> properties;
625 0 : Script::EnumeratePropertyNames(rq, data, true, properties);
626 0 : for (const std::string& p : properties)
627 : {
628 0 : std::string value;
629 0 : if (!Script::GetProperty(rq, data, p.c_str(), value))
630 : {
631 0 : LOGERROR("Could not parse attribute '{}' as string.", p);
632 0 : return;
633 : }
634 0 : game->addAttribute(p, value);
635 0 : }
636 :
637 : // Overwrite some attributes to make it slightly less trivial to do bad things,
638 : // and explicit some invariants.
639 :
640 : // The JID must point to ourself.
641 0 : game->addAttribute("hostJID", GetJID());
642 :
643 : // Push the stanza onto the IQ
644 0 : g->m_GameList.emplace_back(game);
645 :
646 : // Send IQ
647 0 : gloox::IQ iq(gloox::IQ::Set, xpartamuppJid, m_Impl->m_client.getID());
648 0 : iq.addExtension(g.release());
649 0 : DbgXMPP("SendIqRegisterGame [" << tag_xml(iq) << "]");
650 0 : m_Impl->m_client.send(iq);
651 0 : }
652 :
653 : /**
654 : * Send a request to unregister a game to the server.
655 : */
656 0 : void XmppClient::SendIqUnregisterGame()
657 : {
658 0 : gloox::JID xpartamuppJid(m_Impl->m_xpartamuppId);
659 :
660 : // Send IQ
661 0 : GameListQuery* g = new GameListQuery();
662 0 : g->m_Command = "unregister";
663 0 : g->m_GameList.emplace_back(new gloox::Tag("game"));
664 :
665 0 : gloox::IQ iq(gloox::IQ::Set, xpartamuppJid, m_Impl->m_client.getID());
666 0 : iq.addExtension(g);
667 0 : DbgXMPP("SendIqUnregisterGame [" << tag_xml(iq) << "]");
668 0 : m_Impl->m_client.send(iq);
669 0 : }
670 :
671 : /**
672 : * Send a request to change the state of a registered game on the server.
673 : *
674 : * A game can either be in the 'running' or 'waiting' state - the server
675 : * decides which - but we need to update the current players that are
676 : * in-game so the server can make the calculation.
677 : */
678 0 : void XmppClient::SendIqChangeStateGame(const std::string& nbp, const std::string& players)
679 : {
680 0 : gloox::JID xpartamuppJid(m_Impl->m_xpartamuppId);
681 :
682 : // Send IQ
683 0 : GameListQuery* g = new GameListQuery();
684 0 : g->m_Command = "changestate";
685 0 : gloox::Tag* game = new gloox::Tag("game");
686 0 : game->addAttribute("nbp", nbp);
687 0 : game->addAttribute("players", players);
688 0 : g->m_GameList.emplace_back(game);
689 :
690 0 : gloox::IQ iq(gloox::IQ::Set, xpartamuppJid, m_Impl->m_client.getID());
691 0 : iq.addExtension(g);
692 0 : DbgXMPP("SendIqChangeStateGame [" << tag_xml(iq) << "]");
693 0 : m_Impl->m_client.send(iq);
694 0 : }
695 :
696 : /*****************************************************
697 : * iq to clients *
698 : *****************************************************/
699 :
700 : /**
701 : * Send lobby authentication token.
702 : */
703 0 : void XmppClient::SendIqLobbyAuth(const std::string& to, const std::string& token)
704 : {
705 0 : LobbyAuth* auth = new LobbyAuth();
706 0 : auth->m_Token = token;
707 :
708 0 : gloox::JID clientJid(to);
709 0 : gloox::IQ iq(gloox::IQ::Set, clientJid, m_Impl->m_client.getID());
710 0 : iq.addExtension(auth);
711 0 : DbgXMPP("SendIqLobbyAuth [" << tag_xml(iq) << "]");
712 0 : m_Impl->m_client.send(iq);
713 0 : }
714 :
715 : /*****************************************************
716 : * Account registration *
717 : *****************************************************/
718 :
719 0 : void XmppClient::Impl::handleRegistrationFields(const gloox::JID&, int fields, std::string)
720 : {
721 0 : gloox::RegistrationFields vals;
722 0 : vals.username = m_username;
723 0 : vals.password = m_password;
724 0 : m_registration.createAccount(fields, vals);
725 0 : }
726 :
727 : #if GLOOXVERSION >= 0x010100
728 : void XmppClient::Impl::handleRegistrationResult(const gloox::JID&, gloox::RegistrationResult result,
729 : const gloox::Error* /*error*/)
730 : #else
731 0 : void XmppClient::Impl::handleRegistrationResult(const gloox::JID&, gloox::RegistrationResult result)
732 : #endif
733 : {
734 0 : if (result == gloox::RegistrationSuccess)
735 0 : CreateGUIMessage("system", "registered", std::time(nullptr));
736 : else
737 0 : CreateGUIMessage("system", "error", std::time(nullptr), "text", result);
738 0 : }
739 :
740 0 : void XmppClient::Impl::handleAlreadyRegistered(const gloox::JID&)
741 : {
742 0 : DbgXMPP("the account already exists");
743 0 : }
744 :
745 0 : void XmppClient::Impl::handleDataForm(const gloox::JID&, const gloox::DataForm&)
746 : {
747 0 : DbgXMPP("dataForm received");
748 0 : }
749 :
750 0 : void XmppClient::Impl::handleOOB(const gloox::JID&, const gloox::OOB&)
751 : {
752 0 : DbgXMPP("OOB registration requested");
753 0 : }
754 :
755 : /*****************************************************
756 : * Requests from GUI *
757 : *****************************************************/
758 :
759 : /**
760 : * Handle requests from the GUI for the list of players.
761 : *
762 : * @return A JS array containing all known players and their presences
763 : */
764 0 : JS::Value XmppClient::GUIGetPlayerList(const Script::Request& rq)
765 : {
766 0 : JS::RootedValueVector players{rq.cx};
767 :
768 0 : for (const auto& p : m_Impl->m_PlayerMap)
769 : {
770 0 : JS::RootedValue player(rq.cx);
771 :
772 0 : Script::CreateObject(
773 : rq,
774 : &player,
775 0 : "name", p.first,
776 0 : "presence", p.second.m_Presence,
777 0 : "rating", p.second.m_Rating,
778 0 : "role", p.second.m_Role);
779 :
780 0 : if (!players.append(player))
781 0 : throw std::runtime_error{"Append failed"};
782 0 : }
783 0 : return JS::ObjectValue(*JS::NewArrayObject(rq.cx, players));
784 0 : }
785 :
786 : /**
787 : * Handle requests from the GUI for the list of all active games.
788 : *
789 : * @return A JS array containing all known games
790 : */
791 0 : JS::Value XmppClient::GUIGetGameList(const Script::Request& rq)
792 : {
793 0 : JS::RootedValueVector games{rq.cx};
794 :
795 0 : const char* stats[] = { "name", "hostUsername", "hostJID", "state", "hasPassword",
796 : "nbp", "maxnbp", "players", "mapName", "niceMapName", "mapSize", "mapType",
797 : "victoryConditions", "startTime", "mods" };
798 :
799 0 : for(const std::unique_ptr<const gloox::Tag>& t : m_Impl->m_GameList)
800 : {
801 0 : JS::RootedValue game(rq.cx);
802 0 : Script::CreateObject(rq, &game);
803 :
804 0 : for (size_t i = 0; i < ARRAY_SIZE(stats); ++i)
805 0 : Script::SetProperty(rq, game, stats[i], t->findAttribute(stats[i]));
806 :
807 0 : if (!games.append(game))
808 0 : throw std::runtime_error{"Append failed"};
809 0 : }
810 0 : return JS::ObjectValue(*JS::NewArrayObject(rq.cx, games));
811 0 : }
812 :
813 : /**
814 : * Handle requests from the GUI for leaderboard data.
815 : *
816 : * @return A JS array containing all known leaderboard data
817 : */
818 0 : JS::Value XmppClient::GUIGetBoardList(const Script::Request& rq)
819 : {
820 0 : JS::RootedValueVector boardList{rq.cx};
821 :
822 0 : const char* attributes[] = { "name", "rank", "rating" };
823 :
824 0 : for(const std::unique_ptr<const gloox::Tag>& t : m_Impl->m_BoardList)
825 : {
826 0 : JS::RootedValue board(rq.cx);
827 0 : Script::CreateObject(rq, &board);
828 :
829 0 : for (size_t i = 0; i < ARRAY_SIZE(attributes); ++i)
830 0 : Script::SetProperty(rq, board, attributes[i], t->findAttribute(attributes[i]));
831 :
832 0 : if (!boardList.append(board))
833 0 : throw std::runtime_error{"Append failed"};
834 0 : }
835 0 : return JS::ObjectValue(*JS::NewArrayObject(rq.cx, boardList));
836 0 : }
837 :
838 : /**
839 : * Handle requests from the GUI for profile data.
840 : *
841 : * @return A JS array containing the specific user's profile data
842 : */
843 0 : JS::Value XmppClient::GUIGetProfile(const Script::Request& rq)
844 : {
845 0 : JS::RootedValueVector profileData{rq.cx};
846 :
847 0 : const char* stats[] = { "player", "rating", "totalGamesPlayed", "highestRating", "wins", "losses", "rank" };
848 :
849 0 : for (const std::unique_ptr<const gloox::Tag>& t : m_Impl->m_Profile)
850 : {
851 0 : JS::RootedValue profile(rq.cx);
852 0 : Script::CreateObject(rq, &profile);
853 :
854 0 : for (size_t i = 0; i < ARRAY_SIZE(stats); ++i)
855 0 : Script::SetProperty(rq, profile, stats[i], t->findAttribute(stats[i]));
856 :
857 0 : if (!profileData.append(profile))
858 0 : throw std::runtime_error{"Append failed"};
859 0 : }
860 0 : return JS::ObjectValue(*JS::NewArrayObject(rq.cx, profileData));
861 0 : }
862 :
863 : /*****************************************************
864 : * Message interfaces *
865 : *****************************************************/
866 :
867 0 : void SetGUIMessageProperty(const Script::Request&, JS::HandleObject /*messageObj*/)
868 : {
869 0 : }
870 :
871 : template<typename T, typename... Args>
872 0 : void SetGUIMessageProperty(const Script::Request& rq, JS::HandleObject messageObj, const std::string& propertyName, const T& propertyValue, Args const&... args)
873 : {
874 0 : JS::RootedValue scriptPropertyValue(rq.cx);
875 0 : Script::ToJSVal(rq, &scriptPropertyValue, propertyValue);
876 0 : JS_DefineProperty(rq.cx, messageObj, propertyName.c_str(), scriptPropertyValue, JSPROP_ENUMERATE);
877 0 : SetGUIMessageProperty(rq, messageObj, args...);
878 0 : }
879 :
880 : template<typename... Args>
881 0 : void XmppClient::Impl::CreateGUIMessage(
882 : const std::string& type,
883 : const std::string& level,
884 : const std::time_t time,
885 : Args const&... args)
886 : {
887 0 : if (!m_ScriptInterface)
888 0 : return;
889 0 : Script::Request rq(m_ScriptInterface);
890 0 : JS::RootedValue message(rq.cx);
891 0 : Script::CreateObject(
892 : rq,
893 : &message,
894 : "type", type,
895 : "level", level,
896 0 : "historic", false,
897 0 : "time", static_cast<double>(time));
898 :
899 0 : JS::RootedObject messageObj(rq.cx, message.toObjectOrNull());
900 0 : SetGUIMessageProperty(rq, messageObj, args...);
901 0 : Script::DeepFreezeObject(rq, message);
902 0 : if (!m_GuiMessageQueue.append(message))
903 0 : throw std::runtime_error{"Append failed"};
904 0 : }
905 :
906 0 : bool XmppClient::GuiPollHasPlayerListUpdate()
907 : {
908 : // The initial playerlist will be received in multiple messages
909 : // Only inform the GUI after all of these playerlist fragments were received.
910 0 : if (!m_Impl->m_initialLoadComplete)
911 : return false;
912 :
913 0 : return std::exchange(m_Impl->m_PlayerMapUpdate, false);
914 : }
915 :
916 0 : JS::Value XmppClient::GuiPollNewMessages(const Script::Interface& guiInterface)
917 : {
918 0 : if ((isConnected() && !m_Impl->m_initialLoadComplete) || m_Impl->m_GuiMessageQueue.empty())
919 0 : return JS::UndefinedValue();
920 :
921 0 : Script::Request rq(m_Impl->m_ScriptInterface);
922 :
923 : // Optimize for batch message processing that is more
924 : // performance demanding than processing a lone message.
925 0 : JS::RootedValueVector messages{rq.cx};
926 :
927 0 : for (const JS::Value& message : m_Impl->m_GuiMessageQueue)
928 : {
929 0 : if (!messages.append(message))
930 0 : throw std::runtime_error{"Append failed"};
931 :
932 : // Store historic chat messages.
933 : // Only store relevant messages to minimize memory footprint.
934 0 : JS::RootedValue rootedMessage(rq.cx, message);
935 0 : std::string type;
936 0 : Script::GetProperty(rq, rootedMessage, "type", type);
937 0 : if (type != "chat")
938 0 : continue;
939 :
940 0 : std::string level;
941 0 : Script::GetProperty(rq, rootedMessage, "level", level);
942 0 : if (level != "room-message" && level != "private-message")
943 0 : continue;
944 :
945 0 : JS::RootedValue historicMessage(rq.cx, Script::DeepCopy(rq, rootedMessage));
946 0 : Script::SetProperty(rq, historicMessage, "historic", true);
947 0 : Script::DeepFreezeObject(rq, historicMessage);
948 0 : if (!m_Impl->m_HistoricGuiMessages.append(historicMessage))
949 0 : throw std::runtime_error{"Append failed"};
950 0 : }
951 0 : m_Impl->m_GuiMessageQueue.clear();
952 :
953 : // Copy the messages over to the caller script interface.
954 0 : return Script::CloneValueFromOtherCompartment(guiInterface, *m_Impl->m_ScriptInterface,
955 0 : JS::RootedValue{rq.cx, JS::ObjectValue(*JS::NewArrayObject(rq.cx, messages))});
956 0 : }
957 :
958 0 : JS::Value XmppClient::GuiPollHistoricMessages(const Script::Interface& guiInterface)
959 : {
960 0 : if (m_Impl->m_HistoricGuiMessages.empty())
961 0 : return JS::UndefinedValue();
962 :
963 0 : Script::Request rq(m_Impl->m_ScriptInterface);
964 :
965 0 : JS::RootedValueVector messages{rq.cx};
966 :
967 0 : for (const JS::Value& message : m_Impl->m_HistoricGuiMessages)
968 : {
969 0 : if (!messages.append(message))
970 0 : throw std::runtime_error{"Append failed"};
971 : }
972 :
973 : // Copy the messages over to the caller script interface.
974 0 : return Script::CloneValueFromOtherCompartment(guiInterface, *m_Impl->m_ScriptInterface,
975 0 : JS::RootedValue{rq.cx, JS::ObjectValue(*JS::NewArrayObject(rq.cx, messages))});
976 0 : }
977 :
978 : /**
979 : * Send a standard MUC textual message.
980 : */
981 0 : void XmppClient::SendMUCMessage(const std::string& message)
982 : {
983 0 : m_Impl->m_mucRoom->send(message);
984 0 : }
985 :
986 : /**
987 : * Handle a room message.
988 : */
989 0 : void XmppClient::Impl::handleMUCMessage(gloox::MUCRoom*, const gloox::Message& msg, bool priv)
990 : {
991 0 : DbgXMPP(msg.from().resource() << " said " << msg.body());
992 :
993 0 : CreateGUIMessage(
994 : "chat",
995 : priv ? "private-message" : "room-message",
996 : ComputeTimestamp(msg),
997 0 : "from", msg.from().resource(),
998 0 : "text", msg.body());
999 0 : }
1000 :
1001 : /**
1002 : * Handle a private message.
1003 : */
1004 0 : void XmppClient::Impl::handleMessage(const gloox::Message& msg, gloox::MessageSession*)
1005 : {
1006 : DbgXMPP("type " << msg.subtype() << ", subject " << msg.subject()
1007 0 : << ", message " << msg.body() << ", thread id " << msg.thread());
1008 :
1009 0 : CreateGUIMessage(
1010 : "chat",
1011 0 : msg.subtype() == gloox::Message::MessageType::Headline ? "headline" : "private-message",
1012 : ComputeTimestamp(msg),
1013 0 : "from", msg.from().resource(),
1014 0 : "subject", msg.subject(),
1015 0 : "text", msg.body());
1016 0 : }
1017 :
1018 : /**
1019 : * Handle portions of messages containing custom stanza extensions.
1020 : */
1021 0 : bool XmppClient::Impl::handleIq(const gloox::IQ& iq)
1022 : {
1023 0 : DbgXMPP("handleIq [" << tag_xml(iq) << "]");
1024 :
1025 0 : if (iq.subtype() == gloox::IQ::Result)
1026 : {
1027 0 : const GameListQuery* gq = iq.findExtension<GameListQuery>(EXTGAMELISTQUERY);
1028 0 : const BoardListQuery* bq = iq.findExtension<BoardListQuery>(EXTBOARDLISTQUERY);
1029 0 : const ProfileQuery* pq = iq.findExtension<ProfileQuery>(EXTPROFILEQUERY);
1030 0 : const ConnectionData* cd = iq.findExtension<ConnectionData>(EXTCONNECTIONDATA);
1031 0 : if (cd)
1032 : {
1033 0 : if (g_NetServer || !g_NetClient)
1034 : return true;
1035 :
1036 0 : if (!m_connectionDataJid.empty() && m_connectionDataJid.compare(iq.from().full()) != 0) {
1037 0 : LOGMESSAGE("XmppClient: Received connection data from invalid host: {}",
1038 : iq.from().username());
1039 0 : return true;
1040 : }
1041 :
1042 0 : if (!m_connectionDataIqId.empty() && m_connectionDataIqId.compare(iq.id()) != 0) {
1043 0 : LOGMESSAGE("XmppClient: Received connection data with invalid id");
1044 0 : return true;
1045 : }
1046 :
1047 0 : if (!cd->m_Error.empty())
1048 : {
1049 0 : g_NetClient->HandleGetServerDataFailed(cd->m_Error.c_str());
1050 0 : return true;
1051 : }
1052 :
1053 0 : g_NetClient->TryToConnectWithSTUN(cd->m_Ip, stoi(cd->m_Port), iq.from().full(), !cd->m_IsLocalIP.empty());
1054 : }
1055 0 : if (gq)
1056 : {
1057 0 : if (iq.from().full() != m_xpartamuppId)
1058 : {
1059 0 : LOGWARNING("XmppClient: Received game list response from unexpected sender: {}",
1060 : iq.from().full());
1061 0 : return true;
1062 : }
1063 :
1064 0 : m_GameList.clear();
1065 :
1066 0 : for (const gloox::Tag* const& t : gq->m_GameList)
1067 0 : m_GameList.emplace_back(t->clone());
1068 :
1069 0 : CreateGUIMessage("game", "gamelist", std::time(nullptr));
1070 : }
1071 0 : if (bq)
1072 : {
1073 0 : if (iq.from().full() != m_echelonId)
1074 : {
1075 0 : LOGWARNING("XmppClient: Received board list response from unexpected sender: {}",
1076 : iq.from().full());
1077 0 : return true;
1078 : }
1079 :
1080 0 : if (bq->m_Command == "boardlist")
1081 : {
1082 0 : m_BoardList.clear();
1083 :
1084 0 : for (const gloox::Tag* const& t : bq->m_StanzaBoardList)
1085 0 : m_BoardList.emplace_back(t->clone());
1086 :
1087 0 : CreateGUIMessage("game", "leaderboard", std::time(nullptr));
1088 : }
1089 0 : else if (bq->m_Command == "ratinglist")
1090 : {
1091 0 : for (const gloox::Tag* const& t : bq->m_StanzaBoardList)
1092 : {
1093 0 : const PlayerMap::iterator it = m_PlayerMap.find(t->findAttribute("name"));
1094 0 : if (it != m_PlayerMap.end())
1095 : {
1096 0 : it->second.m_Rating = t->findAttribute("rating");
1097 0 : m_PlayerMapUpdate = true;
1098 : }
1099 : }
1100 0 : CreateGUIMessage("game", "ratinglist", std::time(nullptr));
1101 : }
1102 : }
1103 0 : if (pq)
1104 : {
1105 0 : if (iq.from().full() != m_echelonId)
1106 : {
1107 0 : LOGWARNING("XmppClient: Received profile response from unexpected sender: {}",
1108 : iq.from().full());
1109 0 : return true;
1110 : }
1111 :
1112 0 : m_Profile.clear();
1113 :
1114 0 : for (const gloox::Tag* const& t : pq->m_StanzaProfile)
1115 0 : m_Profile.emplace_back(t->clone());
1116 :
1117 0 : CreateGUIMessage("game", "profile", std::time(nullptr));
1118 : }
1119 : }
1120 0 : else if (iq.subtype() == gloox::IQ::Set)
1121 : {
1122 0 : const LobbyAuth* lobbyAuth = iq.findExtension<LobbyAuth>(EXTLOBBYAUTH);
1123 0 : if (lobbyAuth)
1124 : {
1125 0 : LOGMESSAGE("XmppClient: Received lobby auth: {} from {}", lobbyAuth->m_Token,
1126 : iq.from().username());
1127 :
1128 0 : gloox::IQ response(gloox::IQ::Result, iq.from(), iq.id());
1129 0 : m_client.send(response);
1130 :
1131 0 : if (g_NetServer)
1132 0 : g_NetServer->OnLobbyAuth(iq.from().username(), lobbyAuth->m_Token);
1133 : else
1134 0 : LOGMESSAGE("Received lobby authentication request, but not hosting currently!");
1135 0 : }
1136 : }
1137 0 : else if (iq.subtype() == gloox::IQ::Get)
1138 : {
1139 0 : const ConnectionData* cd = iq.findExtension<ConnectionData>(EXTCONNECTIONDATA);
1140 0 : if (cd)
1141 : {
1142 0 : LOGMESSAGE("XmppClient: Received request for connection data from {}",
1143 : iq.from().username());
1144 0 : if (!g_NetServer)
1145 : {
1146 0 : gloox::IQ response(gloox::IQ::Result, iq.from(), iq.id());
1147 0 : ConnectionData* connectionData = new ConnectionData();
1148 0 : connectionData->m_Error = "not_server";
1149 :
1150 0 : response.addExtension(connectionData);
1151 :
1152 0 : m_client.send(response);
1153 0 : return true;
1154 0 : }
1155 0 : if (g_NetServer->IsBanned(iq.from().username()))
1156 : {
1157 0 : gloox::IQ response(gloox::IQ::Result, iq.from(), iq.id());
1158 0 : ConnectionData* connectionData = new ConnectionData();
1159 0 : connectionData->m_Error = "banned";
1160 :
1161 0 : response.addExtension(connectionData);
1162 :
1163 0 : m_client.send(response);
1164 0 : return true;
1165 0 : }
1166 0 : if (!g_NetServer->CheckPasswordAndIncrement(iq.from().username(), cd->m_Password, cd->m_ClientSalt))
1167 : {
1168 0 : gloox::IQ response(gloox::IQ::Result, iq.from(), iq.id());
1169 0 : ConnectionData* connectionData = new ConnectionData();
1170 0 : connectionData->m_Error = "invalid_password";
1171 :
1172 0 : response.addExtension(connectionData);
1173 :
1174 0 : m_client.send(response);
1175 0 : return true;
1176 0 : }
1177 :
1178 0 : gloox::IQ response(gloox::IQ::Result, iq.from(), iq.id());
1179 0 : ConnectionData* connectionData = new ConnectionData();
1180 :
1181 0 : if (cd->m_IsLocalIP == "0")
1182 : {
1183 0 : connectionData->m_Ip = g_NetServer->GetPublicIp();
1184 0 : connectionData->m_Port = std::to_string(g_NetServer->GetPublicPort());
1185 0 : connectionData->m_IsLocalIP = "";
1186 : }
1187 : else
1188 : {
1189 0 : CStr ip;
1190 0 : if (StunClient::FindLocalIP(ip))
1191 : {
1192 0 : connectionData->m_Ip = ip;
1193 0 : connectionData->m_Port = std::to_string(g_NetServer->GetLocalPort());
1194 0 : connectionData->m_IsLocalIP = "true";
1195 : }
1196 : else
1197 0 : connectionData->m_Error = "local_ip_failed";
1198 0 : }
1199 :
1200 0 : response.addExtension(connectionData);
1201 :
1202 0 : m_client.send(response);
1203 0 : }
1204 :
1205 : }
1206 0 : else if (iq.subtype() == gloox::IQ::Error)
1207 0 : CreateGUIMessage("system", "error", std::time(nullptr), "text", iq.error()->error());
1208 : else
1209 : {
1210 0 : CreateGUIMessage("system", "error", std::time(nullptr), "text", wstring_from_utf8(g_L10n.Translate("unknown subtype (see logs)")));
1211 0 : LOGMESSAGE("unknown subtype '{}'", tag_name(iq));
1212 : }
1213 :
1214 : return true;
1215 : }
1216 :
1217 : /**
1218 : * Update local data when a user changes presence.
1219 : */
1220 0 : void XmppClient::Impl::handleMUCParticipantPresence(gloox::MUCRoom*, const gloox::MUCRoomParticipant participant,
1221 : const gloox::Presence& presence)
1222 : {
1223 0 : const std::string& nick = participant.nick->resource();
1224 :
1225 0 : if (presence.presence() == gloox::Presence::Unavailable)
1226 : {
1227 0 : if (!participant.newNick.empty() && (participant.flags & (gloox::UserNickChanged | gloox::UserSelf)))
1228 : {
1229 : // we have a nick change
1230 0 : if (m_PlayerMap.find(participant.newNick) == m_PlayerMap.end())
1231 0 : m_PlayerMap.emplace(
1232 : std::piecewise_construct,
1233 0 : std::forward_as_tuple(participant.newNick),
1234 0 : std::forward_as_tuple(presence.presence(), participant.role, participant.jid ? participant.jid->bare() : "", std::move(m_PlayerMap.at(nick).m_Rating)));
1235 : else
1236 0 : LOGERROR("Nickname changed to an existing nick!");
1237 :
1238 0 : DbgXMPP(nick << " is now known as " << participant.newNick);
1239 0 : CreateGUIMessage(
1240 : "chat",
1241 : "nick",
1242 : std::time(nullptr),
1243 : "oldnick", nick,
1244 : "newnick", participant.newNick);
1245 : }
1246 0 : else if (participant.flags & gloox::UserKicked)
1247 : {
1248 0 : DbgXMPP(nick << " was kicked. Reason: " << participant.reason);
1249 0 : CreateGUIMessage(
1250 : "chat",
1251 : "kicked",
1252 : std::time(nullptr),
1253 : "nick", nick,
1254 0 : "reason", participant.reason);
1255 : }
1256 0 : else if (participant.flags & gloox::UserBanned)
1257 : {
1258 0 : DbgXMPP(nick << " was banned. Reason: " << participant.reason);
1259 0 : CreateGUIMessage(
1260 : "chat",
1261 : "banned",
1262 : std::time(nullptr),
1263 : "nick", nick,
1264 0 : "reason", participant.reason);
1265 : }
1266 : else
1267 : {
1268 0 : DbgXMPP(nick << " left the room (flags " << participant.flags << ")");
1269 0 : CreateGUIMessage(
1270 : "chat",
1271 : "leave",
1272 : std::time(nullptr),
1273 : "nick", nick);
1274 : }
1275 0 : m_PlayerMap.erase(nick);
1276 : }
1277 : else
1278 : {
1279 0 : const PlayerMap::iterator it = m_PlayerMap.find(nick);
1280 :
1281 : /* During the initialization process, we receive join messages for everyone
1282 : * currently in the room. We don't want to display these, so we filter them
1283 : * out. We will always be the last to join during initialization.
1284 : */
1285 0 : if (!m_initialLoadComplete)
1286 : {
1287 0 : if (m_mucRoom->nick() == nick)
1288 0 : m_initialLoadComplete = true;
1289 : }
1290 0 : else if (it == m_PlayerMap.end())
1291 : {
1292 0 : CreateGUIMessage(
1293 : "chat",
1294 : "join",
1295 : std::time(nullptr),
1296 : "nick", nick);
1297 : }
1298 0 : else if (it->second.m_Role != participant.role)
1299 : {
1300 0 : CreateGUIMessage(
1301 : "chat",
1302 : "role",
1303 : std::time(nullptr),
1304 : "nick", nick,
1305 0 : "oldrole", it->second.m_Role,
1306 0 : "newrole", participant.role,
1307 0 : "reason", participant.reason);
1308 : }
1309 : else
1310 : {
1311 : // Don't create a GUI message for regular presence changes, because
1312 : // several hundreds of them accumulate during a match, impacting performance terribly and
1313 : // the only way they are used is to determine whether to update the playerlist.
1314 : }
1315 :
1316 : DbgXMPP(
1317 : nick << " is in the room, "
1318 : "presence: " << GetPresenceString(presence.presence()) << ", "
1319 0 : "role: "<< GetRoleString(participant.role));
1320 :
1321 0 : if (it == m_PlayerMap.end())
1322 : {
1323 0 : m_PlayerMap.emplace(
1324 : std::piecewise_construct,
1325 0 : std::forward_as_tuple(nick),
1326 0 : std::forward_as_tuple(presence.presence(), participant.role,
1327 0 : participant.jid ? participant.jid->bare() : "",
1328 0 : std::string()));
1329 : }
1330 : else
1331 : {
1332 0 : it->second.m_Presence = presence.presence();
1333 0 : it->second.m_Role = participant.role;
1334 0 : if (participant.jid)
1335 0 : it->second.m_BareJid = participant.jid->bare();
1336 : }
1337 : }
1338 :
1339 0 : m_PlayerMapUpdate = true;
1340 0 : }
1341 :
1342 : /**
1343 : * Update local cache when subject changes.
1344 : */
1345 0 : void XmppClient::Impl::handleMUCSubject(gloox::MUCRoom*, const std::string& nick, const std::string& subject)
1346 : {
1347 0 : m_Subject = wstring_from_utf8(subject);
1348 :
1349 0 : CreateGUIMessage(
1350 : "chat",
1351 : "subject",
1352 : std::time(nullptr),
1353 : "nick", nick,
1354 : "subject", m_Subject);
1355 0 : }
1356 :
1357 : /**
1358 : * Get current subject.
1359 : */
1360 0 : const std::wstring& XmppClient::GetSubject()
1361 : {
1362 0 : return m_Impl->m_Subject;
1363 : }
1364 :
1365 : /**
1366 : * Request MUC nick change, real change via mucRoomHandler.
1367 : *
1368 : * @param nick Desired MUC nickname
1369 : */
1370 0 : void XmppClient::SetNick(const std::string& nick)
1371 : {
1372 0 : m_Impl->m_mucRoom->setNick(nick);
1373 0 : }
1374 :
1375 : /**
1376 : * Get current MUC nickname.
1377 : */
1378 0 : std::string XmppClient::GetNick() const
1379 : {
1380 0 : return m_Impl->m_mucRoom->nick();
1381 : }
1382 :
1383 0 : std::string XmppClient::GetJID()
1384 : {
1385 0 : return m_Impl->m_client.jid().full();
1386 : }
1387 :
1388 :
1389 : /**
1390 : * Get the XMPP username.
1391 : *
1392 : * @return current XMPP username
1393 : */
1394 0 : std::string XmppClient::GetUsername() const
1395 : {
1396 0 : return m_Impl->m_username;
1397 : }
1398 :
1399 : /**
1400 : * Change password for authenticated user.
1401 : *
1402 : * @param newPassword New password
1403 : */
1404 0 : void XmppClient::ChangePassword(const std::string& newPassword)
1405 : {
1406 0 : m_Impl->m_registration.changePassword(m_Impl->m_client.jid().username(), newPassword);
1407 0 : }
1408 :
1409 : /**
1410 : * Kick a player from the current room.
1411 : *
1412 : * @param nick Nickname to be kicked
1413 : * @param reason Reason the player was kicked
1414 : */
1415 0 : void XmppClient::kick(const std::string& nick, const std::string& reason)
1416 : {
1417 0 : m_Impl->m_mucRoom->kick(nick, reason);
1418 0 : }
1419 :
1420 : /**
1421 : * Ban a player from the current room.
1422 : *
1423 : * @param nick Nickname to be banned
1424 : * @param reason Reason the player was banned
1425 : */
1426 0 : void XmppClient::ban(const std::string& nick, const std::string& reason)
1427 : {
1428 0 : m_Impl->m_mucRoom->ban(nick, reason);
1429 0 : }
1430 :
1431 : /**
1432 : * Change the xmpp presence of the client.
1433 : *
1434 : * @param presence A string containing the desired presence
1435 : */
1436 0 : void XmppClient::SetPresence(const std::string& presence)
1437 : {
1438 : #define IF(x,y) if (presence == x) m_Impl->m_mucRoom->setPresence(gloox::Presence::y)
1439 0 : IF("available", Available);
1440 0 : else IF("chat", Chat);
1441 0 : else IF("away", Away);
1442 0 : else IF("playing", DND);
1443 0 : else IF("offline", Unavailable);
1444 : // The others are not to be set
1445 : #undef IF
1446 0 : else LOGERROR("Unknown presence '{}'", presence);
1447 0 : }
1448 :
1449 : /**
1450 : * Get the current xmpp presence of the given nick.
1451 : */
1452 0 : const char* XmppClient::GetPresence(const std::string& nick)
1453 : {
1454 0 : const auto it = m_Impl->m_PlayerMap.find(nick);
1455 :
1456 0 : if (it == m_Impl->m_PlayerMap.end())
1457 : return "offline";
1458 :
1459 0 : return GetPresenceString(it->second.m_Presence);
1460 : }
1461 :
1462 : /**
1463 : * Get the current xmpp role of the given nick.
1464 : */
1465 0 : const char* XmppClient::GetRole(const std::string& nick)
1466 : {
1467 0 : const auto it = m_Impl->m_PlayerMap.find(nick);
1468 :
1469 0 : if (it == m_Impl->m_PlayerMap.end())
1470 : return "";
1471 :
1472 0 : return GetRoleString(it->second.m_Role);
1473 : }
1474 :
1475 : /**
1476 : * Get the most recent received rating of the given nick.
1477 : * Notice that this doesn't request a rating profile if it hasn't been received yet.
1478 : */
1479 0 : std::wstring XmppClient::GetRating(const std::string& nick)
1480 : {
1481 0 : const auto it = m_Impl->m_PlayerMap.find(nick);
1482 :
1483 0 : if (it == m_Impl->m_PlayerMap.end())
1484 0 : return std::wstring();
1485 :
1486 0 : return wstring_from_utf8(it->second.m_Rating);
1487 : }
1488 :
1489 : /*****************************************************
1490 : * Utilities *
1491 : *****************************************************/
1492 :
1493 0 : void XmppClient::SendStunEndpointToHost(const std::string& ip, std::uint16_t port,
1494 : const std::string& hostJIDStr)
1495 : {
1496 0 : DbgXMPP("SendStunEndpointToHost " << hostJIDStr);
1497 :
1498 0 : gloox::JID hostJID(hostJIDStr);
1499 0 : gloox::Jingle::Session* session = m_Impl->m_sessionManager.createSession(hostJID, m_Impl.get());
1500 :
1501 0 : gloox::Jingle::ICEUDP::CandidateList candidateList;
1502 :
1503 0 : candidateList.push_back(gloox::Jingle::ICEUDP::Candidate{
1504 0 : "1", // component_id,
1505 0 : "1", // foundation
1506 0 : "0", // candidate_generation
1507 0 : "1", // candidate_id
1508 : ip,
1509 0 : "0", // network
1510 0 : port,
1511 : 0, // priority
1512 0 : "udp",
1513 0 : "", // base_ip
1514 : 0, // base_port
1515 : gloox::Jingle::ICEUDP::ServerReflexive});
1516 :
1517 : // sessionInitiate deletes the new Content, and
1518 : // the Plugin destructor inherited by Content frees the ICEUDP plugin.
1519 :
1520 0 : gloox::Jingle::PluginList pluginList;
1521 0 : pluginList.push_back(new gloox::Jingle::ICEUDP(/*local_pwd*/ "", /*local_ufrag*/ "", candidateList));
1522 :
1523 0 : session->sessionInitiate(new gloox::Jingle::Content(std::string("game-data"), pluginList));
1524 0 : }
1525 :
1526 0 : void XmppClient::Impl::handleSessionAction(gloox::Jingle::Action action, gloox::Jingle::Session* session, const gloox::Jingle::Session::Jingle* jingle)
1527 : {
1528 0 : if (action == gloox::Jingle::SessionInitiate)
1529 0 : handleSessionInitiation(session, jingle);
1530 0 : }
1531 :
1532 0 : void XmppClient::Impl::handleSessionInitiation(gloox::Jingle::Session*,
1533 : const gloox::Jingle::Session::Jingle* jingle)
1534 : {
1535 0 : gloox::Jingle::ICEUDP::Candidate candidate{};
1536 :
1537 0 : const gloox::Jingle::Content* content = static_cast<const gloox::Jingle::Content*>(jingle->plugins().front());
1538 0 : if (content)
1539 : {
1540 0 : const gloox::Jingle::ICEUDP* iceUDP = static_cast<const gloox::Jingle::ICEUDP*>(content->findPlugin(gloox::Jingle::PluginICEUDP));
1541 0 : if (iceUDP)
1542 0 : candidate = iceUDP->candidates().front();
1543 : }
1544 :
1545 0 : if (candidate.ip.empty())
1546 : {
1547 0 : LOGERROR("Failed to retrieve Jingle candidate");
1548 0 : return;
1549 : }
1550 :
1551 0 : if (!g_NetServer)
1552 : {
1553 0 : LOGERROR("Received STUN connection request, but not hosting currently!");
1554 0 : return;
1555 : }
1556 :
1557 0 : g_NetServer->SendHolePunchingMessage(candidate.ip, candidate.port);
1558 0 : }
1559 :
1560 : // ----------------------------------------------------------------------------
1561 : //
1562 : // Roster
1563 : //
1564 : // ----------------------------------------------------------------------------
1565 :
1566 : namespace {
1567 : // TODO: Helper only needed till split view is supported by all compilers.
1568 0 : std::vector<std::string> splitBuddyList(std::string buddyList)
1569 : {
1570 0 : std::vector<std::string> buddies{};
1571 0 : size_t posStart{0};
1572 0 : size_t posEnd{0};
1573 0 : while ((posEnd = buddyList.find(",", posStart)) != std::string::npos)
1574 : {
1575 0 : buddies.push_back(buddyList.substr(posStart, posEnd - posStart));
1576 0 : posStart = posEnd + 1;
1577 : }
1578 0 : buddies.push_back(buddyList.substr(posStart));
1579 0 : return buddies;
1580 0 : }
1581 :
1582 : /**
1583 : * Whether the given roster item is one of the buddies tracked in the buddy list.
1584 : */
1585 0 : bool IsBuddyRosterItem(const gloox::RosterItem& item)
1586 : {
1587 0 : const gloox::StringList groups = item.groups();
1588 0 : return !item.name().empty() &&
1589 0 : std::find(groups.begin(), groups.end(), ROSTER_GROUP_NAME_BUDDIES) != groups.end();
1590 0 : }
1591 : } // namespace
1592 :
1593 0 : void XmppClient::AddBuddy(const std::string& nick)
1594 : {
1595 0 : DbgXMPP("Add buddy: " + nick);
1596 0 : const auto it = m_Impl->m_PlayerMap.find(nick);
1597 :
1598 0 : if (it == m_Impl->m_PlayerMap.end())
1599 0 : LOGWARNING("XmppClient: Can't add unknown player to roster: {}", nick);
1600 0 : else if (it->second.m_BareJid.empty())
1601 0 : LOGWARNING("XmppClient: Anonymous player can't be added to roster: {}", nick);
1602 : else
1603 0 : m_Impl->m_client.rosterManager()->add(it->second.m_BareJid, nick, gloox::StringList{ROSTER_GROUP_NAME_BUDDIES});
1604 0 : }
1605 :
1606 0 : void XmppClient::RemoveBuddy(const std::string& nick)
1607 : {
1608 0 : DbgXMPP("Remove buddy: " + nick);
1609 0 : const auto it = m_Impl->m_PlayerMap.find(nick);
1610 :
1611 0 : if (it == m_Impl->m_PlayerMap.end())
1612 0 : LOGWARNING("XmppClient: Can't remove unknown player from roster: {}", nick);
1613 0 : else if (it->second.m_BareJid.empty())
1614 0 : LOGWARNING("XmppClient: Anonymous player can't be removed from roster: {}", nick);
1615 : else
1616 0 : m_Impl->m_client.rosterManager()->remove(it->second.m_BareJid);
1617 0 : }
1618 :
1619 0 : bool XmppClient::IsBuddy(const std::string& nick) const
1620 : {
1621 0 : return m_Impl->m_Buddies.find(CStr(nick).LowerCase()) != m_Impl->m_Buddies.end();
1622 : }
1623 :
1624 0 : std::set<std::string> XmppClient::GetBuddies() const
1625 : {
1626 0 : return m_Impl->m_Buddies;
1627 : }
1628 :
1629 0 : void XmppClient::Impl::UpdateBuddies()
1630 : {
1631 0 : m_Buddies.clear();
1632 0 : for (const auto& [jid, item] : *m_client.rosterManager()->roster())
1633 : {
1634 0 : if (IsBuddyRosterItem(*item))
1635 0 : m_Buddies.insert(CStr(item->name()).LowerCase());
1636 : }
1637 0 : }
1638 :
1639 0 : void XmppClient::Impl::MigrateBuddyList()
1640 : {
1641 0 : if (g_ConfigDB.Get("lobby.buddies.migrated", false))
1642 : return;
1643 :
1644 0 : if (m_client.rosterManager()->roster()->empty())
1645 : {
1646 0 : const std::string buddyList{g_ConfigDB.Get("lobby.buddies", std::string{})};
1647 0 : for (const std::string& nick : splitBuddyList(buddyList))
1648 : {
1649 0 : if (nick.empty())
1650 0 : continue;
1651 :
1652 0 : m_client.rosterManager()->add(nick + "@" + m_server, nick, gloox::StringList{ROSTER_GROUP_NAME_BUDDIES});
1653 0 : }
1654 0 : }
1655 :
1656 0 : g_ConfigDB.RemoveValue(CFG_USER, "lobby.buddies");
1657 0 : g_ConfigDB.SetValueString(CFG_USER, "lobby.buddies.migrated", "true");
1658 0 : g_ConfigDB.WriteFile(CFG_USER);
1659 0 : }
1660 :
1661 0 : void XmppClient::Impl::handleRoster(const gloox::Roster& /*roster*/)
1662 : {
1663 0 : MigrateBuddyList();
1664 0 : UpdateBuddies();
1665 0 : CreateGUIMessage("roster", "change", std::time(nullptr));
1666 0 : }
1667 :
1668 0 : void XmppClient::Impl::handleItemAdded(const gloox::JID& /*jid*/)
1669 : {
1670 0 : UpdateBuddies();
1671 0 : CreateGUIMessage("roster", "change", std::time(nullptr));
1672 0 : }
1673 :
1674 0 : void XmppClient::Impl::handleItemRemoved(const gloox::JID& jid)
1675 : {
1676 : // gloox (1.0.28) calles this before before updating the roster which means
1677 : // calling UpdateBuddies here would still leave the removed buddy in
1678 : // m_Buddies; drop just that entry instead.
1679 0 : if (const gloox::RosterItem* item = m_client.rosterManager()->getRosterItem(jid); item && IsBuddyRosterItem(*item))
1680 0 : m_Buddies.erase(CStr(item->name()).LowerCase());
1681 :
1682 0 : CreateGUIMessage("roster", "change", std::time(nullptr));
1683 0 : }
1684 :
1685 0 : void XmppClient::Impl::handleItemUpdated(const gloox::JID& /*jid*/)
1686 : {
1687 0 : UpdateBuddies();
1688 0 : CreateGUIMessage("roster", "change", std::time(nullptr));
1689 0 : }
1690 :
1691 0 : void XmppClient::Impl::handleRosterError(const gloox::IQ& iq)
1692 : {
1693 0 : LOGERROR("{}", iq.tag()->xml());
1694 0 : }
|