Filesystem.cpp 18 KB

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