Filesystem.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. namespace
  47. {
  48. size_t getDriveDelim(const std::string &input)
  49. {
  50. for (size_t i = 0; i < input.size(); ++i)
  51. if (input[i] == '/' || input[i] == '\\')
  52. return i;
  53. // Something's horribly wrong
  54. return 0;
  55. }
  56. std::string getDriveRoot(const std::string &input)
  57. {
  58. return input.substr(0, getDriveDelim(input)+1);
  59. }
  60. std::string skipDriveRoot(const std::string &input)
  61. {
  62. return input.substr(getDriveDelim(input)+1);
  63. }
  64. std::string normalize(const std::string &input)
  65. {
  66. std::stringstream out;
  67. bool seenSep = false, isSep = false;
  68. for (size_t i = 0; i < input.size(); ++i)
  69. {
  70. isSep = (input[i] == LOVE_PATH_SEPARATOR[0]);
  71. if (!isSep || !seenSep)
  72. out << input[i];
  73. seenSep = isSep;
  74. }
  75. return out.str();
  76. }
  77. }
  78. namespace love
  79. {
  80. namespace filesystem
  81. {
  82. namespace physfs
  83. {
  84. Filesystem::Filesystem()
  85. : fused(false)
  86. , fusedSet(false)
  87. {
  88. requirePath = {"?.lua", "?/init.lua"};
  89. }
  90. Filesystem::~Filesystem()
  91. {
  92. if (PHYSFS_isInit())
  93. PHYSFS_deinit();
  94. }
  95. const char *Filesystem::getName() const
  96. {
  97. return "love.filesystem.physfs";
  98. }
  99. void Filesystem::init(const char *arg0)
  100. {
  101. if (!PHYSFS_init(arg0))
  102. throw love::Exception("%s", PHYSFS_getLastError());
  103. PHYSFS_Version version = {};
  104. PHYSFS_getLinkedVersion(&version);
  105. // FIXME: This is a workaround for a bug in PHYSFS_enumerateFiles in 2.1-alpha.
  106. if (version.major == 2 && version.minor == 1)
  107. PHYSFS_permitSymbolicLinks(1);
  108. }
  109. void Filesystem::setFused(bool fused)
  110. {
  111. if (fusedSet)
  112. return;
  113. this->fused = fused;
  114. fusedSet = true;
  115. }
  116. bool Filesystem::isFused() const
  117. {
  118. if (!fusedSet)
  119. return false;
  120. return fused;
  121. }
  122. bool Filesystem::setIdentity(const char *ident, bool appendToPath)
  123. {
  124. if (!PHYSFS_isInit())
  125. return false;
  126. std::string old_save_path = save_path_full;
  127. // Store the save directory.
  128. save_identity = std::string(ident);
  129. // Generate the relative path to the game save folder.
  130. save_path_relative = std::string(LOVE_APPDATA_PREFIX LOVE_APPDATA_FOLDER LOVE_PATH_SEPARATOR) + save_identity;
  131. // Generate the full path to the game save folder.
  132. save_path_full = std::string(getAppdataDirectory()) + std::string(LOVE_PATH_SEPARATOR);
  133. if (fused)
  134. save_path_full += std::string(LOVE_APPDATA_PREFIX) + save_identity;
  135. else
  136. save_path_full += save_path_relative;
  137. save_path_full = normalize(save_path_full);
  138. // We now have something like:
  139. // save_identity: game
  140. // save_path_relative: ./LOVE/game
  141. // save_path_full: C:\Documents and Settings\user\Application Data/LOVE/game
  142. // We don't want old read-only save paths to accumulate when we set a new
  143. // identity.
  144. if (!old_save_path.empty())
  145. PHYSFS_removeFromSearchPath(old_save_path.c_str());
  146. // Try to add the save directory to the search path.
  147. // (No error on fail, it means that the path doesn't exist).
  148. PHYSFS_mount(save_path_full.c_str(), nullptr, appendToPath);
  149. // HACK: This forces setupWriteDirectory to be called the next time a file
  150. // is opened for writing - otherwise it won't be called at all if it was
  151. // already called at least once before.
  152. PHYSFS_setWriteDir(nullptr);
  153. return true;
  154. }
  155. const char *Filesystem::getIdentity() const
  156. {
  157. return save_identity.c_str();
  158. }
  159. bool Filesystem::setSource(const char *source)
  160. {
  161. if (!PHYSFS_isInit())
  162. return false;
  163. // Check whether directory is already set.
  164. if (!game_source.empty())
  165. return false;
  166. // Add the directory.
  167. if (!PHYSFS_mount(source, nullptr, 1))
  168. return false;
  169. // Save the game source.
  170. game_source = std::string(source);
  171. return true;
  172. }
  173. const char *Filesystem::getSource() const
  174. {
  175. return game_source.c_str();
  176. }
  177. bool Filesystem::setupWriteDirectory()
  178. {
  179. if (!PHYSFS_isInit())
  180. return false;
  181. // These must all be set.
  182. if (save_identity.empty() || save_path_full.empty() || save_path_relative.empty())
  183. return false;
  184. // We need to make sure the write directory is created. To do that, we also
  185. // need to make sure all its parent directories are also created.
  186. std::string temp_writedir = getDriveRoot(save_path_full);
  187. std::string temp_createdir = skipDriveRoot(save_path_full);
  188. // On some sandboxed platforms, physfs will break when its write directory
  189. // is the root of the drive and it tries to create a folder (even if the
  190. // folder's path is in a writable location.) If the user's home folder is
  191. // in the save path, we'll try starting from there instead.
  192. if (save_path_full.find(getUserDirectory()) == 0)
  193. {
  194. temp_writedir = getUserDirectory();
  195. temp_createdir = save_path_full.substr(getUserDirectory().length());
  196. // Strip leading '/' characters from the path we want to create.
  197. size_t startpos = temp_createdir.find_first_not_of('/');
  198. if (startpos != std::string::npos)
  199. temp_createdir = temp_createdir.substr(startpos);
  200. }
  201. // Set either '/' or the user's home as a writable directory.
  202. // (We must create the save folder before mounting it).
  203. if (!PHYSFS_setWriteDir(temp_writedir.c_str()))
  204. return false;
  205. // Create the save folder. (We're now "at" either '/' or the user's home).
  206. if (!createDirectory(temp_createdir.c_str()))
  207. {
  208. // Clear the write directory in case of error.
  209. PHYSFS_setWriteDir(nullptr);
  210. return false;
  211. }
  212. // Set the final write directory.
  213. if (!PHYSFS_setWriteDir(save_path_full.c_str()))
  214. return false;
  215. // Add the directory. (Will not be readded if already present).
  216. if (!PHYSFS_mount(save_path_full.c_str(), nullptr, 0))
  217. {
  218. PHYSFS_setWriteDir(nullptr); // Clear the write directory in case of error.
  219. return false;
  220. }
  221. return true;
  222. }
  223. bool Filesystem::mount(const char *archive, const char *mountpoint, bool appendToPath)
  224. {
  225. if (!PHYSFS_isInit() || !archive)
  226. return false;
  227. std::string realPath;
  228. std::string sourceBase = getSourceBaseDirectory();
  229. // Check whether the given archive path is in the list of allowed full paths.
  230. auto it = std::find(allowedMountPaths.begin(), allowedMountPaths.end(), archive);
  231. if (it != allowedMountPaths.end())
  232. realPath = *it;
  233. else if (isFused() && sourceBase.compare(archive) == 0)
  234. {
  235. // Special case: if the game is fused and the archive is the source's
  236. // base directory, mount it even though it's outside of the save dir.
  237. realPath = sourceBase;
  238. }
  239. else
  240. {
  241. // Not allowed for safety reasons.
  242. if (strlen(archive) == 0 || strstr(archive, "..") || strcmp(archive, "/") == 0)
  243. return false;
  244. const char *realDir = PHYSFS_getRealDir(archive);
  245. if (!realDir)
  246. return false;
  247. realPath = realDir;
  248. // Always disallow mounting of files inside the game source, since it
  249. // won't work anyway if the game source is a zipped .love file.
  250. if (realPath.find(game_source) == 0)
  251. return false;
  252. realPath += LOVE_PATH_SEPARATOR;
  253. realPath += archive;
  254. }
  255. if (realPath.length() == 0)
  256. return false;
  257. return PHYSFS_mount(realPath.c_str(), mountpoint, appendToPath) != 0;
  258. }
  259. bool Filesystem::unmount(const char *archive)
  260. {
  261. if (!PHYSFS_isInit() || !archive)
  262. return false;
  263. std::string realPath;
  264. std::string sourceBase = getSourceBaseDirectory();
  265. // Check whether the given archive path is in the list of allowed full paths.
  266. auto it = std::find(allowedMountPaths.begin(), allowedMountPaths.end(), archive);
  267. if (it != allowedMountPaths.end())
  268. realPath = *it;
  269. else if (isFused() && sourceBase.compare(archive) == 0)
  270. {
  271. // Special case: if the game is fused and the archive is the source's
  272. // base directory, unmount it even though it's outside of the save dir.
  273. realPath = sourceBase;
  274. }
  275. else
  276. {
  277. // Not allowed for safety reasons.
  278. if (strlen(archive) == 0 || strstr(archive, "..") || strcmp(archive, "/") == 0)
  279. return false;
  280. const char *realDir = PHYSFS_getRealDir(archive);
  281. if (!realDir)
  282. return false;
  283. realPath = realDir;
  284. realPath += LOVE_PATH_SEPARATOR;
  285. realPath += archive;
  286. }
  287. const char *mountPoint = PHYSFS_getMountPoint(realPath.c_str());
  288. if (!mountPoint)
  289. return false;
  290. return PHYSFS_removeFromSearchPath(realPath.c_str()) != 0;
  291. }
  292. love::filesystem::File *Filesystem::newFile(const char *filename) const
  293. {
  294. return new File(filename);
  295. }
  296. FileData *Filesystem::newFileData(void *data, unsigned int size, const char *filename) const
  297. {
  298. FileData *fd = new FileData(size, std::string(filename));
  299. // Copy the data into FileData.
  300. memcpy(fd->getData(), data, size);
  301. return fd;
  302. }
  303. FileData *Filesystem::newFileData(const char *b64, const char *filename) const
  304. {
  305. int size = (int) strlen(b64);
  306. int outsize = 0;
  307. char *dst = b64_decode(b64, size, outsize);
  308. FileData *fd = new FileData(outsize, std::string(filename));
  309. // Copy the data into FileData.
  310. memcpy(fd->getData(), dst, outsize);
  311. delete [] dst;
  312. return fd;
  313. }
  314. const char *Filesystem::getWorkingDirectory()
  315. {
  316. if (cwd.empty())
  317. {
  318. #ifdef LOVE_WINDOWS
  319. WCHAR w_cwd[LOVE_MAX_PATH];
  320. _wgetcwd(w_cwd, LOVE_MAX_PATH);
  321. cwd = to_utf8(w_cwd);
  322. replace_char(cwd, '\\', '/');
  323. #else
  324. char *cwd_char = new char[LOVE_MAX_PATH];
  325. if (getcwd(cwd_char, LOVE_MAX_PATH))
  326. cwd = cwd_char; // if getcwd fails, cwd_char (and thus cwd) will still be empty
  327. delete [] cwd_char;
  328. #endif
  329. }
  330. return cwd.c_str();
  331. }
  332. std::string Filesystem::getUserDirectory()
  333. {
  334. #ifdef LOVE_IOS
  335. // PHYSFS_getUserDir doesn't give exactly the path we want on iOS.
  336. static std::string userDir = normalize(love::ios::getHomeDirectory());
  337. #else
  338. static std::string userDir = normalize(PHYSFS_getUserDir());
  339. #endif
  340. return userDir;
  341. }
  342. std::string Filesystem::getAppdataDirectory()
  343. {
  344. if (appdata.empty())
  345. {
  346. #ifdef LOVE_WINDOWS
  347. wchar_t *w_appdata = _wgetenv(L"APPDATA");
  348. appdata = to_utf8(w_appdata);
  349. replace_char(appdata, '\\', '/');
  350. #elif defined(LOVE_MACOSX)
  351. std::string udir = getUserDirectory();
  352. udir.append("/Library/Application Support");
  353. appdata = normalize(udir);
  354. #elif defined(LOVE_IOS)
  355. appdata = normalize(love::ios::getAppdataDirectory());
  356. #elif defined(LOVE_LINUX)
  357. char *xdgdatahome = getenv("XDG_DATA_HOME");
  358. if (!xdgdatahome)
  359. appdata = normalize(std::string(getUserDirectory()) + "/.local/share/");
  360. else
  361. appdata = xdgdatahome;
  362. #else
  363. appdata = getUserDirectory();
  364. #endif
  365. }
  366. return appdata;
  367. }
  368. const char *Filesystem::getSaveDirectory()
  369. {
  370. return save_path_full.c_str();
  371. }
  372. std::string Filesystem::getSourceBaseDirectory() const
  373. {
  374. size_t source_len = game_source.length();
  375. if (source_len == 0)
  376. return "";
  377. // FIXME: This doesn't take into account parent and current directory
  378. // symbols (i.e. '..' and '.')
  379. #ifdef LOVE_WINDOWS
  380. // In windows, delimiters can be either '/' or '\'.
  381. size_t base_end_pos = game_source.find_last_of("/\\", source_len - 2);
  382. #else
  383. size_t base_end_pos = game_source.find_last_of('/', source_len - 2);
  384. #endif
  385. if (base_end_pos == std::string::npos)
  386. return "";
  387. // If the source is in the unix root (aka '/'), we want to keep the '/'.
  388. if (base_end_pos == 0)
  389. base_end_pos = 1;
  390. return game_source.substr(0, base_end_pos);
  391. }
  392. std::string Filesystem::getRealDirectory(const char *filename) const
  393. {
  394. const char *dir = PHYSFS_getRealDir(filename);
  395. if (dir == nullptr)
  396. throw love::Exception("File does not exist.");
  397. return std::string(dir);
  398. }
  399. bool Filesystem::isDirectory(const char *dir) const
  400. {
  401. return PHYSFS_isDirectory(dir) != 0;
  402. }
  403. bool Filesystem::isFile(const char *file) const
  404. {
  405. return PHYSFS_exists(file) && !PHYSFS_isDirectory(file);
  406. }
  407. bool Filesystem::createDirectory(const char *dir)
  408. {
  409. if (PHYSFS_getWriteDir() == 0 && !setupWriteDirectory())
  410. return false;
  411. if (!PHYSFS_mkdir(dir))
  412. return false;
  413. return true;
  414. }
  415. bool Filesystem::remove(const char *file)
  416. {
  417. if (PHYSFS_getWriteDir() == 0 && !setupWriteDirectory())
  418. return false;
  419. if (!PHYSFS_delete(file))
  420. return false;
  421. return true;
  422. }
  423. FileData *Filesystem::read(const char *filename, int64 size) const
  424. {
  425. File file(filename);
  426. file.open(File::MODE_READ);
  427. // close() is called in the File destructor.
  428. return file.read(size);
  429. }
  430. void Filesystem::write(const char *filename, const void *data, int64 size) const
  431. {
  432. File file(filename);
  433. file.open(File::MODE_WRITE);
  434. // close() is called in the File destructor.
  435. if (!file.write(data, size))
  436. throw love::Exception("Data could not be written.");
  437. }
  438. void Filesystem::append(const char *filename, const void *data, int64 size) const
  439. {
  440. File file(filename);
  441. file.open(File::MODE_APPEND);
  442. // close() is called in the File destructor.
  443. if (!file.write(data, size))
  444. throw love::Exception("Data could not be written.");
  445. }
  446. void Filesystem::getDirectoryItems(const char *dir, std::vector<std::string> &items)
  447. {
  448. char **rc = PHYSFS_enumerateFiles(dir);
  449. for (char **i = rc; *i != 0; i++)
  450. items.push_back(*i);
  451. PHYSFS_freeList(rc);
  452. }
  453. int64 Filesystem::getLastModified(const char *filename) const
  454. {
  455. PHYSFS_sint64 time = PHYSFS_getLastModTime(filename);
  456. if (time == -1)
  457. throw love::Exception("Could not determine file modification date.");
  458. return time;
  459. }
  460. int64 Filesystem::getSize(const char *filename) const
  461. {
  462. File file(filename);
  463. int64 size = file.getSize();
  464. return size;
  465. }
  466. void Filesystem::setSymlinksEnabled(bool enable)
  467. {
  468. PHYSFS_permitSymbolicLinks(enable ? 1 : 0);
  469. }
  470. bool Filesystem::areSymlinksEnabled() const
  471. {
  472. return PHYSFS_symbolicLinksPermitted() != 0;
  473. }
  474. bool Filesystem::isSymlink(const char *filename) const
  475. {
  476. return PHYSFS_isSymbolicLink(filename) != 0;
  477. }
  478. std::vector<std::string> &Filesystem::getRequirePath()
  479. {
  480. return requirePath;
  481. }
  482. void Filesystem::allowMountingForPath(const std::string &path)
  483. {
  484. if (std::find(allowedMountPaths.begin(), allowedMountPaths.end(), path) == allowedMountPaths.end())
  485. allowedMountPaths.push_back(path);
  486. }
  487. } // physfs
  488. } // filesystem
  489. } // love