1/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2/* If you are missing that file, acquire a complete release at teeworlds.com. */
3
4#include "server.h"
5
6#include "databases/connection.h"
7#include "databases/connection_pool.h"
8#include "register.h"
9
10#include <base/bytes.h>
11#include <base/fs.h>
12#include <base/io.h>
13#include <base/logger.h>
14#include <base/secure.h>
15
16#include <engine/config.h>
17#include <engine/console.h>
18#include <engine/engine.h>
19#include <engine/http.h>
20#include <engine/map.h>
21#include <engine/server.h>
22#include <engine/server/authmanager.h>
23#include <engine/shared/compression.h>
24#include <engine/shared/config.h>
25#include <engine/shared/console.h>
26#include <engine/shared/demo.h>
27#include <engine/shared/econ.h>
28#include <engine/shared/fifo.h>
29#include <engine/shared/filecollection.h>
30#include <engine/shared/host_lookup.h>
31#include <engine/shared/json.h>
32#include <engine/shared/jsonwriter.h>
33#include <engine/shared/linereader.h>
34#include <engine/shared/masterserver.h>
35#include <engine/shared/netban.h>
36#include <engine/shared/network.h>
37#include <engine/shared/packer.h>
38#include <engine/shared/protocol.h>
39#include <engine/shared/protocol7.h>
40#include <engine/shared/protocol_ex.h>
41#include <engine/shared/rust_version.h>
42#include <engine/shared/snapshot.h>
43#include <engine/storage.h>
44
45#include <generated/protocol.h>
46
47#include <game/version.h>
48
49#include <zlib.h>
50
51#include <algorithm>
52#include <chrono>
53#include <vector>
54
55using namespace std::chrono_literals;
56
57#if defined(CONF_PLATFORM_ANDROID)
58extern std::vector<std::string> FetchAndroidServerCommandQueue();
59#endif
60
61void CServerBan::InitServerBan(IConsole *pConsole, IStorage *pStorage, CServer *pServer)
62{
63 CNetBan::Init(pConsole, pStorage);
64
65 m_pServer = pServer;
66
67 Console()->Register(pName: "ban", pParams: "s[ip|id] ?i[minutes] r[reason]", Flags: CFGFLAG_SERVER | CFGFLAG_STORE, pfnFunc: ConBanExt, pUser: this, pHelp: "Ban player with ip/client id for x minutes for any reason");
68 Console()->Register(pName: "ban_region", pParams: "s[region] s[ip|id] ?i[minutes] r[reason]", Flags: CFGFLAG_SERVER | CFGFLAG_STORE, pfnFunc: ConBanRegion, pUser: this, pHelp: "Ban player in a region");
69 Console()->Register(pName: "ban_region_range", pParams: "s[region] s[first ip] s[last ip] ?i[minutes] r[reason]", Flags: CFGFLAG_SERVER | CFGFLAG_STORE, pfnFunc: ConBanRegionRange, pUser: this, pHelp: "Ban range in a region");
70}
71
72template<class T>
73int CServerBan::BanExt(T *pBanPool, const typename T::CDataType *pData, int Seconds, const char *pReason, bool VerbatimReason)
74{
75 // validate address
76 if(Server()->m_RconClientId >= 0 && Server()->m_RconClientId < MAX_CLIENTS &&
77 Server()->m_aClients[Server()->m_RconClientId].m_State != CServer::CClient::STATE_EMPTY)
78 {
79 if(NetMatch(pData, Server()->ClientAddr(ClientId: Server()->m_RconClientId)))
80 {
81 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "net_ban", pStr: "ban error (you can't ban yourself)");
82 return -1;
83 }
84
85 for(int i = 0; i < MAX_CLIENTS; ++i)
86 {
87 if(i == Server()->m_RconClientId || Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
88 continue;
89
90 if(Server()->GetAuthedState(ClientId: i) >= Server()->m_RconAuthLevel && NetMatch(pData, Server()->ClientAddr(ClientId: i)))
91 {
92 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "net_ban", pStr: "ban error (command denied)");
93 return -1;
94 }
95 }
96 }
97 else if(Server()->m_RconClientId == IServer::RCON_CID_VOTE)
98 {
99 for(int i = 0; i < MAX_CLIENTS; ++i)
100 {
101 if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
102 continue;
103
104 if(Server()->IsRconAuthed(ClientId: i) && NetMatch(pData, Server()->ClientAddr(ClientId: i)))
105 {
106 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "net_ban", pStr: "ban error (command denied)");
107 return -1;
108 }
109 }
110 }
111
112 int Result = Ban(pBanPool, pData, Seconds, pReason, VerbatimReason);
113 if(Result != 0)
114 return Result;
115
116 // drop banned clients
117 typename T::CDataType Data = *pData;
118 for(int i = 0; i < MAX_CLIENTS; ++i)
119 {
120 if(Server()->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
121 continue;
122
123 if(NetMatch(&Data, Server()->ClientAddr(ClientId: i)))
124 {
125 CNetHash NetHash(&Data);
126 char aBuf[256];
127 MakeBanInfo(pBanPool->Find(&Data, &NetHash), aBuf, sizeof(aBuf), MSGTYPE_PLAYER);
128 Server()->m_NetServer.Drop(ClientId: i, pReason: aBuf);
129 }
130 }
131
132 return Result;
133}
134
135int CServerBan::BanAddr(const NETADDR *pAddr, int Seconds, const char *pReason, bool VerbatimReason)
136{
137 return BanExt(pBanPool: &m_BanAddrPool, pData: pAddr, Seconds, pReason, VerbatimReason);
138}
139
140int CServerBan::BanRange(const CNetRange *pRange, int Seconds, const char *pReason)
141{
142 if(pRange->IsValid())
143 return BanExt(pBanPool: &m_BanRangePool, pData: pRange, Seconds, pReason, VerbatimReason: true);
144
145 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "net_ban", pStr: "ban failed (invalid range)");
146 return -1;
147}
148
149void CServerBan::ConBanExt(IConsole::IResult *pResult, void *pUser)
150{
151 CServerBan *pThis = static_cast<CServerBan *>(pUser);
152
153 const char *pStr = pResult->GetString(Index: 0);
154 int Minutes = pResult->NumArguments() > 1 ? std::clamp(val: pResult->GetInteger(Index: 1), lo: 0, hi: 525600) : 10;
155 const char *pReason = pResult->NumArguments() > 2 ? pResult->GetString(Index: 2) : "Follow the server rules. Type /rules into the chat.";
156
157 if(str_isallnum(str: pStr))
158 {
159 int ClientId = str_toint(str: pStr);
160 if(pResult->m_ClientId >= 0 && !pThis->Server()->ClientSupportsServerMaxClients(ClientId: pResult->m_ClientId))
161 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "net_ban", pStr: "ban error (use a more recent DDNet client)");
162 else if(ClientId < 0 || ClientId >= MAX_CLIENTS || pThis->Server()->m_aClients[ClientId].m_State == CServer::CClient::STATE_EMPTY)
163 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "net_ban", pStr: "ban error (invalid client id)");
164 else
165 pThis->BanAddr(pAddr: pThis->Server()->ClientAddr(ClientId), Seconds: Minutes * 60, pReason, VerbatimReason: false);
166 }
167 else
168 {
169 NETADDR Addr;
170 if(net_addr_from_str(addr: &Addr, string: pStr) == 0)
171 pThis->BanAddr(pAddr: &Addr, Seconds: Minutes * 60, pReason, VerbatimReason: false);
172 else
173 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "net_ban", pStr: "ban error (invalid network address)");
174 }
175}
176
177void CServerBan::ConBanRegion(IConsole::IResult *pResult, void *pUser)
178{
179 const char *pRegion = pResult->GetString(Index: 0);
180 if(str_comp_nocase(a: pRegion, b: g_Config.m_SvRegionName))
181 return;
182
183 pResult->RemoveArgument(Index: 0);
184 ConBanExt(pResult, pUser);
185}
186
187void CServerBan::ConBanRegionRange(IConsole::IResult *pResult, void *pUser)
188{
189 CServerBan *pServerBan = static_cast<CServerBan *>(pUser);
190
191 const char *pRegion = pResult->GetString(Index: 0);
192 if(str_comp_nocase(a: pRegion, b: g_Config.m_SvRegionName))
193 return;
194
195 pResult->RemoveArgument(Index: 0);
196 ConBanRange(pResult, pUser: static_cast<CNetBan *>(pServerBan));
197}
198
199// Not thread-safe!
200class CRconClientLogger : public ILogger
201{
202 CServer *m_pServer;
203 int m_ClientId;
204
205public:
206 CRconClientLogger(CServer *pServer, int ClientId) :
207 m_pServer(pServer),
208 m_ClientId(ClientId)
209 {
210 }
211 void Log(const CLogMessage *pMessage) override;
212};
213
214void CRconClientLogger::Log(const CLogMessage *pMessage)
215{
216 if(m_Filter.Filters(pMessage))
217 {
218 return;
219 }
220 m_pServer->SendRconLogLine(ClientId: m_ClientId, pMessage);
221}
222
223void CServer::CClient::Reset()
224{
225 // reset input
226 for(auto &Input : m_aInputs)
227 Input.m_GameTick = -1;
228 m_CurrentInput = 0;
229 mem_zero(block: &m_LastPreInput, size: sizeof(m_LastPreInput));
230 mem_zero(block: &m_LatestInput, size: sizeof(m_LatestInput));
231
232 m_Snapshots.PurgeAll();
233 m_LastAckedSnapshot = -1;
234 m_LastInputTick = -1;
235 m_SnapRate = CClient::SNAPRATE_INIT;
236 m_Score = -1;
237 m_NextMapChunk = 0;
238 m_NumMapChunks = 0;
239 m_PreInputsTick = -1;
240 m_NumPreInputs = 0;
241 m_Flags = 0;
242 m_RedirectDropTime = 0;
243 m_IngameBeforeRejoin = false;
244
245 std::fill(first: std::begin(arr&: m_aIdMap), last: std::end(arr&: m_aIdMap), value: -1);
246 std::fill(first: std::begin(arr&: m_aReverseIdMap), last: std::end(arr&: m_aReverseIdMap), value: -1);
247}
248
249CServer::CServer()
250{
251 m_pConfig = &g_Config;
252 for(int i = 0; i < MAX_CLIENTS; i++)
253 m_aDemoRecorder[i] = CDemoRecorder(&m_SnapshotDelta, true);
254 m_aDemoRecorder[RECORDER_MANUAL] = CDemoRecorder(&m_SnapshotDelta, false);
255 m_aDemoRecorder[RECORDER_AUTO] = CDemoRecorder(&m_SnapshotDelta, false);
256
257 m_pGameServer = nullptr;
258
259 m_CurrentGameTick = MIN_TICK;
260 m_RunServer = UNINITIALIZED;
261
262 m_aShutdownReason[0] = 0;
263
264 for(int i = 0; i < NUM_MAP_TYPES; i++)
265 {
266 m_apCurrentMapData[i] = nullptr;
267 m_aCurrentMapSize[i] = 0;
268 }
269
270 m_MapReload = false;
271 m_SameMapReload = false;
272 m_ReloadedWhenEmpty = false;
273 m_aMapDownloadUrl[0] = '\0';
274
275 m_RconClientId = IServer::RCON_CID_SERV;
276 m_RconAuthLevel = AUTHED_ADMIN;
277
278 m_ServerInfoFirstRequest = 0;
279 m_ServerInfoNumRequests = 0;
280
281#ifdef CONF_FAMILY_UNIX
282 m_ConnLoggingSocketCreated = false;
283#endif
284
285 m_pConnectionPool = new CDbConnectionPool();
286 m_pRegister = nullptr;
287
288 m_aErrorShutdownReason[0] = 0;
289
290 Init();
291}
292
293CServer::~CServer()
294{
295 for(auto &pCurrentMapData : m_apCurrentMapData)
296 {
297 free(ptr: pCurrentMapData);
298 }
299
300 if(m_RunServer != UNINITIALIZED)
301 {
302 for(auto &Client : m_aClients)
303 {
304 free(ptr: Client.m_pPersistentData);
305 }
306 }
307 free(ptr: m_pPersistentData);
308
309 delete m_pRegister;
310 delete m_pConnectionPool;
311}
312
313const char *CServer::DnsblStateStr(EDnsblState State)
314{
315 switch(State)
316 {
317 case EDnsblState::NONE:
318 return "n/a";
319 case EDnsblState::PENDING:
320 return "pending";
321 case EDnsblState::BLACKLISTED:
322 return "black";
323 case EDnsblState::WHITELISTED:
324 return "white";
325 }
326
327 dbg_assert_failed("Invalid dnsbl State: %d", static_cast<int>(State));
328}
329
330IConsole::EAccessLevel CServer::ConsoleAccessLevel(int ClientId) const
331{
332 int AuthLevel = GetAuthedState(ClientId);
333 switch(AuthLevel)
334 {
335 case AUTHED_ADMIN:
336 return IConsole::EAccessLevel::ADMIN;
337 case AUTHED_MOD:
338 return IConsole::EAccessLevel::MODERATOR;
339 case AUTHED_HELPER:
340 return IConsole::EAccessLevel::HELPER;
341 };
342
343 dbg_assert_failed("Invalid AuthLevel: %d", AuthLevel);
344}
345
346bool CServer::IsClientNameAvailable(int ClientId, const char *pNameRequest)
347{
348 // check for empty names
349 if(!pNameRequest[0])
350 return false;
351
352 // check for names starting with /, as they can be abused to make people
353 // write chat commands
354 if(pNameRequest[0] == '/')
355 return false;
356
357 // make sure that two clients don't have the same name
358 for(int i = 0; i < MAX_CLIENTS; i++)
359 {
360 if(i != ClientId && m_aClients[i].m_State >= CClient::STATE_READY)
361 {
362 if(str_utf8_comp_confusable(str1: pNameRequest, str2: m_aClients[i].m_aName) == 0)
363 return false;
364 }
365 }
366
367 return true;
368}
369
370bool CServer::SetClientNameImpl(int ClientId, const char *pNameRequest, bool Set)
371{
372 dbg_assert(0 <= ClientId && ClientId < MAX_CLIENTS, "Invalid ClientId: %d", ClientId);
373 if(m_aClients[ClientId].m_State < CClient::STATE_READY)
374 return false;
375
376 const CNameBan *pBanned = m_NameBans.IsBanned(pName: pNameRequest);
377 if(pBanned)
378 {
379 if(m_aClients[ClientId].m_State == CClient::STATE_READY && Set)
380 {
381 char aBuf[256];
382 if(pBanned->m_aReason[0])
383 {
384 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Kicked (your name is banned: %s)", pBanned->m_aReason);
385 }
386 else
387 {
388 str_copy(dst&: aBuf, src: "Kicked (your name is banned)");
389 }
390 Kick(ClientId, pReason: aBuf);
391 }
392 return false;
393 }
394
395 // trim the name
396 char aTrimmedName[MAX_NAME_LENGTH];
397 str_copy(dst&: aTrimmedName, src: str_utf8_skip_whitespaces(str: pNameRequest));
398 str_utf8_trim_right(param: aTrimmedName);
399
400 char aNameTry[MAX_NAME_LENGTH];
401 str_copy(dst&: aNameTry, src: aTrimmedName);
402
403 if(!IsClientNameAvailable(ClientId, pNameRequest: aNameTry))
404 {
405 // auto rename
406 for(int i = 1;; i++)
407 {
408 str_format(buffer: aNameTry, buffer_size: sizeof(aNameTry), format: "(%d)%s", i, aTrimmedName);
409 if(IsClientNameAvailable(ClientId, pNameRequest: aNameTry))
410 break;
411 }
412 }
413
414 bool Changed = str_comp(a: m_aClients[ClientId].m_aName, b: aNameTry) != 0;
415
416 if(Set && Changed)
417 {
418 // set the client name
419 str_copy(dst&: m_aClients[ClientId].m_aName, src: aNameTry);
420 GameServer()->TeehistorianRecordPlayerName(ClientId, pName: m_aClients[ClientId].m_aName);
421 GameServer()->OnClientInfoChange(ClientId);
422 }
423
424 return Changed;
425}
426
427bool CServer::SetClientClanImpl(int ClientId, const char *pClanRequest, bool Set)
428{
429 dbg_assert(0 <= ClientId && ClientId < MAX_CLIENTS, "Invalid ClientId: %d", ClientId);
430 if(m_aClients[ClientId].m_State < CClient::STATE_READY)
431 return false;
432
433 const CNameBan *pBanned = m_NameBans.IsBanned(pName: pClanRequest);
434 if(pBanned)
435 {
436 if(m_aClients[ClientId].m_State == CClient::STATE_READY && Set)
437 {
438 char aBuf[256];
439 if(pBanned->m_aReason[0])
440 {
441 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Kicked (your clan is banned: %s)", pBanned->m_aReason);
442 }
443 else
444 {
445 str_copy(dst&: aBuf, src: "Kicked (your clan is banned)");
446 }
447 Kick(ClientId, pReason: aBuf);
448 }
449 return false;
450 }
451
452 // trim the clan
453 char aTrimmedClan[MAX_CLAN_LENGTH];
454 str_copy(dst&: aTrimmedClan, src: str_utf8_skip_whitespaces(str: pClanRequest));
455 str_utf8_trim_right(param: aTrimmedClan);
456
457 bool Changed = str_comp(a: m_aClients[ClientId].m_aClan, b: aTrimmedClan) != 0;
458
459 if(Set && Changed)
460 {
461 // set the client clan
462 str_copy(dst&: m_aClients[ClientId].m_aClan, src: aTrimmedClan);
463 GameServer()->OnClientInfoChange(ClientId);
464 }
465
466 return Changed;
467}
468
469bool CServer::WouldClientNameChange(int ClientId, const char *pNameRequest)
470{
471 return SetClientNameImpl(ClientId, pNameRequest, Set: false);
472}
473
474bool CServer::WouldClientClanChange(int ClientId, const char *pClanRequest)
475{
476 return SetClientClanImpl(ClientId, pClanRequest, Set: false);
477}
478
479void CServer::SetClientName(int ClientId, const char *pName)
480{
481 SetClientNameImpl(ClientId, pNameRequest: pName, Set: true);
482}
483
484void CServer::SetClientClan(int ClientId, const char *pClan)
485{
486 SetClientClanImpl(ClientId, pClanRequest: pClan, Set: true);
487}
488
489void CServer::SetClientCountry(int ClientId, int Country)
490{
491 if(ClientId < 0 || ClientId >= MAX_CLIENTS || m_aClients[ClientId].m_State < CClient::STATE_READY)
492 return;
493
494 if(m_aClients[ClientId].m_Country == Country)
495 return;
496
497 m_aClients[ClientId].m_Country = Country;
498 GameServer()->OnClientInfoChange(ClientId);
499}
500
501void CServer::SetClientScore(int ClientId, std::optional<int> Score)
502{
503 if(ClientId < 0 || ClientId >= MAX_CLIENTS || m_aClients[ClientId].m_State < CClient::STATE_READY)
504 return;
505
506 if(m_aClients[ClientId].m_Score != Score)
507 ExpireServerInfo();
508
509 m_aClients[ClientId].m_Score = Score;
510}
511
512void CServer::SetClientFlags(int ClientId, int Flags)
513{
514 if(ClientId < 0 || ClientId >= MAX_CLIENTS || m_aClients[ClientId].m_State < CClient::STATE_READY)
515 return;
516
517 m_aClients[ClientId].m_Flags = Flags;
518}
519
520void CServer::Kick(int ClientId, const char *pReason)
521{
522 if(ClientId < 0 || ClientId >= MAX_CLIENTS || m_aClients[ClientId].m_State == CClient::STATE_EMPTY)
523 {
524 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "server", pStr: "invalid client id to kick");
525 return;
526 }
527 else if(m_RconClientId == ClientId)
528 {
529 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "server", pStr: "you can't kick yourself");
530 return;
531 }
532 else if(GetAuthedState(ClientId) > m_RconAuthLevel)
533 {
534 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "server", pStr: "kick command denied");
535 return;
536 }
537
538 m_NetServer.Drop(ClientId, pReason);
539}
540
541void CServer::Ban(int ClientId, int Seconds, const char *pReason, bool VerbatimReason)
542{
543 m_NetServer.NetBan()->BanAddr(pAddr: ClientAddr(ClientId), Seconds, pReason, VerbatimReason);
544}
545
546void CServer::ReconnectClient(int ClientId)
547{
548 dbg_assert(0 <= ClientId && ClientId < MAX_CLIENTS, "Invalid ClientId: %d", ClientId);
549 dbg_assert(m_aClients[ClientId].m_State != CClient::STATE_EMPTY, "Client slot empty: %d", ClientId);
550
551 if(GetClientVersion(ClientId) < VERSION_DDNET_RECONNECT)
552 {
553 RedirectClient(ClientId, Port: m_NetServer.Address().port);
554 return;
555 }
556 log_info("server", "telling client to reconnect, cid=%d", ClientId);
557
558 CMsgPacker Msg(NETMSG_RECONNECT, true);
559 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientId);
560
561 if(m_aClients[ClientId].m_State >= CClient::STATE_READY)
562 {
563 GameServer()->OnClientDrop(ClientId, pReason: "reconnect");
564 }
565
566 m_aClients[ClientId].m_RedirectDropTime = time_get() + time_freq() * 10;
567 m_aClients[ClientId].m_State = CClient::STATE_REDIRECTED;
568}
569
570void CServer::RedirectClient(int ClientId, int Port)
571{
572 dbg_assert(0 <= ClientId && ClientId < MAX_CLIENTS, "Invalid ClientId: %d", ClientId);
573 dbg_assert(m_aClients[ClientId].m_State != CClient::STATE_EMPTY, "Client slot empty: %d", ClientId);
574
575 bool SupportsRedirect = GetClientVersion(ClientId) >= VERSION_DDNET_REDIRECT;
576
577 log_info("server", "redirecting client, cid=%d port=%d supported=%d", ClientId, Port, SupportsRedirect);
578
579 if(!SupportsRedirect)
580 {
581 char aBuf[128];
582 bool SamePort = Port == this->Port();
583 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Redirect unsupported: please connect to port %d", Port);
584 Kick(ClientId, pReason: SamePort ? "Redirect unsupported: please reconnect" : aBuf);
585 return;
586 }
587
588 CMsgPacker Msg(NETMSG_REDIRECT, true);
589 Msg.AddInt(i: Port);
590 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientId);
591
592 if(m_aClients[ClientId].m_State >= CClient::STATE_READY)
593 {
594 GameServer()->OnClientDrop(ClientId, pReason: "redirect");
595 }
596
597 m_aClients[ClientId].m_RedirectDropTime = time_get() + time_freq() * 10;
598 m_aClients[ClientId].m_State = CClient::STATE_REDIRECTED;
599}
600
601int64_t CServer::TickStartTime(int Tick)
602{
603 return m_GameStartTime + (time_freq() * Tick) / TickSpeed();
604}
605
606int CServer::Init()
607{
608 for(auto &Client : m_aClients)
609 {
610 Client.m_State = CClient::STATE_EMPTY;
611 Client.m_aName[0] = 0;
612 Client.m_aClan[0] = 0;
613 Client.m_Country = CountryCode::DEFAULT;
614 Client.m_Snapshots.Init();
615 Client.m_Traffic = 0;
616 Client.m_TrafficSince = 0;
617 Client.m_ShowIps = false;
618 Client.m_DebugDummy = false;
619 Client.m_AuthKey = -1;
620 Client.m_Latency = 0;
621 Client.m_Sixup = false;
622 Client.m_RedirectDropTime = 0;
623 Client.m_IngameBeforeRejoin = false;
624 }
625
626 m_CurrentGameTick = MIN_TICK;
627
628 m_StartTime = time_get();
629
630 m_AnnouncementLastLine = -1;
631 std::fill(first: std::begin(arr&: m_aPrevStates), last: std::end(arr&: m_aPrevStates), value: 0);
632
633 return 0;
634}
635
636bool CServer::StrHideIps(const char *pInput, char *pOutputWithIps, size_t OutputWithIpsSize, char *pOutputWithoutIps, size_t OutputWithoutIpsSize)
637{
638 const char *pStart = str_find(haystack: pInput, needle: "<{");
639 const char *pEnd = pStart == nullptr ? nullptr : str_find(haystack: pStart + 2, needle: "}>");
640 pOutputWithIps[0] = '\0';
641 pOutputWithoutIps[0] = '\0';
642
643 if(pStart == nullptr || pEnd == nullptr)
644 {
645 str_copy(dst: pOutputWithIps, src: pInput, dst_size: OutputWithIpsSize);
646 str_copy(dst: pOutputWithoutIps, src: pInput, dst_size: OutputWithoutIpsSize);
647 return false;
648 }
649
650 str_append(dst: pOutputWithIps, src: pInput, dst_size: std::min(a: (size_t)(pStart - pInput + 1), b: OutputWithIpsSize));
651 str_append(dst: pOutputWithIps, src: pStart + 2, dst_size: std::min(a: (size_t)(pEnd - pInput - 1), b: OutputWithIpsSize));
652 str_append(dst: pOutputWithIps, src: pEnd + 2, dst_size: OutputWithIpsSize);
653
654 str_append(dst: pOutputWithoutIps, src: pInput, dst_size: std::min(a: (size_t)(pStart - pInput + 1), b: OutputWithoutIpsSize));
655 str_append(dst: pOutputWithoutIps, src: "XXX", dst_size: OutputWithoutIpsSize);
656 str_append(dst: pOutputWithoutIps, src: pEnd + 2, dst_size: OutputWithoutIpsSize);
657 return true;
658}
659
660void CServer::SendLogLine(const CLogMessage *pMessage)
661{
662 if(pMessage->m_Level <= IConsole::ToLogLevelFilter(ConsoleLevel: g_Config.m_ConsoleOutputLevel))
663 {
664 SendRconLogLine(ClientId: -1, pMessage);
665 }
666 if(pMessage->m_Level <= IConsole::ToLogLevelFilter(ConsoleLevel: g_Config.m_EcOutputLevel))
667 {
668 m_Econ.Send(ClientId: -1, pLine: pMessage->m_aLine);
669 }
670}
671
672void CServer::SetRconCid(int ClientId)
673{
674 m_RconClientId = ClientId;
675}
676
677int CServer::GetAuthedState(int ClientId) const
678{
679 if(ClientId == IConsole::CLIENT_ID_UNSPECIFIED)
680 return AUTHED_ADMIN;
681 if(ClientId == IConsole::CLIENT_ID_GAME)
682 return AUTHED_ADMIN;
683 if(ClientId == IConsole::CLIENT_ID_NO_GAME)
684 return AUTHED_ADMIN;
685 dbg_assert(ClientId >= 0 && ClientId < MAX_CLIENTS, "Invalid ClientId: %d", ClientId);
686 dbg_assert(m_aClients[ClientId].m_State != CServer::CClient::STATE_EMPTY, "Client slot %d is empty", ClientId);
687 return m_AuthManager.KeyLevel(Slot: m_aClients[ClientId].m_AuthKey);
688}
689
690bool CServer::IsRconAuthed(int ClientId) const
691{
692 return GetAuthedState(ClientId) != AUTHED_NO;
693}
694
695bool CServer::IsRconAuthedAdmin(int ClientId) const
696{
697 return GetAuthedState(ClientId) == AUTHED_ADMIN;
698}
699
700const char *CServer::GetAuthName(int ClientId) const
701{
702 dbg_assert(ClientId >= 0 && ClientId < MAX_CLIENTS, "Invalid ClientId: %d", ClientId);
703 dbg_assert(m_aClients[ClientId].m_State != CServer::CClient::STATE_EMPTY, "Client slot %d is empty", ClientId);
704 int Key = m_aClients[ClientId].m_AuthKey;
705 dbg_assert(Key != -1, "Client not authed");
706 return m_AuthManager.KeyIdent(Slot: Key);
707}
708
709bool CServer::HasAuthHidden(int ClientId) const
710{
711 dbg_assert(ClientId >= 0 && ClientId < MAX_CLIENTS, "Invalid ClientId: %d", ClientId);
712 return m_aClients[ClientId].m_AuthHidden;
713}
714
715bool CServer::GetClientInfo(int ClientId, CClientInfo *pInfo) const
716{
717 dbg_assert(ClientId >= 0 && ClientId < MAX_CLIENTS, "Invalid ClientId: %d", ClientId);
718 dbg_assert(pInfo != nullptr, "pInfo cannot be null");
719
720 if(m_aClients[ClientId].IsKnownToGame())
721 {
722 pInfo->m_pName = m_aClients[ClientId].m_aName;
723 pInfo->m_Latency = m_aClients[ClientId].m_Latency;
724 pInfo->m_GotDDNetVersion = m_aClients[ClientId].m_DDNetVersionSettled;
725 pInfo->m_DDNetVersion = m_aClients[ClientId].m_DDNetVersion >= 0 ? m_aClients[ClientId].m_DDNetVersion : VERSION_VANILLA;
726 if(m_aClients[ClientId].m_GotDDNetVersionPacket)
727 {
728 pInfo->m_pConnectionId = &m_aClients[ClientId].m_ConnectionId;
729 pInfo->m_pDDNetVersionStr = m_aClients[ClientId].m_aDDNetVersionStr;
730 }
731 else
732 {
733 pInfo->m_pConnectionId = nullptr;
734 pInfo->m_pDDNetVersionStr = nullptr;
735 }
736 return true;
737 }
738 return false;
739}
740
741void CServer::SetClientDDNetVersion(int ClientId, int DDNetVersion)
742{
743 dbg_assert(ClientId >= 0 && ClientId < MAX_CLIENTS, "Invalid ClientId: %d", ClientId);
744
745 if(m_aClients[ClientId].IsKnownToGame())
746 {
747 m_aClients[ClientId].m_DDNetVersion = DDNetVersion;
748 m_aClients[ClientId].m_DDNetVersionSettled = true;
749 }
750}
751
752const NETADDR *CServer::ClientAddr(int ClientId) const
753{
754 dbg_assert(ClientId >= 0 && ClientId < MAX_CLIENTS, "Invalid ClientId: %d", ClientId);
755 dbg_assert(m_aClients[ClientId].m_State != CServer::CClient::STATE_EMPTY, "Client slot %d is empty", ClientId);
756 if(m_aClients[ClientId].m_DebugDummy)
757 {
758 return &m_aClients[ClientId].m_DebugDummyAddr;
759 }
760 return m_NetServer.ClientAddr(ClientId);
761}
762
763const std::array<char, NETADDR_MAXSTRSIZE> &CServer::ClientAddrStringImpl(int ClientId, bool IncludePort) const
764{
765 dbg_assert(ClientId >= 0 && ClientId < MAX_CLIENTS, "Invalid ClientId: %d", ClientId);
766 dbg_assert(m_aClients[ClientId].m_State != CServer::CClient::STATE_EMPTY, "Client slot %d is empty", ClientId);
767 if(m_aClients[ClientId].m_DebugDummy)
768 {
769 return IncludePort ? m_aClients[ClientId].m_aDebugDummyAddrString : m_aClients[ClientId].m_aDebugDummyAddrStringNoPort;
770 }
771 return m_NetServer.ClientAddrString(ClientId, IncludePort);
772}
773
774const char *CServer::ClientName(int ClientId) const
775{
776 if(ClientId < 0 || ClientId >= MAX_CLIENTS || m_aClients[ClientId].m_State == CServer::CClient::STATE_EMPTY)
777 return "(invalid)";
778 if(m_aClients[ClientId].IsKnownToGame() || m_aClients[ClientId].m_State == CServer::CClient::STATE_REDIRECTED)
779 return m_aClients[ClientId].m_aName;
780 else
781 return "(connecting)";
782}
783
784const char *CServer::ClientClan(int ClientId) const
785{
786 if(ClientId < 0 || ClientId >= MAX_CLIENTS || m_aClients[ClientId].m_State == CServer::CClient::STATE_EMPTY)
787 return "";
788 if(m_aClients[ClientId].IsKnownToGame())
789 return m_aClients[ClientId].m_aClan;
790 else
791 return "";
792}
793
794int CServer::ClientCountry(int ClientId) const
795{
796 if(ClientId < 0 || ClientId >= MAX_CLIENTS || m_aClients[ClientId].m_State == CServer::CClient::STATE_EMPTY)
797 return -1;
798 if(m_aClients[ClientId].IsKnownToGame())
799 return m_aClients[ClientId].m_Country;
800 else
801 return -1;
802}
803
804bool CServer::ClientSlotEmpty(int ClientId) const
805{
806 return ClientId >= 0 && ClientId < MAX_CLIENTS && m_aClients[ClientId].m_State == CServer::CClient::STATE_EMPTY;
807}
808
809bool CServer::ClientIngame(int ClientId) const
810{
811 return ClientId >= 0 && ClientId < MAX_CLIENTS && m_aClients[ClientId].IsKnownToGame();
812}
813
814int CServer::Port() const
815{
816 return m_NetServer.Address().port;
817}
818
819int CServer::MaxClients() const
820{
821 return m_RunServer == UNINITIALIZED ? 0 : m_NetServer.MaxClients();
822}
823
824int CServer::ClientCount() const
825{
826 int ClientCount = 0;
827 for(const auto &Client : m_aClients)
828 {
829 if(Client.m_State != CClient::STATE_EMPTY)
830 {
831 ClientCount++;
832 }
833 }
834
835 return ClientCount;
836}
837
838int CServer::DistinctClientCount() const
839{
840 const NETADDR *apAddresses[MAX_CLIENTS];
841 for(int i = 0; i < MAX_CLIENTS; i++)
842 {
843 // connecting clients with spoofed ips can clog slots without being ingame
844 apAddresses[i] = ClientIngame(ClientId: i) ? ClientAddr(ClientId: i) : nullptr;
845 }
846
847 int ClientCount = 0;
848 for(int i = 0; i < MAX_CLIENTS; i++)
849 {
850 if(apAddresses[i] == nullptr)
851 {
852 continue;
853 }
854 ClientCount++;
855 for(int j = 0; j < i; j++)
856 {
857 if(apAddresses[j] != nullptr && !net_addr_comp_noport(a: apAddresses[i], b: apAddresses[j]))
858 {
859 ClientCount--;
860 break;
861 }
862 }
863 }
864 return ClientCount;
865}
866
867int CServer::GetClientVersion(int ClientId) const
868{
869 // Assume latest client version for server demos
870 if(ClientId == SERVER_DEMO_CLIENT)
871 return DDNET_VERSION_NUMBER;
872
873 CClientInfo Info;
874 if(GetClientInfo(ClientId, pInfo: &Info))
875 return Info.m_DDNetVersion;
876 return VERSION_NONE;
877}
878
879static inline bool RepackMsg(const CMsgPacker *pMsg, CPacker &Packer, bool Sixup)
880{
881 int MsgId = pMsg->m_MsgId;
882 Packer.Reset();
883
884 if(Sixup && !pMsg->m_NoTranslate)
885 {
886 if(pMsg->m_System)
887 {
888 if(MsgId >= OFFSET_UUID)
889 ;
890 else if(MsgId >= NETMSG_MAP_CHANGE && MsgId <= NETMSG_MAP_DATA)
891 ;
892 else if(MsgId >= NETMSG_CON_READY && MsgId <= NETMSG_INPUTTIMING)
893 MsgId += 1;
894 else if(MsgId == NETMSG_RCON_LINE)
895 MsgId = protocol7::NETMSG_RCON_LINE;
896 else if(MsgId >= NETMSG_PING && MsgId <= NETMSG_PING_REPLY)
897 MsgId += 4;
898 else if(MsgId >= NETMSG_RCON_CMD_ADD && MsgId <= NETMSG_RCON_CMD_REM)
899 MsgId -= 11;
900 else
901 {
902 log_error("net", "DROP send sys %d", MsgId);
903 return false;
904 }
905 }
906 else
907 {
908 if(MsgId >= 0 && MsgId < OFFSET_UUID)
909 MsgId = Msg_SixToSeven(a: MsgId);
910
911 if(MsgId < 0)
912 return false;
913 }
914 }
915
916 if(MsgId < OFFSET_UUID)
917 {
918 Packer.AddInt(i: (MsgId << 1) | (pMsg->m_System ? 1 : 0));
919 }
920 else
921 {
922 Packer.AddInt(i: pMsg->m_System ? 1 : 0); // NETMSG_EX, NETMSGTYPE_EX
923 g_UuidManager.PackUuid(Id: MsgId, pPacker: &Packer);
924 }
925 Packer.AddRaw(pData: pMsg->Data(), Size: pMsg->Size());
926
927 return true;
928}
929
930int CServer::SendMsg(CMsgPacker *pMsg, int Flags, int ClientId)
931{
932 CNetChunk Packet;
933 mem_zero(block: &Packet, size: sizeof(CNetChunk));
934 if(Flags & MSGFLAG_VITAL)
935 Packet.m_Flags |= NETSENDFLAG_VITAL;
936 if(Flags & MSGFLAG_FLUSH)
937 Packet.m_Flags |= NETSENDFLAG_FLUSH;
938
939 if(ClientId < 0)
940 {
941 CPacker Pack6, Pack7;
942 if(!RepackMsg(pMsg, Packer&: Pack6, Sixup: false))
943 return -1;
944 if(!RepackMsg(pMsg, Packer&: Pack7, Sixup: true))
945 return -1;
946
947 // write message to demo recorders
948 if(!(Flags & MSGFLAG_NORECORD))
949 {
950 for(auto &Recorder : m_aDemoRecorder)
951 if(Recorder.IsRecording())
952 Recorder.RecordMessage(pData: Pack6.Data(), Size: Pack6.Size());
953 }
954
955 if(!(Flags & MSGFLAG_NOSEND))
956 {
957 for(int i = 0; i < MAX_CLIENTS; i++)
958 {
959 if(m_aClients[i].m_State == CClient::STATE_INGAME)
960 {
961 CPacker *pPack = m_aClients[i].m_Sixup ? &Pack7 : &Pack6;
962 Packet.m_pData = pPack->Data();
963 Packet.m_DataSize = pPack->Size();
964 Packet.m_ClientId = i;
965 if(Antibot()->OnEngineServerMessage(ClientId: i, pData: Packet.m_pData, Size: Packet.m_DataSize, Flags))
966 {
967 continue;
968 }
969 m_NetServer.Send(pChunk: &Packet);
970 }
971 }
972 }
973 }
974 else
975 {
976 CPacker Pack;
977 if(!RepackMsg(pMsg, Packer&: Pack, Sixup: m_aClients[ClientId].m_Sixup))
978 return -1;
979
980 Packet.m_ClientId = ClientId;
981 Packet.m_pData = Pack.Data();
982 Packet.m_DataSize = Pack.Size();
983
984 if(Antibot()->OnEngineServerMessage(ClientId, pData: Packet.m_pData, Size: Packet.m_DataSize, Flags))
985 {
986 return 0;
987 }
988
989 // write message to demo recorders
990 if(!(Flags & MSGFLAG_NORECORD))
991 {
992 if(m_aDemoRecorder[ClientId].IsRecording())
993 m_aDemoRecorder[ClientId].RecordMessage(pData: Pack.Data(), Size: Pack.Size());
994 if(m_aDemoRecorder[RECORDER_MANUAL].IsRecording())
995 m_aDemoRecorder[RECORDER_MANUAL].RecordMessage(pData: Pack.Data(), Size: Pack.Size());
996 if(m_aDemoRecorder[RECORDER_AUTO].IsRecording())
997 m_aDemoRecorder[RECORDER_AUTO].RecordMessage(pData: Pack.Data(), Size: Pack.Size());
998 }
999
1000 if(!(Flags & MSGFLAG_NOSEND))
1001 m_NetServer.Send(pChunk: &Packet);
1002 }
1003
1004 return 0;
1005}
1006
1007void CServer::SendMsgRaw(int ClientId, const void *pData, int Size, int Flags)
1008{
1009 CNetChunk Packet;
1010 mem_zero(block: &Packet, size: sizeof(CNetChunk));
1011 Packet.m_ClientId = ClientId;
1012 Packet.m_pData = pData;
1013 Packet.m_DataSize = Size;
1014 Packet.m_Flags = 0;
1015 if(Flags & MSGFLAG_VITAL)
1016 {
1017 Packet.m_Flags |= NETSENDFLAG_VITAL;
1018 }
1019 if(Flags & MSGFLAG_FLUSH)
1020 {
1021 Packet.m_Flags |= NETSENDFLAG_FLUSH;
1022 }
1023 m_NetServer.Send(pChunk: &Packet);
1024}
1025
1026void CServer::DoSnapshot()
1027{
1028 bool IsGlobalSnap = Config()->m_SvHighBandwidth || (m_CurrentGameTick % 2) == 0;
1029
1030 if(m_aDemoRecorder[RECORDER_MANUAL].IsRecording() || m_aDemoRecorder[RECORDER_AUTO].IsRecording())
1031 {
1032 // create snapshot for demo recording
1033 CSnapshotBuffer Data;
1034
1035 // build snap and possibly add some messages
1036 m_SnapshotBuilder.Init();
1037 GameServer()->OnSnap(ClientId: -1, GlobalSnap: IsGlobalSnap, RecordingDemo: true);
1038 int SnapshotSize = m_SnapshotBuilder.Finish(pBuffer: &Data);
1039
1040 // write snapshot
1041 if(m_aDemoRecorder[RECORDER_MANUAL].IsRecording())
1042 m_aDemoRecorder[RECORDER_MANUAL].RecordSnapshot(Tick: Tick(), pData: Data.AsSnapshot(), Size: SnapshotSize);
1043 if(m_aDemoRecorder[RECORDER_AUTO].IsRecording())
1044 m_aDemoRecorder[RECORDER_AUTO].RecordSnapshot(Tick: Tick(), pData: Data.AsSnapshot(), Size: SnapshotSize);
1045 }
1046
1047 // create snapshots for all clients
1048 for(int i = 0; i < MaxClients(); i++)
1049 {
1050 // client must be ingame to receive snapshots
1051 if(m_aClients[i].m_State != CClient::STATE_INGAME)
1052 continue;
1053
1054 // this client is trying to recover, don't spam snapshots
1055 if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_RECOVER && (Tick() % TickSpeed()) != 0)
1056 continue;
1057
1058 // this client is trying to recover, don't spam snapshots
1059 if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_INIT && (Tick() % 10) != 0)
1060 continue;
1061
1062 // only allow clients with forced high bandwidth on spectate to receive snapshots on non-global ticks
1063 if(!IsGlobalSnap && !(m_aClients[i].m_ForceHighBandwidthOnSpectate && GameServer()->IsClientHighBandwidth(ClientId: i)))
1064 continue;
1065
1066 {
1067 m_SnapshotBuilder.Init(Sixup: m_aClients[i].m_Sixup);
1068
1069 // only snap events on global ticks
1070 GameServer()->OnSnap(ClientId: i, GlobalSnap: IsGlobalSnap, RecordingDemo: m_aDemoRecorder[i].IsRecording());
1071
1072 // finish snapshot
1073 CSnapshotBuffer Data;
1074 int SnapshotSize = m_SnapshotBuilder.Finish(pBuffer: &Data);
1075
1076 if(m_aDemoRecorder[i].IsRecording())
1077 {
1078 // write snapshot
1079 m_aDemoRecorder[i].RecordSnapshot(Tick: Tick(), pData: Data.AsSnapshot(), Size: SnapshotSize);
1080 }
1081
1082 int Crc = Data.AsSnapshot()->Crc();
1083
1084 // Remove old snapshots. Only the last acked snapshot
1085 // is still needed as delta base, keep at most 3
1086 // seconds worth for clients that aren't acking.
1087 //
1088 // This also works for the sentinel value -1 of
1089 // `m_LastAckedSnapshot` (before the first ack):
1090 // the max then falls back to the 3 second cap.
1091 m_aClients[i].m_Snapshots.PurgeUntil(Tick: std::max(a: m_CurrentGameTick - TickSpeed() * 3, b: m_aClients[i].m_LastAckedSnapshot));
1092
1093 // save the snapshot
1094 m_aClients[i].m_Snapshots.Add(Tick: m_CurrentGameTick, Tagtime: time_get(), DataSize: SnapshotSize, pData: Data.AsSnapshot(), AltDataSize: 0, pAltData: nullptr);
1095
1096 // find snapshot that we can perform delta against
1097 int DeltaTick = -1;
1098 const CSnapshot *pDeltashot = CSnapshot::EmptySnapshot();
1099 {
1100 int DeltashotSize;
1101 if(m_aClients[i].m_LastAckedSnapshot >= MIN_TICK)
1102 {
1103 DeltashotSize = m_aClients[i].m_Snapshots.Get(Tick: m_aClients[i].m_LastAckedSnapshot, pTagtime: nullptr, ppData: &pDeltashot, ppAltData: nullptr);
1104 }
1105 else
1106 {
1107 DeltashotSize = -1;
1108 }
1109 if(DeltashotSize >= 0)
1110 {
1111 DeltaTick = m_aClients[i].m_LastAckedSnapshot;
1112 }
1113 else
1114 {
1115 // no acked package found, force client to recover rate
1116 if(m_aClients[i].m_SnapRate == CClient::SNAPRATE_FULL)
1117 m_aClients[i].m_SnapRate = CClient::SNAPRATE_RECOVER;
1118 }
1119 }
1120
1121 // create delta
1122 CSnapshotDelta *const pSnapshotDelta = IsSixup(ClientId: i) ? &m_SnapshotDeltaSixup : &m_SnapshotDelta;
1123 CSnapshotDeltaBuffer DeltaData;
1124 int DeltaSize = pSnapshotDelta->CreateDelta(pFrom: pDeltashot, pTo: Data.AsSnapshot(), pDstData: &DeltaData);
1125
1126 if(DeltaSize)
1127 {
1128 // compress it
1129 const int MaxSize = MAX_SNAPSHOT_PACKSIZE;
1130
1131 char aCompData[CSnapshot::MAX_SIZE];
1132 SnapshotSize = CVariableInt::Compress(pSrc: DeltaData.m_aData, SrcSize: DeltaSize, pDst: aCompData, DstSize: sizeof(aCompData));
1133 const int NumPackets = (SnapshotSize + MaxSize - 1) / MaxSize;
1134 if(SnapshotSize < 0 || NumPackets > CSnapshot::MAX_PARTS)
1135 {
1136 // the client cannot receive this snapshot, it will keep acking the old one
1137 log_error("server", "snapshot for client %d is too large to send, delta_size=%d packed_size=%d", i, DeltaSize, SnapshotSize);
1138 continue;
1139 }
1140
1141 for(int n = 0, Left = SnapshotSize; Left > 0; n++)
1142 {
1143 int Chunk = Left < MaxSize ? Left : MaxSize;
1144 Left -= Chunk;
1145
1146 if(NumPackets == 1)
1147 {
1148 CMsgPacker Msg(NETMSG_SNAPSINGLE, true);
1149 Msg.AddInt(i: m_CurrentGameTick);
1150 Msg.AddInt(i: m_CurrentGameTick - DeltaTick);
1151 Msg.AddInt(i: Crc);
1152 Msg.AddInt(i: Chunk);
1153 Msg.AddRaw(pData: &aCompData[n * MaxSize], Size: Chunk);
1154 SendMsg(pMsg: &Msg, Flags: MSGFLAG_FLUSH, ClientId: i);
1155 }
1156 else
1157 {
1158 CMsgPacker Msg(NETMSG_SNAP, true);
1159 Msg.AddInt(i: m_CurrentGameTick);
1160 Msg.AddInt(i: m_CurrentGameTick - DeltaTick);
1161 Msg.AddInt(i: NumPackets);
1162 Msg.AddInt(i: n);
1163 Msg.AddInt(i: Crc);
1164 Msg.AddInt(i: Chunk);
1165 Msg.AddRaw(pData: &aCompData[n * MaxSize], Size: Chunk);
1166 SendMsg(pMsg: &Msg, Flags: MSGFLAG_FLUSH, ClientId: i);
1167 }
1168 }
1169 }
1170 else
1171 {
1172 CMsgPacker Msg(NETMSG_SNAPEMPTY, true);
1173 Msg.AddInt(i: m_CurrentGameTick);
1174 Msg.AddInt(i: m_CurrentGameTick - DeltaTick);
1175 SendMsg(pMsg: &Msg, Flags: MSGFLAG_FLUSH, ClientId: i);
1176 }
1177 }
1178 }
1179
1180 if(IsGlobalSnap)
1181 {
1182 GameServer()->OnPostGlobalSnap();
1183 }
1184}
1185
1186int CServer::ClientRejoinCallback(int ClientId, void *pUser, bool Sixup, bool VanillaAuth)
1187{
1188 CServer *pThis = (CServer *)pUser;
1189
1190 if(!pThis->m_aClients[ClientId].IsKnownToGame())
1191 {
1192 DelClientCallback(ClientId, pReason: "reconnect", pUser);
1193 if(VanillaAuth)
1194 return NewClientNoAuthCallback(ClientId, pUser);
1195 return NewClientCallback(ClientId, pUser, Sixup);
1196 }
1197
1198 pThis->m_aClients[ClientId].m_AuthKey = -1;
1199 pThis->m_aClients[ClientId].m_pRconCmdToSend = nullptr;
1200 pThis->m_aClients[ClientId].m_MaplistEntryToSend = CClient::MAPLIST_UNINITIALIZED;
1201 pThis->m_aClients[ClientId].m_DDNetVersion = VERSION_NONE;
1202 pThis->m_aClients[ClientId].m_GotDDNetVersionPacket = false;
1203 pThis->m_aClients[ClientId].m_DDNetVersionSettled = false;
1204
1205 pThis->m_aClients[ClientId].Reset();
1206 // Keep game slot
1207 pThis->m_aClients[ClientId].m_IngameBeforeRejoin = true;
1208 pThis->m_aClients[ClientId].m_State = CClient::STATE_CONNECTING;
1209 pThis->m_aClients[ClientId].m_Sixup = Sixup;
1210
1211 pThis->GameServer()->TeehistorianRecordPlayerRejoin(ClientId);
1212 pThis->Antibot()->OnEngineClientDrop(ClientId, pReason: "rejoin");
1213 pThis->Antibot()->OnEngineClientJoin(ClientId);
1214
1215 pThis->SendMap(ClientId);
1216
1217 return 0;
1218}
1219
1220int CServer::NewClientNoAuthCallback(int ClientId, void *pUser)
1221{
1222 CServer *pThis = (CServer *)pUser;
1223
1224 pThis->m_aClients[ClientId].m_DnsblState = EDnsblState::NONE;
1225
1226 pThis->m_aClients[ClientId].m_State = CClient::STATE_CONNECTING;
1227 pThis->m_aClients[ClientId].m_aName[0] = 0;
1228 pThis->m_aClients[ClientId].m_aClan[0] = 0;
1229 pThis->m_aClients[ClientId].m_Country = CountryCode::DEFAULT;
1230 pThis->m_aClients[ClientId].m_AuthKey = -1;
1231 pThis->m_aClients[ClientId].m_AuthTries = 0;
1232 pThis->m_aClients[ClientId].m_AuthHidden = false;
1233 pThis->m_aClients[ClientId].m_pRconCmdToSend = nullptr;
1234 pThis->m_aClients[ClientId].m_MaplistEntryToSend = CClient::MAPLIST_UNINITIALIZED;
1235 pThis->m_aClients[ClientId].m_ShowIps = false;
1236 pThis->m_aClients[ClientId].m_DebugDummy = false;
1237 pThis->m_aClients[ClientId].m_ForceHighBandwidthOnSpectate = false;
1238 pThis->m_aClients[ClientId].m_DDNetVersion = VERSION_NONE;
1239 pThis->m_aClients[ClientId].m_GotDDNetVersionPacket = false;
1240 pThis->m_aClients[ClientId].m_DDNetVersionSettled = false;
1241 pThis->m_aClients[ClientId].Reset();
1242
1243 pThis->GameServer()->TeehistorianRecordPlayerJoin(ClientId, Sixup: false);
1244 pThis->Antibot()->OnEngineClientJoin(ClientId);
1245
1246 pThis->SendCapabilities(ClientId);
1247 pThis->SendMap(ClientId);
1248#if defined(CONF_FAMILY_UNIX)
1249 pThis->SendConnLoggingCommand(Cmd: OPEN_SESSION, pAddr: pThis->ClientAddr(ClientId));
1250#endif
1251 return 0;
1252}
1253
1254int CServer::NewClientCallback(int ClientId, void *pUser, bool Sixup)
1255{
1256 CServer *pThis = (CServer *)pUser;
1257 pThis->m_aClients[ClientId].m_State = CClient::STATE_PREAUTH;
1258 pThis->m_aClients[ClientId].m_DnsblState = EDnsblState::NONE;
1259 pThis->m_aClients[ClientId].m_aName[0] = 0;
1260 pThis->m_aClients[ClientId].m_aClan[0] = 0;
1261 pThis->m_aClients[ClientId].m_Country = CountryCode::DEFAULT;
1262 pThis->m_aClients[ClientId].m_AuthKey = -1;
1263 pThis->m_aClients[ClientId].m_AuthTries = 0;
1264 pThis->m_aClients[ClientId].m_AuthHidden = false;
1265 pThis->m_aClients[ClientId].m_pRconCmdToSend = nullptr;
1266 pThis->m_aClients[ClientId].m_MaplistEntryToSend = CClient::MAPLIST_UNINITIALIZED;
1267 pThis->m_aClients[ClientId].m_Traffic = 0;
1268 pThis->m_aClients[ClientId].m_TrafficSince = 0;
1269 pThis->m_aClients[ClientId].m_ShowIps = false;
1270 pThis->m_aClients[ClientId].m_DebugDummy = false;
1271 pThis->m_aClients[ClientId].m_ForceHighBandwidthOnSpectate = false;
1272 pThis->m_aClients[ClientId].m_DDNetVersion = VERSION_NONE;
1273 pThis->m_aClients[ClientId].m_GotDDNetVersionPacket = false;
1274 pThis->m_aClients[ClientId].m_DDNetVersionSettled = false;
1275 pThis->m_aClients[ClientId].Reset();
1276 pThis->m_aClients[ClientId].m_Sixup = Sixup;
1277
1278 pThis->GameServer()->TeehistorianRecordPlayerJoin(ClientId, Sixup);
1279 pThis->Antibot()->OnEngineClientJoin(ClientId);
1280
1281#if defined(CONF_FAMILY_UNIX)
1282 pThis->SendConnLoggingCommand(Cmd: OPEN_SESSION, pAddr: pThis->ClientAddr(ClientId));
1283#endif
1284 return 0;
1285}
1286
1287void CServer::InitDnsbl(int ClientId)
1288{
1289 NETADDR Addr = *ClientAddr(ClientId);
1290
1291 //TODO: support ipv6
1292 if(Addr.type != NETTYPE_IPV4)
1293 return;
1294
1295 // build dnsbl host lookup
1296 char aBuf[256];
1297 if(Config()->m_SvDnsblKey[0] == '\0')
1298 {
1299 // without key
1300 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%d.%d.%d.%d.%s", Addr.ip[3], Addr.ip[2], Addr.ip[1], Addr.ip[0], Config()->m_SvDnsblHost);
1301 }
1302 else
1303 {
1304 // with key
1305 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s.%d.%d.%d.%d.%s", Config()->m_SvDnsblKey, Addr.ip[3], Addr.ip[2], Addr.ip[1], Addr.ip[0], Config()->m_SvDnsblHost);
1306 }
1307
1308 m_aClients[ClientId].m_pDnsblLookup = std::make_shared<CHostLookup>(args&: aBuf, args: NETTYPE_IPV4);
1309 Engine()->AddJob(pJob: m_aClients[ClientId].m_pDnsblLookup);
1310 m_aClients[ClientId].m_DnsblState = EDnsblState::PENDING;
1311}
1312
1313#ifdef CONF_FAMILY_UNIX
1314void CServer::SendConnLoggingCommand(CONN_LOGGING_CMD Cmd, const NETADDR *pAddr)
1315{
1316 if(!Config()->m_SvConnLoggingServer[0] || !m_ConnLoggingSocketCreated)
1317 return;
1318
1319 // pack the data and send it
1320 unsigned char aData[23] = {0};
1321 aData[0] = Cmd;
1322 mem_copy(dest: &aData[1], source: &pAddr->type, size: 4);
1323 mem_copy(dest: &aData[5], source: pAddr->ip, size: 16);
1324 mem_copy(dest: &aData[21], source: &pAddr->port, size: 2);
1325
1326 net_unix_send(sock: m_ConnLoggingSocket, addr: &m_ConnLoggingDestAddr, data: aData, size: sizeof(aData));
1327}
1328#endif
1329
1330int CServer::DelClientCallback(int ClientId, const char *pReason, void *pUser)
1331{
1332 CServer *pThis = (CServer *)pUser;
1333
1334 char aBuf[256];
1335 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "client dropped. cid=%d addr=<{%s}> reason='%s'", ClientId, pThis->ClientAddrString(ClientId, IncludePort: true), pReason);
1336 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "server", pStr: aBuf);
1337
1338#if defined(CONF_FAMILY_UNIX)
1339 // Make copy of address because the client slot will be empty at the end of the function
1340 const NETADDR Addr = *pThis->ClientAddr(ClientId);
1341#endif
1342
1343 // notify the mod about the drop
1344 if(pThis->m_aClients[ClientId].m_State >= CClient::STATE_READY || pThis->m_aClients[ClientId].m_IngameBeforeRejoin)
1345 pThis->GameServer()->OnClientDrop(ClientId, pReason);
1346
1347 pThis->m_aClients[ClientId].m_State = CClient::STATE_EMPTY;
1348 pThis->m_aClients[ClientId].m_aName[0] = 0;
1349 pThis->m_aClients[ClientId].m_aClan[0] = 0;
1350 pThis->m_aClients[ClientId].m_Country = CountryCode::DEFAULT;
1351 pThis->m_aClients[ClientId].m_AuthKey = -1;
1352 pThis->m_aClients[ClientId].m_AuthTries = 0;
1353 pThis->m_aClients[ClientId].m_AuthHidden = false;
1354 pThis->m_aClients[ClientId].m_pRconCmdToSend = nullptr;
1355 pThis->m_aClients[ClientId].m_MaplistEntryToSend = CClient::MAPLIST_UNINITIALIZED;
1356 pThis->m_aClients[ClientId].m_Traffic = 0;
1357 pThis->m_aClients[ClientId].m_TrafficSince = 0;
1358 pThis->m_aClients[ClientId].m_ShowIps = false;
1359 pThis->m_aClients[ClientId].m_DebugDummy = false;
1360 pThis->m_aClients[ClientId].m_ForceHighBandwidthOnSpectate = false;
1361 pThis->m_aPrevStates[ClientId] = CClient::STATE_EMPTY;
1362 pThis->m_aClients[ClientId].m_Snapshots.PurgeAll();
1363 pThis->m_aClients[ClientId].m_Sixup = false;
1364 pThis->m_aClients[ClientId].m_RedirectDropTime = 0;
1365 pThis->m_aClients[ClientId].m_IngameBeforeRejoin = false;
1366 pThis->m_aClients[ClientId].m_HasPersistentData = false;
1367
1368 pThis->GameServer()->TeehistorianRecordPlayerDrop(ClientId, pReason);
1369 pThis->Antibot()->OnEngineClientDrop(ClientId, pReason);
1370#if defined(CONF_FAMILY_UNIX)
1371 pThis->SendConnLoggingCommand(Cmd: CLOSE_SESSION, pAddr: &Addr);
1372#endif
1373 return 0;
1374}
1375
1376void CServer::SendRconType(int ClientId, bool UsernameReq)
1377{
1378 CMsgPacker Msg(NETMSG_RCONTYPE, true);
1379 Msg.AddInt(i: UsernameReq);
1380 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
1381}
1382
1383void CServer::SendCapabilities(int ClientId)
1384{
1385 CMsgPacker Msg(NETMSG_CAPABILITIES, true);
1386 Msg.AddInt(i: SERVERCAP_CURVERSION); // version
1387 Msg.AddInt(
1388 i: SERVERCAPFLAG_DDNET |
1389 SERVERCAPFLAG_CHATTIMEOUTCODE |
1390 SERVERCAPFLAG_ANYPLAYERFLAG |
1391 SERVERCAPFLAG_PINGEX |
1392 SERVERCAPFLAG_ALLOWDUMMY |
1393 SERVERCAPFLAG_SYNCWEAPONINPUT); // flags
1394 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
1395}
1396
1397void CServer::SendMap(int ClientId)
1398{
1399 int MapType = IsSixup(ClientId) ? MAP_TYPE_SIXUP : MAP_TYPE_SIX;
1400 {
1401 CMsgPacker Msg(NETMSG_MAP_DETAILS, true);
1402 Msg.AddString(pStr: GameServer()->Map()->BaseName(), Limit: 0);
1403 Msg.AddRaw(pData: &m_aCurrentMapSha256[MapType].data, Size: sizeof(m_aCurrentMapSha256[MapType].data));
1404 Msg.AddInt(i: m_aCurrentMapCrc[MapType]);
1405 Msg.AddInt(i: m_aCurrentMapSize[MapType]);
1406 if(m_aMapDownloadUrl[0])
1407 {
1408 Msg.AddString(pStr: m_aMapDownloadUrl, Limit: 0);
1409 }
1410 else
1411 {
1412 Msg.AddString(pStr: "", Limit: 0);
1413 }
1414 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
1415 }
1416 {
1417 CMsgPacker Msg(NETMSG_MAP_CHANGE, true);
1418 Msg.AddString(pStr: GameServer()->Map()->BaseName(), Limit: 0);
1419 Msg.AddInt(i: m_aCurrentMapCrc[MapType]);
1420 Msg.AddInt(i: m_aCurrentMapSize[MapType]);
1421 if(MapType == MAP_TYPE_SIXUP)
1422 {
1423 Msg.AddInt(i: Config()->m_SvMapWindow);
1424 Msg.AddInt(i: NET_MAX_CHUNK_SIZE - 128);
1425 Msg.AddRaw(pData: m_aCurrentMapSha256[MapType].data, Size: sizeof(m_aCurrentMapSha256[MapType].data));
1426 }
1427 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientId);
1428 }
1429
1430 m_aClients[ClientId].m_NextMapChunk = 0;
1431 m_aClients[ClientId].m_NumMapChunks = 0;
1432}
1433
1434void CServer::SendMapData(int ClientId, int Chunk)
1435{
1436 int MapType = IsSixup(ClientId) ? MAP_TYPE_SIXUP : MAP_TYPE_SIX;
1437 unsigned int ChunkSize = NET_MAX_CHUNK_SIZE - 128;
1438 unsigned int Offset = Chunk * ChunkSize;
1439 int Last = 0;
1440
1441 // drop faulty map data requests
1442 if(Chunk < 0 || Offset > m_aCurrentMapSize[MapType])
1443 return;
1444
1445 // a client can ask for the same chunk any number of times
1446 CClient &Client = m_aClients[ClientId];
1447 const unsigned int NumChunks = (m_aCurrentMapSize[MapType] + ChunkSize - 1) / ChunkSize;
1448 if(Client.m_NumMapChunks >= (int)(2 * NumChunks))
1449 return;
1450 Client.m_NumMapChunks++;
1451
1452 if(Offset + ChunkSize >= m_aCurrentMapSize[MapType])
1453 {
1454 ChunkSize = m_aCurrentMapSize[MapType] - Offset;
1455 Last = 1;
1456 }
1457
1458 CMsgPacker Msg(NETMSG_MAP_DATA, true);
1459 if(MapType == MAP_TYPE_SIX)
1460 {
1461 Msg.AddInt(i: Last);
1462 Msg.AddInt(i: m_aCurrentMapCrc[MAP_TYPE_SIX]);
1463 Msg.AddInt(i: Chunk);
1464 Msg.AddInt(i: ChunkSize);
1465 }
1466 Msg.AddRaw(pData: &m_apCurrentMapData[MapType][Offset], Size: ChunkSize);
1467 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientId);
1468
1469 if(Config()->m_Debug)
1470 {
1471 char aBuf[256];
1472 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "sending chunk %d with size %d", Chunk, ChunkSize);
1473 Console()->Print(Level: IConsole::OUTPUT_LEVEL_DEBUG, pFrom: "server", pStr: aBuf);
1474 }
1475}
1476
1477void CServer::SendMapReload(int ClientId)
1478{
1479 CMsgPacker Msg(NETMSG_MAP_RELOAD, true);
1480 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientId);
1481}
1482
1483void CServer::SendConnectionReady(int ClientId)
1484{
1485 CMsgPacker Msg(NETMSG_CON_READY, true);
1486 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientId);
1487}
1488
1489void CServer::SendRconLine(int ClientId, const char *pLine)
1490{
1491 CMsgPacker Msg(NETMSG_RCON_LINE, true);
1492 Msg.AddString(pStr: pLine, Limit: 512);
1493 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
1494}
1495
1496void CServer::SendRconLogLine(int ClientId, const CLogMessage *pMessage)
1497{
1498 char aLine[sizeof(CLogMessage().m_aLine)];
1499 char aLineWithoutIps[sizeof(CLogMessage().m_aLine)];
1500 StrHideIps(pInput: pMessage->m_aLine, pOutputWithIps: aLine, OutputWithIpsSize: sizeof(aLine), pOutputWithoutIps: aLineWithoutIps, OutputWithoutIpsSize: sizeof(aLineWithoutIps));
1501
1502 if(ClientId == -1)
1503 {
1504 for(int i = 0; i < MAX_CLIENTS; i++)
1505 {
1506 if(m_aClients[i].m_State != CClient::STATE_EMPTY && IsRconAuthedAdmin(ClientId: i))
1507 SendRconLine(ClientId: i, pLine: m_aClients[i].m_ShowIps ? aLine : aLineWithoutIps);
1508 }
1509 }
1510 else
1511 {
1512 if(m_aClients[ClientId].m_State != CClient::STATE_EMPTY)
1513 SendRconLine(ClientId, pLine: m_aClients[ClientId].m_ShowIps ? aLine : aLineWithoutIps);
1514 }
1515}
1516
1517void CServer::SendRconCmdAdd(const IConsole::ICommandInfo *pCommandInfo, int ClientId)
1518{
1519 CMsgPacker Msg(NETMSG_RCON_CMD_ADD, true);
1520 Msg.AddString(pStr: pCommandInfo->Name(), Limit: IConsole::TEMPCMD_NAME_LENGTH);
1521 Msg.AddString(pStr: pCommandInfo->Help(), Limit: IConsole::TEMPCMD_HELP_LENGTH);
1522 Msg.AddString(pStr: pCommandInfo->Params(), Limit: IConsole::TEMPCMD_PARAMS_LENGTH);
1523 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
1524}
1525
1526void CServer::SendRconCmdRem(const IConsole::ICommandInfo *pCommandInfo, int ClientId)
1527{
1528 CMsgPacker Msg(NETMSG_RCON_CMD_REM, true);
1529 Msg.AddString(pStr: pCommandInfo->Name(), Limit: IConsole::TEMPCMD_NAME_LENGTH);
1530 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
1531}
1532
1533void CServer::SendRconCmdGroupStart(int ClientId)
1534{
1535 CMsgPacker Msg(NETMSG_RCON_CMD_GROUP_START, true);
1536 Msg.AddInt(i: NumRconCommands(ClientId));
1537 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
1538}
1539
1540void CServer::SendRconCmdGroupEnd(int ClientId)
1541{
1542 CMsgPacker Msg(NETMSG_RCON_CMD_GROUP_END, true);
1543 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
1544}
1545
1546int CServer::NumRconCommands(int ClientId)
1547{
1548 int Num = 0;
1549 for(const IConsole::ICommandInfo *pCmd = Console()->FirstCommandInfo(ClientId, FlagMask: CFGFLAG_SERVER);
1550 pCmd; pCmd = Console()->NextCommandInfo(pInfo: pCmd, ClientId, FlagMask: CFGFLAG_SERVER))
1551 {
1552 Num++;
1553 }
1554 return Num;
1555}
1556
1557void CServer::UpdateClientRconCommands(int ClientId)
1558{
1559 CClient &Client = m_aClients[ClientId];
1560 if(Client.m_State != CClient::STATE_INGAME ||
1561 !IsRconAuthed(ClientId) ||
1562 Client.m_pRconCmdToSend == nullptr)
1563 {
1564 return;
1565 }
1566
1567 for(int i = 0; i < MAX_RCONCMD_SEND && Client.m_pRconCmdToSend; ++i)
1568 {
1569 SendRconCmdAdd(pCommandInfo: Client.m_pRconCmdToSend, ClientId);
1570 Client.m_pRconCmdToSend = Console()->NextCommandInfo(pInfo: Client.m_pRconCmdToSend, ClientId, FlagMask: CFGFLAG_SERVER);
1571 if(Client.m_pRconCmdToSend == nullptr)
1572 {
1573 SendRconCmdGroupEnd(ClientId);
1574 }
1575 }
1576}
1577
1578CServer::CMaplistEntry::CMaplistEntry(const char *pName)
1579{
1580 str_copy(dst&: m_aName, src: pName);
1581}
1582
1583bool CServer::CMaplistEntry::operator<(const CMaplistEntry &Other) const
1584{
1585 return str_comp_filenames(a: m_aName, b: Other.m_aName) < 0;
1586}
1587
1588void CServer::SendMaplistGroupStart(int ClientId)
1589{
1590 CMsgPacker Msg(NETMSG_MAPLIST_GROUP_START, true);
1591 Msg.AddInt(i: m_vMaplistEntries.size());
1592 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
1593}
1594
1595void CServer::SendMaplistGroupEnd(int ClientId)
1596{
1597 CMsgPacker Msg(NETMSG_MAPLIST_GROUP_END, true);
1598 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
1599}
1600
1601void CServer::UpdateClientMaplistEntries(int ClientId)
1602{
1603 CClient &Client = m_aClients[ClientId];
1604 if(Client.m_State != CClient::STATE_INGAME ||
1605 !IsRconAuthed(ClientId) ||
1606 Client.m_Sixup ||
1607 Client.m_pRconCmdToSend != nullptr || // wait for command sending
1608 Client.m_MaplistEntryToSend == CClient::MAPLIST_DISABLED ||
1609 Client.m_MaplistEntryToSend == CClient::MAPLIST_DONE)
1610 {
1611 return;
1612 }
1613
1614 if(Client.m_MaplistEntryToSend == CClient::MAPLIST_UNINITIALIZED)
1615 {
1616 static const char *const MAP_COMMANDS[] = {"sv_map", "change_map"};
1617 const IConsole::EAccessLevel AccessLevel = ConsoleAccessLevel(ClientId);
1618 const bool MapCommandAllowed = std::any_of(first: std::begin(arr: MAP_COMMANDS), last: std::end(arr: MAP_COMMANDS), pred: [&](const char *pMapCommand) {
1619 const IConsole::ICommandInfo *pInfo = Console()->GetCommandInfo(pName: pMapCommand, FlagMask: CFGFLAG_SERVER, Temp: false);
1620 dbg_assert(pInfo != nullptr, "Map command not found");
1621 return AccessLevel <= pInfo->GetAccessLevel();
1622 });
1623 if(MapCommandAllowed)
1624 {
1625 Client.m_MaplistEntryToSend = 0;
1626 SendMaplistGroupStart(ClientId);
1627 }
1628 else
1629 {
1630 Client.m_MaplistEntryToSend = CClient::MAPLIST_DISABLED;
1631 return;
1632 }
1633 }
1634
1635 if((size_t)Client.m_MaplistEntryToSend < m_vMaplistEntries.size())
1636 {
1637 CMsgPacker Msg(NETMSG_MAPLIST_ADD, true);
1638 int Limit = NET_MAX_CHUNK_SIZE - 128;
1639 while((size_t)Client.m_MaplistEntryToSend < m_vMaplistEntries.size())
1640 {
1641 // Space for null termination not included in Limit
1642 const int SizeBefore = Msg.Size();
1643 Msg.AddString(pStr: m_vMaplistEntries[Client.m_MaplistEntryToSend].m_aName, Limit: Limit - 1, AllowTruncation: false);
1644 if(Msg.Error())
1645 {
1646 break;
1647 }
1648 Limit -= Msg.Size() - SizeBefore;
1649 if(Limit <= 1)
1650 {
1651 break;
1652 }
1653 ++Client.m_MaplistEntryToSend;
1654 }
1655 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
1656 }
1657
1658 if((size_t)Client.m_MaplistEntryToSend >= m_vMaplistEntries.size())
1659 {
1660 SendMaplistGroupEnd(ClientId);
1661 Client.m_MaplistEntryToSend = CClient::MAPLIST_DONE;
1662 }
1663}
1664
1665static inline int MsgFromSixup(int Msg, bool System)
1666{
1667 if(System)
1668 {
1669 if(Msg == NETMSG_INFO)
1670 ;
1671 else if(Msg >= 14 && Msg <= 15)
1672 Msg += 11;
1673 else if(Msg >= 18 && Msg <= 28)
1674 Msg = NETMSG_READY + Msg - 18;
1675 else if(Msg < OFFSET_UUID)
1676 return -1;
1677 }
1678
1679 return Msg;
1680}
1681
1682bool CServer::CheckReservedSlotAuth(int ClientId, const char *pPassword)
1683{
1684 if(Config()->m_SvReservedSlotsPass[0] && !str_comp(a: Config()->m_SvReservedSlotsPass, b: pPassword))
1685 {
1686 log_info("server", "ClientId=%d joining reserved slot with reserved slots password", ClientId);
1687 return true;
1688 }
1689
1690 if(!str_comp(a: Config()->m_SvReservedSlotsAuthLevel, b: "4"))
1691 {
1692 return false;
1693 }
1694 if(Config()->m_SvReservedSlotsAuthLevel[0] == '\0')
1695 {
1696 return false;
1697 }
1698
1699 // "^([^:]*):(.*)$"
1700 const char *pInnerPassword = str_find(haystack: pPassword, needle: ":");
1701 if(pInnerPassword == nullptr)
1702 {
1703 return false;
1704 }
1705 char aName[sizeof(Config()->m_Password)];
1706 str_truncate(dst: aName, dst_size: sizeof(aName), src: pPassword, truncation_len: pInnerPassword - pPassword);
1707 int Slot = m_AuthManager.FindKey(pIdent: aName);
1708 const char *pMinAuthLevel = Config()->m_SvReservedSlotsAuthLevel;
1709 std::optional<int> MinAuthLevel = CAuthManager::RoleNameToAuthLevel(pRoleName: pMinAuthLevel);
1710 if(!MinAuthLevel.has_value())
1711 {
1712 if(str_comp(a: pMinAuthLevel, b: "1") == 0)
1713 {
1714 MinAuthLevel = AUTHED_HELPER;
1715 }
1716 else if(str_comp(a: pMinAuthLevel, b: "2") == 0)
1717 {
1718 MinAuthLevel = AUTHED_MOD;
1719 }
1720 else if(str_comp(a: pMinAuthLevel, b: "3") == 0)
1721 {
1722 MinAuthLevel = AUTHED_ADMIN;
1723 }
1724 }
1725 if(!MinAuthLevel.has_value())
1726 {
1727 return false;
1728 }
1729
1730 if(m_AuthManager.CheckKey(Slot, pPw: pInnerPassword + 1) && m_AuthManager.KeyLevel(Slot) >= MinAuthLevel.value())
1731 {
1732 log_info("server", "ClientId=%d joining reserved slot with key='%s'", ClientId, m_AuthManager.KeyIdent(Slot));
1733 return true;
1734 }
1735 return false;
1736}
1737
1738bool CServer::TakePreInputBudget(int ClientId)
1739{
1740 // nothing stops a client from sending more than one input per tick
1741 CClient &Client = m_aClients[ClientId];
1742 if(Client.m_PreInputsTick != Tick())
1743 {
1744 Client.m_PreInputsTick = Tick();
1745 Client.m_NumPreInputs = 0;
1746 }
1747 if(Config()->m_SvMaxPreInputsPerTick != 0 &&
1748 Client.m_NumPreInputs >= Config()->m_SvMaxPreInputsPerTick)
1749 {
1750 return false;
1751 }
1752 Client.m_NumPreInputs++;
1753 return true;
1754}
1755
1756void CServer::ProcessClientPacket(CNetChunk *pPacket)
1757{
1758 int ClientId = pPacket->m_ClientId;
1759 CUnpacker Unpacker;
1760 Unpacker.Reset(pData: pPacket->m_pData, Size: pPacket->m_DataSize);
1761 CMsgPacker Packer(NETMSG_EX, true);
1762
1763 // unpack msgid and system flag
1764 int Msg;
1765 bool Sys;
1766
1767 int Result = UnpackMessageId(pId: &Msg, pSys: &Sys, pUnpacker: &Unpacker, pPacker: &Packer);
1768 if(Result == UNPACKMESSAGE_ERROR)
1769 {
1770 return;
1771 }
1772
1773 if(m_aClients[ClientId].m_Sixup && (Msg = MsgFromSixup(Msg, System: Sys)) < 0)
1774 {
1775 return;
1776 }
1777
1778 if(Config()->m_SvNetlimit && Msg != NETMSG_REQUEST_MAP_DATA)
1779 {
1780 int64_t Now = time_get();
1781 int64_t Diff = Now - m_aClients[ClientId].m_TrafficSince;
1782 double Alpha = Config()->m_SvNetlimitAlpha / 100.0;
1783 double Limit = (double)(Config()->m_SvNetlimit * 1024) / time_freq();
1784
1785 if(m_aClients[ClientId].m_Traffic > Limit)
1786 {
1787 m_NetServer.NetBan()->BanAddr(pAddr: &pPacket->m_Address, Seconds: 600, pReason: "Stressing network", VerbatimReason: false);
1788 return;
1789 }
1790 if(Diff > 100)
1791 {
1792 m_aClients[ClientId].m_Traffic = (Alpha * ((double)pPacket->m_DataSize / Diff)) + (1.0 - Alpha) * m_aClients[ClientId].m_Traffic;
1793 m_aClients[ClientId].m_TrafficSince = Now;
1794 }
1795 }
1796
1797 if(Result == UNPACKMESSAGE_ANSWER)
1798 {
1799 SendMsg(pMsg: &Packer, Flags: MSGFLAG_VITAL, ClientId);
1800 }
1801
1802 {
1803 bool VitalFlag = (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0;
1804 bool NonVitalMsg = Sys && (Msg == NETMSG_INPUT || Msg == NETMSG_PING || Msg == NETMSG_PINGEX);
1805 if(!VitalFlag && !NonVitalMsg)
1806 {
1807 if(g_Config.m_Debug)
1808 {
1809 log_debug(
1810 "server",
1811 "strange message ClientId=%d msg=%d data_size=%d (missing vital flag)",
1812 ClientId,
1813 Msg,
1814 pPacket->m_DataSize);
1815 }
1816 return;
1817 }
1818 }
1819
1820 if(Sys)
1821 {
1822 // system message
1823 if(Msg == NETMSG_CLIENTVER)
1824 {
1825 CUuid *pConnectionId = (CUuid *)Unpacker.GetRaw(Size: sizeof(*pConnectionId));
1826 int DDNetVersion = Unpacker.GetInt();
1827 const char *pDDNetVersionStr = Unpacker.GetString(SanitizeType: CUnpacker::SANITIZE_CC);
1828 if(Unpacker.Error())
1829 return;
1830
1831 OnNetMsgClientVer(ClientId, pConnectionId, DDNetVersion, pDDNetVersionStr);
1832 }
1833 else if(Msg == NETMSG_INFO)
1834 {
1835 const char *pVersion = Unpacker.GetString(SanitizeType: CUnpacker::SANITIZE_CC);
1836 if(Unpacker.Error())
1837 return;
1838 const char *pPassword = Unpacker.GetString(SanitizeType: CUnpacker::SANITIZE_CC);
1839 if(Unpacker.Error())
1840 pPassword = nullptr;
1841
1842 OnNetMsgInfo(ClientId, pVersion, pPasswordOrNullptr: pPassword);
1843 }
1844 else if(Msg == NETMSG_REQUEST_MAP_DATA)
1845 {
1846 if(m_aClients[ClientId].m_State < CClient::STATE_CONNECTING)
1847 return;
1848
1849 if(m_aClients[ClientId].m_Sixup)
1850 {
1851 for(int i = 0; i < Config()->m_SvMapWindow; i++)
1852 {
1853 SendMapData(ClientId, Chunk: m_aClients[ClientId].m_NextMapChunk++);
1854 }
1855 return;
1856 }
1857
1858 int Chunk = Unpacker.GetInt();
1859 if(Unpacker.Error())
1860 {
1861 return;
1862 }
1863 if(Chunk == 0)
1864 {
1865 m_aClients[ClientId].m_NextMapChunk = 0;
1866 }
1867 if(Chunk != m_aClients[ClientId].m_NextMapChunk || !Config()->m_SvFastDownload)
1868 {
1869 SendMapData(ClientId, Chunk);
1870 return;
1871 }
1872
1873 if(Chunk == 0)
1874 {
1875 for(int i = 0; i < Config()->m_SvMapWindow; i++)
1876 {
1877 SendMapData(ClientId, Chunk: i);
1878 }
1879 }
1880 SendMapData(ClientId, Chunk: Config()->m_SvMapWindow + m_aClients[ClientId].m_NextMapChunk);
1881 m_aClients[ClientId].m_NextMapChunk++;
1882 }
1883 else if(Msg == NETMSG_READY)
1884 {
1885 OnNetMsgReady(ClientId);
1886 }
1887 else if(Msg == NETMSG_ENTERGAME)
1888 {
1889 OnNetMsgEnterGame(ClientId);
1890 }
1891 else if(Msg == NETMSG_INPUT)
1892 {
1893 if((pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0)
1894 {
1895 return;
1896 }
1897 if(m_aClients[ClientId].m_State != CClient::STATE_INGAME)
1898 {
1899 return;
1900 }
1901
1902 const int LastAckedSnapshot = Unpacker.GetInt();
1903 if(Unpacker.Error() ||
1904 LastAckedSnapshot < -1 ||
1905 LastAckedSnapshot > Tick())
1906 {
1907 return;
1908 }
1909
1910 int IntendedTick = Unpacker.GetInt();
1911 if(Unpacker.Error() ||
1912 IntendedTick < MIN_TICK ||
1913 IntendedTick > MAX_TICK)
1914 {
1915 return;
1916 }
1917
1918 const int Size = Unpacker.GetInt();
1919 if(Unpacker.Error() ||
1920 Size % (int)sizeof(int32_t) != 0 ||
1921 Size / (int)sizeof(int32_t) < MIN_INPUT_SIZE ||
1922 Size / (int)sizeof(int32_t) > MAX_INPUT_SIZE)
1923 {
1924 return;
1925 }
1926
1927 m_aClients[ClientId].m_LastAckedSnapshot = LastAckedSnapshot;
1928 if(m_aClients[ClientId].m_LastAckedSnapshot >= MIN_TICK)
1929 {
1930 m_aClients[ClientId].m_SnapRate = CClient::SNAPRATE_FULL;
1931
1932 int64_t TagTime;
1933 if(m_aClients[ClientId].m_Snapshots.Get(Tick: m_aClients[ClientId].m_LastAckedSnapshot, pTagtime: &TagTime, ppData: nullptr, ppAltData: nullptr) >= 0)
1934 {
1935 m_aClients[ClientId].m_Latency = (int)(((time_get() - TagTime) * 1000) / time_freq());
1936 }
1937 }
1938
1939 // add message to report the input timing
1940 // skip packets that are old
1941 if(IntendedTick > m_aClients[ClientId].m_LastInputTick)
1942 {
1943 const int TimeLeft = (TickStartTime(Tick: IntendedTick) - time_get()) / (time_freq() / 1000);
1944
1945 CMsgPacker Msgp(NETMSG_INPUTTIMING, true);
1946 Msgp.AddInt(i: IntendedTick);
1947 Msgp.AddInt(i: TimeLeft);
1948 SendMsg(pMsg: &Msgp, Flags: 0, ClientId);
1949 }
1950 m_aClients[ClientId].m_LastInputTick = IntendedTick;
1951
1952 IntendedTick = std::max(a: IntendedTick, b: Tick() + 1);
1953
1954 int aInputData[MAX_INPUT_SIZE];
1955 for(int i = 0; i < Size / (int)sizeof(int32_t); i++)
1956 {
1957 aInputData[i] = Unpacker.GetInt();
1958 }
1959 if(Unpacker.Error())
1960 {
1961 return;
1962 }
1963
1964 CClient::CInput *pInput = &m_aClients[ClientId].m_aInputs[m_aClients[ClientId].m_CurrentInput];
1965 pInput->m_GameTick = IntendedTick;
1966 mem_copy(dest: pInput->m_aData, source: aInputData, size: Size);
1967
1968 // Bound before the pre-input relay below, so that the other clients predict
1969 // with the same input as this server uses
1970 GameServer()->OnClientPrepareInput(ClientId, pInput: pInput->m_aData);
1971
1972 if(g_Config.m_SvPreInput &&
1973 IntendedTick <= Tick() + 4 * TickSpeed() + 1 &&
1974 TakePreInputBudget(ClientId))
1975 {
1976 // send preinputs of ClientId to valid clients
1977 bool aPreInputClients[MAX_CLIENTS] = {};
1978 GameServer()->PreInputClients(ClientId, pClients: aPreInputClients);
1979
1980 CNetMsg_Sv_PreInput PreInput = {};
1981 mem_zero(block: &PreInput, size: sizeof(PreInput));
1982 CNetObj_PlayerInput *pInputData = (CNetObj_PlayerInput *)&pInput->m_aData;
1983
1984 PreInput.m_Direction = pInputData->m_Direction;
1985 PreInput.m_Jump = pInputData->m_Jump;
1986 PreInput.m_Fire = pInputData->m_Fire;
1987 PreInput.m_Hook = pInputData->m_Hook;
1988 PreInput.m_WantedWeapon = pInputData->m_WantedWeapon;
1989 PreInput.m_NextWeapon = pInputData->m_NextWeapon;
1990 PreInput.m_PrevWeapon = pInputData->m_PrevWeapon;
1991
1992 if(mem_comp(a: &m_aClients[ClientId].m_LastPreInput, b: &PreInput, size: sizeof(CNetMsg_Sv_PreInput)) != 0)
1993 {
1994 m_aClients[ClientId].m_LastPreInput = PreInput;
1995
1996 PreInput.m_Owner = ClientId;
1997 PreInput.m_IntendedTick = IntendedTick;
1998
1999 // target angle isn't updated all the time to save bandwidth
2000 PreInput.m_TargetX = pInputData->m_TargetX;
2001 PreInput.m_TargetY = pInputData->m_TargetY;
2002
2003 for(int Id = 0; Id < MAX_CLIENTS; Id++)
2004 {
2005 if(!aPreInputClients[Id])
2006 continue;
2007 if(m_aClients[Id].m_SnapRate != CClient::SNAPRATE_FULL)
2008 continue;
2009
2010 if(!Translate(Target&: PreInput.m_Owner, ClientId: Id))
2011 continue;
2012
2013 SendPackMsg(pMsg: &PreInput, Flags: MSGFLAG_FLUSH | MSGFLAG_NORECORD, ClientId: Id);
2014 // Reset for others after translating and sending
2015 PreInput.m_Owner = ClientId;
2016 }
2017 }
2018 }
2019
2020 mem_copy(dest: m_aClients[ClientId].m_LatestInput.m_aData, source: pInput->m_aData, size: sizeof(m_aClients[ClientId].m_LatestInput.m_aData));
2021
2022 m_aClients[ClientId].m_CurrentInput++;
2023 m_aClients[ClientId].m_CurrentInput %= 200;
2024
2025 // call the mod with the fresh input data
2026 GameServer()->OnClientDirectInput(ClientId, pInput: m_aClients[ClientId].m_LatestInput.m_aData);
2027 }
2028 else if(Msg == NETMSG_RCON_CMD)
2029 {
2030 const char *pCmd = Unpacker.GetString();
2031 if(Unpacker.Error())
2032 return;
2033
2034 OnNetMsgRconCmd(ClientId, pCmd);
2035 }
2036 else if(Msg == NETMSG_RCON_AUTH)
2037 {
2038 const char *pName = "";
2039 if(!IsSixup(ClientId))
2040 pName = Unpacker.GetString(SanitizeType: CUnpacker::SANITIZE_CC); // login name, now used
2041 const char *pPw = Unpacker.GetString(SanitizeType: CUnpacker::SANITIZE_CC);
2042 bool SendRconCmds = true;
2043 if(!IsSixup(ClientId))
2044 SendRconCmds = Unpacker.GetInt() != 0;
2045 if(Unpacker.Error())
2046 return;
2047
2048 OnNetMsgRconAuth(ClientId, pName, pPw, SendRconCmds);
2049 }
2050 else if(Msg == NETMSG_PING)
2051 {
2052 CMsgPacker Msgp(NETMSG_PING_REPLY, true);
2053 int Vital = (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 ? MSGFLAG_VITAL : 0;
2054 SendMsg(pMsg: &Msgp, Flags: MSGFLAG_FLUSH | Vital, ClientId);
2055 }
2056 else if(Msg == NETMSG_PINGEX)
2057 {
2058 CUuid *pId = (CUuid *)Unpacker.GetRaw(Size: sizeof(*pId));
2059 if(Unpacker.Error())
2060 {
2061 return;
2062 }
2063 CMsgPacker Msgp(NETMSG_PONGEX, true);
2064 Msgp.AddRaw(pData: pId, Size: sizeof(*pId));
2065 int Vital = (pPacket->m_Flags & NET_CHUNKFLAG_VITAL) != 0 ? MSGFLAG_VITAL : 0;
2066 SendMsg(pMsg: &Msgp, Flags: MSGFLAG_FLUSH | Vital, ClientId);
2067 }
2068 else
2069 {
2070 if(Config()->m_Debug)
2071 {
2072 constexpr int MaxDumpedDataSize = 32;
2073 char aBuf[MaxDumpedDataSize * 3 + 1];
2074 str_hex(dst: aBuf, dst_size: sizeof(aBuf), data: pPacket->m_pData, data_size: std::min(a: pPacket->m_DataSize, b: MaxDumpedDataSize));
2075
2076 char aBufMsg[256];
2077 str_format(buffer: aBufMsg, buffer_size: sizeof(aBufMsg), format: "strange message ClientId=%d msg=%d data_size=%d", ClientId, Msg, pPacket->m_DataSize);
2078 Console()->Print(Level: IConsole::OUTPUT_LEVEL_DEBUG, pFrom: "server", pStr: aBufMsg);
2079 Console()->Print(Level: IConsole::OUTPUT_LEVEL_DEBUG, pFrom: "server", pStr: aBuf);
2080 }
2081 }
2082 }
2083 else if(m_aClients[ClientId].m_State >= CClient::STATE_READY)
2084 {
2085 // game message
2086 GameServer()->OnMessage(MsgId: Msg, pUnpacker: &Unpacker, ClientId);
2087 }
2088}
2089
2090void CServer::OnNetMsgClientVer(int ClientId, CUuid *pConnectionId, int DDNetVersion, const char *pDDNetVersionStr)
2091{
2092 if(m_aClients[ClientId].m_State != CClient::STATE_PREAUTH)
2093 return;
2094 if(DDNetVersion < 0)
2095 return;
2096
2097 m_aClients[ClientId].m_ConnectionId = *pConnectionId;
2098 m_aClients[ClientId].m_DDNetVersion = DDNetVersion;
2099 str_copy(dst&: m_aClients[ClientId].m_aDDNetVersionStr, src: pDDNetVersionStr);
2100 m_aClients[ClientId].m_DDNetVersionSettled = true;
2101 m_aClients[ClientId].m_GotDDNetVersionPacket = true;
2102 m_aClients[ClientId].m_State = CClient::STATE_AUTH;
2103}
2104
2105void CServer::OnNetMsgInfo(int ClientId, const char *pVersion, const char *pPasswordOrNullptr)
2106{
2107 if(m_aClients[ClientId].m_State != CClient::STATE_PREAUTH && m_aClients[ClientId].m_State != CClient::STATE_AUTH)
2108 return;
2109
2110 if(str_comp(a: pVersion, b: GameServer()->NetVersion()) != 0 && str_comp(a: pVersion, b: "0.7 802f1be60a05665f") != 0)
2111 {
2112 // wrong version
2113 char aReason[256];
2114 str_format(buffer: aReason, buffer_size: sizeof(aReason), format: "Wrong version. Server is running '%s' and client '%s'", GameServer()->NetVersion(), pVersion);
2115 m_NetServer.Drop(ClientId, pReason: aReason);
2116 return;
2117 }
2118
2119 const char *pPassword = pPasswordOrNullptr;
2120 if(!pPassword)
2121 return;
2122
2123 if(Config()->m_Password[0] != 0 && str_comp(a: Config()->m_Password, b: pPassword) != 0)
2124 {
2125 // wrong password
2126 m_NetServer.Drop(ClientId, pReason: "Wrong password");
2127 return;
2128 }
2129
2130 int NumConnectedClients = 0;
2131 for(int i = 0; i < MaxClients(); ++i)
2132 {
2133 if(m_aClients[i].m_State != CClient::STATE_EMPTY)
2134 {
2135 NumConnectedClients++;
2136 }
2137 }
2138
2139 // reserved slot
2140 if(NumConnectedClients > MaxClients() - Config()->m_SvReservedSlots && !CheckReservedSlotAuth(ClientId, pPassword))
2141 {
2142 m_NetServer.Drop(ClientId, pReason: "This server is full");
2143 return;
2144 }
2145
2146 SendRconType(ClientId, UsernameReq: m_AuthManager.NumNonDefaultKeys() > 0);
2147 SendCapabilities(ClientId);
2148 m_aClients[ClientId].m_State = CClient::STATE_CONNECTING;
2149
2150 if(!m_aClients[ClientId].m_IngameBeforeRejoin)
2151 {
2152 SendMap(ClientId);
2153 }
2154}
2155
2156void CServer::OnNetMsgReady(int ClientId)
2157{
2158 if(m_aClients[ClientId].m_State != CClient::STATE_CONNECTING)
2159 return;
2160
2161 log_debug(
2162 "server",
2163 "player is ready. ClientId=%d addr=<{%s}> secure=%s",
2164 ClientId,
2165 ClientAddrString(ClientId, true),
2166 m_NetServer.HasSecurityToken(ClientId) ? "yes" : "no");
2167
2168 void *pPersistentData = nullptr;
2169 if(m_aClients[ClientId].m_HasPersistentData)
2170 {
2171 pPersistentData = m_aClients[ClientId].m_pPersistentData;
2172 m_aClients[ClientId].m_HasPersistentData = false;
2173 }
2174 m_aClients[ClientId].m_State = CClient::STATE_READY;
2175 SendConnectionReady(ClientId);
2176
2177 if(m_aClients[ClientId].m_IngameBeforeRejoin)
2178 {
2179 CNetMsg_Sv_ReadyToEnter Msg;
2180 SendPackMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientId);
2181 }
2182 else
2183 {
2184 GameServer()->OnClientConnected(ClientId, pPersistentData);
2185 }
2186}
2187
2188void CServer::OnNetMsgEnterGame(int ClientId)
2189{
2190 if(m_aClients[ClientId].m_State != CClient::STATE_READY)
2191 return;
2192 if(!GameServer()->IsClientReady(ClientId))
2193 return;
2194
2195 log_info(
2196 "server",
2197 "player has entered the game. ClientId=%d addr=<{%s}> sixup=%d",
2198 ClientId,
2199 ClientAddrString(ClientId, true),
2200 IsSixup(ClientId));
2201 m_aClients[ClientId].m_State = CClient::STATE_INGAME;
2202 if(!IsSixup(ClientId))
2203 {
2204 SendServerInfo(pAddr: ClientAddr(ClientId), Token: -1, Type: SERVERINFO_EXTENDED, SendClients: false);
2205 }
2206 else
2207 {
2208 CMsgPacker ServerInfoMessage(protocol7::NETMSG_SERVERINFO, true, true);
2209 GetServerInfoSixup(pPacker: &ServerInfoMessage, SendClients: false);
2210 SendMsg(pMsg: &ServerInfoMessage, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientId);
2211 }
2212
2213 if(m_aClients[ClientId].m_IngameBeforeRejoin)
2214 {
2215 m_aClients[ClientId].m_IngameBeforeRejoin = false;
2216 GameServer()->OnClientRejoin(ClientId);
2217 }
2218 else
2219 {
2220 GameServer()->OnClientEnter(ClientId);
2221 }
2222}
2223
2224void CServer::OnNetMsgRconCmd(int ClientId, const char *pCmd)
2225{
2226 if(!str_comp(a: pCmd, b: "crashmeplx"))
2227 {
2228 int Version = m_aClients[ClientId].m_DDNetVersion;
2229 if(GameServer()->PlayerExists(ClientId) && Version < VERSION_DDNET_OLD)
2230 {
2231 m_aClients[ClientId].m_DDNetVersion = VERSION_DDNET_OLD;
2232 GameServer()->ReinitPlayerMap(ClientId, Timeout: false);
2233 }
2234 }
2235 else if(IsRconAuthed(ClientId))
2236 {
2237 if(GameServer()->PlayerExists(ClientId))
2238 {
2239 log_info("server", "ClientId=%d key='%s' rcon='%s'", ClientId, GetAuthName(ClientId), pCmd);
2240 m_RconClientId = ClientId;
2241 m_RconAuthLevel = GetAuthedState(ClientId);
2242 {
2243 CRconClientLogger Logger(this, ClientId);
2244 CLogScope Scope(&Logger);
2245 Console()->ExecuteLineFlag(pStr: pCmd, FlasgMask: CFGFLAG_SERVER, ClientId);
2246 }
2247 m_RconClientId = IServer::RCON_CID_SERV;
2248 m_RconAuthLevel = AUTHED_ADMIN;
2249 }
2250 }
2251}
2252
2253void CServer::OnNetMsgRconAuth(int ClientId, const char *pName, const char *pPw, bool SendRconCmds)
2254{
2255 int AuthLevel = -1;
2256 int KeySlot = -1;
2257
2258 if(!pName[0])
2259 {
2260 if(m_AuthManager.CheckKey(Slot: (KeySlot = m_AuthManager.DefaultKey(pRoleName: RoleName::ADMIN)), pPw))
2261 AuthLevel = AUTHED_ADMIN;
2262 else if(m_AuthManager.CheckKey(Slot: (KeySlot = m_AuthManager.DefaultKey(pRoleName: RoleName::MODERATOR)), pPw))
2263 AuthLevel = AUTHED_MOD;
2264 else if(m_AuthManager.CheckKey(Slot: (KeySlot = m_AuthManager.DefaultKey(pRoleName: RoleName::HELPER)), pPw))
2265 AuthLevel = AUTHED_HELPER;
2266 }
2267 else
2268 {
2269 KeySlot = m_AuthManager.FindKey(pIdent: pName);
2270 if(m_AuthManager.CheckKey(Slot: KeySlot, pPw))
2271 AuthLevel = m_AuthManager.KeyLevel(Slot: KeySlot);
2272 }
2273
2274 if(AuthLevel != -1)
2275 {
2276 if(GetAuthedState(ClientId) != AuthLevel)
2277 {
2278 if(!IsSixup(ClientId))
2279 {
2280 CMsgPacker Msgp(NETMSG_RCON_AUTH_STATUS, true);
2281 Msgp.AddInt(i: 1); //authed
2282 Msgp.AddInt(i: 1); //cmdlist
2283 SendMsg(pMsg: &Msgp, Flags: MSGFLAG_VITAL, ClientId);
2284 }
2285 else
2286 {
2287 CMsgPacker Msgp(protocol7::NETMSG_RCON_AUTH_ON, true, true);
2288 SendMsg(pMsg: &Msgp, Flags: MSGFLAG_VITAL, ClientId);
2289 }
2290
2291 m_aClients[ClientId].m_AuthKey = KeySlot;
2292 if(SendRconCmds)
2293 {
2294 m_aClients[ClientId].m_pRconCmdToSend = Console()->FirstCommandInfo(ClientId, FlagMask: CFGFLAG_SERVER);
2295 SendRconCmdGroupStart(ClientId);
2296 if(m_aClients[ClientId].m_pRconCmdToSend == nullptr)
2297 {
2298 SendRconCmdGroupEnd(ClientId);
2299 }
2300 }
2301
2302 const char *pIdent = m_AuthManager.KeyIdent(Slot: KeySlot);
2303 CRconRole *pRole = m_AuthManager.FindRole(pName: CAuthManager::AuthLevelToRoleName(AuthLevel));
2304 dbg_assert(pRole != nullptr, "pRole is nullptr");
2305
2306 char aBuf[512];
2307 str_format(
2308 buffer: aBuf,
2309 buffer_size: sizeof(aBuf),
2310 format: "Successfully authenticated as %s. %s remote console access granted.",
2311 pRole->Name(),
2312 pRole->IsAdmin() ? "Full" : "Limited");
2313 SendRconLine(ClientId, pLine: aBuf);
2314 log_info("server", "ClientId=%d authed with key='%s' (%s)", ClientId, pIdent, pRole->Name());
2315
2316 if(!ClientSupportsServerMaxClients(ClientId))
2317 {
2318 SendRconLine(ClientId, pLine: "Your client does not see the real client IDs of this server. Use a more recent DDNet client.");
2319 }
2320
2321 // DDRace
2322 GameServer()->OnSetAuthed(ClientId, pRole);
2323 }
2324 }
2325 else if(Config()->m_SvRconMaxTries)
2326 {
2327 m_aClients[ClientId].m_AuthTries++;
2328 char aBuf[128];
2329 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Wrong password %d/%d.", m_aClients[ClientId].m_AuthTries, Config()->m_SvRconMaxTries);
2330 SendRconLine(ClientId, pLine: aBuf);
2331 if(m_aClients[ClientId].m_AuthTries >= Config()->m_SvRconMaxTries)
2332 {
2333 if(!Config()->m_SvRconBantime)
2334 m_NetServer.Drop(ClientId, pReason: "Too many remote console authentication tries");
2335 else
2336 m_ServerBan.BanAddr(pAddr: ClientAddr(ClientId), Seconds: Config()->m_SvRconBantime * 60, pReason: "Too many remote console authentication tries", VerbatimReason: false);
2337 }
2338 }
2339 else
2340 {
2341 SendRconLine(ClientId, pLine: "Wrong password.");
2342 }
2343}
2344
2345std::optional<bool> CServer::RateLimitServerInfoConnless()
2346{
2347 const int64_t Now = time_get();
2348 if(Now > m_ServerInfoFirstRequest + time_freq())
2349 {
2350 m_ServerInfoFirstRequest = Now;
2351 m_ServerInfoNumRequests = 0;
2352 }
2353 m_ServerInfoNumRequests++;
2354
2355 // In 0.6 the requesting address is not verified, so responses go to whoever the
2356 // request claims to be from, and they are larger than the request.
2357 if(Config()->m_SvServerInfoRepliesPerSecond != 0 &&
2358 m_ServerInfoNumRequests > Config()->m_SvServerInfoRepliesPerSecond)
2359 {
2360 return std::nullopt;
2361 }
2362 return Config()->m_SvServerInfoPerSecond == 0 ||
2363 m_ServerInfoNumRequests <= Config()->m_SvServerInfoPerSecond;
2364}
2365
2366static inline int GetCacheIndex(int Type, bool SendClient)
2367{
2368 if(Type == SERVERINFO_INGAME)
2369 Type = SERVERINFO_VANILLA;
2370 else if(Type == SERVERINFO_EXTENDED_MORE)
2371 Type = SERVERINFO_EXTENDED;
2372
2373 return Type * 2 + SendClient;
2374}
2375
2376CServer::CCache::CCache()
2377{
2378 m_vCache.clear();
2379}
2380
2381CServer::CCache::~CCache()
2382{
2383 Clear();
2384}
2385
2386CServer::CCache::CCacheChunk::CCacheChunk(const void *pData, int Size)
2387{
2388 m_vData.assign(first: (const uint8_t *)pData, last: (const uint8_t *)pData + Size);
2389}
2390
2391void CServer::CCache::AddChunk(const void *pData, int Size)
2392{
2393 m_vCache.emplace_back(args&: pData, args&: Size);
2394}
2395
2396void CServer::CCache::Clear()
2397{
2398 m_vCache.clear();
2399}
2400
2401void CServer::CacheServerInfo(CCache *pCache, int Type, bool SendClients)
2402{
2403 pCache->Clear();
2404
2405 // One chance to improve the protocol!
2406 CPacker p;
2407 char aBuf[128];
2408
2409 // count the players
2410 int PlayerCount = 0, ClientCount = 0;
2411 for(int i = 0; i < MAX_CLIENTS; i++)
2412 {
2413 if(m_aClients[i].IncludedInServerInfo())
2414 {
2415 if(GameServer()->IsClientPlayer(ClientId: i))
2416 PlayerCount++;
2417
2418 ClientCount++;
2419 }
2420 }
2421
2422 p.Reset();
2423
2424#define ADD_RAW(p, x) (p).AddRaw(x, sizeof(x))
2425#define ADD_INT(p, x) \
2426 do \
2427 { \
2428 str_format(aBuf, sizeof(aBuf), "%d", x); \
2429 (p).AddString(aBuf, 0); \
2430 } while(0)
2431
2432 p.AddString(pStr: GameServer()->Version(), Limit: 32);
2433 if(Type != SERVERINFO_VANILLA && Type != SERVERINFO_64_LEGACY)
2434 {
2435 p.AddString(pStr: Config()->m_SvName, Limit: 256);
2436 }
2437 else
2438 {
2439 if(m_NetServer.MaxClients() <= (Type == SERVERINFO_VANILLA ? VANILLA_MAX_CLIENTS : LEGACY_MAX_CLIENTS))
2440 {
2441 p.AddString(pStr: Config()->m_SvName, Limit: 64);
2442 }
2443 else
2444 {
2445 const int MaxClients = std::max(a: ClientCount, b: m_NetServer.MaxClients() - Config()->m_SvReservedSlots);
2446 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s [%d/%d]", Config()->m_SvName, ClientCount, MaxClients);
2447 p.AddString(pStr: aBuf, Limit: 64);
2448 }
2449 }
2450 p.AddString(pStr: GameServer()->Map()->BaseName(), Limit: 32);
2451
2452 if(Type == SERVERINFO_EXTENDED)
2453 {
2454 ADD_INT(p, m_aCurrentMapCrc[MAP_TYPE_SIX]);
2455 ADD_INT(p, m_aCurrentMapSize[MAP_TYPE_SIX]);
2456 }
2457
2458 // gametype
2459 p.AddString(pStr: GameServer()->GameType(), Limit: 16);
2460
2461 // flags
2462 ADD_INT(p, Config()->m_Password[0] ? SERVER_FLAG_PASSWORD : 0);
2463
2464 int MaxClients = m_NetServer.MaxClients();
2465 // How many clients the used serverinfo protocol supports, has to be tracked
2466 // separately to make sure we don't subtract the reserved slots from it
2467 int MaxClientsProtocol = MAX_CLIENTS;
2468 if(Type == SERVERINFO_VANILLA || Type == SERVERINFO_INGAME)
2469 {
2470 if(ClientCount >= VANILLA_MAX_CLIENTS)
2471 {
2472 if(ClientCount < MaxClients)
2473 ClientCount = VANILLA_MAX_CLIENTS - 1;
2474 else
2475 ClientCount = VANILLA_MAX_CLIENTS;
2476 }
2477 MaxClientsProtocol = VANILLA_MAX_CLIENTS;
2478 if(PlayerCount > ClientCount)
2479 PlayerCount = ClientCount;
2480 }
2481 else if(Type == SERVERINFO_64_LEGACY)
2482 {
2483 if(ClientCount >= LEGACY_MAX_CLIENTS)
2484 {
2485 const int MaxIncludedClients = ClientCount < MaxClients ? LEGACY_MAX_CLIENTS - 1 : LEGACY_MAX_CLIENTS;
2486 PlayerCount = 0;
2487 ClientCount = 0;
2488 for(int i = 0; i < MAX_CLIENTS && ClientCount < MaxIncludedClients; i++)
2489 {
2490 if(m_aClients[i].IncludedInServerInfo())
2491 {
2492 if(GameServer()->IsClientPlayer(ClientId: i))
2493 PlayerCount++;
2494 ClientCount++;
2495 }
2496 }
2497 }
2498 MaxClientsProtocol = LEGACY_MAX_CLIENTS;
2499 }
2500
2501 ADD_INT(p, PlayerCount); // num players
2502 ADD_INT(p, std::min(MaxClientsProtocol, std::max(MaxClients - std::max(Config()->m_SvSpectatorSlots, Config()->m_SvReservedSlots), PlayerCount))); // max players
2503 ADD_INT(p, ClientCount); // num clients
2504 ADD_INT(p, std::min(MaxClientsProtocol, std::max(MaxClients - Config()->m_SvReservedSlots, ClientCount))); // max clients
2505
2506 if(Type == SERVERINFO_EXTENDED)
2507 p.AddString(pStr: "", Limit: 0); // extra info, reserved
2508
2509 const void *pPrefix = p.Data();
2510 int PrefixSize = p.Size();
2511
2512 CPacker q;
2513 int ChunksStored = 0;
2514 int PlayersStored = 0;
2515
2516#define SAVE(size) \
2517 do \
2518 { \
2519 pCache->AddChunk(q.Data(), size); \
2520 ChunksStored++; \
2521 } while(0)
2522
2523#define RESET() \
2524 do \
2525 { \
2526 q.Reset(); \
2527 q.AddRaw(pPrefix, PrefixSize); \
2528 } while(0)
2529
2530 RESET();
2531
2532 if(Type == SERVERINFO_64_LEGACY)
2533 q.AddInt(i: PlayersStored); // offset
2534
2535 if(!SendClients)
2536 {
2537 SAVE(q.Size());
2538 return;
2539 }
2540
2541 if(Type == SERVERINFO_EXTENDED)
2542 {
2543 pPrefix = "";
2544 PrefixSize = 0;
2545 }
2546
2547 int Remaining;
2548 switch(Type)
2549 {
2550 case SERVERINFO_EXTENDED: Remaining = -1; break;
2551 case SERVERINFO_64_LEGACY: Remaining = 24; break;
2552 case SERVERINFO_VANILLA: Remaining = VANILLA_MAX_CLIENTS; break;
2553 case SERVERINFO_INGAME: Remaining = VANILLA_MAX_CLIENTS; break;
2554 default: dbg_assert_failed("Invalid Type: %d", Type);
2555 }
2556
2557 // Use the following strategy for sending:
2558 // For vanilla, send the first 16 players.
2559 // For legacy 64p, send 24 players per packet.
2560 // For extended, send as much players as possible.
2561
2562 for(int i = 0; i < MAX_CLIENTS; i++)
2563 {
2564 if(m_aClients[i].IncludedInServerInfo())
2565 {
2566 if(Type == SERVERINFO_64_LEGACY && PlayersStored == ClientCount)
2567 break;
2568 if(Remaining == 0)
2569 {
2570 if(Type == SERVERINFO_VANILLA || Type == SERVERINFO_INGAME)
2571 break;
2572
2573 // Otherwise we're SERVERINFO_64_LEGACY.
2574 SAVE(q.Size());
2575 RESET();
2576 q.AddInt(i: PlayersStored); // offset
2577 Remaining = 24;
2578 }
2579 if(Remaining > 0)
2580 {
2581 Remaining--;
2582 }
2583
2584 int PreviousSize = q.Size();
2585
2586 q.AddString(pStr: ClientName(ClientId: i), Limit: MAX_NAME_LENGTH); // client name
2587 q.AddString(pStr: ClientClan(ClientId: i), Limit: MAX_CLAN_LENGTH); // client clan
2588
2589 ADD_INT(q, m_aClients[i].m_Country); // client country (ISO 3166-1 numeric)
2590
2591 int Score;
2592 if(m_aClients[i].m_Score.has_value())
2593 {
2594 Score = m_aClients[i].m_Score.value();
2595 if(Score == -FinishTime::NOT_FINISHED_TIMESCORE)
2596 Score = FinishTime::NOT_FINISHED_TIMESCORE - 1;
2597 else if(Score == 0) // 0 time isn't displayed otherwise.
2598 Score = -1;
2599 else
2600 Score = -Score;
2601 }
2602 else
2603 {
2604 Score = FinishTime::NOT_FINISHED_TIMESCORE;
2605 }
2606
2607 ADD_INT(q, Score); // client score
2608 ADD_INT(q, GameServer()->IsClientPlayer(i) ? 1 : 0); // is player?
2609 if(Type == SERVERINFO_EXTENDED)
2610 q.AddString(pStr: "", Limit: 0); // extra info, reserved
2611
2612 if(Type == SERVERINFO_EXTENDED)
2613 {
2614 if(q.Size() >= NET_MAX_CONNLESS_PAYLOAD - 18) // 8 bytes for type, 10 bytes for the largest token
2615 {
2616 // Retry current player.
2617 i--;
2618 SAVE(PreviousSize);
2619 RESET();
2620 ADD_INT(q, ChunksStored);
2621 q.AddString(pStr: "", Limit: 0); // extra info, reserved
2622 continue;
2623 }
2624 }
2625 PlayersStored++;
2626 }
2627 }
2628
2629 SAVE(q.Size());
2630#undef SAVE
2631#undef RESET
2632#undef ADD_RAW
2633#undef ADD_INT
2634}
2635
2636void CServer::CacheServerInfoSixup(CCache *pCache, bool SendClients, int MaxConsideredClients)
2637{
2638 pCache->Clear();
2639
2640 CPacker Packer;
2641 Packer.Reset();
2642
2643 // Could be moved to a separate function and cached
2644 // count the players
2645 int PlayerCount = 0, ClientCount = 0, ClientCountAll = 0;
2646 for(int i = 0; i < MAX_CLIENTS; i++)
2647 {
2648 if(m_aClients[i].IncludedInServerInfo())
2649 {
2650 ClientCountAll++;
2651 if(i < MaxConsideredClients)
2652 {
2653 if(GameServer()->IsClientPlayer(ClientId: i))
2654 PlayerCount++;
2655
2656 ClientCount++;
2657 }
2658 }
2659 }
2660
2661 // 0.7 protocol only supports up to LEGACY_MAX_CLIENTS clients.
2662 if(ClientCount >= LEGACY_MAX_CLIENTS)
2663 {
2664 const int MaxIncludedClients = ClientCountAll < m_NetServer.MaxClients() ? LEGACY_MAX_CLIENTS - 1 : LEGACY_MAX_CLIENTS;
2665 PlayerCount = 0;
2666 ClientCount = 0;
2667 for(int i = 0; i < MaxConsideredClients && ClientCount < MaxIncludedClients; i++)
2668 {
2669 if(m_aClients[i].IncludedInServerInfo())
2670 {
2671 if(GameServer()->IsClientPlayer(ClientId: i))
2672 PlayerCount++;
2673 ClientCount++;
2674 }
2675 }
2676 }
2677
2678 char aVersion[32];
2679 str_format(buffer: aVersion, buffer_size: sizeof(aVersion), format: "0.7↔%s", GameServer()->Version());
2680 Packer.AddString(pStr: aVersion, Limit: 32);
2681 if(!SendClients || (m_NetServer.MaxClients() <= LEGACY_MAX_CLIENTS && ClientCountAll == ClientCount))
2682 {
2683 Packer.AddString(pStr: Config()->m_SvName, Limit: 64);
2684 }
2685 else
2686 {
2687 char aName[64];
2688 str_format(buffer: aName, buffer_size: sizeof(aName), format: "%s [%d/%d]", Config()->m_SvName, ClientCountAll, m_NetServer.MaxClients() - Config()->m_SvReservedSlots);
2689 Packer.AddString(pStr: aName, Limit: 64);
2690 }
2691 Packer.AddString(pStr: Config()->m_SvHostname, Limit: 128);
2692 Packer.AddString(pStr: GameServer()->Map()->BaseName(), Limit: 32);
2693
2694 // gametype
2695 Packer.AddString(pStr: GameServer()->GameType(), Limit: 16);
2696
2697 // flags
2698 int Flags = SERVER_FLAG_TIMESCORE;
2699 if(Config()->m_Password[0]) // password set
2700 Flags |= SERVER_FLAG_PASSWORD;
2701 Packer.AddInt(i: Flags);
2702
2703 int MaxClients = m_NetServer.MaxClients();
2704 Packer.AddInt(i: Config()->m_SvSkillLevel); // server skill level
2705 Packer.AddInt(i: PlayerCount); // num players
2706 Packer.AddInt(i: std::min<int>(a: LEGACY_MAX_CLIENTS, b: std::max(a: MaxClients - std::max(a: Config()->m_SvSpectatorSlots, b: Config()->m_SvReservedSlots), b: PlayerCount))); // max players
2707 Packer.AddInt(i: ClientCount); // num clients
2708 Packer.AddInt(i: std::min<int>(a: LEGACY_MAX_CLIENTS, b: std::max(a: MaxClients - Config()->m_SvReservedSlots, b: ClientCount))); // max clients
2709
2710 if(SendClients)
2711 {
2712 int ClientsIncluded = 0;
2713 for(int i = 0; i < MaxConsideredClients && ClientsIncluded < ClientCount; i++)
2714 {
2715 if(m_aClients[i].IncludedInServerInfo())
2716 {
2717 ClientsIncluded++;
2718 Packer.AddString(pStr: ClientName(ClientId: i), Limit: MAX_NAME_LENGTH); // client name
2719 Packer.AddString(pStr: ClientClan(ClientId: i), Limit: MAX_CLAN_LENGTH); // client clan
2720 Packer.AddInt(i: m_aClients[i].m_Country); // client country (ISO 3166-1 numeric)
2721 Packer.AddInt(i: m_aClients[i].m_Score.value_or(u: -1)); // client score
2722 Packer.AddInt(i: GameServer()->IsClientPlayer(ClientId: i) ? 0 : 1); // flag spectator=1, bot=2 (player=0)
2723
2724 const int MaxPacketSize = NET_MAX_CONNLESS_PAYLOAD - 128;
2725 if(MaxConsideredClients == MAX_CLIENTS)
2726 {
2727 if(Packer.Size() > MaxPacketSize - 32) // -32 because repacking will increase the length of the name
2728 {
2729 // Server info is too large for a packet. Only include as many clients as fit.
2730 // We need to ensure that the client counts match, otherwise the 0.7 client
2731 // will ignore the info, so we repack but only consider the first i clients.
2732 CacheServerInfoSixup(pCache, SendClients: true, MaxConsideredClients: i);
2733 return;
2734 }
2735 }
2736 else
2737 {
2738 dbg_assert(Packer.Size() <= MaxPacketSize, "Max packet size exceeded while repacking. Packer.Size()=%d MaxPacketSize=%d", Packer.Size(), MaxPacketSize);
2739 }
2740 }
2741 }
2742 }
2743
2744 pCache->AddChunk(pData: Packer.Data(), Size: Packer.Size());
2745}
2746
2747void CServer::SendServerInfo(const NETADDR *pAddr, int Token, int Type, bool SendClients)
2748{
2749 CPacker p;
2750 char aBuf[128];
2751 p.Reset();
2752
2753 CCache *pCache = &m_aServerInfoCache[GetCacheIndex(Type, SendClient: SendClients)];
2754
2755#define ADD_RAW(p, x) (p).AddRaw(x, sizeof(x))
2756#define ADD_INT(p, x) \
2757 do \
2758 { \
2759 str_format(aBuf, sizeof(aBuf), "%d", x); \
2760 (p).AddString(aBuf, 0); \
2761 } while(0)
2762
2763 CNetChunk Packet;
2764 Packet.m_ClientId = -1;
2765 Packet.m_Address = *pAddr;
2766 Packet.m_Flags = NETSENDFLAG_CONNLESS;
2767
2768 for(const auto &Chunk : pCache->m_vCache)
2769 {
2770 p.Reset();
2771 if(Type == SERVERINFO_EXTENDED)
2772 {
2773 if(&Chunk == &pCache->m_vCache.front())
2774 p.AddRaw(pData: SERVERBROWSE_INFO_EXTENDED, Size: sizeof(SERVERBROWSE_INFO_EXTENDED));
2775 else
2776 p.AddRaw(pData: SERVERBROWSE_INFO_EXTENDED_MORE, Size: sizeof(SERVERBROWSE_INFO_EXTENDED_MORE));
2777 ADD_INT(p, Token);
2778 }
2779 else if(Type == SERVERINFO_64_LEGACY)
2780 {
2781 ADD_RAW(p, SERVERBROWSE_INFO_64_LEGACY);
2782 ADD_INT(p, Token);
2783 }
2784 else if(Type == SERVERINFO_VANILLA || Type == SERVERINFO_INGAME)
2785 {
2786 ADD_RAW(p, SERVERBROWSE_INFO);
2787 ADD_INT(p, Token);
2788 }
2789 else
2790 {
2791 dbg_assert_failed("Invalid serverinfo Type: %d", Type);
2792 }
2793
2794 p.AddRaw(pData: Chunk.m_vData.data(), Size: Chunk.m_vData.size());
2795 Packet.m_pData = p.Data();
2796 Packet.m_DataSize = p.Size();
2797 m_NetServer.Send(pChunk: &Packet);
2798 }
2799}
2800
2801void CServer::GetServerInfoSixup(CPacker *pPacker, bool SendClients)
2802{
2803 CCache::CCacheChunk &FirstChunk = m_aSixupServerInfoCache[SendClients].m_vCache.front();
2804 pPacker->AddRaw(pData: FirstChunk.m_vData.data(), Size: FirstChunk.m_vData.size());
2805}
2806
2807void CServer::FillAntibot(CAntibotRoundData *pData)
2808{
2809 for(int ClientId = 0; ClientId < MAX_CLIENTS; ClientId++)
2810 {
2811 CAntibotPlayerData *pPlayer = &pData->m_aPlayers[ClientId];
2812 if(m_aClients[ClientId].m_State == CServer::CClient::STATE_EMPTY)
2813 {
2814 pPlayer->m_aAddress[0] = '\0';
2815 }
2816 else
2817 {
2818 // No need for expensive str_copy since we don't truncate and the string is
2819 // ASCII anyway
2820 static_assert(std::size((CAntibotPlayerData{}).m_aAddress) >= NETADDR_MAXSTRSIZE);
2821 static_assert(std::is_same_v<decltype(CServer{}.ClientAddrStringImpl(ClientId, IncludePort: true)), const std::array<char, NETADDR_MAXSTRSIZE> &>);
2822 mem_copy(dest: pPlayer->m_aAddress, source: ClientAddrStringImpl(ClientId, IncludePort: true).data(), size: NETADDR_MAXSTRSIZE);
2823 pPlayer->m_Sixup = m_aClients[ClientId].m_Sixup;
2824 pPlayer->m_DnsblNone = m_aClients[ClientId].m_DnsblState == EDnsblState::NONE;
2825 pPlayer->m_DnsblPending = m_aClients[ClientId].m_DnsblState == EDnsblState::PENDING;
2826 pPlayer->m_DnsblBlacklisted = m_aClients[ClientId].m_DnsblState == EDnsblState::BLACKLISTED;
2827 pPlayer->m_Authed = IsRconAuthed(ClientId);
2828 }
2829 }
2830}
2831
2832void CServer::ExpireServerInfo()
2833{
2834 m_ServerInfoNeedsUpdate = true;
2835}
2836
2837void CServer::ExpireServerInfoAndQueueResend()
2838{
2839 m_ServerInfoNeedsUpdate = true;
2840 m_ServerInfoNeedsResend = true;
2841}
2842
2843void CServer::UpdateRegisterServerInfo()
2844{
2845 // count the players
2846 int PlayerCount = 0, ClientCount = 0;
2847 for(int i = 0; i < MAX_CLIENTS; i++)
2848 {
2849 if(m_aClients[i].IncludedInServerInfo())
2850 {
2851 if(GameServer()->IsClientPlayer(ClientId: i))
2852 PlayerCount++;
2853
2854 ClientCount++;
2855 }
2856 }
2857
2858 int MaxPlayers = std::max(a: m_NetServer.MaxClients() - std::max(a: g_Config.m_SvSpectatorSlots, b: g_Config.m_SvReservedSlots), b: PlayerCount);
2859 int MaxClients = std::max(a: m_NetServer.MaxClients() - g_Config.m_SvReservedSlots, b: ClientCount);
2860 char aMapSha256[SHA256_MAXSTRSIZE];
2861
2862 sha256_str(digest: m_aCurrentMapSha256[MAP_TYPE_SIX], str: aMapSha256, max_len: sizeof(aMapSha256));
2863
2864 CJsonStringWriter JsonWriter;
2865
2866 JsonWriter.BeginObject();
2867 JsonWriter.WriteAttribute(pName: "max_clients");
2868 JsonWriter.WriteIntValue(Value: MaxClients);
2869
2870 JsonWriter.WriteAttribute(pName: "max_players");
2871 JsonWriter.WriteIntValue(Value: MaxPlayers);
2872
2873 JsonWriter.WriteAttribute(pName: "passworded");
2874 JsonWriter.WriteBoolValue(Value: g_Config.m_Password[0]);
2875
2876 JsonWriter.WriteAttribute(pName: "game_type");
2877 JsonWriter.WriteStrValue(pValue: GameServer()->GameType());
2878
2879 if(g_Config.m_SvRegisterCommunityToken[0])
2880 {
2881 if(g_Config.m_SvFlag != -1)
2882 {
2883 JsonWriter.WriteAttribute(pName: "country");
2884 JsonWriter.WriteIntValue(Value: g_Config.m_SvFlag); // ISO 3166-1 numeric
2885 }
2886 }
2887
2888 JsonWriter.WriteAttribute(pName: "name");
2889 JsonWriter.WriteStrValue(pValue: g_Config.m_SvName);
2890
2891 JsonWriter.WriteAttribute(pName: "map");
2892 JsonWriter.BeginObject();
2893 JsonWriter.WriteAttribute(pName: "name");
2894 JsonWriter.WriteStrValue(pValue: GameServer()->Map()->BaseName());
2895 JsonWriter.WriteAttribute(pName: "sha256");
2896 JsonWriter.WriteStrValue(pValue: aMapSha256);
2897 JsonWriter.WriteAttribute(pName: "size");
2898 JsonWriter.WriteIntValue(Value: m_aCurrentMapSize[MAP_TYPE_SIX]);
2899 if(m_aMapDownloadUrl[0])
2900 {
2901 JsonWriter.WriteAttribute(pName: "url");
2902 JsonWriter.WriteStrValue(pValue: m_aMapDownloadUrl);
2903 }
2904 JsonWriter.EndObject();
2905
2906 JsonWriter.WriteAttribute(pName: "version");
2907 JsonWriter.WriteStrValue(pValue: GameServer()->Version());
2908
2909 JsonWriter.WriteAttribute(pName: "client_score_kind");
2910 JsonWriter.WriteStrValue(pValue: "time"); // "points" or "time"
2911
2912 JsonWriter.WriteAttribute(pName: "requires_login");
2913 JsonWriter.WriteBoolValue(Value: false);
2914
2915 {
2916 bool FoundFlags = false;
2917 auto Flag = [&](const char *pFlag) {
2918 if(!FoundFlags)
2919 {
2920 JsonWriter.WriteAttribute(pName: "flags");
2921 JsonWriter.BeginArray();
2922 FoundFlags = true;
2923 }
2924 JsonWriter.WriteStrValue(pValue: pFlag);
2925 };
2926
2927 if(g_Config.m_SvRegisterCommunityToken[0] && g_Config.m_SvOfficialTutorial[0])
2928 {
2929 SHA256_DIGEST Sha256 = sha256(message: g_Config.m_SvOfficialTutorial, message_len: str_length(str: g_Config.m_SvOfficialTutorial));
2930 char aSha256[SHA256_MAXSTRSIZE];
2931 sha256_str(digest: Sha256, str: aSha256, max_len: sizeof(aSha256));
2932 if(str_comp(a: aSha256, b: "8a11dc71274313e78a09ff58b8e696fb5009ce8606d12077ceb78ebf99a57464") == 0)
2933 {
2934 Flag("tutorial");
2935 }
2936 }
2937
2938 if(FoundFlags)
2939 {
2940 JsonWriter.EndArray();
2941 }
2942 }
2943
2944 JsonWriter.WriteAttribute(pName: "clients");
2945 JsonWriter.BeginArray();
2946
2947 for(int i = 0; i < MAX_CLIENTS; i++)
2948 {
2949 if(m_aClients[i].IncludedInServerInfo())
2950 {
2951 JsonWriter.BeginObject();
2952
2953 JsonWriter.WriteAttribute(pName: "name");
2954 JsonWriter.WriteStrValue(pValue: ClientName(ClientId: i));
2955
2956 JsonWriter.WriteAttribute(pName: "clan");
2957 JsonWriter.WriteStrValue(pValue: ClientClan(ClientId: i));
2958
2959 JsonWriter.WriteAttribute(pName: "country");
2960 JsonWriter.WriteIntValue(Value: m_aClients[i].m_Country); // ISO 3166-1 numeric
2961
2962 JsonWriter.WriteAttribute(pName: "score");
2963 JsonWriter.WriteIntValue(Value: m_aClients[i].m_Score.value_or(u: FinishTime::NOT_FINISHED_TIMESCORE));
2964
2965 JsonWriter.WriteAttribute(pName: "is_player");
2966 JsonWriter.WriteBoolValue(Value: GameServer()->IsClientPlayer(ClientId: i));
2967
2968 GameServer()->OnUpdatePlayerServerInfo(pJsonWriter: &JsonWriter, ClientId: i);
2969
2970 JsonWriter.EndObject();
2971 }
2972 }
2973
2974 JsonWriter.EndArray();
2975 JsonWriter.EndObject();
2976
2977 m_pRegister->OnNewInfo(pInfo: JsonWriter.GetOutputString().c_str());
2978}
2979
2980void CServer::UpdateServerInfo(bool Resend)
2981{
2982 if(m_RunServer == UNINITIALIZED)
2983 return;
2984
2985 UpdateRegisterServerInfo();
2986
2987 for(int i = 0; i < 3; i++)
2988 for(int j = 0; j < 2; j++)
2989 CacheServerInfo(pCache: &m_aServerInfoCache[i * 2 + j], Type: i, SendClients: j);
2990
2991 for(int i = 0; i < 2; i++)
2992 CacheServerInfoSixup(pCache: &m_aSixupServerInfoCache[i], SendClients: i, MaxConsideredClients: MAX_CLIENTS);
2993
2994 if(Resend)
2995 {
2996 for(int i = 0; i < MaxClients(); ++i)
2997 {
2998 if(m_aClients[i].m_State != CClient::STATE_EMPTY)
2999 {
3000 if(!IsSixup(ClientId: i))
3001 {
3002 SendServerInfo(pAddr: ClientAddr(ClientId: i), Token: -1, Type: SERVERINFO_INGAME, SendClients: false);
3003 }
3004 else
3005 {
3006 CMsgPacker ServerInfoMessage(protocol7::NETMSG_SERVERINFO, true, true);
3007 GetServerInfoSixup(pPacker: &ServerInfoMessage, SendClients: false);
3008 SendMsg(pMsg: &ServerInfoMessage, Flags: MSGFLAG_VITAL | MSGFLAG_FLUSH, ClientId: i);
3009 }
3010 }
3011 }
3012 m_ServerInfoNeedsResend = false;
3013 }
3014
3015 m_ServerInfoNeedsUpdate = false;
3016}
3017
3018int CServer::GetMaxClients(int ClientId) const
3019{
3020 // Shouldn't catch anything currently
3021 if(ClientId == SERVER_DEMO_CLIENT)
3022 return MAX_CLIENTS;
3023
3024 if(m_aClients[ClientId].m_Sixup)
3025 return LEGACY_MAX_CLIENTS;
3026 if(m_aClients[ClientId].m_DDNetVersion >= VERSION_DDNET_128_PLAYERS)
3027 return MAX_CLIENTS;
3028 if(m_aClients[ClientId].m_DDNetVersion >= VERSION_DDNET_OLD)
3029 return LEGACY_MAX_CLIENTS;
3030 return VANILLA_MAX_CLIENTS;
3031}
3032
3033bool CServer::ClientSupportsServerMaxClients(int ClientId) const
3034{
3035 // server demo pseudo clients operate on untranslated ids
3036 if(ClientId == SERVER_DEMO_CLIENT)
3037 return true;
3038
3039 // We can use `m_NetServer.MaxClients()` instead of `MAX_CLIENTS` here because it can't be changed ingame.
3040 // The playermapping code currently relies on sixup (0.7) clients taking the route through playermapping.
3041 return GetMaxClients(ClientId) >= m_NetServer.MaxClients() && !m_aClients[ClientId].m_Sixup;
3042}
3043
3044void CServer::PumpNetwork()
3045{
3046 CNetChunk Packet;
3047 SECURITY_TOKEN ResponseToken;
3048
3049 m_NetServer.Update();
3050
3051 // Coalesce the flushes triggered while handling this burst of incoming
3052 // packets (preinput broadcasts, timing/ping replies, ...) into one packet
3053 // per recipient, flushed once all packets have been handled below.
3054 m_NetServer.BeginFlushBatch();
3055
3056 // Receive unconditionally, `net_udp_recv()` can hold packets that
3057 // `net_socket_read_wait()` does not see.
3058 {
3059 // process packets
3060 ResponseToken = NET_SECURITY_TOKEN_UNKNOWN;
3061 while(m_NetServer.Recv(pChunk: &Packet, pResponseToken: &ResponseToken))
3062 {
3063 if(Packet.m_ClientId == -1)
3064 {
3065 if(ResponseToken == NET_SECURITY_TOKEN_UNKNOWN && m_pRegister->OnPacket(pPacket: &Packet))
3066 continue;
3067
3068 {
3069 int ExtraToken = 0;
3070 int Type = -1;
3071 if(Packet.m_DataSize >= (int)sizeof(SERVERBROWSE_GETINFO) + 1 &&
3072 mem_comp(a: Packet.m_pData, b: SERVERBROWSE_GETINFO, size: sizeof(SERVERBROWSE_GETINFO)) == 0)
3073 {
3074 if(Packet.m_Flags & NETSENDFLAG_EXTENDED)
3075 {
3076 Type = SERVERINFO_EXTENDED;
3077 ExtraToken = (Packet.m_aExtraData[0] << 8) | Packet.m_aExtraData[1];
3078 }
3079 else
3080 {
3081 Type = SERVERINFO_VANILLA;
3082 }
3083 }
3084 else if(Packet.m_DataSize >= (int)sizeof(SERVERBROWSE_GETINFO_64_LEGACY) + 1 &&
3085 mem_comp(a: Packet.m_pData, b: SERVERBROWSE_GETINFO_64_LEGACY, size: sizeof(SERVERBROWSE_GETINFO_64_LEGACY)) == 0)
3086 {
3087 Type = SERVERINFO_64_LEGACY;
3088 }
3089 if(Type == SERVERINFO_VANILLA && ResponseToken != NET_SECURITY_TOKEN_UNKNOWN && Config()->m_SvSixup)
3090 {
3091 CUnpacker Unpacker;
3092 Unpacker.Reset(pData: (unsigned char *)Packet.m_pData + sizeof(SERVERBROWSE_GETINFO), Size: Packet.m_DataSize - sizeof(SERVERBROWSE_GETINFO));
3093 int SrvBrwsToken = Unpacker.GetInt();
3094 if(Unpacker.Error())
3095 {
3096 continue;
3097 }
3098
3099 const std::optional<bool> SendClients = RateLimitServerInfoConnless();
3100 if(!SendClients.has_value())
3101 {
3102 continue;
3103 }
3104
3105 CPacker Packer;
3106 Packer.Reset();
3107 Packer.AddRaw(pData: SERVERBROWSE_INFO, Size: sizeof(SERVERBROWSE_INFO));
3108 Packer.AddInt(i: SrvBrwsToken);
3109 GetServerInfoSixup(pPacker: &Packer, SendClients: SendClients.value());
3110 CNetBase::SendPacketConnlessWithToken7(Socket: m_NetServer.Socket(), pAddr: &Packet.m_Address, pData: Packer.Data(), DataSize: Packer.Size(), Token: ResponseToken, ResponseToken: m_NetServer.GetToken(Addr: Packet.m_Address));
3111 }
3112 else if(Type != -1)
3113 {
3114 const std::optional<bool> SendClients = RateLimitServerInfoConnless();
3115 if(!SendClients.has_value())
3116 {
3117 continue;
3118 }
3119
3120 int Token = ((unsigned char *)Packet.m_pData)[sizeof(SERVERBROWSE_GETINFO)];
3121 Token |= ExtraToken << 8;
3122 SendServerInfo(pAddr: &Packet.m_Address, Token, Type, SendClients: SendClients.value());
3123 }
3124 }
3125 }
3126 else
3127 {
3128 if(m_aClients[Packet.m_ClientId].m_State == CClient::STATE_REDIRECTED)
3129 continue;
3130
3131 int GameFlags = 0;
3132 if(Packet.m_Flags & NET_CHUNKFLAG_VITAL)
3133 {
3134 GameFlags |= MSGFLAG_VITAL;
3135 }
3136 if(Antibot()->OnEngineClientMessage(ClientId: Packet.m_ClientId, pData: Packet.m_pData, Size: Packet.m_DataSize, Flags: GameFlags))
3137 {
3138 continue;
3139 }
3140
3141 ProcessClientPacket(pPacket: &Packet);
3142 }
3143 }
3144 }
3145 {
3146 unsigned char aBuffer[NET_MAX_CHUNK_SIZE];
3147 int Flags;
3148 mem_zero(block: &Packet, size: sizeof(Packet));
3149 Packet.m_pData = aBuffer;
3150 while(Antibot()->OnEngineSimulateClientMessage(pClientId: &Packet.m_ClientId, pBuffer: aBuffer, BufferSize: sizeof(aBuffer), pOutSize: &Packet.m_DataSize, pFlags: &Flags))
3151 {
3152 Packet.m_Flags = 0;
3153 if(Flags & MSGFLAG_VITAL)
3154 {
3155 Packet.m_Flags |= NET_CHUNKFLAG_VITAL;
3156 }
3157 ProcessClientPacket(pPacket: &Packet);
3158 }
3159 }
3160
3161 m_NetServer.EndFlushBatch();
3162
3163 m_ServerBan.Update();
3164 m_Econ.Update();
3165}
3166
3167void CServer::ChangeMap(const char *pMap)
3168{
3169 str_copy(dst&: Config()->m_SvMap, src: pMap);
3170 m_MapReload = str_comp(a: Config()->m_SvMap, b: GameServer()->Map()->FullName()) != 0;
3171}
3172
3173void CServer::ReloadMap()
3174{
3175 m_SameMapReload = true;
3176}
3177
3178int CServer::LoadMap(const char *pMapName)
3179{
3180 m_MapReload = false;
3181 m_SameMapReload = false;
3182
3183 char aBuf[IO_MAX_PATH_LENGTH];
3184 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "maps/%s.map", pMapName);
3185 if(!str_valid_filename(str: fs_filename(path: aBuf)))
3186 {
3187 log_error("server", "The name '%s' cannot be used for maps because not all platforms support it", aBuf);
3188 return 0;
3189 }
3190 if(!GameServer()->OnMapChange(pNewMapName: aBuf, MapNameSize: sizeof(aBuf)))
3191 {
3192 return 0;
3193 }
3194 if(!GameServer()->Map()->Load(pFullName: pMapName, pStorage: Storage(), pPath: aBuf, StorageType: IStorage::TYPE_ALL))
3195 {
3196 return 0;
3197 }
3198
3199 // reinit snapshot ids
3200 m_IdPool.TimeoutIds();
3201
3202 // get the crc of the map
3203 m_aCurrentMapSha256[MAP_TYPE_SIX] = GameServer()->Map()->Sha256();
3204 m_aCurrentMapCrc[MAP_TYPE_SIX] = GameServer()->Map()->Crc();
3205 char aBufMsg[256];
3206 char aSha256[SHA256_MAXSTRSIZE];
3207 sha256_str(digest: m_aCurrentMapSha256[MAP_TYPE_SIX], str: aSha256, max_len: sizeof(aSha256));
3208 str_format(buffer: aBufMsg, buffer_size: sizeof(aBufMsg), format: "%s sha256 is %s", aBuf, aSha256);
3209 Console()->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "server", pStr: aBufMsg);
3210
3211 // load complete map into memory for download
3212 {
3213 free(ptr: m_apCurrentMapData[MAP_TYPE_SIX]);
3214 void *pData;
3215 Storage()->ReadFile(pFilename: aBuf, Type: IStorage::TYPE_ALL, ppResult: &pData, pResultLen: &m_aCurrentMapSize[MAP_TYPE_SIX]);
3216 m_apCurrentMapData[MAP_TYPE_SIX] = (unsigned char *)pData;
3217 }
3218
3219 if(Config()->m_SvMapsBaseUrl[0])
3220 {
3221 char aEscaped[256];
3222 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s_%s.map", pMapName, aSha256);
3223 EscapeUrl(aBuf&: aEscaped, pStr: aBuf);
3224 str_format(buffer: m_aMapDownloadUrl, buffer_size: sizeof(m_aMapDownloadUrl), format: "%s%s", Config()->m_SvMapsBaseUrl, aEscaped);
3225 }
3226 else
3227 {
3228 m_aMapDownloadUrl[0] = '\0';
3229 }
3230
3231 // load sixup version of the map
3232 if(Config()->m_SvSixup)
3233 {
3234 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "maps7/%s.map", pMapName);
3235 void *pData;
3236 if(!Storage()->ReadFile(pFilename: aBuf, Type: IStorage::TYPE_ALL, ppResult: &pData, pResultLen: &m_aCurrentMapSize[MAP_TYPE_SIXUP]))
3237 {
3238 Config()->m_SvSixup = 0;
3239 if(m_pRegister)
3240 {
3241 m_pRegister->OnConfigChange();
3242 }
3243 log_error("sixup", "couldn't load map %s", aBuf);
3244 log_info("sixup", "disabling 0.7 compatibility");
3245 }
3246 else
3247 {
3248 free(ptr: m_apCurrentMapData[MAP_TYPE_SIXUP]);
3249 m_apCurrentMapData[MAP_TYPE_SIXUP] = (unsigned char *)pData;
3250
3251 m_aCurrentMapSha256[MAP_TYPE_SIXUP] = sha256(message: m_apCurrentMapData[MAP_TYPE_SIXUP], message_len: m_aCurrentMapSize[MAP_TYPE_SIXUP]);
3252 m_aCurrentMapCrc[MAP_TYPE_SIXUP] = crc32(crc: 0, buf: m_apCurrentMapData[MAP_TYPE_SIXUP], len: m_aCurrentMapSize[MAP_TYPE_SIXUP]);
3253 sha256_str(digest: m_aCurrentMapSha256[MAP_TYPE_SIXUP], str: aSha256, max_len: sizeof(aSha256));
3254 str_format(buffer: aBufMsg, buffer_size: sizeof(aBufMsg), format: "%s sha256 is %s", aBuf, aSha256);
3255 Console()->Print(Level: IConsole::OUTPUT_LEVEL_ADDINFO, pFrom: "sixup", pStr: aBufMsg);
3256 }
3257 }
3258 if(!Config()->m_SvSixup)
3259 {
3260 free(ptr: m_apCurrentMapData[MAP_TYPE_SIXUP]);
3261 m_apCurrentMapData[MAP_TYPE_SIXUP] = nullptr;
3262 }
3263
3264 for(int i = 0; i < MAX_CLIENTS; i++)
3265 m_aPrevStates[i] = m_aClients[i].m_State;
3266
3267 return 1;
3268}
3269
3270void CServer::UpdateDebugDummies(bool ForceDisconnect)
3271{
3272 if(m_PreviousDebugDummies == g_Config.m_DbgDummies && !ForceDisconnect)
3273 return;
3274
3275 g_Config.m_DbgDummies = std::clamp(val: g_Config.m_DbgDummies, lo: 0, hi: MaxClients());
3276 for(int DummyIndex = 0; DummyIndex < std::max(a: m_PreviousDebugDummies, b: g_Config.m_DbgDummies); ++DummyIndex)
3277 {
3278 const bool AddDummy = !ForceDisconnect && DummyIndex < g_Config.m_DbgDummies;
3279 const int ClientId = MaxClients() - DummyIndex - 1;
3280 CClient &Client = m_aClients[ClientId];
3281 if(AddDummy && m_aClients[ClientId].m_State == CClient::STATE_EMPTY)
3282 {
3283 NewClientCallback(ClientId, pUser: this, Sixup: false);
3284 Client.m_DebugDummy = true;
3285
3286 // See https://en.wikipedia.org/wiki/Unique_local_address
3287 Client.m_DebugDummyAddr.type = NETTYPE_IPV6;
3288 Client.m_DebugDummyAddr.ip[0] = 0xfd;
3289 // Global ID (40 bits): random
3290 secure_random_fill(bytes: &Client.m_DebugDummyAddr.ip[1], length: 5);
3291 // Subnet ID (16 bits): constant
3292 Client.m_DebugDummyAddr.ip[6] = 0xc0;
3293 Client.m_DebugDummyAddr.ip[7] = 0xde;
3294 // Interface ID (64 bits): set to client ID
3295 Client.m_DebugDummyAddr.ip[8] = 0x00;
3296 Client.m_DebugDummyAddr.ip[9] = 0x00;
3297 Client.m_DebugDummyAddr.ip[10] = 0x00;
3298 Client.m_DebugDummyAddr.ip[11] = 0x00;
3299 uint_to_bytes_be(bytes: &Client.m_DebugDummyAddr.ip[12], value: ClientId);
3300 // Port: random like normal clients
3301 Client.m_DebugDummyAddr.port = secure_rand_below(below: 65535 - 1024) + 1024;
3302 net_addr_str(addr: &Client.m_DebugDummyAddr, string: Client.m_aDebugDummyAddrString.data(), max_length: Client.m_aDebugDummyAddrString.size(), add_port: true);
3303 net_addr_str(addr: &Client.m_DebugDummyAddr, string: Client.m_aDebugDummyAddrStringNoPort.data(), max_length: Client.m_aDebugDummyAddrStringNoPort.size(), add_port: false);
3304
3305 GameServer()->OnClientConnected(ClientId, pPersistentData: nullptr);
3306 Client.m_State = CClient::STATE_INGAME;
3307 Client.m_DDNetVersion = DDNET_VERSION_NUMBER;
3308 Client.m_GotDDNetVersionPacket = true;
3309 Client.m_DDNetVersionSettled = true;
3310 char aDummyName[MAX_NAME_LENGTH];
3311 str_format(buffer: aDummyName, buffer_size: sizeof(aDummyName), format: "Debug dummy %d", DummyIndex + 1);
3312 SetClientName(ClientId, pName: aDummyName);
3313 GameServer()->OnClientEnter(ClientId);
3314 }
3315 else if(!AddDummy && Client.m_DebugDummy)
3316 {
3317 DelClientCallback(ClientId, pReason: "Dropping debug dummy", pUser: this);
3318 }
3319
3320 if(AddDummy && Client.m_DebugDummy)
3321 {
3322 CNetObj_PlayerInput Input = {.m_Direction: 0};
3323 Input.m_Direction = (ClientId & 1) ? -1 : 1;
3324 Client.m_aInputs[0].m_GameTick = Tick() + 1;
3325 mem_copy(dest: Client.m_aInputs[0].m_aData, source: &Input, size: std::min(a: sizeof(Input), b: sizeof(Client.m_aInputs[0].m_aData)));
3326 Client.m_LatestInput = Client.m_aInputs[0];
3327 Client.m_CurrentInput = 0;
3328 }
3329 }
3330
3331 m_PreviousDebugDummies = ForceDisconnect ? 0 : g_Config.m_DbgDummies;
3332}
3333
3334void CServer::WritePortFile()
3335{
3336 const char *pPortFile = Config()->m_SvPortFile;
3337 if(pPortFile[0] == '\0')
3338 {
3339 return;
3340 }
3341
3342 char aPortFileTmp[IO_MAX_PATH_LENGTH];
3343 IStorage::FormatTmpPath(aBuf: aPortFileTmp, BufSize: sizeof(aPortFileTmp), pPath: pPortFile);
3344 IOHANDLE PortFile = Storage()->OpenFile(pFilename: aPortFileTmp, Flags: IOFLAG_WRITE, Type: IStorage::TYPE_SAVE);
3345 if(PortFile != nullptr)
3346 {
3347 char aPort[8];
3348 const int Length = str_format(buffer: aPort, buffer_size: sizeof(aPort), format: "%d", m_NetServer.Address().port);
3349 const bool Written = io_write(io: PortFile, buffer: aPort, size: Length) == (unsigned)Length;
3350 if(io_close(io: PortFile) == 0 && Written &&
3351 Storage()->RenameFile(pOldFilename: aPortFileTmp, pNewFilename: pPortFile, Type: IStorage::TYPE_SAVE))
3352 {
3353 return;
3354 }
3355 Storage()->RemoveFile(pFilename: aPortFileTmp, Type: IStorage::TYPE_SAVE);
3356 }
3357 log_error("server", "Failed to write port file '%s'", pPortFile);
3358}
3359
3360int CServer::Run()
3361{
3362 if(m_RunServer == UNINITIALIZED)
3363 m_RunServer = RUNNING;
3364
3365 m_AuthManager.Init();
3366
3367 if(Config()->m_Debug)
3368 {
3369 g_UuidManager.DebugDump();
3370 }
3371
3372 {
3373 int Size = GameServer()->PersistentClientDataSize();
3374 for(auto &Client : m_aClients)
3375 {
3376 Client.m_HasPersistentData = false;
3377 Client.m_pPersistentData = malloc(size: Size);
3378 }
3379 }
3380 m_pPersistentData = malloc(size: GameServer()->PersistentDataSize());
3381
3382 // load map
3383 if(!LoadMap(pMapName: Config()->m_SvMap))
3384 {
3385 log_error("server", "failed to load map. mapname='%s'", Config()->m_SvMap);
3386 return -1;
3387 }
3388
3389 if(Config()->m_SvSqliteFile[0] != '\0')
3390 {
3391 if(!fs_is_relative_path(path: Config()->m_SvSqliteFile))
3392 {
3393 log_error("server", "sv_sqlite_file must be a relative path. path='%s'", Config()->m_SvSqliteFile);
3394 return -1;
3395 }
3396 char aFullPath[IO_MAX_PATH_LENGTH];
3397 Storage()->GetCompletePath(Type: IStorage::TYPE_SAVE, pDir: Config()->m_SvSqliteFile, pBuffer: aFullPath, BufferSize: sizeof(aFullPath));
3398
3399 if(Config()->m_SvUseSql)
3400 {
3401 DbPool()->RegisterSqliteDatabase(DatabaseMode: CDbConnectionPool::WRITE_BACKUP, aFilename: aFullPath);
3402 }
3403 else
3404 {
3405 DbPool()->RegisterSqliteDatabase(DatabaseMode: CDbConnectionPool::READ, aFilename: aFullPath);
3406 DbPool()->RegisterSqliteDatabase(DatabaseMode: CDbConnectionPool::WRITE, aFilename: aFullPath);
3407 }
3408 }
3409
3410 // start server
3411 NETADDR BindAddr;
3412 if(g_Config.m_Bindaddr[0] == '\0')
3413 {
3414 mem_zero(block: &BindAddr, size: sizeof(BindAddr));
3415 }
3416 else if(net_host_lookup(hostname: g_Config.m_Bindaddr, addr: &BindAddr, types: NETTYPE_ALL) != 0)
3417 {
3418 log_error("server", "The configured bindaddr '%s' cannot be resolved", g_Config.m_Bindaddr);
3419 return -1;
3420 }
3421 BindAddr.type = Config()->m_SvIpv4Only ? (NETTYPE_IPV4 | NETTYPE_WEBSOCKET_IPV4) : NETTYPE_ALL;
3422
3423 int Port = Config()->m_SvPort;
3424 for(BindAddr.port = Port != 0 ? Port : 8303; !m_NetServer.Open(BindAddr, pNetBan: &m_ServerBan, MaxClients: Config()->m_SvMaxClients, MaxClientsPerIp: Config()->m_SvMaxClientsPerIp); BindAddr.port++)
3425 {
3426 if(Port != 0 || BindAddr.port >= 8310)
3427 {
3428 log_error("server", "couldn't open socket. port %d might already be in use", BindAddr.port);
3429 return -1;
3430 }
3431 }
3432
3433 if(Port == 0)
3434 log_info("server", "using port %d", BindAddr.port);
3435
3436#if defined(CONF_UPNP)
3437 m_UPnP.Open(Address: BindAddr);
3438#endif
3439
3440 if(!m_pHttp->Init(ShutdownDelay: std::chrono::seconds{2}))
3441 {
3442 log_error("server", "Failed to initialize the HTTP client.");
3443 return -1;
3444 }
3445
3446 WritePortFile();
3447
3448 m_pEngine = Kernel()->RequestInterface<IEngine>();
3449 m_pRegister = CreateRegister(pConfig: &g_Config, pConsole: m_pConsole, pEngine: m_pEngine, pHttp: m_pHttp, ServerPort: g_Config.m_SvRegisterPort > 0 ? g_Config.m_SvRegisterPort : this->Port(), SixupSecurityToken: m_NetServer.GetGlobalToken());
3450
3451 m_NetServer.SetCallbacks(pfnNewClient: NewClientCallback, pfnNewClientNoAuth: NewClientNoAuthCallback, pfnClientRejoin: ClientRejoinCallback, pfnDelClient: DelClientCallback, pUser: this);
3452
3453 m_Econ.Init(pConfig: Config(), pConsole: Console(), pNetBan: &m_ServerBan);
3454
3455 m_Fifo.Init(pConsole: Console(), pFifoFile: Config()->m_SvInputFifo, Flag: CFGFLAG_SERVER);
3456
3457 char aBuf[256];
3458 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "server name is '%s'", Config()->m_SvName);
3459 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "server", pStr: aBuf);
3460
3461 Antibot()->Init();
3462 GameServer()->OnInit(pPersistentData: nullptr);
3463 if(ErrorShutdown())
3464 {
3465 m_RunServer = STOPPING;
3466 }
3467 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "server", pStr: "version " GAME_RELEASE_VERSION " on " CONF_PLATFORM_STRING " " CONF_ARCH_STRING);
3468 if(GIT_SHORTREV_HASH)
3469 {
3470 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "git revision hash: %s", GIT_SHORTREV_HASH);
3471 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "server", pStr: aBuf);
3472 }
3473
3474 ReadAnnouncementsFile();
3475 InitMaplist();
3476
3477 // process pending commands
3478 m_pConsole->StoreCommands(Store: false);
3479 m_pRegister->OnConfigChange();
3480
3481 if(m_AuthManager.IsGenerated())
3482 {
3483 log_info("server", "+-------------------------+");
3484 log_info("server", "| rcon password: '%s' |", Config()->m_SvRconPassword);
3485 log_info("server", "+-------------------------+");
3486 }
3487
3488 // start game
3489 {
3490 bool NonActive = false;
3491
3492 m_GameStartTime = time_get();
3493
3494 UpdateServerInfo(Resend: false);
3495 while(m_RunServer < STOPPING)
3496 {
3497 if(NonActive)
3498 PumpNetwork();
3499
3500 set_new_tick();
3501
3502 int64_t LastTime = time_get();
3503 int NewTicks = 0;
3504
3505 // load new map
3506 if(m_MapReload || m_SameMapReload || m_CurrentGameTick >= MAX_TICK) // force reload to make sure the ticks stay within a valid range
3507 {
3508 const bool SameMapReload = m_SameMapReload;
3509 // load map
3510 if(LoadMap(pMapName: Config()->m_SvMap))
3511 {
3512 // new map loaded
3513
3514 // ask the game for the data it wants to persist past a map change
3515 for(int i = 0; i < MAX_CLIENTS; i++)
3516 {
3517 if(m_aClients[i].IsKnownToGame())
3518 {
3519 m_aClients[i].m_HasPersistentData = GameServer()->OnClientDataPersist(ClientId: i, pData: m_aClients[i].m_pPersistentData);
3520 }
3521 }
3522
3523 UpdateDebugDummies(ForceDisconnect: true);
3524 GameServer()->OnShutdown(pPersistentData: m_pPersistentData);
3525
3526 for(int ClientId = 0; ClientId < MAX_CLIENTS; ClientId++)
3527 {
3528 if(m_aClients[ClientId].m_State <= CClient::STATE_AUTH)
3529 continue;
3530
3531 if(SameMapReload)
3532 SendMapReload(ClientId);
3533
3534 SendMap(ClientId);
3535 bool HasPersistentData = m_aClients[ClientId].m_HasPersistentData;
3536 m_aClients[ClientId].Reset();
3537 m_aClients[ClientId].m_HasPersistentData = HasPersistentData;
3538 m_aClients[ClientId].m_State = CClient::STATE_CONNECTING;
3539 }
3540
3541 m_GameStartTime = time_get();
3542 m_CurrentGameTick = MIN_TICK;
3543 Kernel()->ReregisterInterface(pInterface: GameServer());
3544 Console()->StoreCommands(Store: true);
3545 GameServer()->OnInit(pPersistentData: m_pPersistentData);
3546 Console()->StoreCommands(Store: false);
3547
3548 for(int ClientId = 0; ClientId < MAX_CLIENTS; ClientId++)
3549 {
3550 CClient &Client = m_aClients[ClientId];
3551 if(Client.m_State < CClient::STATE_PREAUTH)
3552 continue;
3553
3554 // When doing a map change, a new Teehistorian file is created. For players that are already
3555 // on the server, no PlayerJoin event is produced in Teehistorian from the network engine.
3556 // Record PlayerJoin events here to record the Sixup version and player join event.
3557 GameServer()->TeehistorianRecordPlayerJoin(ClientId, Sixup: Client.m_Sixup);
3558
3559 // Record the players auth state aswell if needed.
3560 // This was recorded in AuthInit in the past.
3561 if(IsRconAuthed(ClientId))
3562 {
3563 GameServer()->TeehistorianRecordAuthLogin(
3564 ClientId,
3565 pRoleName: CAuthManager::AuthLevelToRoleName(AuthLevel: GetAuthedState(ClientId)),
3566 pAuthName: GetAuthName(ClientId));
3567 }
3568 }
3569
3570 if(ErrorShutdown())
3571 {
3572 break;
3573 }
3574 ExpireServerInfo();
3575 }
3576 else
3577 {
3578 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "failed to load map. mapname='%s'", Config()->m_SvMap);
3579 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "server", pStr: aBuf);
3580 str_copy(dst&: Config()->m_SvMap, src: GameServer()->Map()->FullName());
3581 }
3582 }
3583
3584 while(LastTime > TickStartTime(Tick: m_CurrentGameTick + 1))
3585 {
3586 GameServer()->OnPreTickTeehistorian();
3587 UpdateDebugDummies(ForceDisconnect: false);
3588
3589 const CClient::CInput *apInput[MAX_CLIENTS] = {};
3590 for(int ClientId = 0; ClientId < MAX_CLIENTS; ClientId++)
3591 {
3592 if(m_aClients[ClientId].m_State != CClient::STATE_INGAME)
3593 continue;
3594 for(const auto &Input : m_aClients[ClientId].m_aInputs)
3595 {
3596 if(Input.m_GameTick == Tick() + 1)
3597 {
3598 apInput[ClientId] = &Input;
3599 break;
3600 }
3601 }
3602 GameServer()->OnClientPredictedEarlyInput(ClientId, pInput: apInput[ClientId] == nullptr ? nullptr : apInput[ClientId]->m_aData);
3603 }
3604
3605 m_CurrentGameTick++;
3606 NewTicks++;
3607
3608 // apply new input
3609 for(int ClientId = 0; ClientId < MAX_CLIENTS; ClientId++)
3610 {
3611 if(m_aClients[ClientId].m_State != CClient::STATE_INGAME)
3612 continue;
3613 GameServer()->OnClientPredictedInput(ClientId, pInput: apInput[ClientId] == nullptr ? nullptr : apInput[ClientId]->m_aData);
3614 }
3615
3616 GameServer()->OnTick();
3617 if(ErrorShutdown())
3618 {
3619 break;
3620 }
3621 }
3622
3623 // snap game
3624 if(NewTicks)
3625 {
3626 DoSnapshot();
3627
3628 const int CommandSendingClientId = Tick() % MAX_CLIENTS;
3629 UpdateClientRconCommands(ClientId: CommandSendingClientId);
3630 UpdateClientMaplistEntries(ClientId: CommandSendingClientId);
3631
3632 m_Fifo.Update();
3633
3634#if defined(CONF_PLATFORM_ANDROID)
3635 std::vector<std::string> vAndroidCommandQueue = FetchAndroidServerCommandQueue();
3636 for(const std::string &Command : vAndroidCommandQueue)
3637 {
3638 Console()->ExecuteLineFlag(Command.c_str(), CFGFLAG_SERVER, IConsole::CLIENT_ID_UNSPECIFIED);
3639 }
3640#endif
3641
3642 // master server stuff
3643 m_pRegister->Update();
3644
3645 if(m_ServerInfoNeedsUpdate)
3646 {
3647 UpdateServerInfo(Resend: m_ServerInfoNeedsResend);
3648 }
3649
3650 Antibot()->OnEngineTick();
3651
3652 // handle dnsbl
3653 if(Config()->m_SvDnsbl)
3654 {
3655 for(int ClientId = 0; ClientId < MAX_CLIENTS; ClientId++)
3656 {
3657 if(m_aClients[ClientId].m_State == CClient::STATE_EMPTY)
3658 continue;
3659
3660 if(m_aClients[ClientId].m_DnsblState == EDnsblState::NONE)
3661 {
3662 // initiate dnsbl lookup
3663 InitDnsbl(ClientId);
3664 }
3665 else if(m_aClients[ClientId].m_DnsblState == EDnsblState::PENDING &&
3666 m_aClients[ClientId].m_pDnsblLookup->State() == IJob::STATE_DONE)
3667 {
3668 if(m_aClients[ClientId].m_pDnsblLookup->Result() != 0)
3669 {
3670 // entry not found -> whitelisted
3671 m_aClients[ClientId].m_DnsblState = EDnsblState::WHITELISTED;
3672
3673 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "ClientId=%d addr=<{%s}> secure=%s whitelisted", ClientId, ClientAddrString(ClientId, IncludePort: true), m_NetServer.HasSecurityToken(ClientId) ? "yes" : "no");
3674 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "dnsbl", pStr: aBuf);
3675 }
3676 else
3677 {
3678 // entry found -> blacklisted
3679 m_aClients[ClientId].m_DnsblState = EDnsblState::BLACKLISTED;
3680
3681 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "ClientId=%d addr=<{%s}> secure=%s blacklisted", ClientId, ClientAddrString(ClientId, IncludePort: true), m_NetServer.HasSecurityToken(ClientId) ? "yes" : "no");
3682 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "dnsbl", pStr: aBuf);
3683
3684 if(Config()->m_SvDnsblBan)
3685 {
3686 m_NetServer.NetBan()->BanAddr(pAddr: ClientAddr(ClientId), Seconds: 60, pReason: Config()->m_SvDnsblBanReason, VerbatimReason: true);
3687 }
3688 }
3689 }
3690 }
3691 }
3692 for(int i = 0; i < MAX_CLIENTS; ++i)
3693 {
3694 if(m_aClients[i].m_State == CClient::STATE_REDIRECTED)
3695 {
3696 if(time_get() > m_aClients[i].m_RedirectDropTime)
3697 {
3698 m_NetServer.Drop(ClientId: i, pReason: "redirected");
3699 }
3700 }
3701 }
3702 }
3703
3704 if(!NonActive)
3705 PumpNetwork();
3706
3707 NonActive = true;
3708 for(const auto &Client : m_aClients)
3709 {
3710 if(Client.m_State != CClient::STATE_EMPTY)
3711 {
3712 NonActive = false;
3713 break;
3714 }
3715 }
3716
3717 if(NonActive)
3718 {
3719 if(Config()->m_SvReloadWhenEmpty == 1)
3720 {
3721 m_MapReload = true;
3722 Config()->m_SvReloadWhenEmpty = 0;
3723 }
3724 else if(Config()->m_SvReloadWhenEmpty == 2 && !m_ReloadedWhenEmpty)
3725 {
3726 m_MapReload = true;
3727 m_ReloadedWhenEmpty = true;
3728 }
3729 }
3730 else
3731 {
3732 m_ReloadedWhenEmpty = false;
3733 }
3734
3735 // wait for incoming data
3736 if(NonActive && Config()->m_SvShutdownWhenEmpty)
3737 {
3738 m_RunServer = STOPPING;
3739 }
3740 else if(NonActive &&
3741 !m_aDemoRecorder[RECORDER_MANUAL].IsRecording() &&
3742 !m_aDemoRecorder[RECORDER_AUTO].IsRecording())
3743 {
3744 net_socket_read_wait(sock: m_NetServer.Socket(), nanoseconds: 1s);
3745 }
3746 else
3747 {
3748 set_new_tick();
3749 LastTime = time_get();
3750 const auto MicrosecondsToWait = std::chrono::duration_cast<std::chrono::microseconds>(d: std::chrono::nanoseconds(TickStartTime(Tick: m_CurrentGameTick + 1) - LastTime)) + 1us;
3751 if(MicrosecondsToWait > 0us)
3752 net_socket_read_wait(sock: m_NetServer.Socket(), nanoseconds: MicrosecondsToWait);
3753 }
3754 if(IsInterrupted())
3755 {
3756 Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "server", pStr: "interrupted");
3757 break;
3758 }
3759 }
3760 }
3761 const char *pDisconnectReason = "Server shutdown";
3762 if(m_aShutdownReason[0])
3763 pDisconnectReason = m_aShutdownReason;
3764
3765 if(ErrorShutdown())
3766 {
3767 log_info("server", "shutdown from game server (%s)", m_aErrorShutdownReason);
3768 pDisconnectReason = m_aErrorShutdownReason;
3769 }
3770 // disconnect all clients on shutdown
3771 for(int i = 0; i < MAX_CLIENTS; ++i)
3772 {
3773 if(m_aClients[i].m_State != CClient::STATE_EMPTY)
3774 m_NetServer.Drop(ClientId: i, pReason: pDisconnectReason);
3775 }
3776
3777 m_pRegister->OnShutdown();
3778 m_Econ.Shutdown();
3779 m_Fifo.Shutdown();
3780 m_pHttp->Shutdown();
3781 Engine()->ShutdownJobs();
3782
3783 GameServer()->OnShutdown(pPersistentData: nullptr);
3784 GameServer()->Map()->Unload();
3785 DbPool()->OnShutdown();
3786
3787#if defined(CONF_UPNP)
3788 m_UPnP.Shutdown();
3789#endif
3790 m_NetServer.Close();
3791
3792 return ErrorShutdown();
3793}
3794
3795void CServer::ConKick(IConsole::IResult *pResult, void *pUser)
3796{
3797 if(pResult->NumArguments() > 1)
3798 {
3799 char aBuf[128];
3800 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Kicked (%s)", pResult->GetString(Index: 1));
3801 ((CServer *)pUser)->Kick(ClientId: pResult->GetVictim(Slot: 0), pReason: aBuf);
3802 }
3803 else
3804 {
3805 ((CServer *)pUser)->Kick(ClientId: pResult->GetVictim(Slot: 0), pReason: "Kicked by console");
3806 }
3807}
3808
3809void CServer::ConStatus(IConsole::IResult *pResult, void *pUser)
3810{
3811 char aBuf[1024];
3812 CServer *pThis = static_cast<CServer *>(pUser);
3813 const char *pName = pResult->NumArguments() == 1 ? pResult->GetString(Index: 0) : "";
3814
3815 for(int i = 0; i < MAX_CLIENTS; i++)
3816 {
3817 if(pThis->m_aClients[i].m_State == CClient::STATE_EMPTY)
3818 continue;
3819
3820 if(!str_utf8_find_nocase(haystack: pThis->m_aClients[i].m_aName, needle: pName))
3821 continue;
3822
3823 if(pThis->m_aClients[i].IsKnownToGame())
3824 {
3825 char aDnsblStr[64];
3826 aDnsblStr[0] = '\0';
3827 if(pThis->Config()->m_SvDnsbl)
3828 {
3829 str_format(buffer: aDnsblStr, buffer_size: sizeof(aDnsblStr), format: " dnsbl=%s", DnsblStateStr(State: pThis->m_aClients[i].m_DnsblState));
3830 }
3831
3832 char aAuthStr[128];
3833 aAuthStr[0] = '\0';
3834 if(pThis->m_aClients[i].m_AuthKey >= 0)
3835 {
3836 const char *pAuthStr = "";
3837 const int AuthState = pThis->GetAuthedState(ClientId: i);
3838
3839 if(AuthState == AUTHED_ADMIN)
3840 {
3841 pAuthStr = "(Admin)";
3842 }
3843 else if(AuthState == AUTHED_MOD)
3844 {
3845 pAuthStr = "(Mod)";
3846 }
3847 else if(AuthState == AUTHED_HELPER)
3848 {
3849 pAuthStr = "(Helper)";
3850 }
3851
3852 str_format(buffer: aAuthStr, buffer_size: sizeof(aAuthStr), format: " key='%s' %s", pThis->m_AuthManager.KeyIdent(Slot: pThis->m_aClients[i].m_AuthKey), pAuthStr);
3853 }
3854
3855 const char *pClientPrefix = "";
3856 if(pThis->m_aClients[i].m_Sixup)
3857 {
3858 pClientPrefix = "0.7:";
3859 }
3860 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "id=%d addr=<{%s}> name='%s' client=%s%d secure=%s flags=%d%s%s",
3861 i, pThis->ClientAddrString(ClientId: i, IncludePort: true), pThis->m_aClients[i].m_aName, pClientPrefix, pThis->m_aClients[i].m_DDNetVersion,
3862 pThis->m_NetServer.HasSecurityToken(ClientId: i) ? "yes" : "no", pThis->m_aClients[i].m_Flags, aDnsblStr, aAuthStr);
3863 }
3864 else
3865 {
3866 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "id=%d addr=<{%s}> connecting", i, pThis->ClientAddrString(ClientId: i, IncludePort: true));
3867 }
3868 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "server", pStr: aBuf);
3869 }
3870}
3871
3872static int GetAuthLevel(const char *pLevel)
3873{
3874 int Level = -1;
3875 if(!str_comp_nocase(a: pLevel, b: "admin"))
3876 Level = AUTHED_ADMIN;
3877 else if(str_startswith(str: pLevel, prefix: "mod"))
3878 Level = AUTHED_MOD;
3879 else if(!str_comp_nocase(a: pLevel, b: "helper"))
3880 Level = AUTHED_HELPER;
3881
3882 return Level;
3883}
3884
3885bool CServer::CanClientUseCommandCallback(int ClientId, const IConsole::ICommandInfo *pCommand, void *pUser)
3886{
3887 return ((CServer *)pUser)->CanClientUseCommand(ClientId, pCommand);
3888}
3889
3890bool CServer::CanClientUseCommand(int ClientId, const IConsole::ICommandInfo *pCommand) const
3891{
3892 // make sure we don't affect the wrong client, disallow id targeting commands when a moderator is using id translation
3893 if(pCommand->TakesClientId() && !ClientSupportsServerMaxClients(ClientId))
3894 return false;
3895 if(pCommand->Flags() & CFGFLAG_CHAT)
3896 return true;
3897 if(pCommand->Flags() & CMDFLAG_PRACTICE)
3898 return true;
3899 if(!IsRconAuthed(ClientId))
3900 return false;
3901 return pCommand->GetAccessLevel() >= ConsoleAccessLevel(ClientId);
3902}
3903
3904void CServer::AuthRemoveKey(int KeySlot)
3905{
3906 m_AuthManager.RemoveKey(Slot: KeySlot);
3907 LogoutKey(Key: KeySlot, pReason: "key removal");
3908
3909 // Update indices.
3910 for(auto &Client : m_aClients)
3911 {
3912 if(Client.m_AuthKey == KeySlot)
3913 {
3914 Client.m_AuthKey = -1;
3915 }
3916 else if(Client.m_AuthKey > KeySlot)
3917 {
3918 --Client.m_AuthKey;
3919 }
3920 }
3921}
3922
3923void CServer::ConAuthAdd(IConsole::IResult *pResult, void *pUser)
3924{
3925 CServer *pThis = (CServer *)pUser;
3926 CAuthManager *pManager = &pThis->m_AuthManager;
3927
3928 const char *pIdent = pResult->GetString(Index: 0);
3929 const char *pLevel = pResult->GetString(Index: 1);
3930 const char *pPw = pResult->GetString(Index: 2);
3931
3932 if(!pManager->IsValidIdent(pIdent))
3933 {
3934 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "ident is invalid");
3935 return;
3936 }
3937
3938 int Level = GetAuthLevel(pLevel);
3939 if(Level == -1)
3940 {
3941 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "level can be one of {\"admin\", \"mod(erator)\", \"helper\"}");
3942 return;
3943 }
3944 // back compat to change "mod", "modder" and so on as parameters to "moderator"
3945 pLevel = CAuthManager::AuthLevelToRoleName(AuthLevel: Level);
3946
3947 bool NeedUpdate = !pManager->NumNonDefaultKeys();
3948 if(pManager->AddKey(pIdent, pPw, pRoleName: pLevel) < 0)
3949 {
3950 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "ident already exists");
3951 }
3952 else
3953 {
3954 if(NeedUpdate)
3955 pThis->SendRconType(ClientId: -1, UsernameReq: true);
3956 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "key added");
3957 }
3958}
3959
3960void CServer::ConAuthAddHashed(IConsole::IResult *pResult, void *pUser)
3961{
3962 CServer *pThis = (CServer *)pUser;
3963 CAuthManager *pManager = &pThis->m_AuthManager;
3964
3965 const char *pIdent = pResult->GetString(Index: 0);
3966 const char *pLevel = pResult->GetString(Index: 1);
3967 const char *pPw = pResult->GetString(Index: 2);
3968 const char *pSalt = pResult->GetString(Index: 3);
3969
3970 if(!pManager->IsValidIdent(pIdent))
3971 {
3972 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "ident is invalid");
3973 return;
3974 }
3975
3976 int Level = GetAuthLevel(pLevel);
3977 if(Level == -1)
3978 {
3979 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "level can be one of {\"admin\", \"mod(erator)\", \"helper\"}");
3980 return;
3981 }
3982 // back compat to change "mod", "modder" and so on as parameters to "moderator"
3983 pLevel = CAuthManager::AuthLevelToRoleName(AuthLevel: Level);
3984
3985 MD5_DIGEST Hash;
3986 unsigned char aSalt[SALT_BYTES];
3987
3988 if(md5_from_str(out: &Hash, str: pPw))
3989 {
3990 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "Malformed password hash");
3991 return;
3992 }
3993 if(str_hex_decode(dst: aSalt, dst_size: sizeof(aSalt), src: pSalt))
3994 {
3995 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "Malformed salt hash");
3996 return;
3997 }
3998
3999 bool NeedUpdate = !pManager->NumNonDefaultKeys();
4000
4001 if(pManager->AddKeyHash(pIdent, Hash, pSalt: aSalt, pRoleName: pLevel) < 0)
4002 {
4003 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "ident already exists");
4004 }
4005 else
4006 {
4007 if(NeedUpdate)
4008 pThis->SendRconType(ClientId: -1, UsernameReq: true);
4009 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "key added");
4010 }
4011}
4012
4013void CServer::ConAuthUpdate(IConsole::IResult *pResult, void *pUser)
4014{
4015 CServer *pThis = (CServer *)pUser;
4016 CAuthManager *pManager = &pThis->m_AuthManager;
4017
4018 const char *pIdent = pResult->GetString(Index: 0);
4019 const char *pLevel = pResult->GetString(Index: 1);
4020 const char *pPw = pResult->GetString(Index: 2);
4021
4022 int KeySlot = pManager->FindKey(pIdent);
4023 if(KeySlot == -1)
4024 {
4025 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "ident couldn't be found");
4026 return;
4027 }
4028
4029 int Level = GetAuthLevel(pLevel);
4030 if(Level == -1)
4031 {
4032 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "level can be one of {\"admin\", \"mod(erator)\", \"helper\"}");
4033 return;
4034 }
4035 // back compat to change "mod", "modder" and so on as parameters to "moderator"
4036 pLevel = CAuthManager::AuthLevelToRoleName(AuthLevel: Level);
4037
4038 pManager->UpdateKey(Slot: KeySlot, pPw, pRoleName: pLevel);
4039 pThis->LogoutKey(Key: KeySlot, pReason: "key update");
4040
4041 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "key updated");
4042}
4043
4044void CServer::ConAuthUpdateHashed(IConsole::IResult *pResult, void *pUser)
4045{
4046 CServer *pThis = (CServer *)pUser;
4047 CAuthManager *pManager = &pThis->m_AuthManager;
4048
4049 const char *pIdent = pResult->GetString(Index: 0);
4050 const char *pLevel = pResult->GetString(Index: 1);
4051 const char *pPw = pResult->GetString(Index: 2);
4052 const char *pSalt = pResult->GetString(Index: 3);
4053
4054 int KeySlot = pManager->FindKey(pIdent);
4055 if(KeySlot == -1)
4056 {
4057 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "ident couldn't be found");
4058 return;
4059 }
4060
4061 int Level = GetAuthLevel(pLevel);
4062 if(Level == -1)
4063 {
4064 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "level can be one of {\"admin\", \"mod(erator)\", \"helper\"}");
4065 return;
4066 }
4067 // back compat to change "mod", "modder" and so on as parameters to "moderator"
4068 pLevel = CAuthManager::AuthLevelToRoleName(AuthLevel: Level);
4069
4070 MD5_DIGEST Hash;
4071 unsigned char aSalt[SALT_BYTES];
4072
4073 if(md5_from_str(out: &Hash, str: pPw))
4074 {
4075 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "Malformed password hash");
4076 return;
4077 }
4078 if(str_hex_decode(dst: aSalt, dst_size: sizeof(aSalt), src: pSalt))
4079 {
4080 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "Malformed salt hash");
4081 return;
4082 }
4083
4084 pManager->UpdateKeyHash(Slot: KeySlot, Hash, pSalt: aSalt, pRoleName: pLevel);
4085 pThis->LogoutKey(Key: KeySlot, pReason: "key update");
4086
4087 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "key updated");
4088}
4089
4090void CServer::ConAuthRemove(IConsole::IResult *pResult, void *pUser)
4091{
4092 CServer *pThis = (CServer *)pUser;
4093 CAuthManager *pManager = &pThis->m_AuthManager;
4094
4095 const char *pIdent = pResult->GetString(Index: 0);
4096
4097 int KeySlot = pManager->FindKey(pIdent);
4098 if(KeySlot == -1)
4099 {
4100 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "ident couldn't be found");
4101 return;
4102 }
4103
4104 pThis->AuthRemoveKey(KeySlot);
4105
4106 if(!pManager->NumNonDefaultKeys())
4107 pThis->SendRconType(ClientId: -1, UsernameReq: false);
4108
4109 pThis->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "auth", pStr: "key removed, all users logged out");
4110}
4111
4112static void ListKeysCallback(const char *pIdent, const char *pRoleName, void *pUser)
4113{
4114 log_info("auth", "%s %s", pIdent, pRoleName);
4115}
4116
4117void CServer::ConAuthList(IConsole::IResult *pResult, void *pUser)
4118{
4119 CServer *pThis = (CServer *)pUser;
4120 CAuthManager *pManager = &pThis->m_AuthManager;
4121
4122 pManager->ListKeys(pfnListCallback: ListKeysCallback, pUser: pThis);
4123}
4124
4125void CServer::ConShutdown(IConsole::IResult *pResult, void *pUser)
4126{
4127 CServer *pThis = static_cast<CServer *>(pUser);
4128 pThis->m_RunServer = STOPPING;
4129 const char *pReason = pResult->GetString(Index: 0);
4130 if(pReason[0])
4131 {
4132 str_copy(dst&: pThis->m_aShutdownReason, src: pReason);
4133 }
4134}
4135
4136void CServer::ConUptime(IConsole::IResult *pResult, void *pUser)
4137{
4138 CServer *pThis = static_cast<CServer *>(pUser);
4139 // str_time expects centiseconds, convert directly to avoid overflow
4140 const int64_t UptimeCentisecs = (time_get() - pThis->m_StartTime) / (time_freq() / 100);
4141 char aTime[64];
4142 str_time(centisecs: UptimeCentisecs, format: ETimeFormat::DAYS, buffer: aTime, buffer_size: sizeof(aTime));
4143 log_info("server", "Uptime %s", aTime);
4144}
4145
4146void CServer::DemoRecorder_HandleAutoStart()
4147{
4148 if(Config()->m_SvAutoDemoRecord)
4149 {
4150 m_aDemoRecorder[RECORDER_AUTO].Stop(Mode: IDemoRecorder::EStopMode::KEEP_FILE);
4151
4152 char aTimestamp[20];
4153 str_timestamp(buffer: aTimestamp, buffer_size: sizeof(aTimestamp));
4154 char aFilename[IO_MAX_PATH_LENGTH];
4155 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "demos/auto/server/%s_%s.demo", GameServer()->Map()->BaseName(), aTimestamp);
4156 m_aDemoRecorder[RECORDER_AUTO].Start(
4157 pStorage: Storage(),
4158 pFilename: aFilename,
4159 pNetversion: GameServer()->NetVersion(),
4160 pMap: GameServer()->Map()->BaseName(),
4161 Sha256: m_aCurrentMapSha256[MAP_TYPE_SIX],
4162 MapCrc: m_aCurrentMapCrc[MAP_TYPE_SIX],
4163 pType: "server",
4164 MapSize: m_aCurrentMapSize[MAP_TYPE_SIX],
4165 pMapData: m_apCurrentMapData[MAP_TYPE_SIX],
4166 MapFile: nullptr,
4167 pfnFilter: nullptr,
4168 pUser: nullptr);
4169
4170 if(Config()->m_SvAutoDemoMax)
4171 {
4172 // clean up auto recorded demos
4173 CFileCollection AutoDemos;
4174 AutoDemos.Init(pStorage: Storage(), pPath: "demos/auto/server", pFileDesc: "", pFileExt: ".demo", MaxEntries: Config()->m_SvAutoDemoMax);
4175 }
4176 }
4177}
4178
4179void CServer::SaveDemo(int ClientId, float Time)
4180{
4181 if(IsRecording(ClientId))
4182 {
4183 char aPlayerName[MAX_NAME_LENGTH];
4184 str_copy(dst&: aPlayerName, src: m_aClients[ClientId].m_aName);
4185 str_sanitize_filename(str: aPlayerName);
4186 char aNewFilename[IO_MAX_PATH_LENGTH];
4187 str_format(buffer: aNewFilename, buffer_size: sizeof(aNewFilename), format: "demos/%s_%s_%05.2f.demo", GameServer()->Map()->BaseName(), aPlayerName, Time);
4188 m_aDemoRecorder[ClientId].Stop(Mode: IDemoRecorder::EStopMode::KEEP_FILE, pTargetFilename: aNewFilename);
4189 }
4190}
4191
4192void CServer::StartRecord(int ClientId)
4193{
4194 if(Config()->m_SvPlayerDemoRecord)
4195 {
4196 char aFilename[IO_MAX_PATH_LENGTH];
4197 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "demos/%s_%d_%d_tmp.demo", GameServer()->Map()->BaseName(), m_NetServer.Address().port, ClientId);
4198 m_aDemoRecorder[ClientId].Start(
4199 pStorage: Storage(),
4200 pFilename: aFilename,
4201 pNetversion: GameServer()->NetVersion(),
4202 pMap: GameServer()->Map()->BaseName(),
4203 Sha256: m_aCurrentMapSha256[MAP_TYPE_SIX],
4204 MapCrc: m_aCurrentMapCrc[MAP_TYPE_SIX],
4205 pType: "server",
4206 MapSize: m_aCurrentMapSize[MAP_TYPE_SIX],
4207 pMapData: m_apCurrentMapData[MAP_TYPE_SIX],
4208 MapFile: nullptr,
4209 pfnFilter: nullptr,
4210 pUser: nullptr);
4211 }
4212}
4213
4214void CServer::StopRecord(int ClientId)
4215{
4216 if(IsRecording(ClientId))
4217 {
4218 m_aDemoRecorder[ClientId].Stop(Mode: IDemoRecorder::EStopMode::REMOVE_FILE);
4219 }
4220}
4221
4222bool CServer::IsRecording(int ClientId)
4223{
4224 return m_aDemoRecorder[ClientId].IsRecording();
4225}
4226
4227void CServer::StopDemos()
4228{
4229 for(int i = 0; i < NUM_RECORDERS; i++)
4230 {
4231 if(!m_aDemoRecorder[i].IsRecording())
4232 continue;
4233
4234 m_aDemoRecorder[i].Stop(Mode: i < MAX_CLIENTS ? IDemoRecorder::EStopMode::REMOVE_FILE : IDemoRecorder::EStopMode::KEEP_FILE);
4235 }
4236}
4237
4238void CServer::ConRecord(IConsole::IResult *pResult, void *pUser)
4239{
4240 CServer *pServer = (CServer *)pUser;
4241
4242 if(pServer->IsRecording(ClientId: RECORDER_MANUAL))
4243 {
4244 pServer->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "demo_recorder", pStr: "Demo recorder already recording");
4245 return;
4246 }
4247
4248 char aFilename[IO_MAX_PATH_LENGTH];
4249 if(pResult->NumArguments())
4250 {
4251 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "demos/%s.demo", pResult->GetString(Index: 0));
4252 }
4253 else
4254 {
4255 char aTimestamp[20];
4256 str_timestamp(buffer: aTimestamp, buffer_size: sizeof(aTimestamp));
4257 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "demos/demo_%s.demo", aTimestamp);
4258 }
4259 pServer->m_aDemoRecorder[RECORDER_MANUAL].Start(
4260 pStorage: pServer->Storage(),
4261 pFilename: aFilename,
4262 pNetversion: pServer->GameServer()->NetVersion(),
4263 pMap: pServer->GameServer()->Map()->BaseName(),
4264 Sha256: pServer->m_aCurrentMapSha256[MAP_TYPE_SIX],
4265 MapCrc: pServer->m_aCurrentMapCrc[MAP_TYPE_SIX],
4266 pType: "server",
4267 MapSize: pServer->m_aCurrentMapSize[MAP_TYPE_SIX],
4268 pMapData: pServer->m_apCurrentMapData[MAP_TYPE_SIX],
4269 MapFile: nullptr,
4270 pfnFilter: nullptr,
4271 pUser: nullptr);
4272}
4273
4274void CServer::ConStopRecord(IConsole::IResult *pResult, void *pUser)
4275{
4276 ((CServer *)pUser)->m_aDemoRecorder[RECORDER_MANUAL].Stop(Mode: IDemoRecorder::EStopMode::KEEP_FILE);
4277}
4278
4279void CServer::ConMapReload(IConsole::IResult *pResult, void *pUser)
4280{
4281 ((CServer *)pUser)->ReloadMap();
4282}
4283
4284void CServer::ConLogout(IConsole::IResult *pResult, void *pUser)
4285{
4286 CServer *pServer = (CServer *)pUser;
4287
4288 if(pServer->m_RconClientId >= 0 && pServer->m_RconClientId < MAX_CLIENTS &&
4289 pServer->m_aClients[pServer->m_RconClientId].m_State != CServer::CClient::STATE_EMPTY)
4290 {
4291 pServer->LogoutClient(ClientId: pServer->m_RconClientId, pReason: "");
4292 }
4293}
4294
4295void CServer::ConShowIps(IConsole::IResult *pResult, void *pUser)
4296{
4297 CServer *pServer = (CServer *)pUser;
4298
4299 if(pServer->m_RconClientId >= 0 && pServer->m_RconClientId < MAX_CLIENTS &&
4300 pServer->m_aClients[pServer->m_RconClientId].m_State != CServer::CClient::STATE_EMPTY)
4301 {
4302 if(pResult->NumArguments())
4303 {
4304 pServer->m_aClients[pServer->m_RconClientId].m_ShowIps = pResult->GetInteger(Index: 0);
4305 }
4306 else
4307 {
4308 char aStr[9];
4309 str_format(buffer: aStr, buffer_size: sizeof(aStr), format: "Value: %d", pServer->m_aClients[pServer->m_RconClientId].m_ShowIps);
4310 pServer->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "server", pStr: aStr);
4311 }
4312 }
4313}
4314
4315void CServer::ConHideAuthStatus(IConsole::IResult *pResult, void *pUser)
4316{
4317 CServer *pServer = (CServer *)pUser;
4318
4319 if(pServer->m_RconClientId >= 0 && pServer->m_RconClientId < MAX_CLIENTS &&
4320 pServer->m_aClients[pServer->m_RconClientId].m_State != CServer::CClient::STATE_EMPTY)
4321 {
4322 if(pResult->NumArguments())
4323 {
4324 pServer->m_aClients[pServer->m_RconClientId].m_AuthHidden = pResult->GetInteger(Index: 0);
4325 }
4326 else
4327 {
4328 char aStr[9];
4329 str_format(buffer: aStr, buffer_size: sizeof(aStr), format: "Value: %d", pServer->m_aClients[pServer->m_RconClientId].m_AuthHidden);
4330 pServer->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "server", pStr: aStr);
4331 }
4332 }
4333}
4334
4335void CServer::ConForceHighBandwidthOnSpectate(IConsole::IResult *pResult, void *pUser)
4336{
4337 CServer *pServer = (CServer *)pUser;
4338
4339 if(pServer->m_RconClientId >= 0 && pServer->m_RconClientId < MAX_CLIENTS &&
4340 pServer->m_aClients[pServer->m_RconClientId].m_State != CServer::CClient::STATE_EMPTY)
4341 {
4342 if(pResult->NumArguments())
4343 {
4344 pServer->m_aClients[pServer->m_RconClientId].m_ForceHighBandwidthOnSpectate = pResult->GetInteger(Index: 0);
4345 }
4346 else
4347 {
4348 char aStr[9];
4349 str_format(buffer: aStr, buffer_size: sizeof(aStr), format: "Value: %d", pServer->m_aClients[pServer->m_RconClientId].m_ForceHighBandwidthOnSpectate);
4350 pServer->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "server", pStr: aStr);
4351 }
4352 }
4353}
4354
4355void CServer::ConAddSqlServer(IConsole::IResult *pResult, void *pUserData)
4356{
4357 CServer *pSelf = (CServer *)pUserData;
4358
4359 if(!MysqlAvailable())
4360 {
4361 log_error("server", "can't add MySQL server: compiled without MySQL support");
4362 return;
4363 }
4364
4365 if(!pSelf->Config()->m_SvUseSql)
4366 return;
4367
4368 if(pResult->NumArguments() < 7 || pResult->NumArguments() > 9)
4369 {
4370 log_error("server", "7 to 9 arguments are required");
4371 return;
4372 }
4373
4374 CMysqlConfig Config;
4375 bool Write;
4376 if(str_comp_nocase(a: pResult->GetString(Index: 0), b: "r") == 0)
4377 {
4378 Write = false;
4379 }
4380 else if(str_comp_nocase(a: pResult->GetString(Index: 0), b: "w") == 0)
4381 {
4382 Write = true;
4383 }
4384 else
4385 {
4386 log_error("server", "choose either 'r' for SqlReadServer or 'w' for SqlWriteServer");
4387 return;
4388 }
4389
4390 str_copy(dst&: Config.m_aDatabase, src: pResult->GetString(Index: 1));
4391 str_copy(dst&: Config.m_aPrefix, src: pResult->GetString(Index: 2));
4392 str_copy(dst&: Config.m_aUser, src: pResult->GetString(Index: 3));
4393 str_copy(dst&: Config.m_aPass, src: pResult->GetString(Index: 4));
4394 str_copy(dst&: Config.m_aIp, src: pResult->GetString(Index: 5));
4395 Config.m_aBindaddr[0] = '\0';
4396 Config.m_Port = pResult->GetInteger(Index: 6);
4397 Config.m_Setup = pResult->NumArguments() >= 8 ? pResult->GetInteger(Index: 7) : true;
4398 Config.m_UseSsl = pResult->NumArguments() >= 9 ? pResult->GetInteger(Index: 8) != 0 : false;
4399 str_copy(dst&: Config.m_aSslCa, src: g_Config.m_SvSqlSslCa);
4400 str_copy(dst&: Config.m_aSslCert, src: g_Config.m_SvSqlSslCert);
4401 str_copy(dst&: Config.m_aSslKey, src: g_Config.m_SvSqlSslKey);
4402
4403 log_info("server",
4404 "Adding new Sql%sServer: DB: '%s' Prefix: '%s' User: '%s' IP: <{%s}> Port: %d",
4405 Write ? "Write" : "Read",
4406 Config.m_aDatabase, Config.m_aPrefix, Config.m_aUser, Config.m_aIp, Config.m_Port);
4407 pSelf->DbPool()->RegisterMysqlDatabase(DatabaseMode: Write ? CDbConnectionPool::WRITE : CDbConnectionPool::READ, pMysqlConfig: &Config);
4408}
4409
4410void CServer::ConDumpSqlServers(IConsole::IResult *pResult, void *pUserData)
4411{
4412 CServer *pSelf = (CServer *)pUserData;
4413
4414 if(str_comp_nocase(a: pResult->GetString(Index: 0), b: "w") == 0)
4415 {
4416 pSelf->DbPool()->Print(DatabaseMode: CDbConnectionPool::WRITE);
4417 pSelf->DbPool()->Print(DatabaseMode: CDbConnectionPool::WRITE_BACKUP);
4418 }
4419 else if(str_comp_nocase(a: pResult->GetString(Index: 0), b: "r") == 0)
4420 {
4421 pSelf->DbPool()->Print(DatabaseMode: CDbConnectionPool::READ);
4422 }
4423 else
4424 {
4425 log_error("server", "choose either 'r' for SqlReadServer or 'w' for SqlWriteServer");
4426 return;
4427 }
4428}
4429
4430void CServer::ConReloadAnnouncement(IConsole::IResult *pResult, void *pUserData)
4431{
4432 CServer *pThis = static_cast<CServer *>(pUserData);
4433 pThis->ReadAnnouncementsFile();
4434}
4435
4436void CServer::ConReloadMaplist(IConsole::IResult *pResult, void *pUserData)
4437{
4438 CServer *pThis = static_cast<CServer *>(pUserData);
4439 pThis->InitMaplist();
4440}
4441
4442void CServer::ConchainSpecialInfoupdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4443{
4444 pfnCallback(pResult, pCallbackUserData);
4445 if(pResult->NumArguments())
4446 {
4447 CServer *pThis = static_cast<CServer *>(pUserData);
4448 str_clean_whitespaces(str: pThis->Config()->m_SvName);
4449 pThis->ExpireServerInfoAndQueueResend();
4450 }
4451}
4452
4453void CServer::ConchainMaxclientsperipUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4454{
4455 pfnCallback(pResult, pCallbackUserData);
4456 if(pResult->NumArguments())
4457 ((CServer *)pUserData)->m_NetServer.SetMaxClientsPerIp(pResult->GetInteger(Index: 0));
4458}
4459
4460void CServer::ConchainCommandAccessUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4461{
4462 if(pResult->NumArguments() == 2)
4463 {
4464 CServer *pThis = static_cast<CServer *>(pUserData);
4465 const IConsole::ICommandInfo *pInfo = pThis->Console()->GetCommandInfo(pName: pResult->GetString(Index: 0), FlagMask: CFGFLAG_SERVER, Temp: false);
4466 IConsole::EAccessLevel OldAccessLevel = IConsole::EAccessLevel::ADMIN;
4467 if(pInfo)
4468 OldAccessLevel = pInfo->GetAccessLevel();
4469 pfnCallback(pResult, pCallbackUserData);
4470 if(pInfo && OldAccessLevel != pInfo->GetAccessLevel())
4471 {
4472 for(int i = 0; i < MAX_CLIENTS; ++i)
4473 {
4474 if(pThis->m_aClients[i].m_State == CServer::CClient::STATE_EMPTY)
4475 continue;
4476 if(!pThis->IsRconAuthed(ClientId: i))
4477 continue;
4478
4479 const IConsole::EAccessLevel ClientAccessLevel = pThis->ConsoleAccessLevel(ClientId: i);
4480 bool HadAccess = OldAccessLevel >= ClientAccessLevel;
4481 bool HasAccess = pInfo->GetAccessLevel() >= ClientAccessLevel;
4482
4483 // Nothing changed
4484 if(HadAccess == HasAccess)
4485 continue;
4486 // Command not sent yet. The sending will happen in alphabetical order with correctly updated permissions.
4487 if(pThis->m_aClients[i].m_pRconCmdToSend && str_comp(a: pResult->GetString(Index: 0), b: pThis->m_aClients[i].m_pRconCmdToSend->Name()) >= 0)
4488 continue;
4489
4490 if(HasAccess)
4491 pThis->SendRconCmdAdd(pCommandInfo: pInfo, ClientId: i);
4492 else
4493 pThis->SendRconCmdRem(pCommandInfo: pInfo, ClientId: i);
4494 }
4495 }
4496 }
4497 else
4498 {
4499 pfnCallback(pResult, pCallbackUserData);
4500 }
4501}
4502
4503void CServer::LogoutClient(int ClientId, const char *pReason)
4504{
4505 if(!IsSixup(ClientId))
4506 {
4507 CMsgPacker Msg(NETMSG_RCON_AUTH_STATUS, true);
4508 Msg.AddInt(i: 0); //authed
4509 Msg.AddInt(i: 0); //cmdlist
4510 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
4511 }
4512 else
4513 {
4514 CMsgPacker Msg(protocol7::NETMSG_RCON_AUTH_OFF, true, true);
4515 SendMsg(pMsg: &Msg, Flags: MSGFLAG_VITAL, ClientId);
4516 }
4517
4518 m_aClients[ClientId].m_AuthTries = 0;
4519 m_aClients[ClientId].m_pRconCmdToSend = nullptr;
4520 m_aClients[ClientId].m_MaplistEntryToSend = CClient::MAPLIST_UNINITIALIZED;
4521
4522 if(*pReason)
4523 {
4524 char aBuf[64];
4525 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Logged out by %s.", pReason);
4526 SendRconLine(ClientId, pLine: aBuf);
4527 log_info("server", "ClientId=%d with key='%s' logged out by %s", ClientId, m_AuthManager.KeyIdent(m_aClients[ClientId].m_AuthKey), pReason);
4528 }
4529 else
4530 {
4531 SendRconLine(ClientId, pLine: "Logout successful.");
4532 log_info("server", "ClientId=%d with key='%s' logged out", ClientId, m_AuthManager.KeyIdent(m_aClients[ClientId].m_AuthKey));
4533 }
4534
4535 m_aClients[ClientId].m_AuthKey = -1;
4536
4537 GameServer()->OnSetAuthed(ClientId, pRole: nullptr);
4538}
4539
4540void CServer::LogoutKey(int Key, const char *pReason)
4541{
4542 for(int i = 0; i < MAX_CLIENTS; i++)
4543 if(m_aClients[i].m_AuthKey == Key)
4544 LogoutClient(ClientId: i, pReason);
4545}
4546
4547void CServer::ConchainRconPasswordChangeGeneric(const char *pRoleName, const char *pCurrent, IConsole::IResult *pResult)
4548{
4549 if(pResult->NumArguments() == 1)
4550 {
4551 int KeySlot = m_AuthManager.DefaultKey(pRoleName);
4552 const char *pNew = pResult->GetString(Index: 0);
4553 if(str_comp(a: pCurrent, b: pNew) == 0)
4554 {
4555 return;
4556 }
4557 if(KeySlot == -1 && pNew[0])
4558 {
4559 m_AuthManager.AddDefaultKey(pRoleName, pPw: pNew);
4560 }
4561 else if(KeySlot >= 0)
4562 {
4563 if(!pNew[0])
4564 {
4565 AuthRemoveKey(KeySlot);
4566 // Already logs users out.
4567 }
4568 else
4569 {
4570 m_AuthManager.UpdateKey(Slot: KeySlot, pPw: pNew, pRoleName);
4571 LogoutKey(Key: KeySlot, pReason: "key update");
4572 }
4573 }
4574 }
4575}
4576
4577void CServer::ConchainRconPasswordChange(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4578{
4579 CServer *pThis = static_cast<CServer *>(pUserData);
4580 pThis->ConchainRconPasswordChangeGeneric(pRoleName: RoleName::ADMIN, pCurrent: pThis->Config()->m_SvRconPassword, pResult);
4581 pfnCallback(pResult, pCallbackUserData);
4582}
4583
4584void CServer::ConchainRconModPasswordChange(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4585{
4586 CServer *pThis = static_cast<CServer *>(pUserData);
4587 pThis->ConchainRconPasswordChangeGeneric(pRoleName: RoleName::MODERATOR, pCurrent: pThis->Config()->m_SvRconModPassword, pResult);
4588 pfnCallback(pResult, pCallbackUserData);
4589}
4590
4591void CServer::ConchainRconHelperPasswordChange(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4592{
4593 CServer *pThis = static_cast<CServer *>(pUserData);
4594 pThis->ConchainRconPasswordChangeGeneric(pRoleName: RoleName::HELPER, pCurrent: pThis->Config()->m_SvRconHelperPassword, pResult);
4595 pfnCallback(pResult, pCallbackUserData);
4596}
4597
4598void CServer::ConchainReservedSlotsAuthLevel(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4599{
4600 const char *pValue = pResult->GetString(Index: 0);
4601 if(pResult->NumArguments() && pResult->GetString(Index: 0)[0] != '\0' && !CAuthManager::RoleNameToAuthLevel(pRoleName: pValue).has_value())
4602 {
4603 if(str_comp(a: pValue, b: "1") == 0)
4604 {
4605 log_warn("server", "got deprecated value %s for sv_reserved_slots_auth_level, please use \"helper\" instead", pValue);
4606 }
4607 else if(str_comp(a: pValue, b: "2") == 0)
4608 {
4609 log_warn("server", "got deprecated value %s for sv_reserved_slots_auth_level, please use \"moderator\" instead", pValue);
4610 }
4611 else if(str_comp(a: pValue, b: "3") == 0)
4612 {
4613 log_warn("server", "got deprecated value %s for sv_reserved_slots_auth_level, please use \"admin\" instead", pValue);
4614 }
4615 else if(str_comp(a: pValue, b: "4") == 0)
4616 {
4617 log_warn("server", "got deprecated value %s for sv_reserved_slots_auth_level, please use \"\" instead", pValue);
4618 }
4619 else
4620 {
4621 log_error("server", "Value can only be one of those: helper, moderator, admin or empty");
4622 return;
4623 }
4624 }
4625
4626 pfnCallback(pResult, pCallbackUserData);
4627}
4628
4629void CServer::ConchainMapUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4630{
4631 CServer *pThis = static_cast<CServer *>(pUserData);
4632 pfnCallback(pResult, pCallbackUserData);
4633 if(pResult->NumArguments() >= 1 && pThis->GameServer()->Map()->IsLoaded())
4634 {
4635 pThis->m_MapReload = str_comp(a: pThis->Config()->m_SvMap, b: pThis->GameServer()->Map()->FullName()) != 0;
4636 }
4637}
4638
4639void CServer::ConchainSixupUpdate(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4640{
4641 pfnCallback(pResult, pCallbackUserData);
4642 CServer *pThis = static_cast<CServer *>(pUserData);
4643 if(pResult->NumArguments() >= 1 && pThis->GameServer()->Map()->IsLoaded())
4644 {
4645 pThis->m_MapReload |= (pThis->m_apCurrentMapData[MAP_TYPE_SIXUP] != nullptr) != (pResult->GetInteger(Index: 0) != 0);
4646 }
4647}
4648
4649void CServer::ConchainRegisterCommunityTokenRedact(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4650{
4651 // community tokens look like this:
4652 // ddtc_6DnZq5Ix0J2kvDHbkPNtb6bsZxOVQg4ly2jw. The first 11 bytes are
4653 // shared between the token and the verification token, so they're
4654 // semi-public. Redact everything beyond that point.
4655 static constexpr int REDACT_FROM = 11;
4656 if(pResult->NumArguments() == 0 && str_length(str: g_Config.m_SvRegisterCommunityToken) > REDACT_FROM)
4657 {
4658 char aTruncated[16];
4659 str_truncate(dst: aTruncated, dst_size: sizeof(aTruncated), src: g_Config.m_SvRegisterCommunityToken, truncation_len: REDACT_FROM);
4660 log_info("config", "Value: %s[REDACTED] (total length %d)", aTruncated, str_length(g_Config.m_SvRegisterCommunityToken));
4661 return;
4662 }
4663 pfnCallback(pResult, pCallbackUserData);
4664}
4665
4666void CServer::ConchainLoglevel(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4667{
4668 CServer *pSelf = (CServer *)pUserData;
4669 pfnCallback(pResult, pCallbackUserData);
4670 if(pResult->NumArguments())
4671 {
4672 pSelf->m_pFileLogger->SetFilter(CLogFilter{.m_MaxLevel: IConsole::ToLogLevelFilter(ConsoleLevel: g_Config.m_Loglevel)});
4673 }
4674}
4675
4676void CServer::ConchainStdoutOutputLevel(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4677{
4678 CServer *pSelf = (CServer *)pUserData;
4679 pfnCallback(pResult, pCallbackUserData);
4680 if(pResult->NumArguments() && pSelf->m_pStdoutLogger)
4681 {
4682 pSelf->m_pStdoutLogger->SetFilter(CLogFilter{.m_MaxLevel: IConsole::ToLogLevelFilter(ConsoleLevel: g_Config.m_StdoutOutputLevel)});
4683 }
4684}
4685
4686void CServer::ConchainAnnouncementFilename(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4687{
4688 CServer *pSelf = (CServer *)pUserData;
4689 bool Changed = pResult->NumArguments() && str_comp(a: pResult->GetString(Index: 0), b: g_Config.m_SvAnnouncementFilename);
4690 pfnCallback(pResult, pCallbackUserData);
4691 if(Changed)
4692 {
4693 pSelf->ReadAnnouncementsFile();
4694 }
4695}
4696
4697void CServer::ConchainInputFifo(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4698{
4699 CServer *pSelf = (CServer *)pUserData;
4700 pfnCallback(pResult, pCallbackUserData);
4701 if(pSelf->m_Fifo.IsInit())
4702 {
4703 pSelf->m_Fifo.Shutdown();
4704 pSelf->m_Fifo.Init(pConsole: pSelf->Console(), pFifoFile: pSelf->Config()->m_SvInputFifo, Flag: CFGFLAG_SERVER);
4705 }
4706}
4707
4708#if defined(CONF_FAMILY_UNIX)
4709void CServer::ConchainConnLoggingServerChange(IConsole::IResult *pResult, void *pUserData, IConsole::FCommandCallback pfnCallback, void *pCallbackUserData)
4710{
4711 pfnCallback(pResult, pCallbackUserData);
4712 if(pResult->NumArguments() == 1)
4713 {
4714 CServer *pServer = (CServer *)pUserData;
4715
4716 // open socket to send new connections
4717 if(!pServer->m_ConnLoggingSocketCreated)
4718 {
4719 pServer->m_ConnLoggingSocket = net_unix_create_unnamed();
4720 if(pServer->m_ConnLoggingSocket == -1)
4721 {
4722 pServer->Console()->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "server", pStr: "Failed to created socket for communication with the connection logging server.");
4723 }
4724 else
4725 {
4726 pServer->m_ConnLoggingSocketCreated = true;
4727 }
4728 }
4729
4730 // set the destination address for the connection logging
4731 net_unix_set_addr(addr: &pServer->m_ConnLoggingDestAddr, path: pResult->GetString(Index: 0));
4732 }
4733}
4734#endif
4735
4736void CServer::RegisterCommands()
4737{
4738 m_pConsole = Kernel()->RequestInterface<IConsole>();
4739 m_pGameServer = Kernel()->RequestInterface<IGameServer>();
4740 m_pHttp = Kernel()->RequestInterface<IEngineHttp>();
4741 m_pStorage = Kernel()->RequestInterface<IStorage>();
4742 m_pAntibot = Kernel()->RequestInterface<IEngineAntibot>();
4743
4744 // register console commands
4745 Console()->Register(pName: "kick", pParams: "v[id] ?r[reason]", Flags: CFGFLAG_SERVER, pfnFunc: ConKick, pUser: this, pHelp: "Kick player with specified id for any reason");
4746 Console()->Register(pName: "status", pParams: "?r[name]", Flags: CFGFLAG_SERVER, pfnFunc: ConStatus, pUser: this, pHelp: "List players containing name or all players");
4747 Console()->Register(pName: "shutdown", pParams: "?r[reason]", Flags: CFGFLAG_SERVER, pfnFunc: ConShutdown, pUser: this, pHelp: "Shut down");
4748 Console()->Register(pName: "uptime", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConUptime, pUser: this, pHelp: "Show server uptime");
4749 Console()->Register(pName: "logout", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConLogout, pUser: this, pHelp: "Logout of rcon");
4750 Console()->Register(pName: "show_ips", pParams: "?i[show]", Flags: CFGFLAG_SERVER, pfnFunc: ConShowIps, pUser: this, pHelp: "Show IP addresses in rcon commands (1 = on, 0 = off)");
4751 Console()->Register(pName: "hide_auth_status", pParams: "?i[hide]", Flags: CFGFLAG_SERVER, pfnFunc: ConHideAuthStatus, pUser: this, pHelp: "Opt out of spectator count and hide auth status to non-authed players (1 = hidden, 0 = shown)");
4752 Console()->Register(pName: "force_high_bandwidth_on_spectate", pParams: "?i[enable]", Flags: CFGFLAG_SERVER, pfnFunc: ConForceHighBandwidthOnSpectate, pUser: this, pHelp: "Force high bandwidth mode when spectating (1 = on, 0 = off)");
4753
4754 Console()->Register(pName: "record", pParams: "?s[file]", Flags: CFGFLAG_SERVER | CFGFLAG_STORE, pfnFunc: ConRecord, pUser: this, pHelp: "Record to a file");
4755 Console()->Register(pName: "stoprecord", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConStopRecord, pUser: this, pHelp: "Stop recording");
4756
4757 Console()->Register(pName: "reload", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConMapReload, pUser: this, pHelp: "Reload the map");
4758
4759 Console()->Register(pName: "add_sqlserver", pParams: "s['r'|'w'] s[Database] s[Prefix] s[User] s[Password] s[IP] i[Port] ?i[SetUpDatabase ?] ?i[SSL ?]", Flags: CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConAddSqlServer, pUser: this, pHelp: "add a sqlserver");
4760 Console()->Register(pName: "dump_sqlservers", pParams: "s['r'|'w']", Flags: CFGFLAG_SERVER, pfnFunc: ConDumpSqlServers, pUser: this, pHelp: "dumps all sqlservers readservers = r, writeservers = w");
4761
4762 Console()->Register(pName: "auth_add", pParams: "s[ident] s[level] r[pw]", Flags: CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConAuthAdd, pUser: this, pHelp: "Add a rcon key");
4763 Console()->Register(pName: "auth_add_p", pParams: "s[ident] s[level] s[hash] s[salt]", Flags: CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConAuthAddHashed, pUser: this, pHelp: "Add a prehashed rcon key");
4764 Console()->Register(pName: "auth_change", pParams: "s[ident] s[level] r[pw]", Flags: CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConAuthUpdate, pUser: this, pHelp: "Update a rcon key");
4765 Console()->Register(pName: "auth_change_p", pParams: "s[ident] s[level] s[hash] s[salt]", Flags: CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConAuthUpdateHashed, pUser: this, pHelp: "Update a rcon key with prehashed data");
4766 Console()->Register(pName: "auth_remove", pParams: "s[ident]", Flags: CFGFLAG_SERVER | CFGFLAG_NONTEEHISTORIC, pfnFunc: ConAuthRemove, pUser: this, pHelp: "Remove a rcon key");
4767 Console()->Register(pName: "auth_list", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConAuthList, pUser: this, pHelp: "List all rcon keys");
4768
4769 Console()->Register(pName: "reload_announcement", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConReloadAnnouncement, pUser: this, pHelp: "Reload the announcements");
4770 Console()->Register(pName: "reload_maplist", pParams: "", Flags: CFGFLAG_SERVER, pfnFunc: ConReloadMaplist, pUser: this, pHelp: "Reload the maplist");
4771
4772 RustVersionRegister(console&: *Console());
4773
4774 Console()->Chain(pName: "sv_name", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
4775 Console()->Chain(pName: "password", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
4776 Console()->Chain(pName: "sv_reserved_slots", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
4777 Console()->Chain(pName: "sv_spectator_slots", pfnChainFunc: ConchainSpecialInfoupdate, pUser: this);
4778
4779 Console()->Chain(pName: "sv_max_clients_per_ip", pfnChainFunc: ConchainMaxclientsperipUpdate, pUser: this);
4780 Console()->Chain(pName: "access_level", pfnChainFunc: ConchainCommandAccessUpdate, pUser: this);
4781
4782 Console()->Chain(pName: "sv_rcon_password", pfnChainFunc: ConchainRconPasswordChange, pUser: this);
4783 Console()->Chain(pName: "sv_rcon_mod_password", pfnChainFunc: ConchainRconModPasswordChange, pUser: this);
4784 Console()->Chain(pName: "sv_rcon_helper_password", pfnChainFunc: ConchainRconHelperPasswordChange, pUser: this);
4785 Console()->Chain(pName: "sv_reserved_slots_auth_level", pfnChainFunc: ConchainReservedSlotsAuthLevel, pUser: this);
4786 Console()->Chain(pName: "sv_map", pfnChainFunc: ConchainMapUpdate, pUser: this);
4787 Console()->Chain(pName: "sv_sixup", pfnChainFunc: ConchainSixupUpdate, pUser: this);
4788 Console()->Chain(pName: "sv_register_community_token", pfnChainFunc: ConchainRegisterCommunityTokenRedact, pUser: nullptr);
4789
4790 Console()->Chain(pName: "loglevel", pfnChainFunc: ConchainLoglevel, pUser: this);
4791 Console()->Chain(pName: "stdout_output_level", pfnChainFunc: ConchainStdoutOutputLevel, pUser: this);
4792
4793 Console()->Chain(pName: "sv_announcement_filename", pfnChainFunc: ConchainAnnouncementFilename, pUser: this);
4794
4795 Console()->Chain(pName: "sv_input_fifo", pfnChainFunc: ConchainInputFifo, pUser: this);
4796
4797#if defined(CONF_FAMILY_UNIX)
4798 Console()->Chain(pName: "sv_conn_logging_server", pfnChainFunc: ConchainConnLoggingServerChange, pUser: this);
4799#endif
4800
4801 // register console commands in sub parts
4802 m_ServerBan.InitServerBan(pConsole: Console(), pStorage: Storage(), pServer: this);
4803 m_NameBans.InitConsole(pConsole: Console());
4804 m_pGameServer->OnConsoleInit();
4805 Console()->SetCanUseCommandCallback(pfnCallback: CanClientUseCommandCallback, pUser: this);
4806}
4807
4808std::optional<int> CServer::SnapNewId()
4809{
4810 return m_IdPool.NewId();
4811}
4812
4813void CServer::SnapFreeId(int Id)
4814{
4815 m_IdPool.FreeId(Id);
4816}
4817
4818bool CServer::SnapNewItem(int Type, int Id, const void *pData, int Size)
4819{
4820 return m_SnapshotBuilder.NewItem(Type, Id, pData, Size);
4821}
4822
4823void CServer::SnapSetStaticsize(int ItemType, int Size)
4824{
4825 m_SnapshotDelta.SetStaticsize(ItemType, Size);
4826}
4827
4828void CServer::SnapSetStaticsize7(int ItemType, int Size)
4829{
4830 m_SnapshotDeltaSixup.SetStaticsize(ItemType, Size);
4831}
4832
4833CServer *CreateServer() { return new CServer(); }
4834
4835// DDRace
4836
4837void CServer::ReadAnnouncementsFile()
4838{
4839 m_vAnnouncements.clear();
4840
4841 if(g_Config.m_SvAnnouncementFilename[0] == '\0')
4842 return;
4843
4844 CLineReader LineReader;
4845 if(!LineReader.OpenFile(File: m_pStorage->OpenFile(pFilename: g_Config.m_SvAnnouncementFilename, Flags: IOFLAG_READ, Type: IStorage::TYPE_ALL)))
4846 {
4847 log_error("server", "Failed load announcements from '%s'", g_Config.m_SvAnnouncementFilename);
4848 return;
4849 }
4850 while(const char *pLine = LineReader.Get())
4851 {
4852 if(str_length(str: pLine) && pLine[0] != '#')
4853 {
4854 m_vAnnouncements.emplace_back(args&: pLine);
4855 }
4856 }
4857 log_info("server", "Loaded %" PRIzu " announcements", m_vAnnouncements.size());
4858}
4859
4860const char *CServer::GetAnnouncementLine()
4861{
4862 if(m_vAnnouncements.empty())
4863 {
4864 return nullptr;
4865 }
4866 else if(m_vAnnouncements.size() == 1)
4867 {
4868 m_AnnouncementLastLine = 0;
4869 }
4870 else if(!g_Config.m_SvAnnouncementRandom)
4871 {
4872 if(++m_AnnouncementLastLine >= m_vAnnouncements.size())
4873 m_AnnouncementLastLine %= m_vAnnouncements.size();
4874 }
4875 else
4876 {
4877 unsigned Rand;
4878 do
4879 {
4880 Rand = rand() % m_vAnnouncements.size();
4881 } while(Rand == m_AnnouncementLastLine);
4882
4883 m_AnnouncementLastLine = Rand;
4884 }
4885
4886 return m_vAnnouncements[m_AnnouncementLastLine].c_str();
4887}
4888
4889struct CSubdirCallbackUserdata
4890{
4891 CServer *m_pServer;
4892 char m_aCurrentFolder[IO_MAX_PATH_LENGTH];
4893};
4894
4895int CServer::MaplistEntryCallback(const char *pFilename, int IsDir, int DirType, void *pUser)
4896{
4897 CSubdirCallbackUserdata *pUserdata = static_cast<CSubdirCallbackUserdata *>(pUser);
4898 CServer *pThis = pUserdata->m_pServer;
4899
4900 if(str_comp(a: pFilename, b: ".") == 0 || str_comp(a: pFilename, b: "..") == 0)
4901 return 0;
4902
4903 char aFilename[IO_MAX_PATH_LENGTH];
4904 if(pUserdata->m_aCurrentFolder[0] != '\0')
4905 str_format(buffer: aFilename, buffer_size: sizeof(aFilename), format: "%s/%s", pUserdata->m_aCurrentFolder, pFilename);
4906 else
4907 str_copy(dst&: aFilename, src: pFilename);
4908
4909 if(IsDir)
4910 {
4911 CSubdirCallbackUserdata Userdata;
4912 Userdata.m_pServer = pThis;
4913 str_copy(dst&: Userdata.m_aCurrentFolder, src: aFilename);
4914 char aFindPath[IO_MAX_PATH_LENGTH];
4915 str_format(buffer: aFindPath, buffer_size: sizeof(aFindPath), format: "maps/%s/", aFilename);
4916 pThis->Storage()->ListDirectory(Type: IStorage::TYPE_ALL, pPath: aFindPath, pfnCallback: MaplistEntryCallback, pUser: &Userdata);
4917 return 0;
4918 }
4919
4920 const char *pSuffix = str_endswith(str: aFilename, suffix: ".map");
4921 if(!pSuffix) // not ending with .map
4922 return 0;
4923 const size_t FilenameLength = pSuffix - aFilename;
4924 aFilename[FilenameLength] = '\0'; // remove suffix
4925 if(FilenameLength >= sizeof(CMaplistEntry().m_aName)) // name too long
4926 return 0;
4927
4928 pThis->m_vMaplistEntries.emplace_back(args&: aFilename);
4929 return 0;
4930}
4931
4932void CServer::InitMaplist()
4933{
4934 m_vMaplistEntries.clear();
4935
4936 CSubdirCallbackUserdata Userdata;
4937 Userdata.m_pServer = this;
4938 Userdata.m_aCurrentFolder[0] = '\0';
4939 Storage()->ListDirectory(Type: IStorage::TYPE_ALL, pPath: "maps/", pfnCallback: MaplistEntryCallback, pUser: &Userdata);
4940
4941 std::sort(first: m_vMaplistEntries.begin(), last: m_vMaplistEntries.end());
4942 log_info("server", "Found %d maps for maplist", (int)m_vMaplistEntries.size());
4943
4944 for(CClient &Client : m_aClients)
4945 {
4946 if(Client.m_State != CClient::STATE_INGAME)
4947 continue;
4948
4949 // Resend maplist to clients that already got it or are currently getting it
4950 if(Client.m_MaplistEntryToSend == CClient::MAPLIST_DONE || Client.m_MaplistEntryToSend >= 0)
4951 {
4952 Client.m_MaplistEntryToSend = CClient::MAPLIST_UNINITIALIZED;
4953 }
4954 }
4955}
4956
4957int *CServer::GetIdMap(int ClientId)
4958{
4959 return m_aClients[ClientId].m_aIdMap;
4960}
4961
4962int *CServer::GetReverseIdMap(int ClientId)
4963{
4964 return m_aClients[ClientId].m_aReverseIdMap;
4965}
4966
4967bool CServer::SetTimedOut(int ClientId, int OrigId)
4968{
4969 if(!m_NetServer.HasErrored(ClientId))
4970 {
4971 return false;
4972 }
4973
4974 // The login was on the current conn, logout should also be on the current conn
4975 if(IsRconAuthed(ClientId: OrigId))
4976 {
4977 LogoutClient(ClientId: OrigId, pReason: "Timeout Protection");
4978 }
4979
4980 m_NetServer.ResumeOldConnection(ClientId, OrigId);
4981
4982 m_aClients[ClientId].m_Sixup = m_aClients[OrigId].m_Sixup;
4983 // This slot keeps playing with the resumed connection, which can use the other
4984 // protocol version, so its snapshots must not be used as delta base anymore.
4985 m_aClients[ClientId].m_Snapshots.PurgeAll();
4986 m_aClients[ClientId].m_LastAckedSnapshot = -1;
4987 m_aClients[ClientId].m_AuthKey = -1;
4988 m_aClients[ClientId].m_Flags = m_aClients[OrigId].m_Flags;
4989 m_aClients[ClientId].m_DDNetVersion = m_aClients[OrigId].m_DDNetVersion;
4990 m_aClients[ClientId].m_GotDDNetVersionPacket = m_aClients[OrigId].m_GotDDNetVersionPacket;
4991 m_aClients[ClientId].m_DDNetVersionSettled = m_aClients[OrigId].m_DDNetVersionSettled;
4992
4993 DelClientCallback(ClientId: OrigId, pReason: "Timeout Protection used", pUser: this);
4994
4995 // ReinitPlayerMap must be called after DelClientCallback to preserve the client id.
4996 // The order is important for the player initialization algorithm in CPlayerMapping::CPlayerMap::InitPlayer
4997 // because it loops over all players to find others with the same ip address.
4998 // IP matching is important for hammerfly/dummy copy to work by guaran-tee-ing dummy and player map have the same ids
4999 // Never forget: 0.7 really implemented netmsgs for join/leave, means client ids have to be stable across using timeout protection.
5000 // When InitPlayer runs it has to assign the same client id as before since local id cant be changed in 0.7
5001 GameServer()->ReinitPlayerMap(ClientId, Timeout: true);
5002 return true;
5003}
5004
5005void CServer::SetErrorShutdown(const char *pReason)
5006{
5007 str_copy(dst&: m_aErrorShutdownReason, src: pReason);
5008}
5009
5010void CServer::SetLoggers(std::shared_ptr<ILogger> &&pFileLogger, std::shared_ptr<ILogger> &&pStdoutLogger)
5011{
5012 m_pFileLogger = pFileLogger;
5013 m_pStdoutLogger = pStdoutLogger;
5014}
5015