Filesystem.cpp 14 KB

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