1#include "updater.h"
2
3#include <base/fs.h>
4#include <base/log.h>
5#include <base/str.h>
6
7#include <engine/client.h>
8#include <engine/engine.h>
9#include <engine/external/json-parser/json.h>
10#include <engine/http.h>
11#include <engine/shared/json.h>
12#include <engine/storage.h>
13
14#include <game/version.h>
15
16#include <unordered_set>
17
18#if !defined(CONF_FAMILY_WINDOWS)
19#include <fcntl.h>
20#include <sys/stat.h>
21#include <unistd.h> // close
22#endif
23
24class CUpdaterFetchTask : public IHttpRequest::IProgressCallback
25{
26 char m_aBuf[256];
27 CUpdater *m_pUpdater;
28 std::shared_ptr<IHttpRequest> m_pHttpRequest;
29
30protected:
31 void OnProgress() override;
32 void OnCompletion(EHttpState State) override;
33
34public:
35 CUpdaterFetchTask(CUpdater *pUpdater, const char *pFile, const char *pDestPath);
36 std::shared_ptr<IHttpRequest> HttpRequest() { return m_pHttpRequest; }
37};
38
39// addition of '/' to keep paths intact, because EscapeUrl() (using curl_easy_escape) doesn't do this
40static inline bool IsUnreserved(unsigned char c)
41{
42 return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||
43 (c >= '0' && c <= '9') || c == '-' || c == '_' ||
44 c == '.' || c == '~' || c == '/';
45}
46
47static bool IsAllowedUpdaterPath(const char *pPath)
48{
49 return fs_is_relative_path(path: pPath) &&
50 str_find(haystack: pPath, needle: "..") == nullptr &&
51 str_valid_filename(str: fs_filename(path: pPath));
52}
53
54static void UrlEncodePath(const char *pIn, char *pOut, size_t OutSize)
55{
56 if(!pIn || !pOut || OutSize == 0)
57 return;
58 static const char HEX[] = "0123456789ABCDEF";
59 size_t WriteIndex = 0;
60 for(size_t i = 0; pIn[i] != '\0'; ++i)
61 {
62 unsigned char c = static_cast<unsigned char>(pIn[i]);
63 if(IsUnreserved(c))
64 {
65 if(OutSize - WriteIndex < 2) // require 1 byte + NUL
66 break;
67 pOut[WriteIndex++] = static_cast<char>(c);
68 }
69 else
70 {
71 if(OutSize - WriteIndex < 4) // require 3 bytes + NUL
72 break;
73 pOut[WriteIndex++] = '%';
74 pOut[WriteIndex++] = HEX[c >> 4]; // upper 4 bits of c
75 pOut[WriteIndex++] = HEX[c & 0x0F]; // lower 4 bits of c
76 }
77 }
78 pOut[WriteIndex] = '\0';
79}
80
81static const char *GetUpdaterUrl(char *pBuf, int BufSize, const char *pFile)
82{
83 char aBuf[1024];
84 UrlEncodePath(pIn: pFile, pOut: aBuf, OutSize: sizeof(aBuf));
85 str_format(buffer: pBuf, buffer_size: BufSize, format: "https://update.ddnet.org/%s", aBuf);
86 return pBuf;
87}
88
89static void FormatUpdaterDestPath(char *pBuf, int BufSize, const char *pFile, const char *pDestPath)
90{
91 if(!pDestPath)
92 {
93 pDestPath = pFile;
94 }
95 str_format(buffer: pBuf, buffer_size: BufSize, format: "update/%s", pDestPath);
96}
97
98#if !defined(CONF_FAMILY_WINDOWS)
99static bool SetExecutableBit(const char *pPath)
100{
101 const int FileDescriptor = open(file: pPath, O_RDWR);
102 if(FileDescriptor < 0)
103 {
104 log_error("updater", "Failed to open file descriptor to set executable bit of '%s'", pPath);
105 return false;
106 }
107 struct stat FileStats;
108 if(fstat(fd: FileDescriptor, buf: &FileStats) != 0)
109 {
110 log_error("updater", "Failed to determine file stats to set executable bit of '%s'", pPath);
111 close(fd: FileDescriptor);
112 return false;
113 }
114 if(fchmod(fd: FileDescriptor, mode: FileStats.st_mode | S_IXUSR | S_IXGRP | S_IXOTH) != 0)
115 {
116 log_error("updater", "Failed to set executable bit of '%s'", pPath);
117 close(fd: FileDescriptor);
118 return false;
119 }
120 close(fd: FileDescriptor);
121 return true;
122}
123#endif
124
125CUpdaterFetchTask::CUpdaterFetchTask(CUpdater *pUpdater, const char *pFile, const char *pDestPath) :
126 m_pUpdater(pUpdater)
127{
128 char aDestination[IO_MAX_PATH_LENGTH];
129 FormatUpdaterDestPath(pBuf: aDestination, BufSize: sizeof(aDestination), pFile, pDestPath);
130 m_pHttpRequest = CreateHttpRequest(pUrl: GetUpdaterUrl(pBuf: m_aBuf, BufSize: sizeof(m_aBuf), pFile));
131 m_pHttpRequest->WriteToFile(pStorage: pUpdater->m_pStorage, pDest: aDestination, StorageType: -2);
132 m_pHttpRequest->SetProgressCallback(this);
133}
134
135void CUpdaterFetchTask::OnProgress()
136{
137 const CLockScope LockScope(m_pUpdater->m_Lock);
138 m_pUpdater->m_Percent = m_pHttpRequest->Progress();
139}
140
141void CUpdaterFetchTask::OnCompletion(EHttpState State)
142{
143 if(!str_comp(a: fs_filename(path: m_pHttpRequest->Dest()), b: "update.json"))
144 {
145 if(State == EHttpState::DONE)
146 m_pUpdater->SetCurrentState(IUpdater::GOT_MANIFEST);
147 else if(State == EHttpState::ERROR)
148 m_pUpdater->SetCurrentState(IUpdater::FAIL);
149 }
150}
151
152CUpdater::CUpdater()
153{
154 m_pClient = nullptr;
155 m_pStorage = nullptr;
156 m_pEngine = nullptr;
157 m_pHttp = nullptr;
158 m_State = CLEAN;
159 m_Percent = 0;
160 m_pCurrentTask = nullptr;
161
162 m_ClientUpdate = m_ServerUpdate = m_ClientFetched = m_ServerFetched = false;
163
164 IStorage::FormatTmpPath(aBuf: m_aClientExecTmp, BufSize: sizeof(m_aClientExecTmp), CLIENT_EXEC);
165 IStorage::FormatTmpPath(aBuf: m_aServerExecTmp, BufSize: sizeof(m_aServerExecTmp), SERVER_EXEC);
166}
167
168void CUpdater::Init()
169{
170 m_pClient = Kernel()->RequestInterface<IClient>();
171 m_pStorage = Kernel()->RequestInterface<IStorage>();
172 m_pEngine = Kernel()->RequestInterface<IEngine>();
173 m_pHttp = Kernel()->RequestInterface<IHttp>();
174}
175
176void CUpdater::SetCurrentState(EUpdaterState NewState)
177{
178 const CLockScope LockScope(m_Lock);
179 m_State = NewState;
180}
181
182IUpdater::EUpdaterState CUpdater::GetCurrentState()
183{
184 const CLockScope LockScope(m_Lock);
185 return m_State;
186}
187
188void CUpdater::GetCurrentFile(char *pBuf, int BufSize)
189{
190 const CLockScope LockScope(m_Lock);
191 str_copy(dst: pBuf, src: m_aStatus, dst_size: BufSize);
192}
193
194int CUpdater::GetCurrentPercent()
195{
196 const CLockScope LockScope(m_Lock);
197 return m_Percent;
198}
199
200void CUpdater::FetchFile(const char *pFile, const char *pDestPath)
201{
202 const CLockScope LockScope(m_Lock);
203 m_pCurrentTask = std::make_shared<CUpdaterFetchTask>(args: this, args&: pFile, args&: pDestPath);
204 str_copy(dst&: m_aStatus, src: m_pCurrentTask->HttpRequest()->Dest());
205 m_pHttp->Run(pRequest: m_pCurrentTask->HttpRequest());
206}
207
208bool CUpdater::MoveFile(const char *pFile)
209{
210 char aBuf[IO_MAX_PATH_LENGTH];
211 bool Success = true;
212
213#if !defined(CONF_FAMILY_WINDOWS)
214 if(str_endswith_nocase(str: pFile, suffix: ".dll"))
215 return Success;
216#endif
217
218#if !defined(CONF_PLATFORM_LINUX)
219 if(str_endswith_nocase(pFile, ".so"))
220 return Success;
221#endif
222
223 if(str_endswith_nocase(str: pFile, suffix: ".dll") || str_endswith_nocase(str: pFile, suffix: ".so"))
224 {
225 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s.old", pFile);
226 m_pStorage->RenameBinaryFile(pOldFilename: pFile, pNewFilename: aBuf);
227 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "update/%s", pFile);
228 Success &= m_pStorage->RenameBinaryFile(pOldFilename: aBuf, pNewFilename: pFile);
229 }
230 else
231 {
232 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "update/%s", pFile);
233 Success &= m_pStorage->RenameBinaryFile(pOldFilename: aBuf, pNewFilename: pFile);
234 }
235
236 return Success;
237}
238
239void CUpdater::Update()
240{
241 switch(GetCurrentState())
242 {
243 case IUpdater::GOT_MANIFEST:
244 PerformUpdate();
245 break;
246 case IUpdater::DOWNLOADING:
247 RunningUpdate();
248 break;
249 case IUpdater::MOVE_FILES:
250 CommitUpdate();
251 break;
252 default:
253 return;
254 }
255}
256
257void CUpdater::AddFileJob(const char *pFile, bool Job)
258{
259 m_FileJobs.emplace_front(args&: pFile, args&: Job);
260}
261
262bool CUpdater::ReplaceClient()
263{
264 log_debug("updater", "Replacing " PLAT_CLIENT_EXEC);
265 bool Success = true;
266 char aPath[IO_MAX_PATH_LENGTH];
267
268 // Replace running executable by renaming twice...
269 m_pStorage->RemoveBinaryFile(CLIENT_EXEC ".old");
270 Success &= m_pStorage->RenameBinaryFile(PLAT_CLIENT_EXEC, CLIENT_EXEC ".old");
271 str_format(buffer: aPath, buffer_size: sizeof(aPath), format: "update/%s", m_aClientExecTmp);
272 Success &= m_pStorage->RenameBinaryFile(pOldFilename: aPath, PLAT_CLIENT_EXEC);
273#if !defined(CONF_FAMILY_WINDOWS)
274 m_pStorage->GetBinaryPath(PLAT_CLIENT_EXEC, pBuffer: aPath, BufferSize: sizeof(aPath));
275 Success &= SetExecutableBit(aPath);
276#endif
277 return Success;
278}
279
280bool CUpdater::ReplaceServer()
281{
282 log_debug("updater", "Replacing " PLAT_SERVER_EXEC);
283 bool Success = true;
284 char aPath[IO_MAX_PATH_LENGTH];
285
286 // Replace running executable by renaming twice...
287 m_pStorage->RemoveBinaryFile(SERVER_EXEC ".old");
288 Success &= m_pStorage->RenameBinaryFile(PLAT_SERVER_EXEC, SERVER_EXEC ".old");
289 str_format(buffer: aPath, buffer_size: sizeof(aPath), format: "update/%s", m_aServerExecTmp);
290 Success &= m_pStorage->RenameBinaryFile(pOldFilename: aPath, PLAT_SERVER_EXEC);
291#if !defined(CONF_FAMILY_WINDOWS)
292 m_pStorage->GetBinaryPath(PLAT_SERVER_EXEC, pBuffer: aPath, BufferSize: sizeof(aPath));
293 Success &= SetExecutableBit(aPath);
294#endif
295 return Success;
296}
297
298void CUpdater::ParseUpdate()
299{
300 char aPath[IO_MAX_PATH_LENGTH];
301 void *pBuf;
302 unsigned Length;
303 if(!m_pStorage->ReadFile(pFilename: m_pStorage->GetBinaryPath(pFilename: "update/update.json", pBuffer: aPath, BufferSize: sizeof(aPath)), Type: IStorage::TYPE_ABSOLUTE, ppResult: &pBuf, pResultLen: &Length))
304 return;
305
306 json_value *pVersions = JsonParse(pJson: (json_char *)pBuf, Length);
307 free(ptr: pBuf);
308
309 if(!pVersions || pVersions->type != json_array)
310 {
311 json_value_free(pVersions);
312 return;
313 }
314
315 // if we're already downloading a file, or it's been deleted in the latest version, we skip it if it comes up again
316 std::unordered_set<std::string> SkipSet;
317
318 for(int i = 0; i < json_array_length(pArray: pVersions); i++)
319 {
320 const json_value *pCurrent = json_array_get(pArray: pVersions, Index: i);
321 if(!pCurrent || pCurrent->type != json_object)
322 continue;
323
324 const char *pVersion = json_string_get(pString: json_object_get(pObject: pCurrent, pIndex: "version"));
325 if(!pVersion)
326 continue;
327
328 if(str_comp(a: pVersion, GAME_RELEASE_VERSION) == 0)
329 break;
330
331 if(json_boolean_get(pBoolean: json_object_get(pObject: pCurrent, pIndex: "client")))
332 m_ClientUpdate = true;
333 if(json_boolean_get(pBoolean: json_object_get(pObject: pCurrent, pIndex: "server")))
334 m_ServerUpdate = true;
335
336 const json_value *pDownload = json_object_get(pObject: pCurrent, pIndex: "download");
337 if(pDownload && pDownload->type == json_array)
338 {
339 for(int j = 0; j < json_array_length(pArray: pDownload); j++)
340 {
341 const char *pName = json_string_get(pString: json_array_get(pArray: pDownload, Index: j));
342 if(!pName || !IsAllowedUpdaterPath(pPath: pName))
343 {
344 log_error("updater", "Update manifest contains invalid path to download: '%s'", pName == nullptr ? "(not a string)" : pName);
345 continue;
346 }
347
348 if(SkipSet.insert(obj: pName).second)
349 {
350 AddFileJob(pFile: pName, Job: true);
351 }
352 }
353 }
354
355 const json_value *pRemove = json_object_get(pObject: pCurrent, pIndex: "remove");
356 if(pRemove && pRemove->type == json_array)
357 {
358 for(int j = 0; j < json_array_length(pArray: pRemove); j++)
359 {
360 const char *pName = json_string_get(pString: json_array_get(pArray: pRemove, Index: j));
361 if(!pName || !IsAllowedUpdaterPath(pPath: pName))
362 {
363 log_error("updater", "Update manifest contains invalid path to remove: '%s'", pName == nullptr ? "(not a string)" : pName);
364 continue;
365 }
366
367 if(SkipSet.insert(obj: pName).second)
368 {
369 AddFileJob(pFile: pName, Job: false);
370 }
371 }
372 }
373 }
374 json_value_free(pVersions);
375}
376
377void CUpdater::InitiateUpdate()
378{
379 SetCurrentState(IUpdater::GETTING_MANIFEST);
380 FetchFile(pFile: "update.json");
381}
382
383void CUpdater::PerformUpdate()
384{
385 SetCurrentState(IUpdater::PARSING_UPDATE);
386 log_debug("updater", "Parsing update.json");
387 ParseUpdate();
388 m_CurrentJob = m_FileJobs.begin();
389 SetCurrentState(IUpdater::DOWNLOADING);
390}
391
392void CUpdater::RunningUpdate()
393{
394 if(m_pCurrentTask)
395 {
396 if(!m_pCurrentTask->HttpRequest()->Done())
397 {
398 return;
399 }
400 else if(m_pCurrentTask->HttpRequest()->State() == EHttpState::ERROR ||
401 m_pCurrentTask->HttpRequest()->State() == EHttpState::ABORTED)
402 {
403 SetCurrentState(IUpdater::FAIL);
404 }
405 }
406
407 if(m_CurrentJob != m_FileJobs.end())
408 {
409 auto &Job = *m_CurrentJob;
410 if(Job.second)
411 {
412 const char *pFile = Job.first.c_str();
413 if(str_endswith_nocase(str: pFile, suffix: ".dll"))
414 {
415#if defined(CONF_FAMILY_WINDOWS)
416 const size_t Length = str_length(pFile);
417 char aBuf[IO_MAX_PATH_LENGTH];
418 str_copy(aBuf, pFile); // SDL
419 str_copy(aBuf + Length - 4, "-" PLAT_NAME, sizeof(aBuf) - Length + 4); // -win32
420 str_append(aBuf, pFile + Length - 4); // .dll
421 FetchFile(aBuf, pFile);
422#endif
423 // Ignore DLL downloads on other platforms
424 }
425 else if(str_endswith_nocase(str: pFile, suffix: ".so"))
426 {
427#if defined(CONF_PLATFORM_LINUX)
428 const size_t Length = str_length(str: pFile);
429 char aBuf[IO_MAX_PATH_LENGTH];
430 str_copy(dst&: aBuf, src: pFile); // libsteam_api
431 str_copy(dst: aBuf + Length - 3, src: "-" PLAT_NAME, dst_size: sizeof(aBuf) - Length + 3); // -linux-x86_64
432 str_append(dst&: aBuf, src: pFile + Length - 3); // .so
433 FetchFile(pFile: aBuf, pDestPath: pFile);
434#endif
435 // Ignore DLL downloads on other platforms, on Linux we statically link anyway
436 }
437 else
438 {
439 FetchFile(pFile);
440 }
441 }
442 m_CurrentJob++;
443 }
444 else
445 {
446 if(m_ServerUpdate && !m_ServerFetched)
447 {
448 FetchFile(PLAT_SERVER_DOWN, pDestPath: m_aServerExecTmp);
449 m_ServerFetched = true;
450 return;
451 }
452
453 if(m_ClientUpdate && !m_ClientFetched)
454 {
455 FetchFile(PLAT_CLIENT_DOWN, pDestPath: m_aClientExecTmp);
456 m_ClientFetched = true;
457 return;
458 }
459
460 SetCurrentState(IUpdater::MOVE_FILES);
461 }
462}
463
464void CUpdater::CommitUpdate()
465{
466 bool Success = true;
467
468 for(auto &FileJob : m_FileJobs)
469 if(FileJob.second)
470 Success &= MoveFile(pFile: FileJob.first.c_str());
471
472 if(m_ClientUpdate)
473 Success &= ReplaceClient();
474 if(m_ServerUpdate)
475 Success &= ReplaceServer();
476
477 if(Success)
478 {
479 for(const auto &[Filename, JobSuccess] : m_FileJobs)
480 if(!JobSuccess)
481 m_pStorage->RemoveBinaryFile(pFilename: Filename.c_str());
482 }
483
484 if(!Success)
485 SetCurrentState(IUpdater::FAIL);
486 else if(m_pClient->State() == IClient::STATE_ONLINE || m_pClient->EditorHasUnsavedData())
487 SetCurrentState(IUpdater::NEED_RESTART);
488 else
489 {
490 m_pClient->Restart();
491 }
492}
493