path_util.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <unordered_map>
  6. #include "common/fs/fs.h"
  7. #include "common/fs/fs_paths.h"
  8. #include "common/fs/path_util.h"
  9. #include "common/logging/log.h"
  10. #ifdef _WIN32
  11. #include <shlobj.h> // Used in GetExeDirectory()
  12. #else
  13. #include <cstdlib> // Used in Get(Home/Data)Directory()
  14. #include <pwd.h> // Used in GetHomeDirectory()
  15. #include <sys/types.h> // Used in GetHomeDirectory()
  16. #include <unistd.h> // Used in GetDataDirectory()
  17. #endif
  18. #ifdef __APPLE__
  19. #include <sys/param.h> // Used in GetBundleDirectory()
  20. // CFURL contains __attribute__ directives that gcc does not know how to parse, so we need to just
  21. // ignore them if we're not using clang. The macro is only used to prevent linking against
  22. // functions that don't exist on older versions of macOS, and the worst case scenario is a linker
  23. // error, so this is perfectly safe, just inconvenient.
  24. #ifndef __clang__
  25. #define availability(...)
  26. #endif
  27. #include <CoreFoundation/CFBundle.h> // Used in GetBundleDirectory()
  28. #include <CoreFoundation/CFString.h> // Used in GetBundleDirectory()
  29. #include <CoreFoundation/CFURL.h> // Used in GetBundleDirectory()
  30. #ifdef availability
  31. #undef availability
  32. #endif
  33. #endif
  34. #ifndef MAX_PATH
  35. #ifdef _WIN32
  36. // This is the maximum number of UTF-16 code units permissible in Windows file paths
  37. #define MAX_PATH 260
  38. #else
  39. // This is the maximum number of UTF-8 code units permissible in all other OSes' file paths
  40. #define MAX_PATH 1024
  41. #endif
  42. #endif
  43. namespace Common::FS {
  44. namespace fs = std::filesystem;
  45. /**
  46. * The PathManagerImpl is a singleton allowing to manage the mapping of
  47. * YuzuPath enums to real filesystem paths.
  48. * This class provides 2 functions: GetYuzuPathImpl and SetYuzuPathImpl.
  49. * These are used by GetYuzuPath and SetYuzuPath respectively to get or modify
  50. * the path mapped by the YuzuPath enum.
  51. */
  52. class PathManagerImpl {
  53. public:
  54. static PathManagerImpl& GetInstance() {
  55. static PathManagerImpl path_manager_impl;
  56. return path_manager_impl;
  57. }
  58. PathManagerImpl(const PathManagerImpl&) = delete;
  59. PathManagerImpl& operator=(const PathManagerImpl&) = delete;
  60. PathManagerImpl(PathManagerImpl&&) = delete;
  61. PathManagerImpl& operator=(PathManagerImpl&&) = delete;
  62. [[nodiscard]] const fs::path& GetYuzuPathImpl(YuzuPath yuzu_path) {
  63. return yuzu_paths.at(yuzu_path);
  64. }
  65. void SetYuzuPathImpl(YuzuPath yuzu_path, const fs::path& new_path) {
  66. yuzu_paths.insert_or_assign(yuzu_path, new_path);
  67. }
  68. private:
  69. PathManagerImpl() {
  70. #ifdef _WIN32
  71. auto yuzu_path = GetExeDirectory() / PORTABLE_DIR;
  72. if (!IsDir(yuzu_path)) {
  73. yuzu_path = GetAppDataRoamingDirectory() / YUZU_DIR;
  74. }
  75. GenerateYuzuPath(YuzuPath::YuzuDir, yuzu_path);
  76. GenerateYuzuPath(YuzuPath::CacheDir, yuzu_path / CACHE_DIR);
  77. GenerateYuzuPath(YuzuPath::ConfigDir, yuzu_path / CONFIG_DIR);
  78. #else
  79. auto yuzu_path = GetCurrentDir() / PORTABLE_DIR;
  80. if (Exists(yuzu_path) && IsDir(yuzu_path)) {
  81. GenerateYuzuPath(YuzuPath::YuzuDir, yuzu_path);
  82. GenerateYuzuPath(YuzuPath::CacheDir, yuzu_path / CACHE_DIR);
  83. GenerateYuzuPath(YuzuPath::ConfigDir, yuzu_path / CONFIG_DIR);
  84. } else {
  85. yuzu_path = GetDataDirectory("XDG_DATA_HOME") / YUZU_DIR;
  86. GenerateYuzuPath(YuzuPath::YuzuDir, yuzu_path);
  87. GenerateYuzuPath(YuzuPath::CacheDir, GetDataDirectory("XDG_CACHE_HOME") / YUZU_DIR);
  88. GenerateYuzuPath(YuzuPath::ConfigDir, GetDataDirectory("XDG_CONFIG_HOME") / YUZU_DIR);
  89. }
  90. #endif
  91. GenerateYuzuPath(YuzuPath::DumpDir, yuzu_path / DUMP_DIR);
  92. GenerateYuzuPath(YuzuPath::KeysDir, yuzu_path / KEYS_DIR);
  93. GenerateYuzuPath(YuzuPath::LoadDir, yuzu_path / LOAD_DIR);
  94. GenerateYuzuPath(YuzuPath::LogDir, yuzu_path / LOG_DIR);
  95. GenerateYuzuPath(YuzuPath::NANDDir, yuzu_path / NAND_DIR);
  96. GenerateYuzuPath(YuzuPath::ScreenshotsDir, yuzu_path / SCREENSHOTS_DIR);
  97. GenerateYuzuPath(YuzuPath::SDMCDir, yuzu_path / SDMC_DIR);
  98. GenerateYuzuPath(YuzuPath::ShaderDir, yuzu_path / SHADER_DIR);
  99. }
  100. ~PathManagerImpl() = default;
  101. void GenerateYuzuPath(YuzuPath yuzu_path, const fs::path& new_path) {
  102. void(FS::CreateDir(new_path));
  103. SetYuzuPathImpl(yuzu_path, new_path);
  104. }
  105. std::unordered_map<YuzuPath, fs::path> yuzu_paths;
  106. };
  107. std::string PathToUTF8String(const fs::path& path) {
  108. const auto utf8_string = path.u8string();
  109. return std::string{utf8_string.begin(), utf8_string.end()};
  110. }
  111. bool ValidatePath(const fs::path& path) {
  112. if (path.empty()) {
  113. LOG_ERROR(Common_Filesystem, "Input path is empty, path={}", PathToUTF8String(path));
  114. return false;
  115. }
  116. #ifdef _WIN32
  117. if (path.u16string().size() >= MAX_PATH) {
  118. LOG_ERROR(Common_Filesystem, "Input path is too long, path={}", PathToUTF8String(path));
  119. return false;
  120. }
  121. #else
  122. if (path.u8string().size() >= MAX_PATH) {
  123. LOG_ERROR(Common_Filesystem, "Input path is too long, path={}", PathToUTF8String(path));
  124. return false;
  125. }
  126. #endif
  127. return true;
  128. }
  129. fs::path ConcatPath(const fs::path& first, const fs::path& second) {
  130. const bool second_has_dir_sep = IsDirSeparator(second.u8string().front());
  131. if (!second_has_dir_sep) {
  132. return (first / second).lexically_normal();
  133. }
  134. fs::path concat_path = first;
  135. concat_path += second;
  136. return concat_path.lexically_normal();
  137. }
  138. fs::path ConcatPathSafe(const fs::path& base, const fs::path& offset) {
  139. const auto concatenated_path = ConcatPath(base, offset);
  140. if (!IsPathSandboxed(base, concatenated_path)) {
  141. return base;
  142. }
  143. return concatenated_path;
  144. }
  145. bool IsPathSandboxed(const fs::path& base, const fs::path& path) {
  146. const auto base_string = RemoveTrailingSeparators(base.lexically_normal()).u8string();
  147. const auto path_string = RemoveTrailingSeparators(path.lexically_normal()).u8string();
  148. if (path_string.size() < base_string.size()) {
  149. return false;
  150. }
  151. return base_string.compare(0, base_string.size(), path_string, 0, base_string.size()) == 0;
  152. }
  153. bool IsDirSeparator(char character) {
  154. return character == '/' || character == '\\';
  155. }
  156. bool IsDirSeparator(char8_t character) {
  157. return character == u8'/' || character == u8'\\';
  158. }
  159. fs::path RemoveTrailingSeparators(const fs::path& path) {
  160. if (path.empty()) {
  161. return path;
  162. }
  163. auto string_path = path.u8string();
  164. while (IsDirSeparator(string_path.back())) {
  165. string_path.pop_back();
  166. }
  167. return fs::path{string_path};
  168. }
  169. const fs::path& GetYuzuPath(YuzuPath yuzu_path) {
  170. return PathManagerImpl::GetInstance().GetYuzuPathImpl(yuzu_path);
  171. }
  172. std::string GetYuzuPathString(YuzuPath yuzu_path) {
  173. return PathToUTF8String(GetYuzuPath(yuzu_path));
  174. }
  175. void SetYuzuPath(YuzuPath yuzu_path, const fs::path& new_path) {
  176. if (!FS::IsDir(new_path)) {
  177. LOG_ERROR(Common_Filesystem, "Filesystem object at new_path={} is not a directory",
  178. PathToUTF8String(new_path));
  179. return;
  180. }
  181. PathManagerImpl::GetInstance().SetYuzuPathImpl(yuzu_path, new_path);
  182. }
  183. #ifdef _WIN32
  184. fs::path GetExeDirectory() {
  185. wchar_t exe_path[MAX_PATH];
  186. GetModuleFileNameW(nullptr, exe_path, MAX_PATH);
  187. if (!exe_path) {
  188. LOG_ERROR(Common_Filesystem,
  189. "Failed to get the path to the executable of the current process");
  190. }
  191. return fs::path{exe_path}.parent_path();
  192. }
  193. fs::path GetAppDataRoamingDirectory() {
  194. PWSTR appdata_roaming_path = nullptr;
  195. SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &appdata_roaming_path);
  196. auto fs_appdata_roaming_path = fs::path{appdata_roaming_path};
  197. CoTaskMemFree(appdata_roaming_path);
  198. if (fs_appdata_roaming_path.empty()) {
  199. LOG_ERROR(Common_Filesystem, "Failed to get the path to the %APPDATA% directory");
  200. }
  201. return fs_appdata_roaming_path;
  202. }
  203. #else
  204. fs::path GetHomeDirectory() {
  205. const char* home_env_var = getenv("HOME");
  206. if (home_env_var) {
  207. return fs::path{home_env_var};
  208. }
  209. LOG_INFO(Common_Filesystem,
  210. "$HOME is not defined in the environment variables, "
  211. "attempting to query passwd to get the home path of the current user");
  212. const auto* pw = getpwuid(getuid());
  213. if (!pw) {
  214. LOG_ERROR(Common_Filesystem, "Failed to get the home path of the current user");
  215. return {};
  216. }
  217. return fs::path{pw->pw_dir};
  218. }
  219. fs::path GetDataDirectory(const std::string& env_name) {
  220. const char* data_env_var = getenv(env_name.c_str());
  221. if (data_env_var) {
  222. return fs::path{data_env_var};
  223. }
  224. if (env_name == "XDG_DATA_HOME") {
  225. return GetHomeDirectory() / ".local/share";
  226. } else if (env_name == "XDG_CACHE_HOME") {
  227. return GetHomeDirectory() / ".cache";
  228. } else if (env_name == "XDG_CONFIG_HOME") {
  229. return GetHomeDirectory() / ".config";
  230. }
  231. return {};
  232. }
  233. #endif
  234. #ifdef __APPLE__
  235. fs::path GetBundleDirectory() {
  236. char app_bundle_path[MAXPATHLEN];
  237. // Get the main bundle for the app
  238. CFURLRef bundle_ref = CFBundleCopyBundleURL(CFBundleGetMainBundle());
  239. CFStringRef bundle_path = CFURLCopyFileSystemPath(bundle_ref, kCFURLPOSIXPathStyle);
  240. CFStringGetFileSystemRepresentation(bundle_path, app_bundle_path, sizeof(app_bundle_path));
  241. CFRelease(bundle_ref);
  242. CFRelease(bundle_path);
  243. return fs::path{app_bundle_path};
  244. }
  245. #endif
  246. // vvvvvvvvvv Deprecated vvvvvvvvvv //
  247. std::string_view RemoveTrailingSlash(std::string_view path) {
  248. if (path.empty()) {
  249. return path;
  250. }
  251. if (path.back() == '\\' || path.back() == '/') {
  252. path.remove_suffix(1);
  253. return path;
  254. }
  255. return path;
  256. }
  257. std::vector<std::string> SplitPathComponents(std::string_view filename) {
  258. std::string copy(filename);
  259. std::replace(copy.begin(), copy.end(), '\\', '/');
  260. std::vector<std::string> out;
  261. std::stringstream stream(copy);
  262. std::string item;
  263. while (std::getline(stream, item, '/')) {
  264. out.push_back(std::move(item));
  265. }
  266. return out;
  267. }
  268. std::string SanitizePath(std::string_view path_, DirectorySeparator directory_separator) {
  269. std::string path(path_);
  270. char type1 = directory_separator == DirectorySeparator::BackwardSlash ? '/' : '\\';
  271. char type2 = directory_separator == DirectorySeparator::BackwardSlash ? '\\' : '/';
  272. if (directory_separator == DirectorySeparator::PlatformDefault) {
  273. #ifdef _WIN32
  274. type1 = '/';
  275. type2 = '\\';
  276. #endif
  277. }
  278. std::replace(path.begin(), path.end(), type1, type2);
  279. auto start = path.begin();
  280. #ifdef _WIN32
  281. // allow network paths which start with a double backslash (e.g. \\server\share)
  282. if (start != path.end())
  283. ++start;
  284. #endif
  285. path.erase(std::unique(start, path.end(),
  286. [type2](char c1, char c2) { return c1 == type2 && c2 == type2; }),
  287. path.end());
  288. return std::string(RemoveTrailingSlash(path));
  289. }
  290. std::string_view GetParentPath(std::string_view path) {
  291. const auto name_bck_index = path.rfind('\\');
  292. const auto name_fwd_index = path.rfind('/');
  293. std::size_t name_index;
  294. if (name_bck_index == std::string_view::npos || name_fwd_index == std::string_view::npos) {
  295. name_index = std::min(name_bck_index, name_fwd_index);
  296. } else {
  297. name_index = std::max(name_bck_index, name_fwd_index);
  298. }
  299. return path.substr(0, name_index);
  300. }
  301. std::string_view GetPathWithoutTop(std::string_view path) {
  302. if (path.empty()) {
  303. return path;
  304. }
  305. while (path[0] == '\\' || path[0] == '/') {
  306. path.remove_prefix(1);
  307. if (path.empty()) {
  308. return path;
  309. }
  310. }
  311. const auto name_bck_index = path.find('\\');
  312. const auto name_fwd_index = path.find('/');
  313. return path.substr(std::min(name_bck_index, name_fwd_index) + 1);
  314. }
  315. std::string_view GetFilename(std::string_view path) {
  316. const auto name_index = path.find_last_of("\\/");
  317. if (name_index == std::string_view::npos) {
  318. return {};
  319. }
  320. return path.substr(name_index + 1);
  321. }
  322. std::string_view GetExtensionFromFilename(std::string_view name) {
  323. const std::size_t index = name.rfind('.');
  324. if (index == std::string_view::npos) {
  325. return {};
  326. }
  327. return name.substr(index + 1);
  328. }
  329. } // namespace Common::FS