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;
703 filename.replace(p + 1, std::string::npos, it2.first);
705 Debug(misc, 9,
" extracting {}", filename);
709 std::unique_ptr<FILE, FileDeleter> in(
FioFOpenFileTar(it2.second, &to_copy));
711 Debug(misc, 6,
"Extracting {} failed; could not open {}", filename, tar_filename);
716 std::unique_ptr<FILE, FileDeleter> out(fopen(filename.c_str(),
"wb"));
718 Debug(misc, 6,
"Extracting {} failed; could not open {}", filename, filename);
725 for (; to_copy != 0; to_copy -= read) {
726 read = fread(buffer, 1, std::min(to_copy,
lengthof(buffer)), in.get());
727 if (read <= 0 || fwrite(buffer, 1, read, out.get()) != read)
break;
731 Debug(misc, 6,
"Extracting {} failed; still {} bytes to copy", filename, to_copy);
736 Debug(misc, 9,
" extraction successful");
758 std::string path = exe;
761 for (
size_t pos = path.find_first_of(
'.'); pos != std::string::npos; pos = path.find_first_of(
'.', pos + 1)) {
769 size_t pos = path.find_last_of(PATHSEPCHAR);
770 if (pos == std::string::npos)
return false;
774 if (chdir(path.c_str()) != 0) {
775 Debug(misc, 0,
"Directory with the binary does not exist?");
818 find_directory(B_USER_SETTINGS_DIRECTORY, &path);
819 return std::string(path.Path());
821 const char *home_env = std::getenv(
"HOME");
822 if (home_env !=
nullptr)
return std::string(home_env);
824 const struct passwd *pw = getpwuid(getuid());
825 if (pw !=
nullptr)
return std::string(pw->pw_dir);
839 const char *xdg_data_home = std::getenv(
"XDG_DATA_HOME");
840 if (xdg_data_home !=
nullptr) {
843 tmp += PERSONAL_DIR[0] ==
'.' ? &PERSONAL_DIR[1] : PERSONAL_DIR;
847 tmp +=
"content_download";
850 }
else if (!homedir.empty()) {
852 tmp += PATHSEP
".local" PATHSEP
"share" PATHSEP;
853 tmp += PERSONAL_DIR[0] ==
'.' ? &PERSONAL_DIR[1] : PERSONAL_DIR;
857 tmp +=
"content_download";
866 #if !defined(WITH_PERSONAL_DIR)
869 if (!homedir.empty()) {
876 tmp +=
"content_download";
885 #if defined(WITH_SHARED_DIR)
894 if (getcwd(cwd, MAX_PATH) ==
nullptr) *cwd =
'\0';
906 if (end == std::string::npos) {
919 if (getcwd(buf,
lengthof(buf)) ==
nullptr) {
930 if (cwd[0] !=
'\0') {
932 if (chdir(cwd) != 0) {
933 Debug(misc, 0,
"Failed to return to working directory!");
937 #if !defined(GLOBAL_DATA_DIR)
940 tmp = GLOBAL_DATA_DIR;
945 extern void CocoaSetApplicationBundleDir();
946 CocoaSetApplicationBundleDir();
965 FillValidSearchPaths(only_local_path);
968 std::string config_home;
970 const char *xdg_config_home = std::getenv(
"XDG_CONFIG_HOME");
971 if (xdg_config_home !=
nullptr) {
972 config_home = xdg_config_home;
973 config_home += PATHSEP;
974 config_home += PERSONAL_DIR[0] ==
'.' ? &PERSONAL_DIR[1] : PERSONAL_DIR;
975 }
else if (!homedir.empty()) {
977 config_home = homedir;
978 config_home += PATHSEP
".config" PATHSEP;
979 config_home += PERSONAL_DIR[0] ==
'.' ? &PERSONAL_DIR[1] : PERSONAL_DIR;
989 std::string config_dir;
994 if (!personal_dir.empty()) {
995 auto end = personal_dir.find_last_of(PATHSEPCHAR);
996 if (end != std::string::npos) personal_dir.erase(end + 1);
997 config_dir = personal_dir;
1001 config_dir = config_home;
1003 static const Searchpath new_openttd_cfg_order[] = {
1008 for (uint i = 0; i <
lengthof(new_openttd_cfg_order); i++) {
1019 Debug(misc, 1,
"{} found as config directory", config_dir);
1022 extern std::string _hotkeys_file;
1023 _hotkeys_file = config_dir +
"hotkeys.cfg";
1032 if (config_dir == config_home) {
1036 if (only_local_path) {
1051 #if defined(WITH_PERSONAL_DIR)
1058 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
1061 for (uint i = 0; i <
lengthof(default_subdirs); i++) {
1069 FillValidSearchPaths(only_local_path);
1073 for (uint i = 0; i <
lengthof(dirs); i++) {
1087 for (
auto &c : filename) {
1091 case ':':
case '\\':
case '*':
case '?':
case '/':
1092 case '<':
case '>':
case '|':
case '"':
1107 std::unique_ptr<char[]>
ReadFileToMem(
const std::string &filename,
size_t &lenp,
size_t maxsize)
1109 FILE *in = fopen(filename.c_str(),
"rb");
1110 if (in ==
nullptr)
return nullptr;
1114 fseek(in, 0, SEEK_END);
1115 size_t len = ftell(in);
1116 fseek(in, 0, SEEK_SET);
1117 if (len > maxsize)
return nullptr;
1119 std::unique_ptr<char[]> mem = std::make_unique<char[]>(len + 1);
1122 if (fread(mem.get(), len, 1, in) != 1)
return nullptr;
1136 if (extension ==
nullptr)
return true;
1138 const char *ext = strrchr(filename, extension[0]);
1151 static uint
ScanPath(
FileScanner *fs,
const char *extension,
const char *path,
size_t basepath_length,
bool recursive)
1155 struct dirent *dirent;
1158 if (path ==
nullptr || (dir =
ttd_opendir(path)) ==
nullptr)
return 0;
1160 while ((dirent = readdir(dir)) !=
nullptr) {
1161 std::string d_name =
FS2OTTD(dirent->d_name);
1163 if (!FiosIsValidFile(path, dirent, &sb))
continue;
1165 std::string filename(path);
1168 if (S_ISDIR(sb.st_mode)) {
1170 if (!recursive)
continue;
1171 if (d_name ==
"." || d_name ==
"..")
continue;
1173 num +=
ScanPath(fs, extension, filename.c_str(), basepath_length, recursive);
1174 }
else if (S_ISREG(sb.st_mode)) {
1194 const auto &filename = tar.first;
1196 if (
MatchesExtension(extension, filename.c_str()) && fs->
AddFile(filename, 0, tar.second.tar_filename)) num++;
1220 std::string path = FioGetDirectory(sp, sd);
1221 num +=
ScanPath(
this, extension, path.c_str(), path.size(), recursive);
1225 for (
const auto &tar : _tar_filelist[sd]) {
1226 num +=
ScanTar(
this, extension, tar);
1254 std::string path(directory);
1256 return ScanPath(
this, extension, path.c_str(), path.size(), recursive);