19 # define access _taccess
20 #elif defined(__HAIKU__)
22 #include <storage/FindDirectory.h>
39 static const char *
const _subdirs[] = {
42 "save" PATHSEP
"autosave" PATHSEP,
44 "scenario" PATHSEP
"heightmap" PATHSEP,
51 "ai" PATHSEP
"library" PATHSEP,
53 "game" PATHSEP
"library" PATHSEP,
55 "social_integration" PATHSEP,
66 std::vector<Searchpath> _valid_searchpaths;
67 std::array<TarList, NUM_SUBDIRS> _tar_list;
70 typedef std::map<std::string, std::string> TarLinkList;
73 extern bool FiosIsValidFile(
const std::string &path,
const struct dirent *ent,
struct stat *sb);
85 static void FillValidSearchPaths(
bool only_local_path)
87 _valid_searchpaths.clear();
89 std::set<std::string> seen{};
90 for (
Searchpath sp = SP_FIRST_DIR; sp < NUM_SEARCHPATHS; sp++) {
93 if (only_local_path) {
108 _valid_searchpaths.emplace_back(sp);
116 _valid_searchpaths.insert(_valid_searchpaths.begin(),
SP_WORKING_DIR);
129 if (f ==
nullptr)
return false;
142 return access(
OTTD2FS(filename).c_str(), 0) == 0;
164 std::string buf = FioGetDirectory(sp, subdir);
181 assert(sp < NUM_SEARCHPATHS);
190 std::string ret = FioGetDirectory(sp, subdir);
198 static FILE *FioFOpenFileSp(
const std::string &filename,
const char *mode,
Searchpath sp,
Subdirectory subdir,
size_t *filesize)
206 MultiByteToWideChar(CP_ACP, 0, mode, -1, Lmode,
lengthof(Lmode));
218 if (mode[0] ==
'r' && GetFileAttributes(
OTTD2FS(buf).c_str()) == INVALID_FILE_ATTRIBUTES)
return nullptr;
221 f = fopen(buf.c_str(), mode);
224 f = fopen(buf.c_str(), mode);
227 if (f !=
nullptr && filesize !=
nullptr) {
229 fseek(f, 0, SEEK_END);
230 *filesize = ftell(f);
231 fseek(f, 0, SEEK_SET);
245 FILE *f = fopen(entry.tar_filename.c_str(),
"rb");
246 if (f ==
nullptr)
return f;
248 if (fseek(f, entry.position, SEEK_SET) < 0) {
253 if (filesize !=
nullptr) *filesize = entry.size;
270 f = FioFOpenFileSp(filename, mode, sp, subdir, filesize);
275 if (f ==
nullptr && mode[0] ==
'r' && subdir !=
NO_DIRECTORY) {
277 std::string resolved_name = filename;
278 strtolower(resolved_name);
281 std::istringstream ss(resolved_name);
282 std::vector<std::string> tokens;
284 while (std::getline(ss, token, PATHSEPCHAR)) {
286 if (tokens.size() < 2)
return nullptr;
288 }
else if (token ==
".") {
292 tokens.push_back(token);
296 resolved_name.clear();
298 for (
const std::string &token : tokens) {
300 resolved_name += PATHSEP;
302 resolved_name += token;
308 const std::string &src = link.first;
309 size_t len = src.length();
310 if (resolved_name.length() >= len && resolved_name[len - 1] == PATHSEPCHAR && src.compare(0, len, resolved_name, 0, len) == 0) {
312 resolved_name.replace(0, len, link.second);
317 TarFileList::iterator it = _tar_filelist[subdir].find(resolved_name);
318 if (it != _tar_filelist[subdir].end()) {
329 if (f !=
nullptr)
break;
351 auto p = name.find_last_of(PATHSEPCHAR);
352 if (p != std::string::npos) {
353 std::string dirname = name.substr(0, p);
355 if (dir ==
nullptr) {
365 CreateDirectory(
OTTD2FS(name).c_str(),
nullptr);
367 mkdir(
OTTD2FS(name).c_str(), 0755);
379 if (buf.empty())
return;
381 if (buf.back() != PATHSEPCHAR) buf.push_back(PATHSEPCHAR);
384 static void TarAddLink(
const std::string &srcParam,
const std::string &destParam,
Subdirectory subdir)
386 std::string src = srcParam;
387 std::string dest = destParam;
389 std::transform(src.begin(), src.end(), src.begin(), tolower);
390 std::transform(dest.begin(), dest.end(), dest.begin(), tolower);
392 TarFileList::iterator dest_file = _tar_filelist[subdir].find(dest);
393 if (dest_file != _tar_filelist[subdir].end()) {
395 _tar_filelist[subdir].insert(TarFileList::value_type(src, dest_file->second));
399 const std::string src_path = ((*src.rbegin() == PATHSEPCHAR) ? src : src + PATHSEPCHAR);
400 const std::string dst_path = (dest.length() == 0 ?
"" : ((*dest.rbegin() == PATHSEPCHAR) ? dest : dest + PATHSEPCHAR));
401 _tar_linklist[subdir].insert(TarLinkList::value_type(src_path, dst_path));
412 for (
char &c : name) {
415 #if (PATHSEPCHAR != '/')
417 if (c ==
'/') c = PATHSEPCHAR;
429 _tar_filelist[sd].clear();
430 _tar_list[sd].clear();
431 uint num = this->
Scan(
".tar", sd,
false);
438 Debug(misc, 2,
"Scanning for tars");
459 Debug(misc, 2,
"Scan complete, found {} files", num);
472 return this->
AddFile(filename, 0);
489 for (; length < buffer_length && buffer[length] !=
'\0'; length++) {}
493 bool TarScanner::AddFile(
const std::string &filename,
size_t, [[maybe_unused]]
const std::string &tar_filename)
496 assert(tar_filename.empty());
521 TarList::iterator it = _tar_list[this->
subdir].find(filename);
522 if (it != _tar_list[this->subdir].end())
return false;
524 FILE *f = fopen(filename.c_str(),
"rb");
529 if (f ==
nullptr)
return false;
531 _tar_list[this->
subdir][filename] = std::string{};
533 std::string filename_base = std::filesystem::path(filename).filename().string();
539 size_t num = 0, pos = 0;
543 memset(&empty[0], 0,
sizeof(empty));
546 size_t num_bytes_read = fread(&th, 1, 512, f);
547 if (num_bytes_read != 512)
break;
548 pos += num_bytes_read;
551 if (strncmp(th.magic,
"ustar", 5) != 0 && memcmp(&th.magic, &empty[0], 512 - offsetof(TarHeader, magic)) != 0) {
553 if (memcmp(&th, &empty[0], 512) == 0)
continue;
555 Debug(misc, 0,
"The file '{}' isn't a valid tar-file", filename);
563 if (th.prefix[0] !=
'\0') {
573 size_t skip = size.empty() ? 0 : std::stoul(size,
nullptr, 8);
575 switch (th.typeflag) {
578 if (name.empty())
break;
582 entry.tar_filename = filename;
584 entry.position = pos;
589 Debug(misc, 6,
"Found file in tar: {} ({} bytes, {} offset)", name, skip, pos);
590 if (_tar_filelist[this->subdir].insert(TarFileList::value_type(filename_base + PATHSEPCHAR + name, entry)).second) num++;
600 if (name.empty() || link.empty())
break;
607 if (link[0] == PATHSEPCHAR) {
608 Debug(misc, 5,
"Ignoring absolute link in tar: {} -> {}", name, link);
614 std::string dest = (std::filesystem::path(name).remove_filename() /= link).lexically_normal().string();
615 if (dest[0] == PATHSEPCHAR || dest.starts_with(
"..")) {
616 Debug(misc, 5,
"Ignoring link pointing outside of data directory: {} -> {}", name, link);
621 Debug(misc, 6,
"Found link in tar: {} -> {}", name, dest);
622 links.insert(TarLinkList::value_type(filename_base + PATHSEPCHAR + name, filename_base + PATHSEPCHAR + dest));
632 Debug(misc, 6,
"Found dir in tar: {}", name);
633 if (_tar_list[this->subdir][filename].empty()) _tar_list[this->
subdir][filename] = name;
642 skip =
Align(skip, 512);
643 if (fseek(f, skip, SEEK_CUR) < 0) {
644 Debug(misc, 0,
"The file '{}' can't be read as a valid tar-file", filename);
651 Debug(misc, 4,
"Found tar '{}' with {} new files", filename, num);
663 for (
auto &it : links) {
664 TarAddLink(it.first, it.second, this->subdir);
679 TarList::iterator it = _tar_list[subdir].find(tar_filename);
681 if (it == _tar_list[subdir].end())
return false;
683 const auto &dirname = (*it).second;
686 if (dirname.empty()) {
687 Debug(misc, 3,
"Extracting {} failed; archive rejected, the contents must be in a sub directory", tar_filename);
691 std::string filename = tar_filename;
692 auto p = filename.find_last_of(PATHSEPCHAR);
694 if (p == std::string::npos)
return false;
696 filename.replace(p + 1, std::string::npos, dirname);
697 Debug(misc, 8,
"Extracting {} to directory {}", tar_filename, filename);
700 for (
auto &it2 : _tar_filelist[subdir]) {
701 if (tar_filename != it2.second.tar_filename)
continue;
704 std::string_view name = it2.first;
705 name.remove_prefix(name.find_first_of(PATHSEPCHAR) + 1);
706 filename.replace(p + 1, std::string::npos, name);
708 Debug(misc, 9,
" extracting {}", filename);
712 std::unique_ptr<FILE, FileDeleter> in(
FioFOpenFileTar(it2.second, &to_copy));
714 Debug(misc, 6,
"Extracting {} failed; could not open {}", filename, tar_filename);
719 std::unique_ptr<FILE, FileDeleter> out(fopen(filename.c_str(),
"wb"));
721 Debug(misc, 6,
"Extracting {} failed; could not open {}", filename, filename);
728 for (; to_copy != 0; to_copy -= read) {
729 read = fread(buffer, 1, std::min(to_copy,
lengthof(buffer)), in.get());
730 if (read <= 0 || fwrite(buffer, 1, read, out.get()) != read)
break;
734 Debug(misc, 6,
"Extracting {} failed; still {} bytes to copy", filename, to_copy);
739 Debug(misc, 9,
" extraction successful");
761 std::string path = exe;
764 for (
size_t pos = path.find_first_of(
'.'); pos != std::string::npos; pos = path.find_first_of(
'.', pos + 1)) {
772 size_t pos = path.find_last_of(PATHSEPCHAR);
773 if (pos == std::string::npos)
return false;
777 if (chdir(path.c_str()) != 0) {
778 Debug(misc, 0,
"Directory with the binary does not exist?");
821 find_directory(B_USER_SETTINGS_DIRECTORY, &path);
822 return std::string(path.Path());
824 const char *home_env = std::getenv(
"HOME");
825 if (home_env !=
nullptr)
return std::string(home_env);
827 const struct passwd *pw = getpwuid(getuid());
828 if (pw !=
nullptr)
return std::string(pw->pw_dir);
842 const char *xdg_data_home = std::getenv(
"XDG_DATA_HOME");
843 if (xdg_data_home !=
nullptr) {
846 tmp += PERSONAL_DIR[0] ==
'.' ? &PERSONAL_DIR[1] : PERSONAL_DIR;
850 tmp +=
"content_download";
853 }
else if (!homedir.empty()) {
855 tmp += PATHSEP
".local" PATHSEP
"share" PATHSEP;
856 tmp += PERSONAL_DIR[0] ==
'.' ? &PERSONAL_DIR[1] : PERSONAL_DIR;
860 tmp +=
"content_download";
869 #if !defined(WITH_PERSONAL_DIR)
872 if (!homedir.empty()) {
879 tmp +=
"content_download";
888 #if defined(WITH_SHARED_DIR)
897 if (getcwd(cwd, MAX_PATH) ==
nullptr) *cwd =
'\0';
909 if (end == std::string::npos) {
922 if (getcwd(buf,
lengthof(buf)) ==
nullptr) {
933 if (cwd[0] !=
'\0') {
935 if (chdir(cwd) != 0) {
936 Debug(misc, 0,
"Failed to return to working directory!");
940 #if !defined(GLOBAL_DATA_DIR)
943 tmp = GLOBAL_DATA_DIR;
948 extern void CocoaSetApplicationBundleDir();
949 CocoaSetApplicationBundleDir();
968 FillValidSearchPaths(only_local_path);
971 std::string config_home;
973 const char *xdg_config_home = std::getenv(
"XDG_CONFIG_HOME");
974 if (xdg_config_home !=
nullptr) {
975 config_home = xdg_config_home;
976 config_home += PATHSEP;
977 config_home += PERSONAL_DIR[0] ==
'.' ? &PERSONAL_DIR[1] : PERSONAL_DIR;
978 }
else if (!homedir.empty()) {
980 config_home = homedir;
981 config_home += PATHSEP
".config" PATHSEP;
982 config_home += PERSONAL_DIR[0] ==
'.' ? &PERSONAL_DIR[1] : PERSONAL_DIR;
992 std::string config_dir;
997 if (!personal_dir.empty()) {
998 auto end = personal_dir.find_last_of(PATHSEPCHAR);
999 if (end != std::string::npos) personal_dir.erase(end + 1);
1000 config_dir = personal_dir;
1004 config_dir = config_home;
1006 static const Searchpath new_openttd_cfg_order[] = {
1011 for (uint i = 0; i <
lengthof(new_openttd_cfg_order); i++) {
1022 Debug(misc, 1,
"{} found as config directory", config_dir);
1025 extern std::string _hotkeys_file;
1026 _hotkeys_file = config_dir +
"hotkeys.cfg";
1035 if (config_dir == config_home) {
1039 if (only_local_path) {
1054 #if defined(WITH_PERSONAL_DIR)
1061 SAVE_DIR,
AUTOSAVE_DIR,
SCENARIO_DIR,
HEIGHTMAP_DIR,
BASESET_DIR,
NEWGRF_DIR,
AI_DIR,
AI_LIBRARY_DIR,
GAME_DIR,
GAME_LIBRARY_DIR,
SCREENSHOT_DIR,
SOCIAL_INTEGRATION_DIR
1064 for (uint i = 0; i <
lengthof(default_subdirs); i++) {
1072 FillValidSearchPaths(only_local_path);
1076 for (uint i = 0; i <
lengthof(dirs); i++) {
1090 for (
auto &c : filename) {
1094 case ':':
case '\\':
case '*':
case '?':
case '/':
1095 case '<':
case '>':
case '|':
case '"':
1110 std::unique_ptr<char[]>
ReadFileToMem(
const std::string &filename,
size_t &lenp,
size_t maxsize)
1112 FILE *in = fopen(filename.c_str(),
"rb");
1113 if (in ==
nullptr)
return nullptr;
1117 fseek(in, 0, SEEK_END);
1118 size_t len = ftell(in);
1119 fseek(in, 0, SEEK_SET);
1120 if (len > maxsize)
return nullptr;
1122 std::unique_ptr<char[]> mem = std::make_unique<char[]>(len + 1);
1125 if (fread(mem.get(), len, 1, in) != 1)
return nullptr;
1139 if (extension ==
nullptr)
return true;
1141 const char *ext = strrchr(filename, extension[0]);
1154 static uint
ScanPath(
FileScanner *fs,
const char *extension,
const char *path,
size_t basepath_length,
bool recursive)
1158 struct dirent *dirent;
1161 if (path ==
nullptr || (dir =
ttd_opendir(path)) ==
nullptr)
return 0;
1163 while ((dirent = readdir(dir)) !=
nullptr) {
1164 std::string d_name =
FS2OTTD(dirent->d_name);
1166 if (!FiosIsValidFile(path, dirent, &sb))
continue;
1168 std::string filename(path);
1171 if (S_ISDIR(sb.st_mode)) {
1173 if (!recursive)
continue;
1174 if (d_name ==
"." || d_name ==
"..")
continue;
1176 num +=
ScanPath(fs, extension, filename.c_str(), basepath_length, recursive);
1177 }
else if (S_ISREG(sb.st_mode)) {
1197 const auto &filename = tar.first;
1199 if (
MatchesExtension(extension, filename.c_str()) && fs->
AddFile(filename, 0, tar.second.tar_filename)) num++;
1223 std::string path = FioGetDirectory(sp, sd);
1224 num +=
ScanPath(
this, extension, path.c_str(), path.size(), recursive);
1228 for (
const auto &tar : _tar_filelist[sd]) {
1229 num +=
ScanTar(
this, extension, tar);
1257 std::string path(directory);
1259 return ScanPath(
this, extension, path.c_str(), path.size(), recursive);