Filesystem.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. /**
  2. * Copyright (c) 2006-2017 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include <iostream>
  21. #include <sstream>
  22. #include <algorithm>
  23. #include "common/utf8.h"
  24. #include "common/b64.h"
  25. #include "Filesystem.h"
  26. #include "File.h"
  27. // PhysFS
  28. #include "libraries/physfs/physfs.h"
  29. // For great CWD. (Current Working Directory)
  30. // Using this instead of boost::filesystem which totally
  31. // cramped our style.
  32. #ifdef LOVE_WINDOWS
  33. # include <windows.h>
  34. # include <direct.h>
  35. #else
  36. # include <sys/param.h>
  37. # include <unistd.h>
  38. #endif
  39. #ifdef LOVE_IOS
  40. # include "common/ios.h"
  41. #endif
  42. #include <string>
  43. #ifdef LOVE_ANDROID
  44. #include <SDL.h>
  45. #include "common/android.h"
  46. #endif
  47. namespace
  48. {
  49. size_t getDriveDelim(const std::string &input)
  50. {
  51. for (size_t i = 0; i < input.size(); ++i)
  52. if (input[i] == '/' || input[i] == '\\')
  53. return i;
  54. // Something's horribly wrong
  55. return 0;
  56. }
  57. std::string getDriveRoot(const std::string &input)
  58. {
  59. return input.substr(0, getDriveDelim(input)+1);
  60. }
  61. std::string skipDriveRoot(const std::string &input)
  62. {
  63. return input.substr(getDriveDelim(input)+1);
  64. }
  65. std::string normalize(const std::string &input)
  66. {
  67. std::stringstream out;
  68. bool seenSep = false, isSep = false;
  69. for (size_t i = 0; i < input.size(); ++i)
  70. {
  71. isSep = (input[i] == LOVE_PATH_SEPARATOR[0]);
  72. if (!isSep || !seenSep)
  73. out << input[i];
  74. seenSep = isSep;
  75. }
  76. return out.str();
  77. }
  78. }
  79. namespace love
  80. {
  81. namespace filesystem
  82. {
  83. namespace physfs
  84. {
  85. Filesystem::Filesystem()
  86. : fused(false)
  87. , fusedSet(false)
  88. {
  89. requirePath = {"?.lua", "?/init.lua"};
  90. cRequirePath = {"??"};
  91. }
  92. Filesystem::~Filesystem()
  93. {
  94. if (PHYSFS_isInit())
  95. PHYSFS_deinit();
  96. }
  97. const char *Filesystem::getName() const
  98. {
  99. return "love.filesystem.physfs";
  100. }
  101. void Filesystem::init(const char *arg0)
  102. {
  103. if (!PHYSFS_init(arg0))
  104. throw love::Exception("%s", PHYSFS_getErrorByCode(PHYSFS_getLastErrorCode()));
  105. // Enable symlinks by default.
  106. setSymlinksEnabled(true);
  107. }
  108. void Filesystem::setFused(bool fused)
  109. {
  110. if (fusedSet)
  111. return;
  112. this->fused = fused;
  113. fusedSet = true;
  114. }
  115. bool Filesystem::isFused() const
  116. {
  117. if (!fusedSet)
  118. return false;
  119. return fused;
  120. }
  121. bool Filesystem::setIdentity(const char *ident, bool appendToPath)
  122. {
  123. if (!PHYSFS_isInit())
  124. return false;
  125. std::string old_save_path = save_path_full;
  126. // Store the save directory.
  127. save_identity = std::string(ident);
  128. // Generate the relative path to the game save folder.
  129. save_path_relative = std::string(LOVE_APPDATA_PREFIX LOVE_APPDATA_FOLDER LOVE_PATH_SEPARATOR) + save_identity;
  130. // Generate the full path to the game save folder.
  131. save_path_full = std::string(getAppdataDirectory()) + std::string(LOVE_PATH_SEPARATOR);
  132. if (fused)
  133. save_path_full += std::string(LOVE_APPDATA_PREFIX) + save_identity;
  134. else
  135. save_path_full += save_path_relative;
  136. save_path_full = normalize(save_path_full);
  137. #ifdef LOVE_ANDROID
  138. if (save_identity == "")
  139. save_identity = "unnamed";
  140. std::string storage_path;
  141. if (isAndroidSaveExternal())
  142. storage_path = SDL_AndroidGetExternalStoragePath();
  143. else
  144. storage_path = SDL_AndroidGetInternalStoragePath();
  145. std::string save_directory = storage_path + "/save";
  146. save_path_full = storage_path + std::string("/save/") + save_identity;
  147. if (!love::android::directoryExists(save_path_full.c_str()) &&
  148. !love::android::mkdir(save_path_full.c_str()))
  149. SDL_Log("Error: Could not create save directory %s!", save_path_full.c_str());
  150. #endif
  151. // We now have something like:
  152. // save_identity: game
  153. // save_path_relative: ./LOVE/game
  154. // save_path_full: C:\Documents and Settings\user\Application Data/LOVE/game
  155. // We don't want old read-only save paths to accumulate when we set a new
  156. // identity.
  157. if (!old_save_path.empty())
  158. PHYSFS_unmount(old_save_path.c_str());
  159. // Try to add the save directory to the search path.
  160. // (No error on fail, it means that the path doesn't exist).
  161. PHYSFS_mount(save_path_full.c_str(), nullptr, appendToPath);
  162. // HACK: This forces setupWriteDirectory to be called the next time a file
  163. // is opened for writing - otherwise it won't be called at all if it was
  164. // already called at least once before.
  165. PHYSFS_setWriteDir(nullptr);
  166. return true;
  167. }
  168. const char *Filesystem::getIdentity() const
  169. {
  170. return save_identity.c_str();
  171. }
  172. bool Filesystem::setSource(const char *source)
  173. {
  174. if (!PHYSFS_isInit())
  175. return false;
  176. // Check whether directory is already set.
  177. if (!game_source.empty())
  178. return false;
  179. std::string new_search_path = source;
  180. #ifdef LOVE_ANDROID
  181. if (!love::android::createStorageDirectories())
  182. SDL_Log("Error creating storage directories!");
  183. char* game_archive_ptr = NULL;
  184. size_t game_archive_size = 0;
  185. bool archive_loaded = false;
  186. // try to load the game that was sent to LÖVE via a Intent
  187. archive_loaded = love::android::loadGameArchiveToMemory(love::android::getSelectedGameFile(), &game_archive_ptr, &game_archive_size);
  188. if (!archive_loaded)
  189. {
  190. // try to load the game in the assets/ folder
  191. archive_loaded = love::android::loadGameArchiveToMemory("game.love", &game_archive_ptr, &game_archive_size);
  192. }
  193. if (archive_loaded)
  194. {
  195. if (!PHYSFS_mountMemory(game_archive_ptr, game_archive_size, love::android::freeGameArchiveMemory, "archive.zip", "/", 0))
  196. {
  197. SDL_Log("Mounting of in-memory game archive failed!");
  198. love::android::freeGameArchiveMemory(game_archive_ptr);
  199. return false;
  200. }
  201. }
  202. else
  203. {
  204. // try to load the game in the directory that was sent to LÖVE via an
  205. // Intent ...
  206. std::string game_path = std::string(love::android::getSelectedGameFile());
  207. if (game_path == "")
  208. {
  209. // ... or fall back to the game at /sdcard/lovegame
  210. game_path = "/sdcard/lovegame/";
  211. }
  212. SDL_RWops *sdcard_main = SDL_RWFromFile(std::string(game_path + "main.lua").c_str(), "rb");
  213. if (sdcard_main)
  214. {
  215. new_search_path = game_path;
  216. sdcard_main->close(sdcard_main);
  217. if (!PHYSFS_mount(new_search_path.c_str(), nullptr, 1))
  218. {
  219. SDL_Log("mounting of %s failed", new_search_path.c_str());
  220. return false;
  221. }
  222. }
  223. else
  224. {
  225. // Neither assets/game.love or /sdcard/lovegame was mounted
  226. // sucessfully, therefore simply fail.
  227. return false;
  228. }
  229. }
  230. #else
  231. // Add the directory.
  232. if (!PHYSFS_mount(new_search_path.c_str(), nullptr, 1))
  233. return false;
  234. #endif
  235. // Save the game source.
  236. game_source = new_search_path;
  237. return true;
  238. }
  239. const char *Filesystem::getSource() const
  240. {
  241. return game_source.c_str();
  242. }
  243. bool Filesystem::setupWriteDirectory()
  244. {
  245. if (!PHYSFS_isInit())
  246. return false;
  247. // These must all be set.
  248. if (save_identity.empty() || save_path_full.empty() || save_path_relative.empty())
  249. return false;
  250. // We need to make sure the write directory is created. To do that, we also
  251. // need to make sure all its parent directories are also created.
  252. std::string temp_writedir = getDriveRoot(save_path_full);
  253. std::string temp_createdir = skipDriveRoot(save_path_full);
  254. // On some sandboxed platforms, physfs will break when its write directory
  255. // is the root of the drive and it tries to create a folder (even if the
  256. // folder's path is in a writable location.) If the user's home folder is
  257. // in the save path, we'll try starting from there instead.
  258. if (save_path_full.find(getUserDirectory()) == 0)
  259. {
  260. temp_writedir = getUserDirectory();
  261. temp_createdir = save_path_full.substr(getUserDirectory().length());
  262. // Strip leading '/' characters from the path we want to create.
  263. size_t startpos = temp_createdir.find_first_not_of('/');
  264. if (startpos != std::string::npos)
  265. temp_createdir = temp_createdir.substr(startpos);
  266. }
  267. // Set either '/' or the user's home as a writable directory.
  268. // (We must create the save folder before mounting it).
  269. if (!PHYSFS_setWriteDir(temp_writedir.c_str()))
  270. return false;
  271. // Create the save folder. (We're now "at" either '/' or the user's home).
  272. if (!createDirectory(temp_createdir.c_str()))
  273. {
  274. // Clear the write directory in case of error.
  275. PHYSFS_setWriteDir(nullptr);
  276. return false;
  277. }
  278. // Set the final write directory.
  279. if (!PHYSFS_setWriteDir(save_path_full.c_str()))
  280. return false;
  281. // Add the directory. (Will not be readded if already present).
  282. if (!PHYSFS_mount(save_path_full.c_str(), nullptr, 0))
  283. {
  284. PHYSFS_setWriteDir(nullptr); // Clear the write directory in case of error.
  285. return false;
  286. }
  287. return true;
  288. }
  289. bool Filesystem::mount(const char *archive, const char *mountpoint, bool appendToPath)
  290. {
  291. if (!PHYSFS_isInit() || !archive)
  292. return false;
  293. std::string realPath;
  294. std::string sourceBase = getSourceBaseDirectory();
  295. // Check whether the given archive path is in the list of allowed full paths.
  296. auto it = std::find(allowedMountPaths.begin(), allowedMountPaths.end(), archive);
  297. if (it != allowedMountPaths.end())
  298. realPath = *it;
  299. else if (isFused() && sourceBase.compare(archive) == 0)
  300. {
  301. // Special case: if the game is fused and the archive is the source's
  302. // base directory, mount it even though it's outside of the save dir.
  303. realPath = sourceBase;
  304. }
  305. else
  306. {
  307. // Not allowed for safety reasons.
  308. if (strlen(archive) == 0 || strstr(archive, "..") || strcmp(archive, "/") == 0)
  309. return false;
  310. const char *realDir = PHYSFS_getRealDir(archive);
  311. if (!realDir)
  312. return false;
  313. realPath = realDir;
  314. // Always disallow mounting of files inside the game source, since it
  315. // won't work anyway if the game source is a zipped .love file.
  316. if (realPath.find(game_source) == 0)
  317. return false;
  318. realPath += LOVE_PATH_SEPARATOR;
  319. realPath += archive;
  320. }
  321. if (realPath.length() == 0)
  322. return false;
  323. return PHYSFS_mount(realPath.c_str(), mountpoint, appendToPath) != 0;
  324. }
  325. bool Filesystem::unmount(const char *archive)
  326. {
  327. if (!PHYSFS_isInit() || !archive)
  328. return false;
  329. std::string realPath;
  330. std::string sourceBase = getSourceBaseDirectory();
  331. // Check whether the given archive path is in the list of allowed full paths.
  332. auto it = std::find(allowedMountPaths.begin(), allowedMountPaths.end(), archive);
  333. if (it != allowedMountPaths.end())
  334. realPath = *it;
  335. else if (isFused() && sourceBase.compare(archive) == 0)
  336. {
  337. // Special case: if the game is fused and the archive is the source's
  338. // base directory, unmount it even though it's outside of the save dir.
  339. realPath = sourceBase;
  340. }
  341. else
  342. {
  343. // Not allowed for safety reasons.
  344. if (strlen(archive) == 0 || strstr(archive, "..") || strcmp(archive, "/") == 0)
  345. return false;
  346. const char *realDir = PHYSFS_getRealDir(archive);
  347. if (!realDir)
  348. return false;
  349. realPath = realDir;
  350. realPath += LOVE_PATH_SEPARATOR;
  351. realPath += archive;
  352. }
  353. const char *mountPoint = PHYSFS_getMountPoint(realPath.c_str());
  354. if (!mountPoint)
  355. return false;
  356. return PHYSFS_unmount(realPath.c_str()) != 0;
  357. }
  358. love::filesystem::File *Filesystem::newFile(const char *filename) const
  359. {
  360. return new File(filename);
  361. }
  362. const char *Filesystem::getWorkingDirectory()
  363. {
  364. if (cwd.empty())
  365. {
  366. #ifdef LOVE_WINDOWS
  367. WCHAR w_cwd[LOVE_MAX_PATH];
  368. _wgetcwd(w_cwd, LOVE_MAX_PATH);
  369. cwd = to_utf8(w_cwd);
  370. replace_char(cwd, '\\', '/');
  371. #else
  372. char *cwd_char = new char[LOVE_MAX_PATH];
  373. if (getcwd(cwd_char, LOVE_MAX_PATH))
  374. cwd = cwd_char; // if getcwd fails, cwd_char (and thus cwd) will still be empty
  375. delete [] cwd_char;
  376. #endif
  377. }
  378. return cwd.c_str();
  379. }
  380. std::string Filesystem::getUserDirectory()
  381. {
  382. #ifdef LOVE_IOS
  383. // PHYSFS_getUserDir doesn't give exactly the path we want on iOS.
  384. static std::string userDir = normalize(love::ios::getHomeDirectory());
  385. #else
  386. static std::string userDir = normalize(PHYSFS_getUserDir());
  387. #endif
  388. return userDir;
  389. }
  390. std::string Filesystem::getAppdataDirectory()
  391. {
  392. if (appdata.empty())
  393. {
  394. #ifdef LOVE_WINDOWS_UWP
  395. appdata = getUserDirectory();
  396. #elif defined(LOVE_WINDOWS)
  397. wchar_t *w_appdata = _wgetenv(L"APPDATA");
  398. appdata = to_utf8(w_appdata);
  399. replace_char(appdata, '\\', '/');
  400. #elif defined(LOVE_MACOSX)
  401. std::string udir = getUserDirectory();
  402. udir.append("/Library/Application Support");
  403. appdata = normalize(udir);
  404. #elif defined(LOVE_IOS)
  405. appdata = normalize(love::ios::getAppdataDirectory());
  406. #elif defined(LOVE_LINUX)
  407. char *xdgdatahome = getenv("XDG_DATA_HOME");
  408. if (!xdgdatahome)
  409. appdata = normalize(std::string(getUserDirectory()) + "/.local/share/");
  410. else
  411. appdata = xdgdatahome;
  412. #else
  413. appdata = getUserDirectory();
  414. #endif
  415. }
  416. return appdata;
  417. }
  418. const char *Filesystem::getSaveDirectory()
  419. {
  420. return save_path_full.c_str();
  421. }
  422. std::string Filesystem::getSourceBaseDirectory() const
  423. {
  424. size_t source_len = game_source.length();
  425. if (source_len == 0)
  426. return "";
  427. // FIXME: This doesn't take into account parent and current directory
  428. // symbols (i.e. '..' and '.')
  429. #ifdef LOVE_WINDOWS
  430. // In windows, delimiters can be either '/' or '\'.
  431. size_t base_end_pos = game_source.find_last_of("/\\", source_len - 2);
  432. #else
  433. size_t base_end_pos = game_source.find_last_of('/', source_len - 2);
  434. #endif
  435. if (base_end_pos == std::string::npos)
  436. return "";
  437. // If the source is in the unix root (aka '/'), we want to keep the '/'.
  438. if (base_end_pos == 0)
  439. base_end_pos = 1;
  440. return game_source.substr(0, base_end_pos);
  441. }
  442. std::string Filesystem::getRealDirectory(const char *filename) const
  443. {
  444. if (!PHYSFS_isInit())
  445. throw love::Exception("PhysFS is not initialized.");
  446. const char *dir = PHYSFS_getRealDir(filename);
  447. if (dir == nullptr)
  448. throw love::Exception("File does not exist on disk.");
  449. return std::string(dir);
  450. }
  451. bool Filesystem::getInfo(const char *filepath, Info &info) const
  452. {
  453. if (!PHYSFS_isInit())
  454. return false;
  455. PHYSFS_Stat stat = {};
  456. if (!PHYSFS_stat(filepath, &stat))
  457. return false;
  458. info.size = (int64) stat.filesize;
  459. info.modtime = (int64) stat.modtime;
  460. if (stat.filetype == PHYSFS_FILETYPE_REGULAR)
  461. info.type = FILETYPE_FILE;
  462. else if (stat.filetype == PHYSFS_FILETYPE_DIRECTORY)
  463. info.type = FILETYPE_DIRECTORY;
  464. else if (stat.filetype == PHYSFS_FILETYPE_SYMLINK)
  465. info.type = FILETYPE_SYMLINK;
  466. else
  467. info.type = FILETYPE_OTHER;
  468. return true;
  469. }
  470. bool Filesystem::createDirectory(const char *dir)
  471. {
  472. if (!PHYSFS_isInit())
  473. return false;
  474. if (PHYSFS_getWriteDir() == 0 && !setupWriteDirectory())
  475. return false;
  476. if (!PHYSFS_mkdir(dir))
  477. return false;
  478. return true;
  479. }
  480. bool Filesystem::remove(const char *file)
  481. {
  482. if (!PHYSFS_isInit())
  483. return false;
  484. if (PHYSFS_getWriteDir() == 0 && !setupWriteDirectory())
  485. return false;
  486. if (!PHYSFS_delete(file))
  487. return false;
  488. return true;
  489. }
  490. FileData *Filesystem::read(const char *filename, int64 size) const
  491. {
  492. File file(filename);
  493. file.open(File::MODE_READ);
  494. // close() is called in the File destructor.
  495. return file.read(size);
  496. }
  497. void Filesystem::write(const char *filename, const void *data, int64 size) const
  498. {
  499. File file(filename);
  500. file.open(File::MODE_WRITE);
  501. // close() is called in the File destructor.
  502. if (!file.write(data, size))
  503. throw love::Exception("Data could not be written.");
  504. }
  505. void Filesystem::append(const char *filename, const void *data, int64 size) const
  506. {
  507. File file(filename);
  508. file.open(File::MODE_APPEND);
  509. // close() is called in the File destructor.
  510. if (!file.write(data, size))
  511. throw love::Exception("Data could not be written.");
  512. }
  513. void Filesystem::getDirectoryItems(const char *dir, std::vector<std::string> &items)
  514. {
  515. if (!PHYSFS_isInit())
  516. return;
  517. char **rc = PHYSFS_enumerateFiles(dir);
  518. if (rc == nullptr)
  519. return;
  520. for (char **i = rc; *i != 0; i++)
  521. items.push_back(*i);
  522. PHYSFS_freeList(rc);
  523. }
  524. void Filesystem::setSymlinksEnabled(bool enable)
  525. {
  526. if (!PHYSFS_isInit())
  527. return;
  528. PHYSFS_permitSymbolicLinks(enable ? 1 : 0);
  529. }
  530. bool Filesystem::areSymlinksEnabled() const
  531. {
  532. if (!PHYSFS_isInit())
  533. return false;
  534. return PHYSFS_symbolicLinksPermitted() != 0;
  535. }
  536. std::vector<std::string> &Filesystem::getRequirePath()
  537. {
  538. return requirePath;
  539. }
  540. std::vector<std::string> &Filesystem::getCRequirePath()
  541. {
  542. return cRequirePath;
  543. }
  544. void Filesystem::allowMountingForPath(const std::string &path)
  545. {
  546. if (std::find(allowedMountPaths.begin(), allowedMountPaths.end(), path) == allowedMountPaths.end())
  547. allowedMountPaths.push_back(path);
  548. }
  549. } // physfs
  550. } // filesystem
  551. } // love