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#include "serverbrowser.h"
4
5#include "serverbrowser_http.h"
6#include "serverbrowser_ping_cache.h"
7
8#include <base/dbg.h>
9#include <base/hash_ctxt.h>
10#include <base/log.h>
11#include <base/mem.h>
12#include <base/secure.h>
13#include <base/str.h>
14#include <base/time.h>
15
16#include <engine/console.h>
17#include <engine/engine.h>
18#include <engine/favorites.h>
19#include <engine/friends.h>
20#include <engine/http.h>
21#include <engine/shared/config.h>
22#include <engine/shared/json.h>
23#include <engine/shared/masterserver.h>
24#include <engine/shared/network.h>
25#include <engine/shared/packer.h>
26#include <engine/shared/protocol.h>
27#include <engine/shared/serverinfo.h>
28#include <engine/storage.h>
29
30#include <algorithm>
31#include <map>
32#include <set>
33#include <vector>
34
35class CSortWrap
36{
37 typedef bool (CServerBrowser::*SortFunc)(int, int) const;
38 SortFunc m_pfnSort;
39 CServerBrowser *m_pThis;
40
41public:
42 CSortWrap(CServerBrowser *pServer, SortFunc Func) :
43 m_pfnSort(Func), m_pThis(pServer) {}
44 bool operator()(int a, int b) { return (g_Config.m_BrSortOrder ? (m_pThis->*m_pfnSort)(b, a) : (m_pThis->*m_pfnSort)(a, b)); }
45};
46
47static bool MatchesPart(const char *a, const char *b)
48{
49 return str_utf8_find_nocase(haystack: a, needle: b) != nullptr;
50}
51
52static bool MatchesExactly(const char *a, const char *b)
53{
54 return str_comp(a, b: &b[1]) == 0;
55}
56
57static NETADDR CommunityAddressKey(const NETADDR &Addr)
58{
59 NETADDR AddressKey = Addr;
60 AddressKey.type &= ~NETTYPE_TW7;
61 return AddressKey;
62}
63
64CServerBrowser::CServerBrowser() :
65 m_CommunityCache(this),
66 m_CountriesFilter(&m_CommunityCache),
67 m_TypesFilter(&m_CommunityCache)
68{
69 m_NeedResort = false;
70 m_Sorthash = 0;
71
72 m_ServerlistType = 0;
73 m_BroadcastTime = 0;
74 secure_random_fill(bytes: m_aTokenSeed, length: sizeof(m_aTokenSeed));
75
76 CleanUp();
77}
78
79CServerBrowser::~CServerBrowser()
80{
81 json_value_free(m_pDDNetInfo);
82
83 delete m_pHttp;
84 m_pHttp = nullptr;
85 delete m_pPingCache;
86 m_pPingCache = nullptr;
87}
88
89void CServerBrowser::Shutdown()
90{
91 m_pHttp->Shutdown();
92}
93
94void CServerBrowser::SetBaseInfo(class CNetClient *pClient, const char *pNetVersion)
95{
96 m_pNetClient = pClient;
97 str_copy(dst&: m_aNetVersion, src: pNetVersion);
98 m_pConsole = Kernel()->RequestInterface<IConsole>();
99 m_pConfigManager = Kernel()->RequestInterface<IConfigManager>();
100 m_pEngine = Kernel()->RequestInterface<IEngine>();
101 m_pFavorites = Kernel()->RequestInterface<IFavorites>();
102 m_pFriends = Kernel()->RequestInterface<IFriends>();
103 m_pStorage = Kernel()->RequestInterface<IStorage>();
104 m_pHttpClient = Kernel()->RequestInterface<IHttp>();
105 m_pPingCache = CreateServerBrowserPingCache(pConsole: m_pConsole, pStorage: m_pStorage);
106
107 RegisterCommands();
108}
109
110void CServerBrowser::OnInit()
111{
112 m_pHttp = CreateServerBrowserHttp(pEngine: m_pEngine, pStorage: m_pStorage, pHttp: m_pHttpClient, pPreviousBestUrl: g_Config.m_BrCachedBestServerinfoUrl);
113}
114
115void CServerBrowser::RegisterCommands()
116{
117 m_pConfigManager->RegisterCallback(pfnFunc: CServerBrowser::ConfigSaveCallback, pUserData: this);
118 m_pConsole->Register(pName: "add_favorite_community", pParams: "s[community_id]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_AddFavoriteCommunity, pUser: this, pHelp: "Add a community as a favorite");
119 m_pConsole->Register(pName: "remove_favorite_community", pParams: "s[community_id]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_RemoveFavoriteCommunity, pUser: this, pHelp: "Remove a community from the favorites");
120 m_pConsole->Register(pName: "add_excluded_community", pParams: "s[community_id]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_AddExcludedCommunity, pUser: this, pHelp: "Add a community to the exclusion filter");
121 m_pConsole->Register(pName: "remove_excluded_community", pParams: "s[community_id]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_RemoveExcludedCommunity, pUser: this, pHelp: "Remove a community from the exclusion filter");
122 m_pConsole->Register(pName: "add_excluded_country", pParams: "s[community_id] s[country_code]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_AddExcludedCountry, pUser: this, pHelp: "Add a country to the exclusion filter for a specific community (ISO 3166-1 numeric)");
123 m_pConsole->Register(pName: "remove_excluded_country", pParams: "s[community_id] s[country_code]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_RemoveExcludedCountry, pUser: this, pHelp: "Remove a country from the exclusion filter for a specific community (ISO 3166-1 numeric)");
124 m_pConsole->Register(pName: "add_excluded_type", pParams: "s[community_id] s[type]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_AddExcludedType, pUser: this, pHelp: "Add a type to the exclusion filter for a specific community");
125 m_pConsole->Register(pName: "remove_excluded_type", pParams: "s[community_id] s[type]", Flags: CFGFLAG_CLIENT, pfnFunc: Con_RemoveExcludedType, pUser: this, pHelp: "Remove a type from the exclusion filter for a specific community");
126 m_pConsole->Register(pName: "leak_ip_address_to_all_servers", pParams: "", Flags: CFGFLAG_CLIENT, pfnFunc: Con_LeakIpAddress, pUser: this, pHelp: "Leaks your IP address to all servers by pinging each of them, also acquiring the latency in the process");
127}
128
129void CServerBrowser::ConfigSaveCallback(IConfigManager *pConfigManager, void *pUserData)
130{
131 CServerBrowser *pThis = static_cast<CServerBrowser *>(pUserData);
132 pThis->FavoriteCommunitiesFilter().Save(pConfigManager);
133 pThis->CommunitiesFilter().Save(pConfigManager);
134 pThis->CountriesFilter().Save(pConfigManager);
135 pThis->TypesFilter().Save(pConfigManager);
136}
137
138void CServerBrowser::Con_AddFavoriteCommunity(IConsole::IResult *pResult, void *pUserData)
139{
140 CServerBrowser *pThis = static_cast<CServerBrowser *>(pUserData);
141 const char *pCommunityId = pResult->GetString(Index: 0);
142 if(!pThis->ValidateCommunityId(pCommunityId))
143 return;
144 pThis->FavoriteCommunitiesFilter().Add(pCommunityId);
145}
146
147void CServerBrowser::Con_RemoveFavoriteCommunity(IConsole::IResult *pResult, void *pUserData)
148{
149 CServerBrowser *pThis = static_cast<CServerBrowser *>(pUserData);
150 const char *pCommunityId = pResult->GetString(Index: 0);
151 if(!pThis->ValidateCommunityId(pCommunityId))
152 return;
153 pThis->FavoriteCommunitiesFilter().Remove(pCommunityId);
154}
155
156void CServerBrowser::Con_AddExcludedCommunity(IConsole::IResult *pResult, void *pUserData)
157{
158 CServerBrowser *pThis = static_cast<CServerBrowser *>(pUserData);
159 const char *pCommunityId = pResult->GetString(Index: 0);
160 if(!pThis->ValidateCommunityId(pCommunityId))
161 return;
162 pThis->CommunitiesFilter().Add(pCommunityId);
163}
164
165void CServerBrowser::Con_RemoveExcludedCommunity(IConsole::IResult *pResult, void *pUserData)
166{
167 CServerBrowser *pThis = static_cast<CServerBrowser *>(pUserData);
168 const char *pCommunityId = pResult->GetString(Index: 0);
169 if(!pThis->ValidateCommunityId(pCommunityId))
170 return;
171 pThis->CommunitiesFilter().Remove(pCommunityId);
172}
173
174void CServerBrowser::Con_AddExcludedCountry(IConsole::IResult *pResult, void *pUserData)
175{
176 CServerBrowser *pThis = static_cast<CServerBrowser *>(pUserData);
177 const char *pCommunityId = pResult->GetString(Index: 0);
178 const char *pCountryName = pResult->GetString(Index: 1);
179 if(!pThis->ValidateCommunityId(pCommunityId) || !pThis->ValidateCountryName(pCountryName))
180 return;
181 pThis->CountriesFilter().Add(pCommunityId, pCountryName);
182}
183
184void CServerBrowser::Con_RemoveExcludedCountry(IConsole::IResult *pResult, void *pUserData)
185{
186 CServerBrowser *pThis = static_cast<CServerBrowser *>(pUserData);
187 const char *pCommunityId = pResult->GetString(Index: 0);
188 const char *pCountryName = pResult->GetString(Index: 1);
189 if(!pThis->ValidateCommunityId(pCommunityId) || !pThis->ValidateCountryName(pCountryName))
190 return;
191 pThis->CountriesFilter().Remove(pCommunityId, pCountryName);
192}
193
194void CServerBrowser::Con_AddExcludedType(IConsole::IResult *pResult, void *pUserData)
195{
196 CServerBrowser *pThis = static_cast<CServerBrowser *>(pUserData);
197 const char *pCommunityId = pResult->GetString(Index: 0);
198 const char *pTypeName = pResult->GetString(Index: 1);
199 if(!pThis->ValidateCommunityId(pCommunityId) || !pThis->ValidateTypeName(pTypeName))
200 return;
201 pThis->TypesFilter().Add(pCommunityId, pTypeName);
202}
203
204void CServerBrowser::Con_RemoveExcludedType(IConsole::IResult *pResult, void *pUserData)
205{
206 CServerBrowser *pThis = static_cast<CServerBrowser *>(pUserData);
207 const char *pCommunityId = pResult->GetString(Index: 0);
208 const char *pTypeName = pResult->GetString(Index: 1);
209 if(!pThis->ValidateCommunityId(pCommunityId) || !pThis->ValidateTypeName(pTypeName))
210 return;
211 pThis->TypesFilter().Remove(pCommunityId, pTypeName);
212}
213
214void CServerBrowser::Con_LeakIpAddress(IConsole::IResult *pResult, void *pUserData)
215{
216 CServerBrowser *pThis = static_cast<CServerBrowser *>(pUserData);
217
218 // We only consider the first address of every server.
219
220 std::vector<int> vSortedServers;
221 // Sort servers by IP address, ignoring port.
222 class CAddrComparer
223 {
224 public:
225 CServerBrowser *m_pThis;
226 bool operator()(int i, int j) const
227 {
228 NETADDR Addr1 = m_pThis->m_vpServerlist[i]->m_Info.m_aAddresses[0];
229 NETADDR Addr2 = m_pThis->m_vpServerlist[j]->m_Info.m_aAddresses[0];
230 Addr1.port = 0;
231 Addr2.port = 0;
232 return net_addr_comp(a: &Addr1, b: &Addr2) < 0;
233 }
234 };
235 vSortedServers.reserve(n: pThis->m_vpServerlist.size());
236 for(int i = 0; i < (int)pThis->m_vpServerlist.size(); i++)
237 {
238 vSortedServers.push_back(x: i);
239 }
240 std::sort(first: vSortedServers.begin(), last: vSortedServers.end(), comp: CAddrComparer{.m_pThis: pThis});
241
242 // Group the servers into those with same IP address (but differing
243 // port).
244 NETADDR Addr;
245 int Start = -1;
246 for(int i = 0; i <= (int)vSortedServers.size(); i++)
247 {
248 NETADDR NextAddr;
249 if(i < (int)vSortedServers.size())
250 {
251 NextAddr = pThis->m_vpServerlist[vSortedServers[i]]->m_Info.m_aAddresses[0];
252 NextAddr.port = 0;
253 }
254 bool New = Start == -1 || i == (int)vSortedServers.size() || net_addr_comp(a: &Addr, b: &NextAddr) != 0;
255 if(Start != -1 && New)
256 {
257 int Chosen = Start + secure_rand_below(below: i - Start);
258 CServerEntry *pChosen = pThis->m_vpServerlist[vSortedServers[Chosen]];
259 pChosen->m_RequestIgnoreInfo = true;
260 pThis->QueueRequest(pEntry: pChosen);
261 char aAddr[NETADDR_MAXSTRSIZE];
262 net_addr_str(addr: &pChosen->m_Info.m_aAddresses[0], string: aAddr, max_length: sizeof(aAddr), add_port: true);
263 dbg_msg(sys: "serverbrowser", fmt: "queuing ping request for %s", aAddr);
264 }
265 if(i < (int)vSortedServers.size() && New)
266 {
267 Start = i;
268 Addr = NextAddr;
269 }
270 }
271}
272
273static bool ValidIdentifier(const char *pId, size_t MaxLength)
274{
275 if(pId[0] == '\0' || (size_t)str_length(str: pId) >= MaxLength)
276 {
277 return false;
278 }
279
280 for(int i = 0; pId[i] != '\0'; ++i)
281 {
282 if(pId[i] == '"' || pId[i] == '/' || pId[i] == '\\')
283 {
284 return false;
285 }
286 }
287 return true;
288}
289
290static bool ValidateIdentifier(const char *pId, size_t MaxLength, const char *pContext, IConsole *pConsole)
291{
292 if(!ValidIdentifier(pId, MaxLength))
293 {
294 char aError[32 + IConsole::CMDLINE_LENGTH];
295 str_format(buffer: aError, buffer_size: sizeof(aError), format: "%s '%s' is not valid", pContext, pId);
296 pConsole->Print(Level: IConsole::OUTPUT_LEVEL_STANDARD, pFrom: "serverbrowser", pStr: aError);
297 return false;
298 }
299 return true;
300}
301
302bool CServerBrowser::ValidateCommunityId(const char *pCommunityId) const
303{
304 return ValidateIdentifier(pId: pCommunityId, MaxLength: CServerInfo::MAX_COMMUNITY_ID_LENGTH, pContext: "Community ID", pConsole: m_pConsole);
305}
306
307bool CServerBrowser::ValidateCountryName(const char *pCountryName) const
308{
309 return ValidateIdentifier(pId: pCountryName, MaxLength: CServerInfo::MAX_COMMUNITY_COUNTRY_LENGTH, pContext: "Country name", pConsole: m_pConsole);
310}
311
312bool CServerBrowser::ValidateTypeName(const char *pTypeName) const
313{
314 return ValidateIdentifier(pId: pTypeName, MaxLength: CServerInfo::MAX_COMMUNITY_TYPE_LENGTH, pContext: "Type name", pConsole: m_pConsole);
315}
316
317int CServerBrowser::Players(const CServerInfo &Item) const
318{
319 return g_Config.m_BrFilterSpectators ? Item.m_NumPlayers : Item.m_NumClients;
320}
321
322int CServerBrowser::Max(const CServerInfo &Item) const
323{
324 return g_Config.m_BrFilterSpectators ? Item.m_MaxPlayers : Item.m_MaxClients;
325}
326
327const CServerInfo *CServerBrowser::SortedGet(int Index) const
328{
329 if(Index < 0 || Index >= (int)m_vSortedServerlist.size())
330 return nullptr;
331 return &m_vpServerlist[m_vSortedServerlist[Index]]->m_Info;
332}
333
334const CServerInfo *CServerBrowser::Get(int Index) const
335{
336 if(Index < 0 || Index >= (int)m_vpServerlist.size())
337 return nullptr;
338 return &m_vpServerlist[Index]->m_Info;
339}
340
341int CServerBrowser::GenerateToken(const NETADDR &Addr) const
342{
343 SHA256_CTX Sha256;
344 sha256_init(ctxt: &Sha256);
345 sha256_update(ctxt: &Sha256, data: m_aTokenSeed, data_len: sizeof(m_aTokenSeed));
346 sha256_update(ctxt: &Sha256, data: (unsigned char *)&Addr, data_len: sizeof(Addr));
347 SHA256_DIGEST Digest = sha256_finish(ctxt: &Sha256);
348 return (Digest.data[0] << 16) | (Digest.data[1] << 8) | Digest.data[2];
349}
350
351int CServerBrowser::GetBasicToken(int Token)
352{
353 return Token & 0xff;
354}
355
356int CServerBrowser::GetExtraToken(int Token)
357{
358 return Token >> 8;
359}
360
361bool CServerBrowser::SortCompareName(int Index1, int Index2) const
362{
363 CServerEntry *pIndex1 = m_vpServerlist[Index1];
364 CServerEntry *pIndex2 = m_vpServerlist[Index2];
365 // make sure empty entries are listed last
366 return (pIndex1->m_GotInfo && pIndex2->m_GotInfo) || (!pIndex1->m_GotInfo && !pIndex2->m_GotInfo) ? str_comp(a: pIndex1->m_Info.m_aName, b: pIndex2->m_Info.m_aName) < 0 :
367 pIndex1->m_GotInfo != 0;
368}
369
370bool CServerBrowser::SortCompareMap(int Index1, int Index2) const
371{
372 CServerEntry *pIndex1 = m_vpServerlist[Index1];
373 CServerEntry *pIndex2 = m_vpServerlist[Index2];
374 return str_comp(a: pIndex1->m_Info.m_aMap, b: pIndex2->m_Info.m_aMap) < 0;
375}
376
377bool CServerBrowser::SortComparePing(int Index1, int Index2) const
378{
379 CServerEntry *pIndex1 = m_vpServerlist[Index1];
380 CServerEntry *pIndex2 = m_vpServerlist[Index2];
381 return pIndex1->m_Info.m_Latency < pIndex2->m_Info.m_Latency;
382}
383
384bool CServerBrowser::SortCompareGametype(int Index1, int Index2) const
385{
386 CServerEntry *pIndex1 = m_vpServerlist[Index1];
387 CServerEntry *pIndex2 = m_vpServerlist[Index2];
388 return str_comp(a: pIndex1->m_Info.m_aGameType, b: pIndex2->m_Info.m_aGameType) < 0;
389}
390
391bool CServerBrowser::SortCompareNumPlayers(int Index1, int Index2) const
392{
393 CServerEntry *pIndex1 = m_vpServerlist[Index1];
394 CServerEntry *pIndex2 = m_vpServerlist[Index2];
395 return pIndex1->m_Info.m_NumFilteredPlayers > pIndex2->m_Info.m_NumFilteredPlayers;
396}
397
398bool CServerBrowser::SortCompareNumClients(int Index1, int Index2) const
399{
400 CServerEntry *pIndex1 = m_vpServerlist[Index1];
401 CServerEntry *pIndex2 = m_vpServerlist[Index2];
402 return pIndex1->m_Info.m_NumClients > pIndex2->m_Info.m_NumClients;
403}
404
405bool CServerBrowser::SortCompareNumFriends(int Index1, int Index2) const
406{
407 CServerEntry *pIndex1 = m_vpServerlist[Index1];
408 CServerEntry *pIndex2 = m_vpServerlist[Index2];
409
410 if(pIndex1->m_Info.m_FriendNum == pIndex2->m_Info.m_FriendNum)
411 return pIndex1->m_Info.m_NumFilteredPlayers > pIndex2->m_Info.m_NumFilteredPlayers;
412 else
413 return pIndex1->m_Info.m_FriendNum > pIndex2->m_Info.m_FriendNum;
414}
415
416bool CServerBrowser::SortCompareNumPlayersAndPing(int Index1, int Index2) const
417{
418 CServerEntry *pIndex1 = m_vpServerlist[Index1];
419 CServerEntry *pIndex2 = m_vpServerlist[Index2];
420
421 if(pIndex1->m_Info.m_NumFilteredPlayers == pIndex2->m_Info.m_NumFilteredPlayers)
422 return pIndex1->m_Info.m_Latency > pIndex2->m_Info.m_Latency;
423 else if(pIndex1->m_Info.m_NumFilteredPlayers == 0 || pIndex2->m_Info.m_NumFilteredPlayers == 0 || pIndex1->m_Info.m_Latency / 100 == pIndex2->m_Info.m_Latency / 100)
424 return pIndex1->m_Info.m_NumFilteredPlayers < pIndex2->m_Info.m_NumFilteredPlayers;
425 else
426 return pIndex1->m_Info.m_Latency > pIndex2->m_Info.m_Latency;
427}
428
429bool CServerBrowser::SortCompareFavoritesNumPlayersAndPing(int Index1, int Index2) const
430{
431 const CServerEntry *pIndex1 = m_vpServerlist[Index1];
432 const CServerEntry *pIndex2 = m_vpServerlist[Index2];
433 const bool IsFavorite1 = pIndex1->m_Info.m_Favorite != TRISTATE::NONE;
434 const bool IsFavorite2 = pIndex2->m_Info.m_Favorite != TRISTATE::NONE;
435 if(IsFavorite1 == IsFavorite2)
436 return SortCompareNumPlayersAndPing(Index1, Index2);
437 return IsFavorite1 && !IsFavorite2;
438}
439
440void CServerBrowser::Filter()
441{
442 m_NumSortedPlayers = 0;
443
444 m_vSortedServerlist.clear();
445 m_vSortedServerlist.reserve(n: m_vpServerlist.size());
446
447 for(auto &Community : m_vCommunities)
448 {
449 Community.m_NumPlayers = 0;
450 }
451
452 // filter the servers
453 for(int ServerIndex = 0; ServerIndex < (int)m_vpServerlist.size(); ServerIndex++)
454 {
455 CServerInfo &Info = m_vpServerlist[ServerIndex]->m_Info;
456 bool Filtered = false;
457
458 if(g_Config.m_BrFilterEmpty && Info.m_NumFilteredPlayers == 0)
459 Filtered = true;
460 else if(g_Config.m_BrFilterFull && Players(Item: Info) == Max(Item: Info))
461 Filtered = true;
462 else if(g_Config.m_BrFilterPw && Info.m_Flags & SERVER_FLAG_PASSWORD)
463 Filtered = true;
464 else if(g_Config.m_BrFilterServerAddress[0] && !str_find_nocase(haystack: Info.m_aAddress, needle: g_Config.m_BrFilterServerAddress))
465 Filtered = true;
466 else if(g_Config.m_BrFilterGametypeStrict && g_Config.m_BrFilterGametype[0] && str_comp_nocase(a: Info.m_aGameType, b: g_Config.m_BrFilterGametype))
467 Filtered = true;
468 else if(!g_Config.m_BrFilterGametypeStrict && g_Config.m_BrFilterGametype[0] && !str_utf8_find_nocase(haystack: Info.m_aGameType, needle: g_Config.m_BrFilterGametype))
469 Filtered = true;
470 else if(g_Config.m_BrFilterUnfinishedMap && Info.m_HasRank == CServerInfo::RANK_RANKED)
471 Filtered = true;
472 else if(g_Config.m_BrFilterLogin && Info.m_RequiresLogin)
473 Filtered = true;
474 else
475 {
476 if(!Communities().empty())
477 {
478 if(m_ServerlistType == IServerBrowser::TYPE_INTERNET || m_ServerlistType == IServerBrowser::TYPE_FAVORITES)
479 {
480 Filtered = CommunitiesFilter().Filtered(pCommunityId: Info.m_aCommunityId);
481 }
482 if(m_ServerlistType == IServerBrowser::TYPE_INTERNET || m_ServerlistType == IServerBrowser::TYPE_FAVORITES ||
483 (m_ServerlistType >= IServerBrowser::TYPE_FAVORITE_COMMUNITY_1 && m_ServerlistType <= IServerBrowser::TYPE_FAVORITE_COMMUNITY_5))
484 {
485 Filtered = Filtered || CountriesFilter().Filtered(pCountryName: Info.m_aCommunityCountry);
486 Filtered = Filtered || TypesFilter().Filtered(pTypeName: Info.m_aCommunityType);
487 }
488 }
489
490 if(!Filtered && g_Config.m_BrFilterCountry)
491 {
492 Filtered = true;
493 // match against player country
494 for(const auto &Client : Info.m_vClients)
495 {
496 if(Client.m_Country == g_Config.m_BrFilterCountryIndex)
497 {
498 Filtered = false;
499 break;
500 }
501 }
502 }
503
504 if(!Filtered && g_Config.m_BrFilterString[0] != '\0')
505 {
506 Info.m_QuickSearchHit = 0;
507
508 const char *pStr = g_Config.m_BrFilterString;
509 char aFilterStr[sizeof(g_Config.m_BrFilterString)];
510 char aFilterStrTrimmed[sizeof(g_Config.m_BrFilterString)];
511 while((pStr = str_next_token(str: pStr, delim: IServerBrowser::SEARCH_EXCLUDE_TOKEN, buffer: aFilterStr, buffer_size: sizeof(aFilterStr))))
512 {
513 str_copy(dst&: aFilterStrTrimmed, src: str_utf8_skip_whitespaces(str: aFilterStr));
514 str_utf8_trim_right(param: aFilterStrTrimmed);
515
516 if(aFilterStrTrimmed[0] == '\0')
517 {
518 continue;
519 }
520 auto MatchesFn = MatchesPart;
521 const int FilterLen = str_length(str: aFilterStrTrimmed);
522 if(aFilterStrTrimmed[0] == '"' && aFilterStrTrimmed[FilterLen - 1] == '"')
523 {
524 aFilterStrTrimmed[FilterLen - 1] = '\0';
525 MatchesFn = MatchesExactly;
526 }
527
528 // match against server name
529 if(MatchesFn(Info.m_aName, aFilterStrTrimmed))
530 {
531 Info.m_QuickSearchHit |= IServerBrowser::QUICK_SERVERNAME;
532 }
533
534 // match against players
535 for(const auto &Client : Info.m_vClients)
536 {
537 if(MatchesFn(Client.m_aName, aFilterStrTrimmed) ||
538 MatchesFn(Client.m_aClan, aFilterStrTrimmed))
539 {
540 if(g_Config.m_BrFilterConnectingPlayers &&
541 str_comp(a: Client.m_aName, b: "(connecting)") == 0 &&
542 Client.m_aClan[0] == '\0')
543 {
544 continue;
545 }
546 Info.m_QuickSearchHit |= IServerBrowser::QUICK_PLAYER;
547 break;
548 }
549 }
550
551 // match against map
552 if(MatchesFn(Info.m_aMap, aFilterStrTrimmed))
553 {
554 Info.m_QuickSearchHit |= IServerBrowser::QUICK_MAPNAME;
555 }
556 }
557
558 if(!Info.m_QuickSearchHit)
559 Filtered = true;
560 }
561
562 if(!Filtered && g_Config.m_BrExcludeString[0] != '\0')
563 {
564 const char *pStr = g_Config.m_BrExcludeString;
565 char aExcludeStr[sizeof(g_Config.m_BrExcludeString)];
566 char aExcludeStrTrimmed[sizeof(g_Config.m_BrExcludeString)];
567 while((pStr = str_next_token(str: pStr, delim: IServerBrowser::SEARCH_EXCLUDE_TOKEN, buffer: aExcludeStr, buffer_size: sizeof(aExcludeStr))))
568 {
569 str_copy(dst&: aExcludeStrTrimmed, src: str_utf8_skip_whitespaces(str: aExcludeStr));
570 str_utf8_trim_right(param: aExcludeStrTrimmed);
571
572 if(aExcludeStrTrimmed[0] == '\0')
573 {
574 continue;
575 }
576 auto MatchesFn = MatchesPart;
577 const int FilterLen = str_length(str: aExcludeStrTrimmed);
578 if(aExcludeStrTrimmed[0] == '"' && aExcludeStrTrimmed[FilterLen - 1] == '"')
579 {
580 aExcludeStrTrimmed[FilterLen - 1] = '\0';
581 MatchesFn = MatchesExactly;
582 }
583
584 // match against server name
585 if(MatchesFn(Info.m_aName, aExcludeStrTrimmed))
586 {
587 Filtered = true;
588 break;
589 }
590
591 // match against map
592 if(MatchesFn(Info.m_aMap, aExcludeStrTrimmed))
593 {
594 Filtered = true;
595 break;
596 }
597
598 // match against gametype
599 if(MatchesFn(Info.m_aGameType, aExcludeStrTrimmed))
600 {
601 Filtered = true;
602 break;
603 }
604 }
605 }
606 }
607
608 // We need to update the friends even if the server is filtered,
609 // because friends are shown regardless of the filter.
610 UpdateServerFriends(pInfo: &Info);
611
612 if(!Filtered)
613 {
614 if(!g_Config.m_BrFilterFriends || Info.m_FriendState != IFriends::FRIEND_NO)
615 {
616 m_NumSortedPlayers += Info.m_NumFilteredPlayers;
617 m_vSortedServerlist.push_back(x: ServerIndex);
618 }
619 }
620
621 if(Info.m_NumClients > 0)
622 {
623 auto Community = std::find_if(first: m_vCommunities.begin(), last: m_vCommunities.end(), pred: [pCommunityId = Info.m_aCommunityId](const auto &Elem) {
624 return str_comp(Elem.Id(), pCommunityId) == 0;
625 });
626 if(Community != m_vCommunities.end())
627 {
628 Community->m_NumPlayers += Info.m_NumClients;
629 }
630 }
631 }
632
633 std::stable_sort(first: m_vCommunities.begin(), last: m_vCommunities.end(), comp: [](const CCommunity &Lhs, const CCommunity &Rhs) {
634 return Lhs.NumPlayers() > Rhs.NumPlayers();
635 });
636}
637
638int CServerBrowser::SortHash() const
639{
640 int i = g_Config.m_BrSort & 0xff;
641 i |= g_Config.m_BrFilterEmpty << 4;
642 i |= g_Config.m_BrFilterFull << 5;
643 i |= g_Config.m_BrFilterSpectators << 6;
644 i |= g_Config.m_BrFilterFriends << 7;
645 i |= g_Config.m_BrFilterPw << 8;
646 i |= g_Config.m_BrSortOrder << 9;
647 i |= g_Config.m_BrFilterGametypeStrict << 12;
648 i |= g_Config.m_BrFilterUnfinishedMap << 13;
649 i |= g_Config.m_BrFilterCountry << 14;
650 i |= g_Config.m_BrFilterConnectingPlayers << 15;
651 i |= g_Config.m_BrFilterLogin << 16;
652 return i;
653}
654
655void CServerBrowser::Sort()
656{
657 // update number of filtered players
658 for(CServerEntry *pEntry : m_vpServerlist)
659 {
660 UpdateServerFilteredPlayers(pInfo: &pEntry->m_Info);
661 }
662
663 // create filtered list
664 Filter();
665
666 // sort
667 if(g_Config.m_BrSortOrder == 2 && (g_Config.m_BrSort == IServerBrowser::SORT_NUMPLAYERS || g_Config.m_BrSort == IServerBrowser::SORT_PING))
668 std::stable_sort(first: m_vSortedServerlist.begin(), last: m_vSortedServerlist.end(), comp: CSortWrap(this, &CServerBrowser::SortCompareNumPlayersAndPing));
669 else if(g_Config.m_BrSort == IServerBrowser::SORT_NAME)
670 std::stable_sort(first: m_vSortedServerlist.begin(), last: m_vSortedServerlist.end(), comp: CSortWrap(this, &CServerBrowser::SortCompareName));
671 else if(g_Config.m_BrSort == IServerBrowser::SORT_PING)
672 std::stable_sort(first: m_vSortedServerlist.begin(), last: m_vSortedServerlist.end(), comp: CSortWrap(this, &CServerBrowser::SortComparePing));
673 else if(g_Config.m_BrSort == IServerBrowser::SORT_MAP)
674 std::stable_sort(first: m_vSortedServerlist.begin(), last: m_vSortedServerlist.end(), comp: CSortWrap(this, &CServerBrowser::SortCompareMap));
675 else if(g_Config.m_BrSort == IServerBrowser::SORT_NUMFRIENDS)
676 std::stable_sort(first: m_vSortedServerlist.begin(), last: m_vSortedServerlist.end(), comp: CSortWrap(this, &CServerBrowser::SortCompareNumFriends));
677 else if(g_Config.m_BrSort == IServerBrowser::SORT_NUMPLAYERS)
678 std::stable_sort(first: m_vSortedServerlist.begin(), last: m_vSortedServerlist.end(), comp: CSortWrap(this, &CServerBrowser::SortCompareNumPlayers));
679 else if(g_Config.m_BrSort == IServerBrowser::SORT_GAMETYPE)
680 std::stable_sort(first: m_vSortedServerlist.begin(), last: m_vSortedServerlist.end(), comp: CSortWrap(this, &CServerBrowser::SortCompareGametype));
681 else if(g_Config.m_BrSort == IServerBrowser::SORT_FAVORITES)
682 std::stable_sort(first: m_vSortedServerlist.begin(), last: m_vSortedServerlist.end(), comp: CSortWrap(this, &CServerBrowser::SortCompareFavoritesNumPlayersAndPing));
683
684 m_Sorthash = SortHash();
685}
686
687void CServerBrowser::RemoveRequest(CServerEntry *pEntry)
688{
689 if(pEntry->m_pPrevReq || pEntry->m_pNextReq || m_pFirstReqServer == pEntry)
690 {
691 if(pEntry->m_pPrevReq)
692 pEntry->m_pPrevReq->m_pNextReq = pEntry->m_pNextReq;
693 else
694 m_pFirstReqServer = pEntry->m_pNextReq;
695
696 if(pEntry->m_pNextReq)
697 pEntry->m_pNextReq->m_pPrevReq = pEntry->m_pPrevReq;
698 else
699 m_pLastReqServer = pEntry->m_pPrevReq;
700
701 pEntry->m_pPrevReq = nullptr;
702 pEntry->m_pNextReq = nullptr;
703 m_NumRequests--;
704 }
705}
706
707CServerBrowser::CServerEntry *CServerBrowser::Find(const NETADDR &Addr)
708{
709 auto Entry = m_ByAddr.find(key: Addr);
710 if(Entry == m_ByAddr.end())
711 {
712 return nullptr;
713 }
714 return m_vpServerlist[Entry->second];
715}
716
717void CServerBrowser::QueueRequest(CServerEntry *pEntry)
718{
719 // add it to the list of servers that we should request info from
720 pEntry->m_pPrevReq = m_pLastReqServer;
721 if(m_pLastReqServer)
722 m_pLastReqServer->m_pNextReq = pEntry;
723 else
724 m_pFirstReqServer = pEntry;
725 m_pLastReqServer = pEntry;
726 pEntry->m_pNextReq = nullptr;
727 m_NumRequests++;
728}
729
730static void ServerBrowserFormatAddresses(char *pBuffer, int BufferSize, NETADDR *pAddrs, int NumAddrs)
731{
732 pBuffer[0] = '\0';
733 for(int i = 0; i < NumAddrs; i++)
734 {
735 if(i != 0)
736 {
737 str_append(dst: pBuffer, src: ",", dst_size: BufferSize);
738 }
739 if(pAddrs[i].type & NETTYPE_TW7)
740 {
741 str_append(dst: pBuffer, src: "tw-0.7+udp://", dst_size: BufferSize);
742 }
743 char aIpAddr[NETADDR_MAXSTRSIZE];
744 net_addr_str(addr: &pAddrs[i], string: aIpAddr, max_length: sizeof(aIpAddr), add_port: true);
745 str_append(dst: pBuffer, src: aIpAddr, dst_size: BufferSize);
746 }
747}
748
749void CServerBrowser::SetInfo(CServerEntry *pEntry, const CServerInfo &Info) const
750{
751 const TRISTATE Favorite = pEntry->m_Info.m_Favorite;
752 const TRISTATE FavoriteAllowPing = pEntry->m_Info.m_FavoriteAllowPing;
753 const int ServerIndex = pEntry->m_Info.m_ServerIndex;
754 const int NumAddresses = pEntry->m_Info.m_NumAddresses;
755 NETADDR aAddresses[MAX_SERVER_ADDRESSES];
756 mem_copy(dest: aAddresses, source: pEntry->m_Info.m_aAddresses, size: sizeof(aAddresses));
757 char aCommunityId[CServerInfo::MAX_COMMUNITY_ID_LENGTH];
758 char aCommunityCountry[CServerInfo::MAX_COMMUNITY_COUNTRY_LENGTH];
759 char aCommunityType[CServerInfo::MAX_COMMUNITY_TYPE_LENGTH];
760 str_copy(dst&: aCommunityId, src: pEntry->m_Info.m_aCommunityId);
761 str_copy(dst&: aCommunityCountry, src: pEntry->m_Info.m_aCommunityCountry);
762 str_copy(dst&: aCommunityType, src: pEntry->m_Info.m_aCommunityType);
763
764 pEntry->m_Info = Info;
765 pEntry->m_Info.m_Favorite = Favorite;
766 pEntry->m_Info.m_FavoriteAllowPing = FavoriteAllowPing;
767 pEntry->m_Info.m_ServerIndex = ServerIndex;
768 mem_copy(dest: pEntry->m_Info.m_aAddresses, source: aAddresses, size: sizeof(pEntry->m_Info.m_aAddresses));
769 pEntry->m_Info.m_NumAddresses = NumAddresses;
770 ServerBrowserFormatAddresses(pBuffer: pEntry->m_Info.m_aAddress, BufferSize: sizeof(pEntry->m_Info.m_aAddress), pAddrs: pEntry->m_Info.m_aAddresses, NumAddrs: pEntry->m_Info.m_NumAddresses);
771 str_copy(dst&: pEntry->m_Info.m_aCommunityId, src: aCommunityId);
772 str_copy(dst&: pEntry->m_Info.m_aCommunityCountry, src: aCommunityCountry);
773 str_copy(dst&: pEntry->m_Info.m_aCommunityType, src: aCommunityType);
774 UpdateServerRank(pInfo: &pEntry->m_Info);
775 pEntry->m_Info.m_GametypeColor = CServerInfo::GametypeColor(pGametype: pEntry->m_Info.m_aGameType);
776
777 if(pEntry->m_Info.m_ClientScoreKind == CServerInfo::CLIENT_SCORE_KIND_UNSPECIFIED)
778 {
779 if(str_find_nocase(haystack: pEntry->m_Info.m_aGameType, needle: "race") || str_find_nocase(haystack: pEntry->m_Info.m_aGameType, needle: "fastcap"))
780 {
781 pEntry->m_Info.m_ClientScoreKind = CServerInfo::CLIENT_SCORE_KIND_TIME_BACKCOMPAT;
782 }
783 else
784 {
785 pEntry->m_Info.m_ClientScoreKind = CServerInfo::CLIENT_SCORE_KIND_POINTS;
786 }
787 }
788
789 class CPlayerScoreNameLess
790 {
791 const int m_ScoreKind;
792
793 public:
794 CPlayerScoreNameLess(int ClientScoreKind) :
795 m_ScoreKind(ClientScoreKind)
796 {
797 }
798
799 bool operator()(const CServerInfo::CClient &Client0, const CServerInfo::CClient &Client1) const
800 {
801 // Sort players before non players
802 if(Client0.m_Player && !Client1.m_Player)
803 return true;
804 if(!Client0.m_Player && Client1.m_Player)
805 return false;
806
807 int Score0 = Client0.m_Score;
808 int Score1 = Client1.m_Score;
809
810 if(m_ScoreKind == CServerInfo::CLIENT_SCORE_KIND_TIME || m_ScoreKind == CServerInfo::CLIENT_SCORE_KIND_TIME_BACKCOMPAT)
811 {
812 // Sort unfinished (-9999) and still connecting players (-1) after others
813 if(Score0 < 0 && Score1 >= 0)
814 return false;
815 if(Score0 >= 0 && Score1 < 0)
816 return true;
817 }
818
819 if(Score0 != Score1)
820 {
821 // Handle the sign change introduced with CLIENT_SCORE_KIND_TIME
822 if(m_ScoreKind == CServerInfo::CLIENT_SCORE_KIND_TIME)
823 return Score0 < Score1;
824 else
825 return Score0 > Score1;
826 }
827
828 return str_comp_nocase(a: Client0.m_aName, b: Client1.m_aName) < 0;
829 }
830 };
831
832 std::sort(first: pEntry->m_Info.m_vClients.begin(), last: pEntry->m_Info.m_vClients.end(), comp: CPlayerScoreNameLess(pEntry->m_Info.m_ClientScoreKind));
833
834 pEntry->m_GotInfo = 1;
835}
836
837void CServerBrowser::SetLatency(NETADDR Addr, int Latency)
838{
839 m_pPingCache->CachePing(Addr, Ping: Latency);
840
841 Addr.port = 0;
842 for(CServerEntry *pEntry : m_vpServerlist)
843 {
844 if(!pEntry->m_GotInfo)
845 {
846 continue;
847 }
848 bool Found = false;
849 for(int i = 0; i < pEntry->m_Info.m_NumAddresses; i++)
850 {
851 NETADDR Other = pEntry->m_Info.m_aAddresses[i];
852 Other.port = 0;
853 if(Addr == Other)
854 {
855 Found = true;
856 break;
857 }
858 }
859 if(!Found)
860 {
861 continue;
862 }
863 int Ping = m_pPingCache->GetPing(pAddrs: pEntry->m_Info.m_aAddresses, NumAddrs: pEntry->m_Info.m_NumAddresses);
864 if(Ping == -1)
865 {
866 continue;
867 }
868 pEntry->m_Info.m_Latency = Ping;
869 pEntry->m_Info.m_LatencyIsEstimated = false;
870 }
871}
872
873CServerBrowser::CServerEntry *CServerBrowser::Add(const NETADDR *pAddrs, int NumAddrs)
874{
875 // create new pEntry
876 CServerEntry *pEntry = &m_ServerlistStorage.emplace_back();
877
878 // set the info
879 mem_copy(dest: pEntry->m_Info.m_aAddresses, source: pAddrs, size: NumAddrs * sizeof(pAddrs[0]));
880 pEntry->m_Info.m_NumAddresses = NumAddrs;
881
882 pEntry->m_Info.m_Latency = 999;
883 pEntry->m_Info.m_HasRank = CServerInfo::RANK_UNAVAILABLE;
884 ServerBrowserFormatAddresses(pBuffer: pEntry->m_Info.m_aAddress, BufferSize: sizeof(pEntry->m_Info.m_aAddress), pAddrs: pEntry->m_Info.m_aAddresses, NumAddrs: pEntry->m_Info.m_NumAddresses);
885 UpdateServerCommunity(pInfo: &pEntry->m_Info);
886 str_copy(dst&: pEntry->m_Info.m_aName, src: pEntry->m_Info.m_aAddress);
887
888 // check if it's a favorite
889 pEntry->m_Info.m_Favorite = m_pFavorites->IsFavorite(pAddrs: pEntry->m_Info.m_aAddresses, NumAddrs: pEntry->m_Info.m_NumAddresses);
890 pEntry->m_Info.m_FavoriteAllowPing = m_pFavorites->IsPingAllowed(pAddrs: pEntry->m_Info.m_aAddresses, NumAddrs: pEntry->m_Info.m_NumAddresses);
891
892 int ServerIndex = m_vpServerlist.size();
893 for(int i = 0; i < NumAddrs; i++)
894 {
895 m_ByAddr[pAddrs[i]] = ServerIndex;
896 }
897
898 // add to list
899 pEntry->m_Info.m_ServerIndex = ServerIndex;
900 if(m_vpServerlist.capacity() == 0)
901 {
902 m_vpServerlist.reserve(n: 128);
903 }
904 m_vpServerlist.push_back(x: pEntry);
905
906 return pEntry;
907}
908
909CServerBrowser::CServerEntry *CServerBrowser::ReplaceEntry(CServerEntry *pEntry, const NETADDR *pAddrs, int NumAddrs)
910{
911 for(int i = 0; i < pEntry->m_Info.m_NumAddresses; i++)
912 {
913 m_ByAddr.erase(key: pEntry->m_Info.m_aAddresses[i]);
914 }
915
916 // set the info
917 mem_copy(dest: pEntry->m_Info.m_aAddresses, source: pAddrs, size: NumAddrs * sizeof(pAddrs[0]));
918 pEntry->m_Info.m_NumAddresses = NumAddrs;
919
920 pEntry->m_Info.m_Latency = 999;
921 pEntry->m_Info.m_HasRank = CServerInfo::RANK_UNAVAILABLE;
922 ServerBrowserFormatAddresses(pBuffer: pEntry->m_Info.m_aAddress, BufferSize: sizeof(pEntry->m_Info.m_aAddress), pAddrs: pEntry->m_Info.m_aAddresses, NumAddrs: pEntry->m_Info.m_NumAddresses);
923 UpdateServerCommunity(pInfo: &pEntry->m_Info);
924 str_copy(dst&: pEntry->m_Info.m_aName, src: pEntry->m_Info.m_aAddress);
925
926 pEntry->m_Info.m_Favorite = m_pFavorites->IsFavorite(pAddrs: pEntry->m_Info.m_aAddresses, NumAddrs: pEntry->m_Info.m_NumAddresses);
927 pEntry->m_Info.m_FavoriteAllowPing = m_pFavorites->IsPingAllowed(pAddrs: pEntry->m_Info.m_aAddresses, NumAddrs: pEntry->m_Info.m_NumAddresses);
928
929 for(int i = 0; i < NumAddrs; i++)
930 {
931 m_ByAddr[pAddrs[i]] = pEntry->m_Info.m_ServerIndex;
932 }
933
934 return pEntry;
935}
936
937void CServerBrowser::OnServerInfoUpdate(const NETADDR &Addr, int Token, const CServerInfo *pInfo)
938{
939 int BasicToken = Token;
940 int ExtraToken = 0;
941 if(pInfo->m_Type == SERVERINFO_EXTENDED)
942 {
943 BasicToken = Token & 0xff;
944 ExtraToken = Token >> 8;
945 }
946
947 CServerEntry *pEntry = Find(Addr);
948
949 if(m_ServerlistType == IServerBrowser::TYPE_LAN)
950 {
951 if(!pEntry)
952 {
953 NETADDR LookupAddr = Addr;
954 if(Addr.type & NETTYPE_TW7)
955 {
956 // don't add 0.7 server if 0.6 server with the same IP and port already exists
957 LookupAddr.type &= ~NETTYPE_TW7;
958 pEntry = Find(Addr: LookupAddr);
959 if(pEntry)
960 return;
961 }
962 else
963 {
964 // replace 0.7 bridge server with 0.6
965 LookupAddr.type |= NETTYPE_TW7;
966 pEntry = Find(Addr: LookupAddr);
967 if(pEntry)
968 pEntry = ReplaceEntry(pEntry, pAddrs: &Addr, NumAddrs: 1);
969 }
970 }
971
972 NETADDR Broadcast = NETADDR_ZEROED;
973 Broadcast.type = (m_pNetClient->NetType() & ~(NETTYPE_WEBSOCKET_IPV4 | NETTYPE_WEBSOCKET_IPV6)) | NETTYPE_LINK_BROADCAST;
974 int TokenBC = GenerateToken(Addr: Broadcast);
975 bool Drop = false;
976 Drop = Drop || BasicToken != GetBasicToken(Token: TokenBC);
977 Drop = Drop || (pInfo->m_Type == SERVERINFO_EXTENDED && ExtraToken != GetExtraToken(Token: TokenBC));
978 if(Drop)
979 {
980 return;
981 }
982
983 if(!pEntry)
984 pEntry = Add(pAddrs: &Addr, NumAddrs: 1);
985 }
986 else
987 {
988 if(!pEntry)
989 {
990 return;
991 }
992 int TokenAddr = GenerateToken(Addr);
993 bool Drop = false;
994 Drop = Drop || BasicToken != GetBasicToken(Token: TokenAddr);
995 Drop = Drop || (pInfo->m_Type == SERVERINFO_EXTENDED && ExtraToken != GetExtraToken(Token: TokenAddr));
996 if(Drop)
997 {
998 return;
999 }
1000 }
1001
1002 if(m_ServerlistType == IServerBrowser::TYPE_LAN)
1003 {
1004 SetInfo(pEntry, Info: *pInfo);
1005 pEntry->m_Info.m_Latency = std::min(a: static_cast<int>((time_get() - m_BroadcastTime) * 1000 / time_freq()), b: 999);
1006 }
1007 else if(pEntry->m_RequestTime > 0)
1008 {
1009 if(!pEntry->m_RequestIgnoreInfo)
1010 {
1011 SetInfo(pEntry, Info: *pInfo);
1012 }
1013
1014 int Latency = std::min(a: static_cast<int>((time_get() - pEntry->m_RequestTime) * 1000 / time_freq()), b: 999);
1015 if(!pEntry->m_RequestIgnoreInfo)
1016 {
1017 pEntry->m_Info.m_Latency = Latency;
1018 }
1019 else
1020 {
1021 char aAddr[NETADDR_MAXSTRSIZE];
1022 net_addr_str(addr: &Addr, string: aAddr, max_length: sizeof(aAddr), add_port: true);
1023 dbg_msg(sys: "serverbrowser", fmt: "received ping response from %s", aAddr);
1024 SetLatency(Addr, Latency);
1025 }
1026 pEntry->m_RequestTime = -1; // Request has been answered
1027 }
1028 RemoveRequest(pEntry);
1029 RequestResort();
1030}
1031
1032void CServerBrowser::Refresh(int Type, bool Force)
1033{
1034 bool ServerListTypeChanged = Force || m_ServerlistType != Type;
1035 int OldServerListType = m_ServerlistType;
1036 m_ServerlistType = Type;
1037 secure_random_fill(bytes: m_aTokenSeed, length: sizeof(m_aTokenSeed));
1038
1039 if(Type == IServerBrowser::TYPE_LAN || (ServerListTypeChanged && OldServerListType == IServerBrowser::TYPE_LAN))
1040 CleanUp();
1041
1042 if(Type == IServerBrowser::TYPE_LAN)
1043 {
1044 unsigned char aBuffer[sizeof(SERVERBROWSE_GETINFO) + 1];
1045 CNetChunk Packet;
1046
1047 /* do the broadcast version */
1048 mem_zero(block: &Packet, size: sizeof(Packet));
1049 Packet.m_Address.type = (m_pNetClient->NetType() & ~(NETTYPE_WEBSOCKET_IPV4 | NETTYPE_WEBSOCKET_IPV6)) | NETTYPE_LINK_BROADCAST;
1050 Packet.m_Flags = NETSENDFLAG_CONNLESS | NETSENDFLAG_EXTENDED;
1051 Packet.m_DataSize = sizeof(aBuffer);
1052 Packet.m_pData = aBuffer;
1053
1054 int Token = GenerateToken(Addr: Packet.m_Address);
1055 mem_copy(dest: aBuffer, source: SERVERBROWSE_GETINFO, size: sizeof(SERVERBROWSE_GETINFO));
1056 aBuffer[sizeof(SERVERBROWSE_GETINFO)] = GetBasicToken(Token);
1057
1058 Packet.m_aExtraData[0] = GetExtraToken(Token) >> 8;
1059 Packet.m_aExtraData[1] = GetExtraToken(Token) & 0xff;
1060
1061 m_BroadcastTime = time_get();
1062
1063 CPacker Packer;
1064 Packer.Reset();
1065 Packer.AddRaw(pData: SERVERBROWSE_GETINFO, Size: sizeof(SERVERBROWSE_GETINFO));
1066 Packer.AddInt(i: Token);
1067
1068 CNetChunk Packet7;
1069 mem_zero(block: &Packet7, size: sizeof(Packet7));
1070 Packet7.m_Address.type = (m_pNetClient->NetType() & ~(NETTYPE_WEBSOCKET_IPV4 | NETTYPE_WEBSOCKET_IPV6)) | NETTYPE_TW7 | NETTYPE_LINK_BROADCAST;
1071 Packet7.m_Flags = NETSENDFLAG_CONNLESS;
1072 Packet7.m_DataSize = Packer.Size();
1073 Packet7.m_pData = Packer.Data();
1074
1075 for(int Port = LAN_PORT_BEGIN; Port <= LAN_PORT_END; Port++)
1076 {
1077 Packet.m_Address.port = Port;
1078 m_pNetClient->Send(pChunk: &Packet);
1079
1080 Packet7.m_Address.port = Port;
1081 m_pNetClient->Send(pChunk: &Packet7);
1082 }
1083
1084 if(g_Config.m_Debug)
1085 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_DEBUG, pFrom: "serverbrowser", pStr: "broadcasting for servers");
1086 }
1087 else
1088 {
1089 m_pHttp->Refresh();
1090 m_pPingCache->Load();
1091 m_RefreshingHttp = true;
1092
1093 if(ServerListTypeChanged && m_pHttp->NumServers() > 0)
1094 {
1095 CleanUp();
1096 UpdateFromHttp();
1097 Sort();
1098 }
1099 }
1100}
1101
1102void CServerBrowser::RequestImpl(const NETADDR &Addr, CServerEntry *pEntry, int *pBasicToken, int *pToken, bool RandomToken) const
1103{
1104 if(g_Config.m_Debug)
1105 {
1106 char aAddrStr[NETADDR_MAXSTRSIZE];
1107 net_addr_str(addr: &Addr, string: aAddrStr, max_length: sizeof(aAddrStr), add_port: true);
1108 char aBuf[256];
1109 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "requesting server info from %s", aAddrStr);
1110 m_pConsole->Print(Level: IConsole::OUTPUT_LEVEL_DEBUG, pFrom: "serverbrowser", pStr: aBuf);
1111 }
1112
1113 int Token = GenerateToken(Addr);
1114 if(RandomToken)
1115 {
1116 int AvoidBasicToken = GetBasicToken(Token);
1117 do
1118 {
1119 secure_random_fill(bytes: &Token, length: sizeof(Token));
1120 Token &= 0xffffff;
1121 } while(GetBasicToken(Token) == AvoidBasicToken);
1122 }
1123 if(pToken)
1124 {
1125 *pToken = Token;
1126 }
1127 if(pBasicToken)
1128 {
1129 *pBasicToken = GetBasicToken(Token);
1130 }
1131
1132 if(Addr.type & NETTYPE_TW7)
1133 {
1134 CPacker Packer;
1135 Packer.Reset();
1136 Packer.AddRaw(pData: SERVERBROWSE_GETINFO, Size: sizeof(SERVERBROWSE_GETINFO));
1137 Packer.AddInt(i: Token);
1138
1139 CNetChunk Packet;
1140 Packet.m_ClientId = -1;
1141 Packet.m_Address = Addr;
1142 Packet.m_Flags = NETSENDFLAG_CONNLESS;
1143 Packet.m_DataSize = Packer.Size();
1144 Packet.m_pData = Packer.Data();
1145 mem_zero(block: &Packet.m_aExtraData, size: sizeof(Packet.m_aExtraData));
1146
1147 m_pNetClient->Send(pChunk: &Packet);
1148 }
1149 else
1150 {
1151 unsigned char aBuffer[sizeof(SERVERBROWSE_GETINFO) + 1];
1152 mem_copy(dest: aBuffer, source: SERVERBROWSE_GETINFO, size: sizeof(SERVERBROWSE_GETINFO));
1153 aBuffer[sizeof(SERVERBROWSE_GETINFO)] = GetBasicToken(Token);
1154
1155 CNetChunk Packet;
1156 Packet.m_ClientId = -1;
1157 Packet.m_Address = Addr;
1158 Packet.m_Flags = NETSENDFLAG_CONNLESS | NETSENDFLAG_EXTENDED;
1159 Packet.m_DataSize = sizeof(aBuffer);
1160 Packet.m_pData = aBuffer;
1161 mem_zero(block: &Packet.m_aExtraData, size: sizeof(Packet.m_aExtraData));
1162 Packet.m_aExtraData[0] = GetExtraToken(Token) >> 8;
1163 Packet.m_aExtraData[1] = GetExtraToken(Token) & 0xff;
1164
1165 m_pNetClient->Send(pChunk: &Packet);
1166 }
1167
1168 if(pEntry)
1169 pEntry->m_RequestTime = time_get();
1170}
1171
1172void CServerBrowser::RequestCurrentServer(const NETADDR &Addr) const
1173{
1174 RequestImpl(Addr, pEntry: nullptr, pBasicToken: nullptr, pToken: nullptr, RandomToken: false);
1175}
1176
1177void CServerBrowser::RequestCurrentServerWithRandomToken(const NETADDR &Addr, int *pBasicToken, int *pToken) const
1178{
1179 RequestImpl(Addr, pEntry: nullptr, pBasicToken, pToken, RandomToken: true);
1180}
1181
1182void CServerBrowser::SetCurrentServerPing(const NETADDR &Addr, int Ping)
1183{
1184 SetLatency(Addr, Latency: std::min(a: Ping, b: 999));
1185}
1186
1187void CServerBrowser::UpdateFromHttp()
1188{
1189 const int OwnLocation = DetermineOwnLocation();
1190
1191 int NumServers = m_pHttp->NumServers();
1192 m_vpServerlist.reserve(n: NumServers);
1193 std::function<bool(const NETADDR *, int)> Want = [](const NETADDR *pAddrs, int NumAddrs) { return true; };
1194 if(m_ServerlistType == IServerBrowser::TYPE_FAVORITES)
1195 {
1196 Want = [this](const NETADDR *pAddrs, int NumAddrs) -> bool {
1197 return m_pFavorites->IsFavorite(pAddrs, NumAddrs) != TRISTATE::NONE;
1198 };
1199 }
1200 else if(m_ServerlistType >= IServerBrowser::TYPE_FAVORITE_COMMUNITY_1 && m_ServerlistType <= IServerBrowser::TYPE_FAVORITE_COMMUNITY_5)
1201 {
1202 const size_t CommunityIndex = m_ServerlistType - IServerBrowser::TYPE_FAVORITE_COMMUNITY_1;
1203 std::vector<const CCommunity *> vpFavoriteCommunities = FavoriteCommunities();
1204 dbg_assert(CommunityIndex < vpFavoriteCommunities.size(), "Invalid community index");
1205 const CCommunity *pWantedCommunity = vpFavoriteCommunities[CommunityIndex];
1206 const bool IsNoneCommunity = str_comp(a: pWantedCommunity->Id(), b: COMMUNITY_NONE) == 0;
1207 Want = [this, pWantedCommunity, IsNoneCommunity](const NETADDR *pAddrs, int NumAddrs) -> bool {
1208 for(int AddressIndex = 0; AddressIndex < NumAddrs; AddressIndex++)
1209 {
1210 const auto CommunityServer = m_CommunityServersByAddr.find(key: CommunityAddressKey(Addr: pAddrs[AddressIndex]));
1211 if(CommunityServer != m_CommunityServersByAddr.end())
1212 {
1213 if(IsNoneCommunity)
1214 {
1215 // Servers with community "none" are not present in m_CommunityServersByAddr, so we ignore
1216 // any server that is found in this map to determine only the servers without community.
1217 return false;
1218 }
1219 else if(str_comp(a: CommunityServer->second.CommunityId(), b: pWantedCommunity->Id()) == 0)
1220 {
1221 return true;
1222 }
1223 }
1224 }
1225 return IsNoneCommunity;
1226 };
1227 }
1228
1229 for(int i = 0; i < NumServers; i++)
1230 {
1231 const CServerInfo &Info = m_pHttp->Server(Index: i);
1232 if(!Want(Info.m_aAddresses, Info.m_NumAddresses))
1233 {
1234 continue;
1235 }
1236 CServerEntry *pEntry = Add(pAddrs: Info.m_aAddresses, NumAddrs: Info.m_NumAddresses);
1237 SetInfo(pEntry, Info);
1238 UpdateServerLatency(pInfo: &pEntry->m_Info, OwnLocation);
1239 pEntry->m_RequestIgnoreInfo = true;
1240 }
1241
1242 if(m_ServerlistType == IServerBrowser::TYPE_FAVORITES)
1243 {
1244 const IFavorites::CEntry *pFavorites;
1245 int NumFavorites;
1246 m_pFavorites->AllEntries(ppEntries: &pFavorites, pNumEntries: &NumFavorites);
1247 for(int i = 0; i < NumFavorites; i++)
1248 {
1249 bool Found = false;
1250 for(int j = 0; j < pFavorites[i].m_NumAddrs; j++)
1251 {
1252 if(Find(Addr: pFavorites[i].m_aAddrs[j]))
1253 {
1254 Found = true;
1255 break;
1256 }
1257 }
1258 if(Found)
1259 {
1260 continue;
1261 }
1262 // (Also add favorites we're not allowed to ping.)
1263 CServerEntry *pEntry = Add(pAddrs: pFavorites[i].m_aAddrs, NumAddrs: pFavorites[i].m_NumAddrs);
1264 if(pFavorites[i].m_AllowPing)
1265 {
1266 QueueRequest(pEntry);
1267 }
1268 }
1269 }
1270
1271 RequestResort();
1272}
1273
1274void CServerBrowser::CleanUp()
1275{
1276 // clear out everything
1277 m_vSortedServerlist.clear();
1278 m_vpServerlist.clear();
1279 m_ServerlistStorage.clear();
1280 m_NumSortedPlayers = 0;
1281 m_ByAddr.clear();
1282 m_pFirstReqServer = nullptr;
1283 m_pLastReqServer = nullptr;
1284 m_NumRequests = 0;
1285 m_CurrentMaxRequests = g_Config.m_BrMaxRequests;
1286}
1287
1288void CServerBrowser::Update()
1289{
1290 int64_t Timeout = time_freq();
1291 int64_t Now = time_get();
1292
1293 const char *pHttpBestUrl;
1294 if(!m_pHttp->GetBestUrl(pBestUrl: &pHttpBestUrl) && pHttpBestUrl != m_pHttpPrevBestUrl)
1295 {
1296 str_copy(dst&: g_Config.m_BrCachedBestServerinfoUrl, src: pHttpBestUrl);
1297 m_pHttpPrevBestUrl = pHttpBestUrl;
1298 }
1299
1300 m_pHttp->Update();
1301
1302 if(m_ServerlistType != TYPE_LAN && m_RefreshingHttp && !m_pHttp->IsRefreshing())
1303 {
1304 m_RefreshingHttp = false;
1305 CleanUp();
1306 UpdateFromHttp();
1307 // TODO: move this somewhere else
1308 Sort();
1309 return;
1310 }
1311
1312 {
1313 CServerEntry *pEntry = m_pFirstReqServer;
1314 int Count = 0;
1315 while(true)
1316 {
1317 if(!pEntry) // no more entries
1318 break;
1319 if(pEntry->m_RequestTime && pEntry->m_RequestTime + Timeout < Now)
1320 {
1321 pEntry = pEntry->m_pNextReq;
1322 continue;
1323 }
1324 // no more than 10 concurrent requests
1325 if(Count == m_CurrentMaxRequests)
1326 break;
1327
1328 if(pEntry->m_RequestTime == 0)
1329 {
1330 RequestImpl(Addr: pEntry->m_Info.m_aAddresses[0], pEntry, pBasicToken: nullptr, pToken: nullptr, RandomToken: false);
1331 }
1332
1333 Count++;
1334 pEntry = pEntry->m_pNextReq;
1335 }
1336
1337 if(m_pFirstReqServer && Count == 0 && m_CurrentMaxRequests > 1) //NO More current Server Requests
1338 {
1339 //reset old ones
1340 pEntry = m_pFirstReqServer;
1341 while(true)
1342 {
1343 if(!pEntry) // no more entries
1344 break;
1345 pEntry->m_RequestTime = 0;
1346 pEntry = pEntry->m_pNextReq;
1347 }
1348
1349 //update max-requests
1350 m_CurrentMaxRequests = m_CurrentMaxRequests / 2;
1351 if(m_CurrentMaxRequests < 1)
1352 m_CurrentMaxRequests = 1;
1353 }
1354 else if(Count == 0 && m_CurrentMaxRequests == 1) //we reached the limit, just release all left requests. IF a server sends us a packet, a new request will be added automatically, so we can delete all
1355 {
1356 pEntry = m_pFirstReqServer;
1357 while(true)
1358 {
1359 if(!pEntry) // no more entries
1360 break;
1361 CServerEntry *pNext = pEntry->m_pNextReq;
1362 RemoveRequest(pEntry); //release request
1363 pEntry = pNext;
1364 }
1365 }
1366 }
1367
1368 // check if we need to resort
1369 if(m_Sorthash != SortHash() || m_NeedResort)
1370 {
1371 for(CServerEntry *pEntry : m_vpServerlist)
1372 {
1373 CServerInfo *pInfo = &pEntry->m_Info;
1374 pInfo->m_Favorite = m_pFavorites->IsFavorite(pAddrs: pInfo->m_aAddresses, NumAddrs: pInfo->m_NumAddresses);
1375 pInfo->m_FavoriteAllowPing = m_pFavorites->IsPingAllowed(pAddrs: pInfo->m_aAddresses, NumAddrs: pInfo->m_NumAddresses);
1376 }
1377 Sort();
1378 m_NeedResort = false;
1379 }
1380}
1381
1382const json_value *CServerBrowser::LoadDDNetInfo()
1383{
1384 LoadDDNetInfoJson();
1385 const int PreviousOwnLocation = DetermineOwnLocation();
1386 LoadDDNetLocation();
1387 const int OwnLocation = DetermineOwnLocation();
1388 const bool UpdateLatency = PreviousOwnLocation != OwnLocation;
1389 LoadDDNetServers();
1390 for(CServerEntry *pEntry : m_vpServerlist)
1391 {
1392 UpdateServerCommunity(pInfo: &pEntry->m_Info);
1393 UpdateServerRank(pInfo: &pEntry->m_Info);
1394 if(UpdateLatency)
1395 {
1396 UpdateServerLatency(pInfo: &pEntry->m_Info, OwnLocation);
1397 }
1398 }
1399 ValidateServerlistType();
1400 RequestResort();
1401 return m_pDDNetInfo;
1402}
1403
1404void CServerBrowser::LoadDDNetInfoJson()
1405{
1406 void *pBuf;
1407 unsigned Length;
1408 if(!m_pStorage->ReadFile(pFilename: DDNET_INFO_FILE, Type: IStorage::TYPE_SAVE, ppResult: &pBuf, pResultLen: &Length))
1409 {
1410 // Keep old info if available
1411 return;
1412 }
1413
1414 m_DDNetInfoSha256 = sha256(message: pBuf, message_len: Length);
1415
1416 json_value_free(m_pDDNetInfo);
1417 json_settings JsonSettings{};
1418 char aError[256];
1419 m_pDDNetInfo = JsonParseEx(pSettings: &JsonSettings, pJson: static_cast<json_char *>(pBuf), Length, pError: aError);
1420 free(ptr: pBuf);
1421
1422 if(m_pDDNetInfo == nullptr)
1423 {
1424 log_error("serverbrowser", "invalid info json: '%s'", aError);
1425 }
1426 else if(m_pDDNetInfo->type != json_object)
1427 {
1428 log_error("serverbrowser", "invalid info root");
1429 json_value_free(m_pDDNetInfo);
1430 m_pDDNetInfo = nullptr;
1431 }
1432}
1433
1434void CServerBrowser::LoadDDNetLocation()
1435{
1436 m_OwnLocation = CServerInfo::LOC_UNKNOWN;
1437 if(m_pDDNetInfo)
1438 {
1439 const json_value &Location = (*m_pDDNetInfo)["location"];
1440 if(Location.type != json_string || CServerInfo::ParseLocation(pResult: &m_OwnLocation, pString: Location))
1441 {
1442 log_error("serverbrowser", "invalid location");
1443 }
1444 }
1445}
1446
1447bool CServerBrowser::ParseCommunityServers(CCommunity *pCommunity, const json_value &Servers)
1448{
1449 for(unsigned ServerIndex = 0; ServerIndex < Servers.u.array.length; ++ServerIndex)
1450 {
1451 // pServer - { name, flagId, servers }
1452 const json_value &Server = Servers[ServerIndex];
1453 if(Server.type != json_object)
1454 {
1455 log_error("serverbrowser", "invalid server (ServerIndex=%u)", ServerIndex);
1456 return false;
1457 }
1458
1459 const json_value &Name = Server["name"];
1460 const json_value &FlagId = Server["flagId"];
1461 const json_value &Types = Server["servers"];
1462 if(Name.type != json_string || FlagId.type != json_integer || Types.type != json_object)
1463 {
1464 log_error("serverbrowser", "invalid server attribute (ServerIndex=%u)", ServerIndex);
1465 return false;
1466 }
1467 if(Types.u.object.length == 0)
1468 continue;
1469
1470 if(str_has_cc(str: Name.u.string.ptr))
1471 {
1472 log_error("serverbrowser", "invalid community country name (ServerIndex=%u)", ServerIndex);
1473 return false;
1474 }
1475 if(!in_range(a: FlagId.u.integer, lower: (int64_t)CountryCode::MINIMUM, upper: (int64_t)CountryCode::MAXIMUM))
1476 {
1477 log_error("serverbrowser", "invalid community country code (ServerIndex=%u)", ServerIndex);
1478 return false;
1479 }
1480 pCommunity->m_vCountries.emplace_back(args: Name.u.string.ptr, args: FlagId.u.integer);
1481 CCommunityCountry *pCountry = &pCommunity->m_vCountries.back();
1482
1483 for(unsigned TypeIndex = 0; TypeIndex < Types.u.object.length; ++TypeIndex)
1484 {
1485 const json_value &Addresses = *Types.u.object.values[TypeIndex].value;
1486 if(Addresses.type != json_array)
1487 {
1488 log_error("serverbrowser", "invalid addresses (ServerIndex=%u, TypeIndex=%u)", ServerIndex, TypeIndex);
1489 return false;
1490 }
1491 if(Addresses.u.array.length == 0)
1492 continue;
1493
1494 const char *pTypeName = Types.u.object.values[TypeIndex].name;
1495
1496 // add type if it doesn't exist already
1497 const auto CommunityType = std::find_if(first: pCommunity->m_vTypes.begin(), last: pCommunity->m_vTypes.end(), pred: [pTypeName](const auto &Elem) {
1498 return str_comp(Elem.Name(), pTypeName) == 0;
1499 });
1500 if(CommunityType == pCommunity->m_vTypes.end())
1501 {
1502 pCommunity->m_vTypes.emplace_back(args&: pTypeName);
1503 }
1504
1505 // add addresses
1506 for(unsigned AddressIndex = 0; AddressIndex < Addresses.u.array.length; ++AddressIndex)
1507 {
1508 const json_value &Address = Addresses[AddressIndex];
1509 if(Address.type != json_string)
1510 {
1511 log_error("serverbrowser", "invalid address (ServerIndex=%u, TypeIndex=%u, AddressIndex=%u)", ServerIndex, TypeIndex, AddressIndex);
1512 return false;
1513 }
1514 NETADDR NetAddr;
1515 if(net_addr_from_str(addr: &NetAddr, string: Address.u.string.ptr))
1516 {
1517 log_error("serverbrowser", "invalid address (ServerIndex=%u, TypeIndex=%u, AddressIndex=%u)", ServerIndex, TypeIndex, AddressIndex);
1518 continue;
1519 }
1520 pCountry->m_vServers.emplace_back(args&: NetAddr, args&: pTypeName);
1521 }
1522 }
1523 }
1524 return true;
1525}
1526
1527bool CServerBrowser::ParseCommunityFinishes(CCommunity *pCommunity, const json_value &Finishes)
1528{
1529 for(unsigned FinishIndex = 0; FinishIndex < Finishes.u.array.length; ++FinishIndex)
1530 {
1531 const json_value &Finish = Finishes[FinishIndex];
1532 if(Finish.type != json_string)
1533 {
1534 log_error("serverbrowser", "invalid rank (FinishIndex=%u)", FinishIndex);
1535 return false;
1536 }
1537 pCommunity->m_FinishedMaps.emplace(args: (const char *)Finish);
1538 }
1539 return true;
1540}
1541
1542void CServerBrowser::LoadDDNetServers()
1543{
1544 // Parse communities
1545 m_vCommunities.clear();
1546 m_CommunityServersByAddr.clear();
1547
1548 if(!m_pDDNetInfo)
1549 {
1550 return;
1551 }
1552
1553 const json_value &Communities = (*m_pDDNetInfo)["communities"];
1554 if(Communities.type != json_array)
1555 {
1556 return;
1557 }
1558
1559 for(unsigned CommunityIndex = 0; CommunityIndex < Communities.u.array.length; ++CommunityIndex)
1560 {
1561 const json_value &Community = Communities[CommunityIndex];
1562 if(Community.type != json_object)
1563 {
1564 log_error("serverbrowser", "invalid community (CommunityIndex=%d)", (int)CommunityIndex);
1565 continue;
1566 }
1567 const json_value &Id = Community["id"];
1568 if(Id.type != json_string)
1569 {
1570 log_error("serverbrowser", "invalid community id (CommunityIndex=%d)", (int)CommunityIndex);
1571 continue;
1572 }
1573 const json_value &Icon = Community["icon"];
1574 const json_value &IconSha256 = Icon["sha256"];
1575 const json_value &IconUrl = Icon["url"];
1576 const json_value &Name = Community["name"];
1577 const json_value HasFinishes = Community["has_finishes"];
1578 const json_value *pFinishes = &Community["finishes"];
1579 const json_value *pServers = &Community["servers"];
1580 // We accidentally set finishes/servers to be part of icon in
1581 // the past, so support that, too. Can be removed once we make
1582 // a breaking change to the whole thing, necessitating a new
1583 // endpoint.
1584 if(pFinishes->type == json_none)
1585 {
1586 pServers = &Icon["finishes"];
1587 }
1588 if(pServers->type == json_none)
1589 {
1590 pServers = &Icon["servers"];
1591 }
1592 // Backward compatibility.
1593 if(pFinishes->type == json_none)
1594 {
1595 if(str_comp(a: Id, b: COMMUNITY_DDNET) == 0)
1596 {
1597 pFinishes = &(*m_pDDNetInfo)["maps"];
1598 }
1599 }
1600 if(pServers->type == json_none)
1601 {
1602 if(str_comp(a: Id, b: COMMUNITY_DDNET) == 0)
1603 {
1604 pServers = &(*m_pDDNetInfo)["servers"];
1605 }
1606 else if(str_comp(a: Id, b: "kog") == 0)
1607 {
1608 pServers = &(*m_pDDNetInfo)["servers-kog"];
1609 }
1610 }
1611 if(false ||
1612 Icon.type != json_object ||
1613 IconSha256.type != json_string ||
1614 IconUrl.type != json_string ||
1615 Name.type != json_string ||
1616 HasFinishes.type != json_boolean ||
1617 (pFinishes->type != json_array && pFinishes->type != json_none) ||
1618 pServers->type != json_array)
1619 {
1620 log_error("serverbrowser", "invalid community attribute (CommunityId=%s)", (const char *)Id);
1621 continue;
1622 }
1623 SHA256_DIGEST ParsedIconSha256;
1624 if(sha256_from_str(out: &ParsedIconSha256, str: IconSha256) != 0)
1625 {
1626 log_error("serverbrowser", "invalid community icon sha256 (CommunityId=%s)", (const char *)Id);
1627 continue;
1628 }
1629 CCommunity NewCommunity(Id, Name, ParsedIconSha256, IconUrl);
1630 if(!ParseCommunityServers(pCommunity: &NewCommunity, Servers: *pServers))
1631 {
1632 log_error("serverbrowser", "invalid community servers (CommunityId=%s)", NewCommunity.Id());
1633 continue;
1634 }
1635 NewCommunity.m_HasFinishes = HasFinishes;
1636 if(NewCommunity.m_HasFinishes && pFinishes->type == json_array && !ParseCommunityFinishes(pCommunity: &NewCommunity, Finishes: *pFinishes))
1637 {
1638 log_error("serverbrowser", "invalid community finishes (CommunityId=%s)", NewCommunity.Id());
1639 continue;
1640 }
1641
1642 for(const auto &Country : NewCommunity.Countries())
1643 {
1644 for(const auto &Server : Country.Servers())
1645 {
1646 m_CommunityServersByAddr.emplace(args: CommunityAddressKey(Addr: Server.Address()), args: CCommunityServer(NewCommunity.Id(), Country.Name(), Server.TypeName()));
1647 }
1648 }
1649 m_vCommunities.push_back(x: std::move(NewCommunity));
1650 }
1651
1652 // Add default none community
1653 {
1654 CCommunity NoneCommunity(COMMUNITY_NONE, "None", std::nullopt, "");
1655 NoneCommunity.m_vCountries.emplace_back(args: COMMUNITY_COUNTRY_NONE, args: CountryCode::DEFAULT);
1656 NoneCommunity.m_vTypes.emplace_back(args: COMMUNITY_TYPE_NONE);
1657 m_vCommunities.push_back(x: std::move(NoneCommunity));
1658 }
1659
1660 // Remove unknown elements from exclude lists
1661 CleanFilters();
1662}
1663
1664void CServerBrowser::UpdateServerFilteredPlayers(CServerInfo *pInfo) const
1665{
1666 pInfo->m_NumFilteredPlayers = g_Config.m_BrFilterSpectators ? pInfo->m_NumPlayers : pInfo->m_NumClients;
1667 if(g_Config.m_BrFilterConnectingPlayers)
1668 {
1669 for(const auto &Client : pInfo->m_vClients)
1670 {
1671 if((!g_Config.m_BrFilterSpectators || Client.m_Player) && str_comp(a: Client.m_aName, b: "(connecting)") == 0 && Client.m_aClan[0] == '\0')
1672 pInfo->m_NumFilteredPlayers--;
1673 }
1674 }
1675}
1676
1677void CServerBrowser::UpdateServerFriends(CServerInfo *pInfo) const
1678{
1679 pInfo->m_FriendState = IFriends::FRIEND_NO;
1680 pInfo->m_FriendNum = 0;
1681 for(auto &Client : pInfo->m_vClients)
1682 {
1683 Client.m_FriendState = m_pFriends->GetFriendState(pName: Client.m_aName, pClan: Client.m_aClan);
1684 pInfo->m_FriendState = std::max(a: pInfo->m_FriendState, b: Client.m_FriendState);
1685 if(Client.m_FriendState != IFriends::FRIEND_NO)
1686 pInfo->m_FriendNum++;
1687 }
1688}
1689
1690void CServerBrowser::UpdateServerCommunity(CServerInfo *pInfo) const
1691{
1692 for(int AddressIndex = 0; AddressIndex < pInfo->m_NumAddresses; AddressIndex++)
1693 {
1694 const auto Community = m_CommunityServersByAddr.find(key: CommunityAddressKey(Addr: pInfo->m_aAddresses[AddressIndex]));
1695 if(Community != m_CommunityServersByAddr.end())
1696 {
1697 str_copy(dst&: pInfo->m_aCommunityId, src: Community->second.CommunityId());
1698 str_copy(dst&: pInfo->m_aCommunityCountry, src: Community->second.CountryName());
1699 str_copy(dst&: pInfo->m_aCommunityType, src: Community->second.TypeName());
1700 return;
1701 }
1702 }
1703 str_copy(dst&: pInfo->m_aCommunityId, src: COMMUNITY_NONE);
1704 str_copy(dst&: pInfo->m_aCommunityCountry, src: COMMUNITY_COUNTRY_NONE);
1705 str_copy(dst&: pInfo->m_aCommunityType, src: COMMUNITY_TYPE_NONE);
1706}
1707
1708void CServerBrowser::UpdateServerRank(CServerInfo *pInfo) const
1709{
1710 const CCommunity *pCommunity = Community(pCommunityId: pInfo->m_aCommunityId);
1711 pInfo->m_HasRank = pCommunity == nullptr ? CServerInfo::RANK_UNAVAILABLE : pCommunity->HasRank(pMap: pInfo->m_aMap);
1712}
1713
1714void CServerBrowser::UpdateServerLatency(CServerInfo *pInfo, int OwnLocation) const
1715{
1716 int Ping = m_pPingCache->GetPing(pAddrs: pInfo->m_aAddresses, NumAddrs: pInfo->m_NumAddresses);
1717 pInfo->m_LatencyIsEstimated = Ping == -1;
1718 if(pInfo->m_LatencyIsEstimated)
1719 {
1720 pInfo->m_Latency = CServerInfo::EstimateLatency(Loc1: OwnLocation, Loc2: pInfo->m_Location);
1721 }
1722 else
1723 {
1724 pInfo->m_Latency = Ping;
1725 }
1726}
1727
1728int CServerBrowser::DetermineOwnLocation() const
1729{
1730 if(str_comp(a: g_Config.m_BrLocation, b: "auto") == 0)
1731 {
1732 return m_OwnLocation;
1733 }
1734
1735 int OwnLocation;
1736 if(CServerInfo::ParseLocation(pResult: &OwnLocation, pString: g_Config.m_BrLocation))
1737 {
1738 log_error("serverbrowser", "Cannot parse br_location: '%s'", g_Config.m_BrLocation);
1739 }
1740 return OwnLocation;
1741}
1742
1743void CServerBrowser::ValidateServerlistType()
1744{
1745 if(m_ServerlistType >= IServerBrowser::TYPE_FAVORITE_COMMUNITY_1 &&
1746 m_ServerlistType <= IServerBrowser::TYPE_FAVORITE_COMMUNITY_5)
1747 {
1748 const size_t CommunityIndex = m_ServerlistType - IServerBrowser::TYPE_FAVORITE_COMMUNITY_1;
1749 if(CommunityIndex >= FavoriteCommunities().size())
1750 {
1751 // Reset to internet type if there is no favorite community for the current browser type,
1752 // in case communities have been removed.
1753 m_ServerlistType = IServerBrowser::TYPE_INTERNET;
1754 }
1755 }
1756}
1757
1758const char *CServerBrowser::GetTutorialServer()
1759{
1760 const CCommunity *pCommunity = Community(pCommunityId: COMMUNITY_DDNET);
1761 if(pCommunity == nullptr)
1762 return nullptr;
1763
1764 const char *pBestAddr = nullptr;
1765 int BestLatency = std::numeric_limits<int>::max();
1766 for(const auto &Country : pCommunity->Countries())
1767 {
1768 for(const auto &Server : Country.Servers())
1769 {
1770 if(str_comp(a: Server.TypeName(), b: "Tutorial") != 0)
1771 continue;
1772 const CServerEntry *pEntry = Find(Addr: Server.Address());
1773 if(!pEntry)
1774 continue;
1775 if(pEntry->m_Info.m_NumPlayers > pEntry->m_Info.m_MaxPlayers - 10)
1776 continue;
1777 if(pEntry->m_Info.m_Latency >= BestLatency)
1778 continue;
1779 BestLatency = pEntry->m_Info.m_Latency;
1780 pBestAddr = pEntry->m_Info.m_aAddress;
1781 }
1782 }
1783 return pBestAddr;
1784}
1785
1786bool CServerBrowser::IsRefreshing() const
1787{
1788 return m_pFirstReqServer != nullptr;
1789}
1790
1791bool CServerBrowser::IsGettingServerlist() const
1792{
1793 return m_pHttp->IsRefreshing();
1794}
1795
1796bool CServerBrowser::IsServerlistError() const
1797{
1798 return m_pHttp->IsError();
1799}
1800
1801int CServerBrowser::LoadingProgression() const
1802{
1803 if(m_vpServerlist.empty())
1804 return 0;
1805
1806 int Servers = m_vpServerlist.size();
1807 int Loaded = m_vpServerlist.size() - m_NumRequests;
1808 return 100.0f * Loaded / Servers;
1809}
1810
1811bool CCommunity::HasCountry(const char *pCountryName) const
1812{
1813 return std::find_if(first: Countries().begin(), last: Countries().end(), pred: [pCountryName](const auto &Elem) {
1814 return str_comp(Elem.Name(), pCountryName) == 0;
1815 }) != Countries().end();
1816}
1817
1818bool CCommunity::HasType(const char *pTypeName) const
1819{
1820 return std::find_if(first: Types().begin(), last: Types().end(), pred: [pTypeName](const auto &Elem) {
1821 return str_comp(Elem.Name(), pTypeName) == 0;
1822 }) != Types().end();
1823}
1824
1825CServerInfo::ERankState CCommunity::HasRank(const char *pMap) const
1826{
1827 if(!HasRanks())
1828 return CServerInfo::RANK_UNAVAILABLE;
1829 const CCommunityMap Needle(pMap);
1830 return !m_FinishedMaps.contains(x: Needle) ? CServerInfo::RANK_UNRANKED : CServerInfo::RANK_RANKED;
1831}
1832
1833const std::vector<CCommunity> &CServerBrowser::Communities() const
1834{
1835 return m_vCommunities;
1836}
1837
1838const CCommunity *CServerBrowser::Community(const char *pCommunityId) const
1839{
1840 const auto Community = std::find_if(first: Communities().begin(), last: Communities().end(), pred: [pCommunityId](const auto &Elem) {
1841 return str_comp(Elem.Id(), pCommunityId) == 0;
1842 });
1843 return Community == Communities().end() ? nullptr : &(*Community);
1844}
1845
1846std::vector<const CCommunity *> CServerBrowser::SelectedCommunities() const
1847{
1848 std::vector<const CCommunity *> vpSelected;
1849 for(const auto &Community : Communities())
1850 {
1851 if(!CommunitiesFilter().Filtered(pCommunityId: Community.Id()))
1852 {
1853 vpSelected.push_back(x: &Community);
1854 }
1855 }
1856 return vpSelected;
1857}
1858
1859std::vector<const CCommunity *> CServerBrowser::FavoriteCommunities() const
1860{
1861 // This is done differently than SelectedCommunities because the favorite
1862 // communities should be returned in the order specified by the user.
1863 std::vector<const CCommunity *> vpFavorites;
1864 for(const auto &CommunityId : FavoriteCommunitiesFilter().Entries())
1865 {
1866 const CCommunity *pCommunity = Community(pCommunityId: CommunityId.Id());
1867 if(pCommunity)
1868 {
1869 vpFavorites.push_back(x: pCommunity);
1870 }
1871 }
1872 return vpFavorites;
1873}
1874
1875std::vector<const CCommunity *> CServerBrowser::CurrentCommunities() const
1876{
1877 if(m_ServerlistType == IServerBrowser::TYPE_INTERNET || m_ServerlistType == IServerBrowser::TYPE_FAVORITES)
1878 {
1879 return SelectedCommunities();
1880 }
1881 else if(m_ServerlistType >= IServerBrowser::TYPE_FAVORITE_COMMUNITY_1 && m_ServerlistType <= IServerBrowser::TYPE_FAVORITE_COMMUNITY_5)
1882 {
1883 const size_t CommunityIndex = m_ServerlistType - IServerBrowser::TYPE_FAVORITE_COMMUNITY_1;
1884 std::vector<const CCommunity *> vpFavoriteCommunities = FavoriteCommunities();
1885 dbg_assert(CommunityIndex < vpFavoriteCommunities.size(), "Invalid favorite community serverbrowser type");
1886 return {vpFavoriteCommunities[CommunityIndex]};
1887 }
1888 else
1889 {
1890 return {};
1891 }
1892}
1893
1894unsigned CServerBrowser::CurrentCommunitiesHash() const
1895{
1896 unsigned Hash = 5381;
1897 for(const CCommunity *pCommunity : CurrentCommunities())
1898 {
1899 Hash = (Hash << 5) + Hash + str_quickhash(str: pCommunity->Id());
1900 }
1901 return Hash;
1902}
1903
1904void CCommunityCache::Update(bool Force)
1905{
1906 const unsigned CommunitiesHash = m_pServerBrowser->CurrentCommunitiesHash();
1907 const bool TypeChanged = m_LastType != m_pServerBrowser->GetCurrentType();
1908 const bool CurrentCommunitiesChanged = m_LastType == m_pServerBrowser->GetCurrentType() && m_SelectedCommunitiesHash != CommunitiesHash;
1909 if(CurrentCommunitiesChanged && m_pServerBrowser->GetCurrentType() >= IServerBrowser::TYPE_FAVORITE_COMMUNITY_1 && m_pServerBrowser->GetCurrentType() <= IServerBrowser::TYPE_FAVORITE_COMMUNITY_5)
1910 {
1911 // Favorite community was changed while its type is active,
1912 // refresh to get correct serverlist for updated community.
1913 m_pServerBrowser->Refresh(Type: m_pServerBrowser->GetCurrentType(), Force: true);
1914 }
1915
1916 if(!Force && m_InfoSha256 == m_pServerBrowser->DDNetInfoSha256() &&
1917 !CurrentCommunitiesChanged && !TypeChanged)
1918 {
1919 return;
1920 }
1921
1922 m_InfoSha256 = m_pServerBrowser->DDNetInfoSha256();
1923 m_LastType = m_pServerBrowser->GetCurrentType();
1924 m_SelectedCommunitiesHash = CommunitiesHash;
1925 m_vpSelectedCommunities = m_pServerBrowser->CurrentCommunities();
1926
1927 m_vpSelectableCountries.clear();
1928 m_vpSelectableTypes.clear();
1929 for(const CCommunity *pCommunity : m_vpSelectedCommunities)
1930 {
1931 for(const auto &Country : pCommunity->Countries())
1932 {
1933 const auto ExistingCountry = std::find_if(first: m_vpSelectableCountries.begin(), last: m_vpSelectableCountries.end(), pred: [&](const CCommunityCountry *pOther) {
1934 return str_comp(a: Country.Name(), b: pOther->Name()) == 0 && Country.FlagId() == pOther->FlagId();
1935 });
1936 if(ExistingCountry == m_vpSelectableCountries.end())
1937 {
1938 m_vpSelectableCountries.push_back(x: &Country);
1939 }
1940 }
1941 for(const auto &Type : pCommunity->Types())
1942 {
1943 const auto ExistingType = std::find_if(first: m_vpSelectableTypes.begin(), last: m_vpSelectableTypes.end(), pred: [&](const CCommunityType *pOther) {
1944 return str_comp(a: Type.Name(), b: pOther->Name()) == 0;
1945 });
1946 if(ExistingType == m_vpSelectableTypes.end())
1947 {
1948 m_vpSelectableTypes.push_back(x: &Type);
1949 }
1950 }
1951 }
1952
1953 m_AnyRanksAvailable = std::any_of(first: m_vpSelectedCommunities.begin(), last: m_vpSelectedCommunities.end(), pred: [](const CCommunity *pCommunity) {
1954 return pCommunity->HasRanks();
1955 });
1956
1957 // Country/type filters not shown if there are no countries and types, or if only the none-community is selected
1958 m_CountryTypesFilterAvailable = (!m_vpSelectableCountries.empty() || !m_vpSelectableTypes.empty()) &&
1959 (m_vpSelectedCommunities.size() != 1 || str_comp(a: m_vpSelectedCommunities[0]->Id(), b: IServerBrowser::COMMUNITY_NONE) != 0);
1960
1961 if(m_pServerBrowser->GetCurrentType() >= IServerBrowser::TYPE_FAVORITE_COMMUNITY_1 && m_pServerBrowser->GetCurrentType() <= IServerBrowser::TYPE_FAVORITE_COMMUNITY_5)
1962 {
1963 const size_t CommunityIndex = m_pServerBrowser->GetCurrentType() - IServerBrowser::TYPE_FAVORITE_COMMUNITY_1;
1964 std::vector<const CCommunity *> vpFavoriteCommunities = m_pServerBrowser->FavoriteCommunities();
1965 dbg_assert(CommunityIndex < vpFavoriteCommunities.size(), "Invalid favorite community serverbrowser type");
1966 m_pCountryTypeFilterKey = vpFavoriteCommunities[CommunityIndex]->Id();
1967 }
1968 else
1969 {
1970 m_pCountryTypeFilterKey = IServerBrowser::COMMUNITY_ALL;
1971 }
1972
1973 m_pServerBrowser->CleanFilters();
1974}
1975
1976void CFavoriteCommunityFilterList::Add(const char *pCommunityId)
1977{
1978 // Remove community if it's already a favorite, so it will be added again at
1979 // the end of the list, to allow setting the entire list easier with binds.
1980 Remove(pCommunityId);
1981
1982 // Ensure maximum number of favorite communities, by removing the least-recently
1983 // added community from the beginning, when the maximum number of favorite
1984 // communities has been reached.
1985 constexpr size_t MaxFavoriteCommunities = IServerBrowser::TYPE_FAVORITE_COMMUNITY_5 - IServerBrowser::TYPE_FAVORITE_COMMUNITY_1 + 1;
1986 if(m_vEntries.size() >= MaxFavoriteCommunities)
1987 {
1988 dbg_assert(m_vEntries.size() == MaxFavoriteCommunities, "Maximum number of communities can never be exceeded");
1989 m_vEntries.erase(position: m_vEntries.begin());
1990 }
1991 m_vEntries.emplace_back(args&: pCommunityId);
1992}
1993
1994void CFavoriteCommunityFilterList::Remove(const char *pCommunityId)
1995{
1996 auto FoundCommunity = std::find(first: m_vEntries.begin(), last: m_vEntries.end(), val: CCommunityId(pCommunityId));
1997 if(FoundCommunity != m_vEntries.end())
1998 {
1999 m_vEntries.erase(position: FoundCommunity);
2000 }
2001}
2002
2003void CFavoriteCommunityFilterList::Clear()
2004{
2005 m_vEntries.clear();
2006}
2007
2008bool CFavoriteCommunityFilterList::Filtered(const char *pCommunityId) const
2009{
2010 return std::find(first: m_vEntries.begin(), last: m_vEntries.end(), val: CCommunityId(pCommunityId)) != m_vEntries.end();
2011}
2012
2013bool CFavoriteCommunityFilterList::Empty() const
2014{
2015 return m_vEntries.empty();
2016}
2017
2018void CFavoriteCommunityFilterList::Clean(const std::vector<CCommunity> &vAllowedCommunities)
2019{
2020 auto It = std::remove_if(first: m_vEntries.begin(), last: m_vEntries.end(), pred: [&](const auto &Community) {
2021 return std::find_if(vAllowedCommunities.begin(), vAllowedCommunities.end(), [&](const CCommunity &AllowedCommunity) {
2022 return str_comp(Community.Id(), AllowedCommunity.Id()) == 0;
2023 }) == vAllowedCommunities.end();
2024 });
2025 m_vEntries.erase(first: It, last: m_vEntries.end());
2026}
2027
2028void CFavoriteCommunityFilterList::Save(IConfigManager *pConfigManager) const
2029{
2030 char aBuf[32 + CServerInfo::MAX_COMMUNITY_ID_LENGTH];
2031 for(const auto &FavoriteCommunity : m_vEntries)
2032 {
2033 str_copy(dst&: aBuf, src: "add_favorite_community \"");
2034 str_append(dst&: aBuf, src: FavoriteCommunity.Id());
2035 str_append(dst&: aBuf, src: "\"");
2036 pConfigManager->WriteLine(pLine: aBuf);
2037 }
2038}
2039
2040const std::vector<CCommunityId> &CFavoriteCommunityFilterList::Entries() const
2041{
2042 return m_vEntries;
2043}
2044
2045template<typename TNamedElement, typename TElementName>
2046static bool IsSubsetEquals(const std::vector<const TNamedElement *> &vpLeft, const std::set<TElementName> &Right)
2047{
2048 return vpLeft.size() <= Right.size() && std::all_of(vpLeft.begin(), vpLeft.end(), [&](const TNamedElement *pElem) {
2049 return Right.contains(TElementName(pElem->Name()));
2050 });
2051}
2052
2053void CExcludedCommunityFilterList::Add(const char *pCommunityId)
2054{
2055 m_Entries.emplace(args&: pCommunityId);
2056}
2057
2058void CExcludedCommunityFilterList::Remove(const char *pCommunityId)
2059{
2060 m_Entries.erase(x: CCommunityId(pCommunityId));
2061}
2062
2063void CExcludedCommunityFilterList::Clear()
2064{
2065 m_Entries.clear();
2066}
2067
2068bool CExcludedCommunityFilterList::Filtered(const char *pCommunityId) const
2069{
2070 return std::find(first: m_Entries.begin(), last: m_Entries.end(), val: CCommunityId(pCommunityId)) != m_Entries.end();
2071}
2072
2073bool CExcludedCommunityFilterList::Empty() const
2074{
2075 return m_Entries.empty();
2076}
2077
2078void CExcludedCommunityFilterList::Clean(const std::vector<CCommunity> &vAllowedCommunities)
2079{
2080 for(auto It = m_Entries.begin(); It != m_Entries.end();)
2081 {
2082 const bool Found = std::find_if(first: vAllowedCommunities.begin(), last: vAllowedCommunities.end(), pred: [&](const CCommunity &AllowedCommunity) {
2083 return str_comp(a: It->Id(), b: AllowedCommunity.Id()) == 0;
2084 }) != vAllowedCommunities.end();
2085 if(Found)
2086 {
2087 ++It;
2088 }
2089 else
2090 {
2091 It = m_Entries.erase(position: It);
2092 }
2093 }
2094 // Prevent filter that would exclude all allowed communities
2095 if(m_Entries.size() == vAllowedCommunities.size())
2096 {
2097 m_Entries.clear();
2098 }
2099}
2100
2101void CExcludedCommunityFilterList::Save(IConfigManager *pConfigManager) const
2102{
2103 char aBuf[32 + CServerInfo::MAX_COMMUNITY_ID_LENGTH];
2104 for(const auto &ExcludedCommunity : m_Entries)
2105 {
2106 str_copy(dst&: aBuf, src: "add_excluded_community \"");
2107 str_append(dst&: aBuf, src: ExcludedCommunity.Id());
2108 str_append(dst&: aBuf, src: "\"");
2109 pConfigManager->WriteLine(pLine: aBuf);
2110 }
2111}
2112
2113void CExcludedCommunityCountryFilterList::Add(const char *pCountryName)
2114{
2115 // Handle special case that all selectable entries are currently filtered,
2116 // where adding more entries to the exclusion list would have no effect.
2117 auto CommunityEntry = m_Entries.find(x: m_pCommunityCache->CountryTypeFilterKey());
2118 if(CommunityEntry != m_Entries.end() && IsSubsetEquals(vpLeft: m_pCommunityCache->SelectableCountries(), Right: CommunityEntry->second))
2119 {
2120 for(const CCommunityCountry *pSelectableCountry : m_pCommunityCache->SelectableCountries())
2121 {
2122 CommunityEntry->second.erase(x: pSelectableCountry->Name());
2123 }
2124 }
2125
2126 Add(pCommunityId: m_pCommunityCache->CountryTypeFilterKey(), pCountryName);
2127}
2128
2129void CExcludedCommunityCountryFilterList::Add(const char *pCommunityId, const char *pCountryName)
2130{
2131 CCommunityId CommunityId(pCommunityId);
2132 if(!m_Entries.contains(x: CommunityId))
2133 {
2134 m_Entries[CommunityId] = {};
2135 }
2136 m_Entries[CommunityId].emplace(args&: pCountryName);
2137}
2138
2139void CExcludedCommunityCountryFilterList::Remove(const char *pCountryName)
2140{
2141 Remove(pCommunityId: m_pCommunityCache->CountryTypeFilterKey(), pCountryName);
2142}
2143
2144void CExcludedCommunityCountryFilterList::Remove(const char *pCommunityId, const char *pCountryName)
2145{
2146 auto CommunityEntry = m_Entries.find(x: CCommunityId(pCommunityId));
2147 if(CommunityEntry != m_Entries.end())
2148 {
2149 CommunityEntry->second.erase(x: pCountryName);
2150 }
2151}
2152
2153void CExcludedCommunityCountryFilterList::Clear()
2154{
2155 auto CommunityEntry = m_Entries.find(x: m_pCommunityCache->CountryTypeFilterKey());
2156 if(CommunityEntry != m_Entries.end())
2157 {
2158 CommunityEntry->second.clear();
2159 }
2160}
2161
2162bool CExcludedCommunityCountryFilterList::Filtered(const char *pCountryName) const
2163{
2164 auto CommunityEntry = m_Entries.find(x: CCommunityId(m_pCommunityCache->CountryTypeFilterKey()));
2165 if(CommunityEntry == m_Entries.end())
2166 return false;
2167
2168 const auto &CountryEntries = CommunityEntry->second;
2169 return !IsSubsetEquals(vpLeft: m_pCommunityCache->SelectableCountries(), Right: CountryEntries) && CountryEntries.contains(x: CCommunityCountryName(pCountryName));
2170}
2171
2172bool CExcludedCommunityCountryFilterList::Empty() const
2173{
2174 auto CommunityEntry = m_Entries.find(x: CCommunityId(m_pCommunityCache->CountryTypeFilterKey()));
2175 return CommunityEntry == m_Entries.end() ||
2176 CommunityEntry->second.empty() ||
2177 IsSubsetEquals(vpLeft: m_pCommunityCache->SelectableCountries(), Right: CommunityEntry->second);
2178}
2179
2180void CExcludedCommunityCountryFilterList::Clean(const std::vector<CCommunity> &vAllowedCommunities)
2181{
2182 for(auto It = m_Entries.begin(); It != m_Entries.end();)
2183 {
2184 const bool AllEntry = str_comp(a: It->first.Id(), b: IServerBrowser::COMMUNITY_ALL) == 0;
2185 const bool Found = AllEntry || std::find_if(first: vAllowedCommunities.begin(), last: vAllowedCommunities.end(), pred: [&](const CCommunity &AllowedCommunity) {
2186 return str_comp(a: It->first.Id(), b: AllowedCommunity.Id()) == 0;
2187 }) != vAllowedCommunities.end();
2188 if(Found)
2189 {
2190 ++It;
2191 }
2192 else
2193 {
2194 It = m_Entries.erase(position: It);
2195 }
2196 }
2197
2198 for(const CCommunity &AllowedCommunity : vAllowedCommunities)
2199 {
2200 auto CommunityEntry = m_Entries.find(x: CCommunityId(AllowedCommunity.Id()));
2201 if(CommunityEntry != m_Entries.end())
2202 {
2203 auto &CountryEntries = CommunityEntry->second;
2204 for(auto It = CountryEntries.begin(); It != CountryEntries.end();)
2205 {
2206 if(AllowedCommunity.HasCountry(pCountryName: It->Name()))
2207 {
2208 ++It;
2209 }
2210 else
2211 {
2212 It = CountryEntries.erase(position: It);
2213 }
2214 }
2215 // Prevent filter that would exclude all allowed countries
2216 if(CountryEntries.size() == AllowedCommunity.Countries().size())
2217 {
2218 CountryEntries.clear();
2219 }
2220 }
2221 }
2222
2223 auto AllCommunityEntry = m_Entries.find(x: CCommunityId(IServerBrowser::COMMUNITY_ALL));
2224 if(AllCommunityEntry != m_Entries.end())
2225 {
2226 auto &CountryEntries = AllCommunityEntry->second;
2227 for(auto It = CountryEntries.begin(); It != CountryEntries.end();)
2228 {
2229 if(std::any_of(first: vAllowedCommunities.begin(), last: vAllowedCommunities.end(), pred: [&](const auto &Community) { return Community.HasCountry(It->Name()); }))
2230 {
2231 ++It;
2232 }
2233 else
2234 {
2235 It = CountryEntries.erase(position: It);
2236 }
2237 }
2238 // Prevent filter that would exclude all allowed countries
2239 std::set<CCommunityCountryName> UniqueCountries;
2240 for(const CCommunity &AllowedCommunity : vAllowedCommunities)
2241 {
2242 for(const CCommunityCountry &Country : AllowedCommunity.Countries())
2243 {
2244 UniqueCountries.emplace(args: Country.Name());
2245 }
2246 }
2247 if(CountryEntries.size() == UniqueCountries.size())
2248 {
2249 CountryEntries.clear();
2250 }
2251 }
2252}
2253
2254void CExcludedCommunityCountryFilterList::Save(IConfigManager *pConfigManager) const
2255{
2256 char aBuf[32 + CServerInfo::MAX_COMMUNITY_ID_LENGTH + CServerInfo::MAX_COMMUNITY_COUNTRY_LENGTH];
2257 for(const auto &[Community, Countries] : m_Entries)
2258 {
2259 for(const auto &Country : Countries)
2260 {
2261 str_copy(dst&: aBuf, src: "add_excluded_country \"");
2262 str_append(dst&: aBuf, src: Community.Id());
2263 str_append(dst&: aBuf, src: "\" \"");
2264 str_append(dst&: aBuf, src: Country.Name());
2265 str_append(dst&: aBuf, src: "\"");
2266 pConfigManager->WriteLine(pLine: aBuf);
2267 }
2268 }
2269}
2270
2271void CExcludedCommunityTypeFilterList::Add(const char *pTypeName)
2272{
2273 // Handle special case that all selectable entries are currently filtered,
2274 // where adding more entries to the exclusion list would have no effect.
2275 auto CommunityEntry = m_Entries.find(x: m_pCommunityCache->CountryTypeFilterKey());
2276 if(CommunityEntry != m_Entries.end() && IsSubsetEquals(vpLeft: m_pCommunityCache->SelectableTypes(), Right: CommunityEntry->second))
2277 {
2278 for(const CCommunityType *pSelectableType : m_pCommunityCache->SelectableTypes())
2279 {
2280 CommunityEntry->second.erase(x: pSelectableType->Name());
2281 }
2282 }
2283
2284 Add(pCommunityId: m_pCommunityCache->CountryTypeFilterKey(), pTypeName);
2285}
2286
2287void CExcludedCommunityTypeFilterList::Add(const char *pCommunityId, const char *pTypeName)
2288{
2289 CCommunityId CommunityId(pCommunityId);
2290 if(!m_Entries.contains(x: CommunityId))
2291 {
2292 m_Entries[CommunityId] = {};
2293 }
2294 m_Entries[CommunityId].emplace(args&: pTypeName);
2295}
2296
2297void CExcludedCommunityTypeFilterList::Remove(const char *pTypeName)
2298{
2299 Remove(pCommunityId: m_pCommunityCache->CountryTypeFilterKey(), pTypeName);
2300}
2301
2302void CExcludedCommunityTypeFilterList::Remove(const char *pCommunityId, const char *pTypeName)
2303{
2304 auto CommunityEntry = m_Entries.find(x: CCommunityId(pCommunityId));
2305 if(CommunityEntry != m_Entries.end())
2306 {
2307 CommunityEntry->second.erase(x: pTypeName);
2308 }
2309}
2310
2311void CExcludedCommunityTypeFilterList::Clear()
2312{
2313 auto CommunityEntry = m_Entries.find(x: m_pCommunityCache->CountryTypeFilterKey());
2314 if(CommunityEntry != m_Entries.end())
2315 {
2316 CommunityEntry->second.clear();
2317 }
2318}
2319
2320bool CExcludedCommunityTypeFilterList::Filtered(const char *pTypeName) const
2321{
2322 auto CommunityEntry = m_Entries.find(x: CCommunityId(m_pCommunityCache->CountryTypeFilterKey()));
2323 if(CommunityEntry == m_Entries.end())
2324 return false;
2325
2326 const auto &TypeEntries = CommunityEntry->second;
2327 return !IsSubsetEquals(vpLeft: m_pCommunityCache->SelectableTypes(), Right: TypeEntries) && TypeEntries.contains(x: CCommunityTypeName(pTypeName));
2328}
2329
2330bool CExcludedCommunityTypeFilterList::Empty() const
2331{
2332 auto CommunityEntry = m_Entries.find(x: CCommunityId(m_pCommunityCache->CountryTypeFilterKey()));
2333 return CommunityEntry == m_Entries.end() ||
2334 CommunityEntry->second.empty() ||
2335 IsSubsetEquals(vpLeft: m_pCommunityCache->SelectableTypes(), Right: CommunityEntry->second);
2336}
2337
2338void CExcludedCommunityTypeFilterList::Clean(const std::vector<CCommunity> &vAllowedCommunities)
2339{
2340 for(auto It = m_Entries.begin(); It != m_Entries.end();)
2341 {
2342 const bool AllEntry = str_comp(a: It->first.Id(), b: IServerBrowser::COMMUNITY_ALL) == 0;
2343 const bool Found = AllEntry || std::find_if(first: vAllowedCommunities.begin(), last: vAllowedCommunities.end(), pred: [&](const CCommunity &AllowedCommunity) {
2344 return str_comp(a: It->first.Id(), b: AllowedCommunity.Id()) == 0;
2345 }) != vAllowedCommunities.end();
2346 if(Found)
2347 {
2348 ++It;
2349 }
2350 else
2351 {
2352 It = m_Entries.erase(position: It);
2353 }
2354 }
2355
2356 for(const CCommunity &AllowedCommunity : vAllowedCommunities)
2357 {
2358 auto CommunityEntry = m_Entries.find(x: CCommunityId(AllowedCommunity.Id()));
2359 if(CommunityEntry != m_Entries.end())
2360 {
2361 auto &TypeEntries = CommunityEntry->second;
2362 for(auto It = TypeEntries.begin(); It != TypeEntries.end();)
2363 {
2364 if(AllowedCommunity.HasType(pTypeName: It->Name()))
2365 {
2366 ++It;
2367 }
2368 else
2369 {
2370 It = TypeEntries.erase(position: It);
2371 }
2372 }
2373 // Prevent filter that would exclude all allowed types
2374 if(TypeEntries.size() == AllowedCommunity.Types().size())
2375 {
2376 TypeEntries.clear();
2377 }
2378 }
2379 }
2380
2381 auto AllCommunityEntry = m_Entries.find(x: CCommunityId(IServerBrowser::COMMUNITY_ALL));
2382 if(AllCommunityEntry != m_Entries.end())
2383 {
2384 auto &TypeEntries = AllCommunityEntry->second;
2385 for(auto It = TypeEntries.begin(); It != TypeEntries.end();)
2386 {
2387 if(std::any_of(first: vAllowedCommunities.begin(), last: vAllowedCommunities.end(), pred: [&](const auto &Community) { return Community.HasType(It->Name()); }))
2388 {
2389 ++It;
2390 }
2391 else
2392 {
2393 It = TypeEntries.erase(position: It);
2394 }
2395 }
2396 // Prevent filter that would exclude all allowed types
2397 std::unordered_set<CCommunityCountryName> UniqueTypes;
2398 for(const CCommunity &AllowedCommunity : vAllowedCommunities)
2399 {
2400 for(const CCommunityType &Type : AllowedCommunity.Types())
2401 {
2402 UniqueTypes.emplace(args: Type.Name());
2403 }
2404 }
2405 if(TypeEntries.size() == UniqueTypes.size())
2406 {
2407 TypeEntries.clear();
2408 }
2409 }
2410}
2411
2412void CExcludedCommunityTypeFilterList::Save(IConfigManager *pConfigManager) const
2413{
2414 char aBuf[32 + CServerInfo::MAX_COMMUNITY_ID_LENGTH + CServerInfo::MAX_COMMUNITY_TYPE_LENGTH];
2415 for(const auto &[Community, Types] : m_Entries)
2416 {
2417 for(const auto &Type : Types)
2418 {
2419 str_copy(dst&: aBuf, src: "add_excluded_type \"");
2420 str_append(dst&: aBuf, src: Community.Id());
2421 str_append(dst&: aBuf, src: "\" \"");
2422 str_append(dst&: aBuf, src: Type.Name());
2423 str_append(dst&: aBuf, src: "\"");
2424 pConfigManager->WriteLine(pLine: aBuf);
2425 }
2426 }
2427}
2428
2429void CServerBrowser::CleanFilters()
2430{
2431 // Keep filters if we failed to load any communities
2432 if(Communities().empty())
2433 return;
2434 FavoriteCommunitiesFilter().Clean(vAllowedCommunities: Communities());
2435 CommunitiesFilter().Clean(vAllowedCommunities: Communities());
2436 CountriesFilter().Clean(vAllowedCommunities: Communities());
2437 TypesFilter().Clean(vAllowedCommunities: Communities());
2438}
2439
2440bool CServerBrowser::IsRegistered(const NETADDR &Addr)
2441{
2442 const int NumServers = m_pHttp->NumServers();
2443 for(int i = 0; i < NumServers; i++)
2444 {
2445 const CServerInfo &Info = m_pHttp->Server(Index: i);
2446 for(int j = 0; j < Info.m_NumAddresses; j++)
2447 {
2448 if(net_addr_comp(a: &Info.m_aAddresses[j], b: &Addr) == 0)
2449 {
2450 return true;
2451 }
2452 }
2453 }
2454 return false;
2455}
2456
2457int CServerInfo::EstimateLatency(int Loc1, int Loc2)
2458{
2459 if(Loc1 == LOC_UNKNOWN || Loc2 == LOC_UNKNOWN)
2460 {
2461 return 999;
2462 }
2463 if(Loc1 != Loc2)
2464 {
2465 return 199;
2466 }
2467 return 99;
2468}
2469
2470ColorRGBA CServerInfo::GametypeColor(const char *pGametype)
2471{
2472 ColorHSLA HslaColor;
2473 if(str_comp(a: pGametype, b: "DM") == 0 || str_comp(a: pGametype, b: "TDM") == 0 || str_comp(a: pGametype, b: "CTF") == 0 || str_comp(a: pGametype, b: "LMS") == 0 || str_comp(a: pGametype, b: "LTS") == 0)
2474 HslaColor = ColorHSLA(0.33f, 1.0f, 0.75f);
2475 else if(str_find_nocase(haystack: pGametype, needle: "catch"))
2476 HslaColor = ColorHSLA(0.17f, 1.0f, 0.75f);
2477 else if(str_find_nocase(haystack: pGametype, needle: "dm") || str_find_nocase(haystack: pGametype, needle: "tdm") || str_find_nocase(haystack: pGametype, needle: "ctf") || str_find_nocase(haystack: pGametype, needle: "lms") || str_find_nocase(haystack: pGametype, needle: "lts"))
2478 {
2479 if(pGametype[0] == 'i' || pGametype[0] == 'g')
2480 HslaColor = ColorHSLA(0.0f, 1.0f, 0.75f);
2481 else
2482 HslaColor = ColorHSLA(0.40f, 1.0f, 0.75f);
2483 }
2484 else if(str_find_nocase(haystack: pGametype, needle: "s-ddracex"))
2485 HslaColor = ColorHSLA(1.0f, 1.0f, 0.7f);
2486 else if(str_find_nocase(haystack: pGametype, needle: "f-ddrace") || str_find_nocase(haystack: pGametype, needle: "freeze"))
2487 HslaColor = ColorHSLA(0.0f, 1.0f, 0.75f);
2488 else if(str_find_nocase(haystack: pGametype, needle: "fng"))
2489 HslaColor = ColorHSLA(0.83f, 1.0f, 0.75f);
2490 else if(str_find_nocase(haystack: pGametype, needle: "gores"))
2491 HslaColor = ColorHSLA(0.525f, 1.0f, 0.75f);
2492 else if(str_find_nocase(haystack: pGametype, needle: "BW"))
2493 HslaColor = ColorHSLA(0.05f, 1.0f, 0.75f);
2494 else if(str_find_nocase(haystack: pGametype, needle: "ddracenet") || str_find_nocase(haystack: pGametype, needle: "ddnet") || str_find_nocase(haystack: pGametype, needle: "0xf"))
2495 HslaColor = ColorHSLA(0.58f, 1.0f, 0.75f);
2496 else if(str_find_nocase(haystack: pGametype, needle: "ddrace") || str_find_nocase(haystack: pGametype, needle: "mkrace"))
2497 HslaColor = ColorHSLA(0.75f, 1.0f, 0.75f);
2498 else if(str_find_nocase(haystack: pGametype, needle: "race") || str_find_nocase(haystack: pGametype, needle: "fastcap"))
2499 HslaColor = ColorHSLA(0.46f, 1.0f, 0.75f);
2500 else
2501 HslaColor = ColorHSLA(1.0f, 1.0f, 1.0f);
2502 return color_cast<ColorRGBA>(hsl: HslaColor);
2503}
2504
2505bool CServerInfo::ParseLocation(int *pResult, const char *pString)
2506{
2507 *pResult = LOC_UNKNOWN;
2508 int Length = str_length(str: pString);
2509 if(Length < 2)
2510 {
2511 return true;
2512 }
2513 // ISO continent code. Allow antarctica, but treat it as unknown.
2514 static const char s_apLocations[NUM_LOCS][6] = {
2515 "an", // LOC_UNKNOWN
2516 "af", // LOC_AFRICA
2517 "as", // LOC_ASIA
2518 "oc", // LOC_AUSTRALIA
2519 "eu", // LOC_EUROPE
2520 "na", // LOC_NORTH_AMERICA
2521 "sa", // LOC_SOUTH_AMERICA
2522 "as:cn", // LOC_CHINA
2523 };
2524 for(int i = std::size(s_apLocations) - 1; i >= 0; i--)
2525 {
2526 if(str_startswith(str: pString, prefix: s_apLocations[i]))
2527 {
2528 *pResult = i;
2529 return false;
2530 }
2531 }
2532 return true;
2533}
2534