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 <base/dbg.h>
4#include <base/fs.h>
5#include <base/hash_ctxt.h>
6#include <base/io.h>
7#include <base/log.h>
8#include <base/math.h>
9#include <base/process.h>
10#include <base/str.h>
11
12#include <engine/client/updater.h>
13#include <engine/shared/linereader.h>
14#include <engine/storage.h>
15
16#include <unordered_set>
17
18#ifdef CONF_PLATFORM_HAIKU
19#include <cstdlib>
20#endif
21
22#include <zlib.h>
23
24class CStorage : public IStorage
25{
26 char m_aaStoragePaths[MAX_PATHS][IO_MAX_PATH_LENGTH];
27 int m_NumPaths = 0;
28 char m_aUserdir[IO_MAX_PATH_LENGTH] = "";
29 char m_aDatadir[IO_MAX_PATH_LENGTH] = "";
30 char m_aCurrentdir[IO_MAX_PATH_LENGTH] = "";
31 char m_aBinarydir[IO_MAX_PATH_LENGTH] = "";
32
33public:
34 bool Init(EInitializationType InitializationType, int NumArgs, const char **ppArguments)
35 {
36 dbg_assert(NumArgs > 0, "Expected at least one argument");
37 const char *pExecutablePath = ppArguments[0];
38
39 FindUserDirectory();
40 FindDataDirectory(pArgv0: pExecutablePath);
41 FindCurrentDirectory();
42 FindBinaryDirectory(pArgv0: pExecutablePath);
43
44 if(!LoadPathsFromFile(pArgv0: pExecutablePath))
45 {
46 return false;
47 }
48
49 if(!m_NumPaths)
50 {
51 if(!AddDefaultPaths())
52 {
53 return false;
54 }
55 }
56
57 if(InitializationType == EInitializationType::BASIC)
58 {
59 return true;
60 }
61
62 if(m_aaStoragePaths[TYPE_SAVE][0] != '\0')
63 {
64 if(fs_makedir_rec_for(path: m_aaStoragePaths[TYPE_SAVE]) != 0 ||
65 fs_makedir(path: m_aaStoragePaths[TYPE_SAVE]) != 0)
66 {
67 log_error("storage", "failed to create the user directory");
68 return false;
69 }
70 }
71
72 bool Success = true;
73 if(InitializationType == EInitializationType::CLIENT)
74 {
75 static constexpr const char *CLIENT_DIRS[] = {
76 "assets",
77 "assets/emoticons",
78 "assets/entities",
79 "assets/extras",
80 "assets/game",
81 "assets/hud",
82 "assets/particles",
83 "audio",
84 "communityicons",
85 "downloadedmaps",
86 "downloadedskins",
87 "mapres",
88 "maps",
89 "maps/auto",
90 "screenshots",
91 "screenshots/auto",
92 "screenshots/auto/stats",
93 "skins",
94 "skins7",
95 "themes",
96#if defined(CONF_VIDEORECORDER)
97 "videos"
98#endif
99 };
100
101 for(const char *pDir : CLIENT_DIRS)
102 Success &= CreateFolder(pFoldername: pDir, Type: TYPE_SAVE);
103 }
104
105 static constexpr const char *COMMON_DIRS[] = {
106 "dumps",
107 "demos",
108 "demos/auto",
109 "demos/auto/marked",
110 "demos/auto/race",
111 "demos/auto/server",
112 "demos/replays",
113 "editor",
114 "editor/automap",
115 "ghosts",
116 "teehistorian"};
117
118 for(const char *pDir : COMMON_DIRS)
119 Success &= CreateFolder(pFoldername: pDir, Type: TYPE_SAVE);
120
121 if(!Success)
122 {
123 log_error("storage", "failed to create default folders in the user directory");
124 }
125
126 return Success;
127 }
128
129 bool LoadPathsFromFile(const char *pArgv0)
130 {
131 // check current directory
132 IOHANDLE File = io_open(filename: "storage.cfg", flags: IOFLAG_READ);
133 if(!File)
134 {
135 // check usable path in argv[0]
136 unsigned int Pos = ~0U;
137 for(unsigned i = 0; pArgv0[i]; i++)
138 if(pArgv0[i] == '/' || pArgv0[i] == '\\')
139 Pos = i;
140 if(Pos < IO_MAX_PATH_LENGTH)
141 {
142 char aBuffer[IO_MAX_PATH_LENGTH];
143 str_copy(dst: aBuffer, src: pArgv0, dst_size: Pos + 1);
144 str_append(dst&: aBuffer, src: "/storage.cfg");
145 File = io_open(filename: aBuffer, flags: IOFLAG_READ);
146 }
147 }
148
149 CLineReader LineReader;
150 if(!LineReader.OpenFile(File))
151 {
152 log_error("storage", "couldn't open storage.cfg");
153 return true;
154 }
155 while(const char *pLine = LineReader.Get())
156 {
157 const char *pLineWithoutPrefix = str_startswith(str: pLine, prefix: "add_path ");
158 if(pLineWithoutPrefix)
159 {
160 if(!AddPath(pPath: pLineWithoutPrefix) && !m_NumPaths)
161 {
162 log_error("storage", "failed to add path for the user directory");
163 return false;
164 }
165 }
166 }
167
168 if(!m_NumPaths)
169 {
170 log_error("storage", "no usable paths found in storage.cfg");
171 }
172 return true;
173 }
174
175 bool AddDefaultPaths()
176 {
177 log_info("storage", "using standard paths");
178 if(!AddPath(pPath: "$USERDIR"))
179 {
180 log_error("storage", "failed to add default path for the user directory");
181 return false;
182 }
183 AddPath(pPath: "$DATADIR");
184 AddPath(pPath: "$CURRENTDIR");
185 return true;
186 }
187
188 bool AddPath(const char *pPath)
189 {
190 if(!pPath[0])
191 {
192 log_error("storage", "cannot add empty path");
193 return false;
194 }
195 if(m_NumPaths >= MAX_PATHS)
196 {
197 log_error("storage", "cannot add path '%s', the maximum number of paths is %d", pPath, MAX_PATHS);
198 return false;
199 }
200
201 if(!str_comp(a: pPath, b: "$USERDIR"))
202 {
203 if(m_aUserdir[0])
204 {
205 str_copy(dst&: m_aaStoragePaths[m_NumPaths++], src: m_aUserdir);
206 log_info("storage", "added path '$USERDIR' ('%s')", m_aUserdir);
207 return true;
208 }
209 else
210 {
211 log_error("storage", "cannot add path '$USERDIR' because it could not be determined");
212 return false;
213 }
214 }
215 else if(!str_comp(a: pPath, b: "$DATADIR"))
216 {
217 if(m_aDatadir[0])
218 {
219 str_copy(dst&: m_aaStoragePaths[m_NumPaths++], src: m_aDatadir);
220 log_info("storage", "added path '$DATADIR' ('%s')", m_aDatadir);
221 return true;
222 }
223 else
224 {
225 log_error("storage", "cannot add path '$DATADIR' because it could not be determined");
226 return false;
227 }
228 }
229 else if(!str_comp(a: pPath, b: "$CURRENTDIR"))
230 {
231 m_aaStoragePaths[m_NumPaths++][0] = '\0';
232 log_info("storage", "added path '$CURRENTDIR' ('%s')", m_aCurrentdir);
233 return true;
234 }
235 else if(str_utf8_check(str: pPath))
236 {
237 if(fs_is_dir(path: pPath))
238 {
239 str_copy(dst&: m_aaStoragePaths[m_NumPaths++], src: pPath);
240 log_info("storage", "added path '%s'", pPath);
241 return true;
242 }
243 else
244 {
245 log_error("storage", "cannot add path '%s', which is not a directory", pPath);
246 return false;
247 }
248 }
249 else
250 {
251 log_error("storage", "cannot add path containing invalid UTF-8");
252 return false;
253 }
254 }
255
256 void FindUserDirectory()
257 {
258#if defined(CONF_PLATFORM_ANDROID)
259 // See InitAndroid in android_main.cpp for details about Android storage handling.
260 // The current working directory is set to the app specific external storage location
261 // on Android. The user data is stored within a folder "user" in the external storage.
262 str_copy(m_aUserdir, "user");
263#else
264 char aFallbackUserdir[IO_MAX_PATH_LENGTH];
265 if(fs_storage_path(appname: "DDNet", path: m_aUserdir, max: sizeof(m_aUserdir)))
266 {
267 log_error("storage", "could not determine user directory");
268 }
269 if(fs_storage_path(appname: "Teeworlds", path: aFallbackUserdir, max: sizeof(aFallbackUserdir)))
270 {
271 log_error("storage", "could not determine fallback user directory");
272 }
273
274 if((m_aUserdir[0] == '\0' || !fs_is_dir(path: m_aUserdir)) && aFallbackUserdir[0] != '\0' && fs_is_dir(path: aFallbackUserdir))
275 {
276 str_copy(dst&: m_aUserdir, src: aFallbackUserdir);
277 }
278#endif
279 }
280
281 void FindDataDirectory(const char *pArgv0)
282 {
283 // 1) use data-dir in PWD if present
284 if(fs_is_dir(path: "data/mapres"))
285 {
286 str_copy(dst&: m_aDatadir, src: "data");
287 return;
288 }
289
290#if defined(DATA_DIR)
291 // 2) use compiled-in data-dir if present
292 if(fs_is_dir(DATA_DIR "/mapres"))
293 {
294 str_copy(m_aDatadir, DATA_DIR);
295 return;
296 }
297#endif
298
299 // 3) check for usable path in argv[0]
300 {
301#ifdef CONF_PLATFORM_HAIKU
302 pArgv0 = realpath(pArgv0, nullptr);
303#endif
304 unsigned int Pos = ~0U;
305 for(unsigned i = 0; pArgv0[i]; i++)
306 if(pArgv0[i] == '/' || pArgv0[i] == '\\')
307 Pos = i;
308
309 if(Pos < IO_MAX_PATH_LENGTH)
310 {
311 char aBuf[IO_MAX_PATH_LENGTH];
312 char aDir[IO_MAX_PATH_LENGTH];
313 str_copy(dst: aDir, src: pArgv0, dst_size: Pos + 1);
314 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s/data/mapres", aDir);
315 if(fs_is_dir(path: aBuf))
316 {
317 str_format(buffer: m_aDatadir, buffer_size: sizeof(m_aDatadir), format: "%s/data", aDir);
318 return;
319 }
320 }
321 }
322#ifdef CONF_PLATFORM_HAIKU
323 free((void *)pArgv0);
324#endif
325
326#if defined(CONF_FAMILY_UNIX)
327 // 4) check for all default locations
328 {
329 const char *apDirs[] = {
330 "/usr/share/ddnet",
331 "/usr/share/games/ddnet",
332 "/usr/local/share/ddnet",
333 "/usr/local/share/games/ddnet",
334 "/usr/pkg/share/ddnet",
335 "/usr/pkg/share/games/ddnet",
336 "/opt/ddnet"};
337
338 for(const char *pDir : apDirs)
339 {
340 char aBuf[IO_MAX_PATH_LENGTH];
341 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s/data/mapres", pDir);
342 if(fs_is_dir(path: aBuf))
343 {
344 str_format(buffer: m_aDatadir, buffer_size: sizeof(m_aDatadir), format: "%s/data", pDir);
345 return;
346 }
347 }
348 }
349#endif
350
351 log_warn("storage", "no data directory found");
352 }
353
354 bool FindCurrentDirectory()
355 {
356 if(!fs_getcwd(buffer: m_aCurrentdir, buffer_size: sizeof(m_aCurrentdir)))
357 {
358 log_error("storage", "could not determine current directory");
359 return false;
360 }
361 return true;
362 }
363
364 void FindBinaryDirectory(const char *pArgv0)
365 {
366#if defined(BINARY_DIR)
367 str_copy(m_aBinarydir, BINARY_DIR);
368 return;
369#endif
370
371 if(fs_executable_path(buffer: m_aBinarydir, buffer_size: sizeof(m_aBinarydir)) == 0)
372 {
373 dbg_assert(fs_parent_dir(m_aBinarydir) == 0, "Could not determine parent of executable: '%s'", m_aBinarydir);
374 return;
375 }
376
377 // check for usable path in argv[0]
378 {
379 unsigned int Pos = ~0U;
380 for(unsigned i = 0; pArgv0[i]; i++)
381 if(pArgv0[i] == '/' || pArgv0[i] == '\\')
382 Pos = i;
383
384 if(Pos < IO_MAX_PATH_LENGTH)
385 {
386 char aBuf[IO_MAX_PATH_LENGTH];
387 str_copy(dst: m_aBinarydir, src: pArgv0, dst_size: Pos + 1);
388 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s/" PLAT_SERVER_EXEC, m_aBinarydir);
389 if(fs_is_file(path: aBuf))
390 {
391 return;
392 }
393 // Also look for client binary. (see https://github.com/ddnet/ddnet/issues/11418)
394 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "%s/" PLAT_CLIENT_EXEC, m_aBinarydir);
395 if(fs_is_file(path: aBuf))
396 {
397 return;
398 }
399 }
400 }
401
402 // no binary directory found, use $PATH on Posix, $PWD on Windows
403 m_aBinarydir[0] = '\0';
404 }
405
406 int NumPaths() const override
407 {
408 return m_NumPaths;
409 }
410
411 struct SListDirectoryInfoUniqueCallbackData
412 {
413 FS_LISTDIR_CALLBACK_FILEINFO m_pfnDelegate;
414 void *m_pDelegateUser;
415 std::unordered_set<std::string> m_Seen;
416 };
417
418 static int ListDirectoryInfoUniqueCallback(const CFsFileInfo *pInfo, int IsDir, int Type, void *pUser)
419 {
420 SListDirectoryInfoUniqueCallbackData *pData = static_cast<SListDirectoryInfoUniqueCallbackData *>(pUser);
421 auto [_, InsertionTookPlace] = pData->m_Seen.emplace(args: pInfo->m_pName);
422 if(InsertionTookPlace)
423 return pData->m_pfnDelegate(pInfo, IsDir, Type, pData->m_pDelegateUser);
424 return 0;
425 }
426
427 void ListDirectoryInfo(int Type, const char *pPath, FS_LISTDIR_CALLBACK_FILEINFO pfnCallback, void *pUser) override
428 {
429 char aBuffer[IO_MAX_PATH_LENGTH];
430 if(Type == TYPE_ALL)
431 {
432 SListDirectoryInfoUniqueCallbackData Data;
433 Data.m_pfnDelegate = pfnCallback;
434 Data.m_pDelegateUser = pUser;
435 // list all available directories
436 for(int i = TYPE_SAVE; i < m_NumPaths; ++i)
437 fs_listdir_fileinfo(dir: GetPath(Type: i, pDir: pPath, pBuffer: aBuffer, BufferSize: sizeof(aBuffer)), cb: ListDirectoryInfoUniqueCallback, type: i, user: &Data);
438 }
439 else if(Type >= TYPE_SAVE && Type < m_NumPaths)
440 {
441 // list wanted directory
442 fs_listdir_fileinfo(dir: GetPath(Type, pDir: pPath, pBuffer: aBuffer, BufferSize: sizeof(aBuffer)), cb: pfnCallback, type: Type, user: pUser);
443 }
444 else
445 {
446 dbg_assert_failed("Type invalid");
447 }
448 }
449
450 struct SListDirectoryUniqueCallbackData
451 {
452 FS_LISTDIR_CALLBACK m_pfnDelegate;
453 void *m_pDelegateUser;
454 std::unordered_set<std::string> m_Seen;
455 };
456
457 static int ListDirectoryUniqueCallback(const char *pName, int IsDir, int Type, void *pUser)
458 {
459 SListDirectoryUniqueCallbackData *pData = static_cast<SListDirectoryUniqueCallbackData *>(pUser);
460 auto [_, InsertionTookPlace] = pData->m_Seen.emplace(args&: pName);
461 if(InsertionTookPlace)
462 return pData->m_pfnDelegate(pName, IsDir, Type, pData->m_pDelegateUser);
463 return 0;
464 }
465
466 void ListDirectory(int Type, const char *pPath, FS_LISTDIR_CALLBACK pfnCallback, void *pUser) override
467 {
468 char aBuffer[IO_MAX_PATH_LENGTH];
469 if(Type == TYPE_ALL)
470 {
471 SListDirectoryUniqueCallbackData Data;
472 Data.m_pfnDelegate = pfnCallback;
473 Data.m_pDelegateUser = pUser;
474 // list all available directories
475 for(int i = TYPE_SAVE; i < m_NumPaths; ++i)
476 fs_listdir(dir: GetPath(Type: i, pDir: pPath, pBuffer: aBuffer, BufferSize: sizeof(aBuffer)), cb: ListDirectoryUniqueCallback, type: i, user: &Data);
477 }
478 else if(Type >= TYPE_SAVE && Type < m_NumPaths)
479 {
480 // list wanted directory
481 fs_listdir(dir: GetPath(Type, pDir: pPath, pBuffer: aBuffer, BufferSize: sizeof(aBuffer)), cb: pfnCallback, type: Type, user: pUser);
482 }
483 else
484 {
485 dbg_assert_failed("Type invalid");
486 }
487 }
488
489 const char *GetPath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) const
490 {
491 if(Type == TYPE_ABSOLUTE)
492 {
493 str_copy(dst: pBuffer, src: pDir, dst_size: BufferSize);
494 }
495 else
496 {
497 str_format(buffer: pBuffer, buffer_size: BufferSize, format: "%s%s%s", m_aaStoragePaths[Type], !m_aaStoragePaths[Type][0] ? "" : "/", pDir);
498 }
499 return pBuffer;
500 }
501
502 void TranslateType(int &Type, const char *pPath) const
503 {
504 if(Type == TYPE_SAVE_OR_ABSOLUTE)
505 Type = fs_is_relative_path(path: pPath) ? TYPE_SAVE : TYPE_ABSOLUTE;
506 else if(Type == TYPE_ALL_OR_ABSOLUTE)
507 Type = fs_is_relative_path(path: pPath) ? TYPE_ALL : TYPE_ABSOLUTE;
508 }
509
510 IOHANDLE OpenFile(const char *pFilename, int Flags, int Type, char *pBuffer = nullptr, int BufferSize = 0) override
511 {
512 TranslateType(Type, pPath: pFilename);
513
514 dbg_assert((Flags & IOFLAG_WRITE) == 0 || Type == TYPE_SAVE || Type == TYPE_ABSOLUTE, "IOFLAG_WRITE only usable with TYPE_SAVE and TYPE_ABSOLUTE");
515
516 char aBuffer[IO_MAX_PATH_LENGTH];
517 if(!pBuffer)
518 {
519 pBuffer = aBuffer;
520 BufferSize = sizeof(aBuffer);
521 }
522 pBuffer[0] = '\0';
523
524 if(Type == TYPE_ABSOLUTE)
525 {
526 return io_open(filename: GetPath(Type: TYPE_ABSOLUTE, pDir: pFilename, pBuffer, BufferSize), flags: Flags);
527 }
528
529 if(str_startswith(str: pFilename, prefix: "mapres/../skins/"))
530 {
531 pFilename = pFilename + str_length(str: "mapres/../");
532 }
533 if(pFilename[0] == '/' || pFilename[0] == '\\' || str_find(haystack: pFilename, needle: "../") != nullptr || str_find(haystack: pFilename, needle: "..\\") != nullptr
534#ifdef CONF_FAMILY_WINDOWS
535 || (pFilename[0] && pFilename[1] == ':')
536#endif
537 )
538 {
539 // don't escape base directory
540 return nullptr;
541 }
542 else if(Type == TYPE_ALL)
543 {
544 // check all available directories
545 for(int i = TYPE_SAVE; i < m_NumPaths; ++i)
546 {
547 IOHANDLE Handle = io_open(filename: GetPath(Type: i, pDir: pFilename, pBuffer, BufferSize), flags: Flags);
548 if(Handle)
549 {
550 return Handle;
551 }
552 }
553 return nullptr;
554 }
555 else if(Type >= TYPE_SAVE && Type < m_NumPaths)
556 {
557 // check wanted directory
558 return io_open(filename: GetPath(Type, pDir: pFilename, pBuffer, BufferSize), flags: Flags);
559 }
560 else
561 {
562 dbg_assert_failed("Type invalid");
563 }
564 }
565
566 template<typename F>
567 bool GenericExists(const char *pFilename, int Type, F &&CheckFunction) const
568 {
569 TranslateType(Type, pPath: pFilename);
570
571 char aBuffer[IO_MAX_PATH_LENGTH];
572 if(Type == TYPE_ALL)
573 {
574 // check all available directories
575 for(int i = TYPE_SAVE; i < m_NumPaths; ++i)
576 {
577 if(CheckFunction(GetPath(Type: i, pDir: pFilename, pBuffer: aBuffer, BufferSize: sizeof(aBuffer))))
578 return true;
579 }
580 return false;
581 }
582 else if(Type == TYPE_ABSOLUTE || (Type >= TYPE_SAVE && Type < m_NumPaths))
583 {
584 // check wanted directory
585 return CheckFunction(GetPath(Type, pDir: pFilename, pBuffer: aBuffer, BufferSize: sizeof(aBuffer)));
586 }
587 else
588 {
589 dbg_assert_failed("Type invalid");
590 }
591 }
592
593 bool FileExists(const char *pFilename, int Type) override
594 {
595 return GenericExists(pFilename, Type, CheckFunction&: fs_is_file);
596 }
597
598 bool FolderExists(const char *pFilename, int Type) override
599 {
600 return GenericExists(pFilename, Type, CheckFunction&: fs_is_dir);
601 }
602
603 bool ReadFile(const char *pFilename, int Type, void **ppResult, unsigned *pResultLen) override
604 {
605 IOHANDLE File = OpenFile(pFilename, Flags: IOFLAG_READ, Type);
606 if(!File)
607 {
608 *ppResult = nullptr;
609 *pResultLen = 0;
610 return false;
611 }
612 const bool ReadSuccess = io_read_all(io: File, result: ppResult, result_len: pResultLen);
613 io_close(io: File);
614 if(!ReadSuccess)
615 {
616 *ppResult = nullptr;
617 *pResultLen = 0;
618 return false;
619 }
620 return true;
621 }
622
623 char *ReadFileStr(const char *pFilename, int Type) override
624 {
625 IOHANDLE File = OpenFile(pFilename, Flags: IOFLAG_READ, Type);
626 if(!File)
627 return nullptr;
628 char *pResult = io_read_all_str(io: File);
629 io_close(io: File);
630 return pResult;
631 }
632
633 bool RetrieveTimes(const char *pFilename, int Type, time_t *pCreated, time_t *pModified) override
634 {
635 dbg_assert(Type == TYPE_ABSOLUTE || (Type >= TYPE_SAVE && Type < m_NumPaths), "Type invalid");
636
637 char aBuffer[IO_MAX_PATH_LENGTH];
638 return fs_file_time(name: GetPath(Type, pDir: pFilename, pBuffer: aBuffer, BufferSize: sizeof(aBuffer)), created: pCreated, modified: pModified) == 0;
639 }
640
641 bool CalculateHashes(const char *pFilename, int Type, SHA256_DIGEST *pSha256, unsigned *pCrc) override
642 {
643 dbg_assert(pSha256 != nullptr || pCrc != nullptr, "At least one output argument required");
644
645 IOHANDLE File = OpenFile(pFilename, Flags: IOFLAG_READ, Type);
646 if(!File)
647 return false;
648
649 SHA256_CTX Sha256Ctxt;
650 if(pSha256 != nullptr)
651 sha256_init(ctxt: &Sha256Ctxt);
652 if(pCrc != nullptr)
653 *pCrc = 0;
654 unsigned char aBuffer[64 * 1024];
655 while(true)
656 {
657 unsigned Bytes = io_read(io: File, buffer: aBuffer, size: sizeof(aBuffer));
658 if(Bytes == 0)
659 break;
660 if(pSha256 != nullptr)
661 sha256_update(ctxt: &Sha256Ctxt, data: aBuffer, data_len: Bytes);
662 if(pCrc != nullptr)
663 *pCrc = crc32(crc: *pCrc, buf: aBuffer, len: Bytes);
664 }
665 if(pSha256 != nullptr)
666 *pSha256 = sha256_finish(ctxt: &Sha256Ctxt);
667
668 io_close(io: File);
669 return true;
670 }
671
672 struct CFindCBData
673 {
674 CStorage *m_pStorage;
675 const char *m_pFilename;
676 const char *m_pPath;
677 char *m_pBuffer;
678 int m_BufferSize;
679 };
680
681 static int FindFileCallback(const char *pName, int IsDir, int Type, void *pUser)
682 {
683 CFindCBData Data = *static_cast<CFindCBData *>(pUser);
684 if(IsDir)
685 {
686 if(pName[0] == '.')
687 return 0;
688
689 // search within the folder
690 char aBuf[IO_MAX_PATH_LENGTH];
691 char aPath[IO_MAX_PATH_LENGTH];
692 str_format(buffer: aPath, buffer_size: sizeof(aPath), format: "%s/%s", Data.m_pPath, pName);
693 Data.m_pPath = aPath;
694 fs_listdir(dir: Data.m_pStorage->GetPath(Type, pDir: aPath, pBuffer: aBuf, BufferSize: sizeof(aBuf)), cb: FindFileCallback, type: Type, user: &Data);
695 if(Data.m_pBuffer[0])
696 return 1;
697 }
698 else if(!str_comp(a: pName, b: Data.m_pFilename))
699 {
700 // found the file = end
701 str_format(buffer: Data.m_pBuffer, buffer_size: Data.m_BufferSize, format: "%s/%s", Data.m_pPath, Data.m_pFilename);
702 return 1;
703 }
704
705 return 0;
706 }
707
708 bool FindFile(const char *pFilename, const char *pPath, int Type, char *pBuffer, int BufferSize) override
709 {
710 dbg_assert(BufferSize >= 1, "BufferSize invalid");
711
712 pBuffer[0] = 0;
713
714 CFindCBData Data;
715 Data.m_pStorage = this;
716 Data.m_pFilename = pFilename;
717 Data.m_pPath = pPath;
718 Data.m_pBuffer = pBuffer;
719 Data.m_BufferSize = BufferSize;
720
721 char aBuf[IO_MAX_PATH_LENGTH];
722 if(Type == TYPE_ALL)
723 {
724 // search within all available directories
725 for(int i = TYPE_SAVE; i < m_NumPaths; ++i)
726 {
727 fs_listdir(dir: GetPath(Type: i, pDir: pPath, pBuffer: aBuf, BufferSize: sizeof(aBuf)), cb: FindFileCallback, type: i, user: &Data);
728 if(pBuffer[0])
729 return true;
730 }
731 }
732 else if(Type >= TYPE_SAVE && Type < m_NumPaths)
733 {
734 // search within wanted directory
735 fs_listdir(dir: GetPath(Type, pDir: pPath, pBuffer: aBuf, BufferSize: sizeof(aBuf)), cb: FindFileCallback, type: Type, user: &Data);
736 }
737 else
738 {
739 dbg_assert_failed("Type invalid");
740 }
741
742 return pBuffer[0] != 0;
743 }
744
745 struct SFindFilesCallbackData
746 {
747 CStorage *m_pStorage;
748 const char *m_pFilename;
749 const char *m_pPath;
750 std::set<std::string> *m_pEntries;
751 };
752
753 static int FindFilesCallback(const char *pName, int IsDir, int Type, void *pUser)
754 {
755 SFindFilesCallbackData Data = *static_cast<SFindFilesCallbackData *>(pUser);
756 if(IsDir)
757 {
758 if(pName[0] == '.')
759 return 0;
760
761 // search within the folder
762 char aBuf[IO_MAX_PATH_LENGTH];
763 char aPath[IO_MAX_PATH_LENGTH];
764 str_format(buffer: aPath, buffer_size: sizeof(aPath), format: "%s/%s", Data.m_pPath, pName);
765 Data.m_pPath = aPath;
766 fs_listdir(dir: Data.m_pStorage->GetPath(Type, pDir: aPath, pBuffer: aBuf, BufferSize: sizeof(aBuf)), cb: FindFilesCallback, type: Type, user: &Data);
767 }
768 else if(!str_comp(a: pName, b: Data.m_pFilename))
769 {
770 char aBuffer[IO_MAX_PATH_LENGTH];
771 str_format(buffer: aBuffer, buffer_size: sizeof(aBuffer), format: "%s/%s", Data.m_pPath, Data.m_pFilename);
772 Data.m_pEntries->emplace(args&: aBuffer);
773 }
774
775 return 0;
776 }
777
778 size_t FindFiles(const char *pFilename, const char *pPath, int Type, std::set<std::string> *pEntries) override
779 {
780 SFindFilesCallbackData Data;
781 Data.m_pStorage = this;
782 Data.m_pFilename = pFilename;
783 Data.m_pPath = pPath;
784 Data.m_pEntries = pEntries;
785
786 char aBuf[IO_MAX_PATH_LENGTH];
787 if(Type == TYPE_ALL)
788 {
789 // search within all available directories
790 for(int i = TYPE_SAVE; i < m_NumPaths; ++i)
791 {
792 fs_listdir(dir: GetPath(Type: i, pDir: pPath, pBuffer: aBuf, BufferSize: sizeof(aBuf)), cb: FindFilesCallback, type: i, user: &Data);
793 }
794 }
795 else if(Type >= TYPE_SAVE && Type < m_NumPaths)
796 {
797 // search within wanted directory
798 fs_listdir(dir: GetPath(Type, pDir: pPath, pBuffer: aBuf, BufferSize: sizeof(aBuf)), cb: FindFilesCallback, type: Type, user: &Data);
799 }
800 else
801 {
802 dbg_assert_failed("Type invalid");
803 }
804
805 return pEntries->size();
806 }
807
808 bool RemoveFile(const char *pFilename, int Type) override
809 {
810 dbg_assert(Type == TYPE_ABSOLUTE || (Type >= TYPE_SAVE && Type < m_NumPaths), "Type invalid");
811
812 char aBuffer[IO_MAX_PATH_LENGTH];
813 GetPath(Type, pDir: pFilename, pBuffer: aBuffer, BufferSize: sizeof(aBuffer));
814
815 return fs_remove(filename: aBuffer) == 0;
816 }
817
818 bool RemoveFolder(const char *pFilename, int Type) override
819 {
820 dbg_assert(Type == TYPE_ABSOLUTE || (Type >= TYPE_SAVE && Type < m_NumPaths), "Type invalid");
821
822 char aBuffer[IO_MAX_PATH_LENGTH];
823 GetPath(Type, pDir: pFilename, pBuffer: aBuffer, BufferSize: sizeof(aBuffer));
824
825 return fs_removedir(path: aBuffer) == 0;
826 }
827
828 bool RemoveBinaryFile(const char *pFilename) override
829 {
830 char aBuffer[IO_MAX_PATH_LENGTH];
831 GetBinaryPath(pFilename, pBuffer: aBuffer, BufferSize: sizeof(aBuffer));
832
833 return fs_remove(filename: aBuffer) == 0;
834 }
835
836 bool RenameFile(const char *pOldFilename, const char *pNewFilename, int Type) override
837 {
838 dbg_assert(Type >= TYPE_SAVE && Type < m_NumPaths, "Type invalid");
839
840 char aOldBuffer[IO_MAX_PATH_LENGTH];
841 char aNewBuffer[IO_MAX_PATH_LENGTH];
842 GetPath(Type, pDir: pOldFilename, pBuffer: aOldBuffer, BufferSize: sizeof(aOldBuffer));
843 GetPath(Type, pDir: pNewFilename, pBuffer: aNewBuffer, BufferSize: sizeof(aNewBuffer));
844
845 return fs_rename(oldname: aOldBuffer, newname: aNewBuffer) == 0;
846 }
847
848 bool RenameBinaryFile(const char *pOldFilename, const char *pNewFilename) override
849 {
850 char aOldBuffer[IO_MAX_PATH_LENGTH];
851 char aNewBuffer[IO_MAX_PATH_LENGTH];
852 GetBinaryPath(pFilename: pOldFilename, pBuffer: aOldBuffer, BufferSize: sizeof(aOldBuffer));
853 GetBinaryPath(pFilename: pNewFilename, pBuffer: aNewBuffer, BufferSize: sizeof(aNewBuffer));
854
855 if(fs_makedir_rec_for(path: aNewBuffer) < 0)
856 {
857 log_error("storage", "failed to create folders for: %s", aNewBuffer);
858 return false;
859 }
860
861 return fs_rename(oldname: aOldBuffer, newname: aNewBuffer) == 0;
862 }
863
864 bool CreateFolder(const char *pFoldername, int Type) override
865 {
866 dbg_assert(Type >= TYPE_SAVE && Type < m_NumPaths, "Type invalid");
867
868 char aBuffer[IO_MAX_PATH_LENGTH];
869 GetPath(Type, pDir: pFoldername, pBuffer: aBuffer, BufferSize: sizeof(aBuffer));
870
871 return fs_makedir(path: aBuffer) == 0;
872 }
873
874 void GetCompletePath(int Type, const char *pDir, char *pBuffer, unsigned BufferSize) override
875 {
876 TranslateType(Type, pPath: pDir);
877 dbg_assert(Type >= TYPE_SAVE && Type < m_NumPaths, "Type invalid");
878 GetPath(Type, pDir, pBuffer, BufferSize);
879 }
880
881 const char *GetBinaryPath(const char *pFilename, char *pBuffer, unsigned BufferSize) override
882 {
883 str_format(buffer: pBuffer, buffer_size: BufferSize, format: "%s%s%s", m_aBinarydir, !m_aBinarydir[0] ? "" : "/", pFilename);
884 return pBuffer;
885 }
886
887 const char *GetBinaryPathAbsolute(const char *pFilename, char *pBuffer, unsigned BufferSize) override
888 {
889 char aBinaryPath[IO_MAX_PATH_LENGTH];
890 GetBinaryPath(pFilename, pBuffer: aBinaryPath, BufferSize: sizeof(aBinaryPath));
891 if(fs_is_relative_path(path: aBinaryPath))
892 {
893 if(fs_getcwd(buffer: pBuffer, buffer_size: BufferSize))
894 {
895 str_append(dst: pBuffer, src: "/", dst_size: BufferSize);
896 str_append(dst: pBuffer, src: aBinaryPath, dst_size: BufferSize);
897 }
898 }
899 else
900 {
901 str_copy(dst: pBuffer, src: aBinaryPath, dst_size: BufferSize);
902 }
903 return pBuffer;
904 }
905
906 static IStorage *Create(EInitializationType InitializationType, int NumArgs, const char **ppArguments)
907 {
908 CStorage *pStorage = new CStorage();
909 if(!pStorage->Init(InitializationType, NumArgs, ppArguments))
910 {
911 delete pStorage;
912 return nullptr;
913 }
914 return pStorage;
915 }
916};
917
918const char *IStorage::FormatTmpPath(char *aBuf, unsigned BufSize, const char *pPath)
919{
920 str_format(buffer: aBuf, buffer_size: BufSize, format: "%s.%d.tmp", pPath, process_id());
921 return aBuf;
922}
923
924IStorage *CreateStorage(IStorage::EInitializationType InitializationType, int NumArgs, const char **ppArguments)
925{
926 return CStorage::Create(InitializationType, NumArgs, ppArguments);
927}
928
929std::unique_ptr<IStorage> CreateLocalStorage()
930{
931 std::unique_ptr<CStorage> pStorage = std::make_unique<CStorage>();
932 if(!pStorage->FindCurrentDirectory() ||
933 !pStorage->AddPath(pPath: "$CURRENTDIR"))
934 {
935 return std::unique_ptr<IStorage>(nullptr);
936 }
937 return pStorage;
938}
939
940std::unique_ptr<IStorage> CreateTempStorage(const char *pDirectory, int NumArgs, const char **ppArguments)
941{
942 dbg_assert(NumArgs > 0, "Expected at least one argument");
943 std::unique_ptr<CStorage> pStorage = std::make_unique<CStorage>();
944 pStorage->FindDataDirectory(pArgv0: ppArguments[0]);
945 if(!pStorage->FindCurrentDirectory() ||
946 !pStorage->AddPath(pPath: pDirectory) ||
947 !pStorage->AddPath(pPath: "$DATADIR") ||
948 !pStorage->AddPath(pPath: "$CURRENTDIR"))
949 {
950 return std::unique_ptr<IStorage>(nullptr);
951 }
952 return pStorage;
953}
954