1#include "score.h"
2
3#include "player.h"
4#include "save.h"
5#include "scoreworker.h"
6
7#include <base/dbg.h>
8#include <base/io.h>
9#include <base/secure.h>
10#include <base/str.h>
11
12#include <engine/server.h>
13#include <engine/server/databases/connection_pool.h>
14#include <engine/shared/config.h>
15#include <engine/shared/console.h>
16#include <engine/shared/linereader.h>
17#include <engine/storage.h>
18
19#include <generated/wordlist.h>
20
21#include <game/server/gamecontext.h>
22#include <game/server/gamemodes/ddnet.h>
23#include <game/team_state.h>
24
25#include <memory>
26
27class IDbConnection;
28
29std::shared_ptr<CScorePlayerResult> CScore::NewSqlPlayerResult(int ClientId)
30{
31 CPlayer *pCurPlayer = GameServer()->m_apPlayers[ClientId];
32 if(pCurPlayer->m_ScoreQueryResult != nullptr) // TODO: send player a message: "too many requests"
33 return nullptr;
34 pCurPlayer->m_ScoreQueryResult = std::make_shared<CScorePlayerResult>();
35 return pCurPlayer->m_ScoreQueryResult;
36}
37
38void CScore::ExecPlayerThread(
39 bool (*pFuncPtr)(IDbConnection *, const ISqlData *, char *pError, int ErrorSize),
40 const char *pThreadName,
41 int ClientId,
42 const char *pName,
43 int Offset)
44{
45 auto pResult = NewSqlPlayerResult(ClientId);
46 if(pResult == nullptr)
47 return;
48 auto Tmp = std::make_unique<CSqlPlayerRequest>(args&: pResult);
49 str_copy(dst&: Tmp->m_aName, src: pName);
50 str_copy(dst&: Tmp->m_aMap, src: GameServer()->Map()->BaseName());
51 str_copy(dst&: Tmp->m_aServer, src: g_Config.m_SvSqlServerName);
52 str_copy(dst&: Tmp->m_aRequestingPlayer, src: Server()->ClientName(ClientId));
53 Tmp->m_Offset = Offset;
54
55 m_pPool->Execute(pFunc: pFuncPtr, pSqlRequestData: std::move(Tmp), pName: pThreadName);
56}
57
58bool CScore::RateLimitPlayer(int ClientId)
59{
60 CPlayer *pPlayer = GameServer()->m_apPlayers[ClientId];
61 if(pPlayer == nullptr)
62 return true;
63 if(pPlayer->m_LastSqlQuery + (int64_t)g_Config.m_SvSqlQueriesDelay * Server()->TickSpeed() >= Server()->Tick())
64 return true;
65 pPlayer->m_LastSqlQuery = Server()->Tick();
66 return false;
67}
68
69void CScore::GeneratePassphrase(char *pBuf, int BufSize)
70{
71 for(int i = 0; i < 3; i++)
72 {
73 if(i != 0)
74 str_append(dst: pBuf, src: " ", dst_size: BufSize);
75 // TODO: decide if the slight bias towards lower numbers is ok
76 int Rand = m_Prng.RandomBits() % m_vWordlist.size();
77 str_append(dst: pBuf, src: m_vWordlist[Rand].c_str(), dst_size: BufSize);
78 }
79}
80
81CScore::CScore(CGameContext *pGameServer, CDbConnectionPool *pPool) :
82 m_pPool(pPool),
83 m_pGameServer(pGameServer),
84 m_pServer(pGameServer->Server())
85{
86 LoadBestTime();
87
88 uint64_t aSeed[2];
89 secure_random_fill(bytes: aSeed, length: sizeof(aSeed));
90 m_Prng.Seed(aSeed);
91
92 CLineReader LineReader;
93 if(LineReader.OpenFile(File: GameServer()->Storage()->OpenFile(pFilename: "wordlist.txt", Flags: IOFLAG_READ, Type: IStorage::TYPE_ALL)))
94 {
95 while(const char *pLine = LineReader.Get())
96 {
97 char aWord[32] = {0};
98 sscanf(s: pLine, format: "%*s %31s", aWord);
99 aWord[31] = 0;
100 m_vWordlist.emplace_back(args&: aWord);
101 }
102 }
103 else
104 {
105 dbg_msg(sys: "sql", fmt: "failed to open wordlist, using fallback");
106 m_vWordlist.assign(first: std::begin(arr: g_aFallbackWordlist), last: std::end(arr: g_aFallbackWordlist));
107 }
108
109 if(m_vWordlist.size() < 1000)
110 {
111 dbg_msg(sys: "sql", fmt: "too few words in wordlist");
112 Server()->SetErrorShutdown("sql too few words in wordlist");
113 return;
114 }
115}
116
117void CScore::LoadBestTime()
118{
119 if(m_pGameServer->m_pController->m_pLoadBestTimeResult)
120 return; // already in progress
121
122 auto LoadBestTimeResult = std::make_shared<CScoreLoadBestTimeResult>();
123 m_pGameServer->m_pController->m_pLoadBestTimeResult = LoadBestTimeResult;
124
125 auto Tmp = std::make_unique<CSqlLoadBestTimeRequest>(args&: LoadBestTimeResult);
126 str_copy(dst&: Tmp->m_aMap, src: GameServer()->Map()->BaseName());
127 m_pPool->Execute(pFunc: CScoreWorker::LoadBestTime, pSqlRequestData: std::move(Tmp), pName: "load best time");
128}
129
130void CScore::LoadMapInfo()
131{
132 if(m_pGameServer->m_pLoadMapInfoResult)
133 return; // already in progress
134
135 auto pResult = std::make_shared<CScorePlayerResult>();
136 m_pGameServer->m_pLoadMapInfoResult = pResult;
137
138 auto Tmp = std::make_unique<CSqlPlayerRequest>(args&: pResult);
139 str_copy(dst&: Tmp->m_aName, src: GameServer()->Map()->BaseName());
140 Tmp->m_aRequestingPlayer[0] = '\0'; // no player, so no "your time" in result
141 m_pPool->Execute(pFunc: CScoreWorker::MapInfo, pSqlRequestData: std::move(Tmp), pName: "load map info");
142}
143
144void CScore::LoadPlayerData(int ClientId, const char *pName)
145{
146 ExecPlayerThread(pFuncPtr: CScoreWorker::LoadPlayerData, pThreadName: "load player data", ClientId, pName, Offset: 0);
147}
148
149void CScore::LoadPlayerTimeCp(int ClientId, const char *pName)
150{
151 if(RateLimitPlayer(ClientId))
152 return;
153 ExecPlayerThread(pFuncPtr: CScoreWorker::LoadPlayerTimeCp, pThreadName: "load player timecp", ClientId, pName, Offset: 0);
154}
155
156void CScore::MapVote(int ClientId, const char *pMapName)
157{
158 if(RateLimitPlayer(ClientId))
159 return;
160 ExecPlayerThread(pFuncPtr: CScoreWorker::MapVote, pThreadName: "map vote", ClientId, pName: pMapName, Offset: 0);
161}
162
163void CScore::MapInfo(int ClientId, const char *pMapName)
164{
165 if(RateLimitPlayer(ClientId))
166 return;
167 ExecPlayerThread(pFuncPtr: CScoreWorker::MapInfo, pThreadName: "map info", ClientId, pName: pMapName, Offset: 0);
168}
169
170void CScore::SaveScore(int ClientId, int TimeTicks, const char *pTimestamp, const float aTimeCp[NUM_CHECKPOINTS], bool NotEligible)
171{
172 CConsole *pCon = (CConsole *)GameServer()->Console();
173 if(pCon->Cheated() || NotEligible)
174 return;
175
176 GameServer()->TeehistorianRecordPlayerFinish(ClientId, TimeTicks);
177
178 CPlayer *pCurPlayer = GameServer()->m_apPlayers[ClientId];
179 if(pCurPlayer->m_ScoreFinishResult != nullptr)
180 dbg_msg(sys: "sql", fmt: "WARNING: previous save score result didn't complete, overwriting it now");
181 pCurPlayer->m_ScoreFinishResult = std::make_shared<CScorePlayerResult>();
182 auto Tmp = std::make_unique<CSqlScoreData>(args&: pCurPlayer->m_ScoreFinishResult);
183 str_copy(dst&: Tmp->m_aMap, src: GameServer()->Map()->BaseName());
184 FormatUuid(Uuid: GameServer()->GameUuid(), pBuffer: Tmp->m_aGameUuid, BufferLength: sizeof(Tmp->m_aGameUuid));
185 Tmp->m_ClientId = ClientId;
186 str_copy(dst&: Tmp->m_aName, src: Server()->ClientName(ClientId));
187 Tmp->m_Time = (float)(TimeTicks) / (float)Server()->TickSpeed();
188 str_copy(dst&: Tmp->m_aTimestamp, src: pTimestamp);
189 for(int i = 0; i < NUM_CHECKPOINTS; i++)
190 Tmp->m_aCurrentTimeCp[i] = aTimeCp[i];
191
192 m_pPool->ExecuteWrite(pFunc: CScoreWorker::SaveScore, pSqlRequestData: std::move(Tmp), pName: "save score");
193}
194
195void CScore::SaveTeamScore(int Team, int *pClientIds, unsigned int Size, int TimeTicks, const char *pTimestamp)
196{
197 CConsole *pCon = (CConsole *)GameServer()->Console();
198 if(pCon->Cheated())
199 return;
200 for(unsigned int i = 0; i < Size; i++)
201 {
202 if(GameServer()->m_apPlayers[pClientIds[i]]->m_NotEligibleForFinish)
203 return;
204 }
205
206 GameServer()->TeehistorianRecordTeamFinish(TeamId: Team, TimeTicks);
207
208 auto Tmp = std::make_unique<CSqlTeamScoreData>();
209 for(unsigned int i = 0; i < Size; i++)
210 str_copy(dst&: Tmp->m_aaNames[i], src: Server()->ClientName(ClientId: pClientIds[i]));
211 Tmp->m_Size = Size;
212 Tmp->m_Time = (float)TimeTicks / (float)Server()->TickSpeed();
213 str_copy(dst&: Tmp->m_aTimestamp, src: pTimestamp);
214 FormatUuid(Uuid: GameServer()->GameUuid(), pBuffer: Tmp->m_aGameUuid, BufferLength: sizeof(Tmp->m_aGameUuid));
215 str_copy(dst&: Tmp->m_aMap, src: GameServer()->Map()->BaseName());
216 Tmp->m_TeamrankUuid = RandomUuid();
217
218 m_pPool->ExecuteWrite(pFunc: CScoreWorker::SaveTeamScore, pSqlRequestData: std::move(Tmp), pName: "save team score");
219}
220
221void CScore::ShowRank(int ClientId, const char *pName)
222{
223 if(RateLimitPlayer(ClientId))
224 return;
225 ExecPlayerThread(pFuncPtr: CScoreWorker::ShowRank, pThreadName: "show rank", ClientId, pName, Offset: 0);
226}
227
228void CScore::ShowTeamRank(int ClientId, const char *pName)
229{
230 if(RateLimitPlayer(ClientId))
231 return;
232 ExecPlayerThread(pFuncPtr: CScoreWorker::ShowTeamRank, pThreadName: "show team rank", ClientId, pName, Offset: 0);
233}
234
235void CScore::ShowTop(int ClientId, int Offset)
236{
237 if(RateLimitPlayer(ClientId))
238 return;
239 ExecPlayerThread(pFuncPtr: CScoreWorker::ShowTop, pThreadName: "show top5", ClientId, pName: "", Offset);
240}
241
242void CScore::ShowTeamTop5(int ClientId, int Offset)
243{
244 if(RateLimitPlayer(ClientId))
245 return;
246 ExecPlayerThread(pFuncPtr: CScoreWorker::ShowTeamTop5, pThreadName: "show team top5", ClientId, pName: "", Offset);
247}
248
249void CScore::ShowPlayerTeamTop5(int ClientId, const char *pName, int Offset)
250{
251 if(RateLimitPlayer(ClientId))
252 return;
253 ExecPlayerThread(pFuncPtr: CScoreWorker::ShowPlayerTeamTop5, pThreadName: "show team top5 player", ClientId, pName, Offset);
254}
255
256void CScore::ShowTimes(int ClientId, int Offset)
257{
258 if(RateLimitPlayer(ClientId))
259 return;
260 ExecPlayerThread(pFuncPtr: CScoreWorker::ShowTimes, pThreadName: "show times", ClientId, pName: "", Offset);
261}
262
263void CScore::ShowTimes(int ClientId, const char *pName, int Offset)
264{
265 if(RateLimitPlayer(ClientId))
266 return;
267 ExecPlayerThread(pFuncPtr: CScoreWorker::ShowTimes, pThreadName: "show times", ClientId, pName, Offset);
268}
269
270void CScore::ShowPoints(int ClientId, const char *pName)
271{
272 if(RateLimitPlayer(ClientId))
273 return;
274 ExecPlayerThread(pFuncPtr: CScoreWorker::ShowPoints, pThreadName: "show points", ClientId, pName, Offset: 0);
275}
276
277void CScore::ShowTopPoints(int ClientId, int Offset)
278{
279 if(RateLimitPlayer(ClientId))
280 return;
281 ExecPlayerThread(pFuncPtr: CScoreWorker::ShowTopPoints, pThreadName: "show top points", ClientId, pName: "", Offset);
282}
283
284void CScore::RandomMap(int ClientId, int MinStars, int MaxStars)
285{
286 auto pResult = std::make_shared<CScoreRandomMapResult>(args&: ClientId);
287 GameServer()->m_SqlRandomMapResult = pResult;
288
289 auto Tmp = std::make_unique<CSqlRandomMapRequest>(args&: pResult);
290 Tmp->m_MinStars = MinStars;
291 Tmp->m_MaxStars = MaxStars;
292 str_copy(dst&: Tmp->m_aCurrentMap, src: GameServer()->Map()->BaseName());
293 str_copy(dst&: Tmp->m_aServerType, src: g_Config.m_SvServerType);
294 str_copy(dst&: Tmp->m_aRequestingPlayer, src: ClientId == -1 ? "nameless tee" : GameServer()->Server()->ClientName(ClientId));
295
296 m_pPool->Execute(pFunc: CScoreWorker::RandomMap, pSqlRequestData: std::move(Tmp), pName: "random map");
297}
298
299void CScore::RandomUnfinishedMap(int ClientId, int MinStars, int MaxStars)
300{
301 auto pResult = std::make_shared<CScoreRandomMapResult>(args&: ClientId);
302 GameServer()->m_SqlRandomMapResult = pResult;
303
304 auto Tmp = std::make_unique<CSqlRandomMapRequest>(args&: pResult);
305 Tmp->m_MinStars = MinStars;
306 Tmp->m_MaxStars = MaxStars;
307 str_copy(dst&: Tmp->m_aCurrentMap, src: GameServer()->Map()->BaseName());
308 str_copy(dst&: Tmp->m_aServerType, src: g_Config.m_SvServerType);
309 str_copy(dst&: Tmp->m_aRequestingPlayer, src: ClientId == -1 ? "nameless tee" : GameServer()->Server()->ClientName(ClientId));
310
311 m_pPool->Execute(pFunc: CScoreWorker::RandomUnfinishedMap, pSqlRequestData: std::move(Tmp), pName: "random unfinished map");
312}
313
314void CScore::SaveTeam(int ClientId, const char *pCode, const char *pServer)
315{
316 if(RateLimitPlayer(ClientId))
317 return;
318 auto *pController = GameServer()->m_pController;
319 int Team = pController->Teams().m_Core.Team(ClientId);
320 if(pController->Teams().GetSaving(TeamId: Team))
321 {
322 GameServer()->SendChatTarget(To: ClientId, pText: "Team save already in progress");
323 return;
324 }
325 if(pController->Teams().IsPractice(Team))
326 {
327 GameServer()->SendChatTarget(To: ClientId, pText: "Team save disabled for teams in practice mode");
328 return;
329 }
330
331 auto SaveResult = std::make_shared<CScoreSaveResult>(args&: ClientId, args: Server()->ClientName(ClientId), args&: pServer);
332 SaveResult->m_SaveId = RandomUuid();
333 ESaveResult Result = SaveResult->m_SavedTeam.Save(pGameServer: GameServer(), Team);
334 if(CSaveTeam::HandleSaveError(Result, ClientId, pGameContext: GameServer()))
335 return;
336 pController->Teams().SetSaving(TeamId: Team, SaveResult);
337
338 auto Tmp = std::make_unique<CSqlTeamSaveData>(args&: SaveResult);
339 str_copy(dst&: Tmp->m_aCode, src: pCode);
340 str_copy(dst&: Tmp->m_aMap, src: GameServer()->Map()->BaseName());
341 str_copy(dst&: Tmp->m_aServer, src: pServer);
342 str_copy(dst&: Tmp->m_aClientName, src: this->Server()->ClientName(ClientId));
343 Tmp->m_aGeneratedCode[0] = '\0';
344 GeneratePassphrase(pBuf: Tmp->m_aGeneratedCode, BufSize: sizeof(Tmp->m_aGeneratedCode));
345
346 pController->Teams().KillCharacterOrTeam(ClientId, Team);
347
348 GameServer()->SendSaveCode(
349 Team,
350 TeamSize: SaveResult->m_SavedTeam.GetMembersCount(),
351 State: SAVESTATE_PENDING,
352 pError: "",
353 pSaveRequester: SaveResult->m_aRequestingPlayer,
354 pServerName: Tmp->m_aServer,
355 pGeneratedCode: Tmp->m_aGeneratedCode,
356 pCode: Tmp->m_aCode);
357
358 m_pPool->ExecuteWrite(pFunc: CScoreWorker::SaveTeam, pSqlRequestData: std::move(Tmp), pName: "save team");
359}
360
361void CScore::LoadTeam(const char *pCode, int ClientId)
362{
363 if(RateLimitPlayer(ClientId))
364 return;
365 auto *pController = GameServer()->m_pController;
366 int Team = pController->Teams().m_Core.Team(ClientId);
367 if(pController->Teams().GetSaving(TeamId: Team))
368 {
369 GameServer()->SendChatTarget(To: ClientId, pText: "Team load already in progress");
370 return;
371 }
372 if(!pController->Teams().IsValidTeamNumber(Team) || (g_Config.m_SvTeam != SV_TEAM_FORCED_SOLO && Team == TEAM_FLOCK))
373 {
374 GameServer()->SendChatTarget(To: ClientId, pText: "You have to be in a team (from 1-127)");
375 return;
376 }
377 if(pController->Teams().GetTeamState(Team) != ETeamState::OPEN)
378 {
379 GameServer()->SendChatTarget(To: ClientId, pText: "Team can't be loaded while racing");
380 return;
381 }
382 if(pController->Teams().TeamFlock(Team))
383 {
384 GameServer()->SendChatTarget(To: ClientId, pText: "Team can't be loaded while in team 0 mode");
385 return;
386 }
387 if(pController->Teams().IsPractice(Team))
388 {
389 GameServer()->SendChatTarget(To: ClientId, pText: "Team can't be loaded while practice is enabled");
390 return;
391 }
392 auto SaveResult = std::make_shared<CScoreSaveResult>(args&: ClientId, args: Server()->ClientName(ClientId), args&: g_Config.m_SvSqlServerName);
393 SaveResult->m_Status = CScoreSaveResult::LOAD_FAILED;
394 pController->Teams().SetSaving(TeamId: Team, SaveResult);
395 auto Tmp = std::make_unique<CSqlTeamLoadRequest>(args&: SaveResult);
396 str_copy(dst&: Tmp->m_aCode, src: pCode);
397 str_copy(dst&: Tmp->m_aMap, src: GameServer()->Map()->BaseName());
398 str_copy(dst&: Tmp->m_aRequestingPlayer, src: Server()->ClientName(ClientId));
399 Tmp->m_NumPlayer = 0;
400 for(int i = 0; i < MAX_CLIENTS; i++)
401 {
402 if(pController->Teams().m_Core.Team(ClientId: i) == Team)
403 {
404 // put all names at the beginning of the array
405 str_copy(dst&: Tmp->m_aClientNames[Tmp->m_NumPlayer], src: Server()->ClientName(ClientId: i));
406 Tmp->m_aClientId[Tmp->m_NumPlayer] = i;
407 Tmp->m_NumPlayer++;
408 }
409 }
410 m_pPool->ExecuteWrite(pFunc: CScoreWorker::LoadTeam, pSqlRequestData: std::move(Tmp), pName: "load team");
411}
412
413void CScore::GetSaves(int ClientId)
414{
415 if(RateLimitPlayer(ClientId))
416 return;
417 ExecPlayerThread(pFuncPtr: CScoreWorker::GetSaves, pThreadName: "get saves", ClientId, pName: "", Offset: 0);
418}
419