Filesystem.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725
  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::mount(Data *data, const char *archivename, const char *mountpoint, bool appendToPath)
  326. {
  327. if (!PHYSFS_isInit())
  328. return false;
  329. if (PHYSFS_mountMemory(data->getData(), data->getSize(), nullptr, archivename, mountpoint, appendToPath) != 0)
  330. {
  331. mountedData[archivename] = data;
  332. return true;
  333. }
  334. return false;
  335. }
  336. bool Filesystem::unmount(const char *archive)
  337. {
  338. if (!PHYSFS_isInit() || !archive)
  339. return false;
  340. auto datait = mountedData.find(archive);
  341. if (datait != mountedData.end() && PHYSFS_unmount(archive) != 0)
  342. {
  343. mountedData.erase(datait);
  344. return true;
  345. }
  346. std::string realPath;
  347. std::string sourceBase = getSourceBaseDirectory();
  348. // Check whether the given archive path is in the list of allowed full paths.
  349. auto it = std::find(allowedMountPaths.begin(), allowedMountPaths.end(), archive);
  350. if (it != allowedMountPaths.end())
  351. realPath = *it;
  352. else if (isFused() && sourceBase.compare(archive) == 0)
  353. {
  354. // Special case: if the game is fused and the archive is the source's
  355. // base directory, unmount it even though it's outside of the save dir.
  356. realPath = sourceBase;
  357. }
  358. else
  359. {
  360. // Not allowed for safety reasons.
  361. if (strlen(archive) == 0 || strstr(archive, "..") || strcmp(archive, "/") == 0)
  362. return false;
  363. const char *realDir = PHYSFS_getRealDir(archive);
  364. if (!realDir)
  365. return false;
  366. realPath = realDir;
  367. realPath += LOVE_PATH_SEPARATOR;
  368. realPath += archive;
  369. }
  370. const char *mountPoint = PHYSFS_getMountPoint(realPath.c_str());
  371. if (!mountPoint)
  372. return false;
  373. return PHYSFS_unmount(realPath.c_str()) != 0;
  374. }
  375. bool Filesystem::unmount(Data *data)
  376. {
  377. for (const auto &datapair : mountedData)
  378. {
  379. if (datapair.second.get() == data)
  380. {
  381. std::string archive = datapair.first;
  382. return unmount(archive.c_str());
  383. }
  384. }
  385. return false;
  386. }
  387. love::filesystem::File *Filesystem::newFile(const char *filename) const
  388. {
  389. return new File(filename);
  390. }
  391. const char *Filesystem::getWorkingDirectory()
  392. {
  393. if (cwd.empty())
  394. {
  395. #ifdef LOVE_WINDOWS
  396. WCHAR w_cwd[LOVE_MAX_PATH];
  397. _wgetcwd(w_cwd, LOVE_MAX_PATH);
  398. cwd = to_utf8(w_cwd);
  399. replace_char(cwd, '\\', '/');
  400. #else
  401. char *cwd_char = new char[LOVE_MAX_PATH];
  402. if (getcwd(cwd_char, LOVE_MAX_PATH))
  403. cwd = cwd_char; // if getcwd fails, cwd_char (and thus cwd) will still be empty
  404. delete [] cwd_char;
  405. #endif
  406. }
  407. return cwd.c_str();
  408. }
  409. std::string Filesystem::getUserDirectory()
  410. {
  411. #ifdef LOVE_IOS
  412. // PHYSFS_getUserDir doesn't give exactly the path we want on iOS.
  413. static std::string userDir = normalize(love::ios::getHomeDirectory());
  414. #else
  415. static std::string userDir = normalize(PHYSFS_getUserDir());
  416. #endif
  417. return userDir;
  418. }
  419. std::string Filesystem::getAppdataDirectory()
  420. {
  421. if (appdata.empty())
  422. {
  423. #ifdef LOVE_WINDOWS_UWP
  424. appdata = getUserDirectory();
  425. #elif defined(LOVE_WINDOWS)
  426. wchar_t *w_appdata = _wgetenv(L"APPDATA");
  427. appdata = to_utf8(w_appdata);
  428. replace_char(appdata, '\\', '/');
  429. #elif defined(LOVE_MACOSX)
  430. std::string udir = getUserDirectory();
  431. udir.append("/Library/Application Support");
  432. appdata = normalize(udir);
  433. #elif defined(LOVE_IOS)
  434. appdata = normalize(love::ios::getAppdataDirectory());
  435. #elif defined(LOVE_LINUX)
  436. char *xdgdatahome = getenv("XDG_DATA_HOME");
  437. if (!xdgdatahome)
  438. appdata = normalize(std::string(getUserDirectory()) + "/.local/share/");
  439. else
  440. appdata = xdgdatahome;
  441. #else
  442. appdata = getUserDirectory();
  443. #endif
  444. }
  445. return appdata;
  446. }
  447. const char *Filesystem::getSaveDirectory()
  448. {
  449. return save_path_full.c_str();
  450. }
  451. std::string Filesystem::getSourceBaseDirectory() const
  452. {
  453. size_t source_len = game_source.length();
  454. if (source_len == 0)
  455. return "";
  456. // FIXME: This doesn't take into account parent and current directory
  457. // symbols (i.e. '..' and '.')
  458. #ifdef LOVE_WINDOWS
  459. // In windows, delimiters can be either '/' or '\'.
  460. size_t base_end_pos = game_source.find_last_of("/\\", source_len - 2);
  461. #else
  462. size_t base_end_pos = game_source.find_last_of('/', source_len - 2);
  463. #endif
  464. if (base_end_pos == std::string::npos)
  465. return "";
  466. // If the source is in the unix root (aka '/'), we want to keep the '/'.
  467. if (base_end_pos == 0)
  468. base_end_pos = 1;
  469. return game_source.substr(0, base_end_pos);
  470. }
  471. std::string Filesystem::getRealDirectory(const char *filename) const
  472. {
  473. if (!PHYSFS_isInit())
  474. throw love::Exception("PhysFS is not initialized.");
  475. const char *dir = PHYSFS_getRealDir(filename);
  476. if (dir == nullptr)
  477. throw love::Exception("File does not exist on disk.");
  478. return std::string(dir);
  479. }
  480. bool Filesystem::getInfo(const char *filepath, Info &info) const
  481. {
  482. if (!PHYSFS_isInit())
  483. return false;
  484. PHYSFS_Stat stat = {};
  485. if (!PHYSFS_stat(filepath, &stat))
  486. return false;
  487. info.size = (int64) stat.filesize;
  488. info.modtime = (int64) stat.modtime;
  489. if (stat.filetype == PHYSFS_FILETYPE_REGULAR)
  490. info.type = FILETYPE_FILE;
  491. else if (stat.filetype == PHYSFS_FILETYPE_DIRECTORY)
  492. info.type = FILETYPE_DIRECTORY;
  493. else if (stat.filetype == PHYSFS_FILETYPE_SYMLINK)
  494. info.type = FILETYPE_SYMLINK;
  495. else
  496. info.type = FILETYPE_OTHER;
  497. return true;
  498. }
  499. bool Filesystem::createDirectory(const char *dir)
  500. {
  501. if (!PHYSFS_isInit())
  502. return false;
  503. if (PHYSFS_getWriteDir() == 0 && !setupWriteDirectory())
  504. return false;
  505. if (!PHYSFS_mkdir(dir))
  506. return false;
  507. return true;
  508. }
  509. bool Filesystem::remove(const char *file)
  510. {
  511. if (!PHYSFS_isInit())
  512. return false;
  513. if (PHYSFS_getWriteDir() == 0 && !setupWriteDirectory())
  514. return false;
  515. if (!PHYSFS_delete(file))
  516. return false;
  517. return true;
  518. }
  519. FileData *Filesystem::read(const char *filename, int64 size) const
  520. {
  521. File file(filename);
  522. file.open(File::MODE_READ);
  523. // close() is called in the File destructor.
  524. return file.read(size);
  525. }
  526. void Filesystem::write(const char *filename, const void *data, int64 size) const
  527. {
  528. File file(filename);
  529. file.open(File::MODE_WRITE);
  530. // close() is called in the File destructor.
  531. if (!file.write(data, size))
  532. throw love::Exception("Data could not be written.");
  533. }
  534. void Filesystem::append(const char *filename, const void *data, int64 size) const
  535. {
  536. File file(filename);
  537. file.open(File::MODE_APPEND);
  538. // close() is called in the File destructor.
  539. if (!file.write(data, size))
  540. throw love::Exception("Data could not be written.");
  541. }
  542. void Filesystem::getDirectoryItems(const char *dir, std::vector<std::string> &items)
  543. {
  544. if (!PHYSFS_isInit())
  545. return;
  546. char **rc = PHYSFS_enumerateFiles(dir);
  547. if (rc == nullptr)
  548. return;
  549. for (char **i = rc; *i != 0; i++)
  550. items.push_back(*i);
  551. PHYSFS_freeList(rc);
  552. }
  553. void Filesystem::setSymlinksEnabled(bool enable)
  554. {
  555. if (!PHYSFS_isInit())
  556. return;
  557. PHYSFS_permitSymbolicLinks(enable ? 1 : 0);
  558. }
  559. bool Filesystem::areSymlinksEnabled() const
  560. {
  561. if (!PHYSFS_isInit())
  562. return false;
  563. return PHYSFS_symbolicLinksPermitted() != 0;
  564. }
  565. std::vector<std::string> &Filesystem::getRequirePath()
  566. {
  567. return requirePath;
  568. }
  569. std::vector<std::string> &Filesystem::getCRequirePath()
  570. {
  571. return cRequirePath;
  572. }
  573. void Filesystem::allowMountingForPath(const std::string &path)
  574. {
  575. if (std::find(allowedMountPaths.begin(), allowedMountPaths.end(), path) == allowedMountPaths.end())
  576. allowedMountPaths.push_back(path);
  577. }
  578. } // physfs
  579. } // filesystem
  580. } // love