filesys.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. /*
  2. Minetest
  3. Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "filesys.h"
  17. #include "util/string.h"
  18. #include <iostream>
  19. #include <cstdio>
  20. #include <cstdlib>
  21. #include <cstring>
  22. #include <cerrno>
  23. #include <fstream>
  24. #include "log.h"
  25. #include "config.h"
  26. #include "porting.h"
  27. #ifndef SERVER
  28. #include "irr_ptr.h"
  29. #endif
  30. namespace fs
  31. {
  32. #ifdef _WIN32
  33. /***********
  34. * Windows *
  35. ***********/
  36. #ifndef _WIN32_WINNT
  37. #define _WIN32_WINNT 0x0501
  38. #endif
  39. #include <windows.h>
  40. #include <shlwapi.h>
  41. #include <io.h>
  42. #include <direct.h>
  43. std::vector<DirListNode> GetDirListing(const std::string &pathstring)
  44. {
  45. std::vector<DirListNode> listing;
  46. WIN32_FIND_DATA FindFileData;
  47. HANDLE hFind = INVALID_HANDLE_VALUE;
  48. DWORD dwError;
  49. std::string dirSpec = pathstring + "\\*";
  50. // Find the first file in the directory.
  51. hFind = FindFirstFile(dirSpec.c_str(), &FindFileData);
  52. if (hFind == INVALID_HANDLE_VALUE) {
  53. dwError = GetLastError();
  54. if (dwError != ERROR_FILE_NOT_FOUND && dwError != ERROR_PATH_NOT_FOUND) {
  55. errorstream << "GetDirListing: FindFirstFile error."
  56. << " Error is " << dwError << std::endl;
  57. }
  58. } else {
  59. // NOTE:
  60. // Be very sure to not include '..' in the results, it will
  61. // result in an epic failure when deleting stuff.
  62. DirListNode node;
  63. node.name = FindFileData.cFileName;
  64. node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  65. if (node.name != "." && node.name != "..")
  66. listing.push_back(node);
  67. // List all the other files in the directory.
  68. while (FindNextFile(hFind, &FindFileData) != 0) {
  69. DirListNode node;
  70. node.name = FindFileData.cFileName;
  71. node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  72. if(node.name != "." && node.name != "..")
  73. listing.push_back(node);
  74. }
  75. dwError = GetLastError();
  76. FindClose(hFind);
  77. if (dwError != ERROR_NO_MORE_FILES) {
  78. errorstream << "GetDirListing: FindNextFile error."
  79. << " Error is " << dwError << std::endl;
  80. listing.clear();
  81. return listing;
  82. }
  83. }
  84. return listing;
  85. }
  86. bool CreateDir(const std::string &path)
  87. {
  88. bool r = CreateDirectory(path.c_str(), NULL);
  89. if(r == true)
  90. return true;
  91. if(GetLastError() == ERROR_ALREADY_EXISTS)
  92. return true;
  93. return false;
  94. }
  95. bool PathExists(const std::string &path)
  96. {
  97. return (GetFileAttributes(path.c_str()) != INVALID_FILE_ATTRIBUTES);
  98. }
  99. bool IsPathAbsolute(const std::string &path)
  100. {
  101. return !PathIsRelative(path.c_str());
  102. }
  103. bool IsDir(const std::string &path)
  104. {
  105. DWORD attr = GetFileAttributes(path.c_str());
  106. return (attr != INVALID_FILE_ATTRIBUTES &&
  107. (attr & FILE_ATTRIBUTE_DIRECTORY));
  108. }
  109. bool IsExecutable(const std::string &path)
  110. {
  111. DWORD type;
  112. return GetBinaryType(path.c_str(), &type) != 0;
  113. }
  114. bool IsDirDelimiter(char c)
  115. {
  116. return c == '/' || c == '\\';
  117. }
  118. bool RecursiveDelete(const std::string &path)
  119. {
  120. infostream << "Recursively deleting \"" << path << "\"" << std::endl;
  121. if (!IsDir(path)) {
  122. infostream << "RecursiveDelete: Deleting file " << path << std::endl;
  123. if (!DeleteFile(path.c_str())) {
  124. errorstream << "RecursiveDelete: Failed to delete file "
  125. << path << std::endl;
  126. return false;
  127. }
  128. return true;
  129. }
  130. infostream << "RecursiveDelete: Deleting content of directory "
  131. << path << std::endl;
  132. std::vector<DirListNode> content = GetDirListing(path);
  133. for (const DirListNode &n: content) {
  134. std::string fullpath = path + DIR_DELIM + n.name;
  135. if (!RecursiveDelete(fullpath)) {
  136. errorstream << "RecursiveDelete: Failed to recurse to "
  137. << fullpath << std::endl;
  138. return false;
  139. }
  140. }
  141. infostream << "RecursiveDelete: Deleting directory " << path << std::endl;
  142. if (!RemoveDirectory(path.c_str())) {
  143. errorstream << "Failed to recursively delete directory "
  144. << path << std::endl;
  145. return false;
  146. }
  147. return true;
  148. }
  149. bool DeleteSingleFileOrEmptyDirectory(const std::string &path)
  150. {
  151. DWORD attr = GetFileAttributes(path.c_str());
  152. bool is_directory = (attr != INVALID_FILE_ATTRIBUTES &&
  153. (attr & FILE_ATTRIBUTE_DIRECTORY));
  154. if(!is_directory)
  155. {
  156. bool did = DeleteFile(path.c_str());
  157. return did;
  158. }
  159. else
  160. {
  161. bool did = RemoveDirectory(path.c_str());
  162. return did;
  163. }
  164. }
  165. std::string TempPath()
  166. {
  167. DWORD bufsize = GetTempPath(0, NULL);
  168. if(bufsize == 0){
  169. errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
  170. return "";
  171. }
  172. std::string buf;
  173. buf.resize(bufsize);
  174. DWORD len = GetTempPath(bufsize, &buf[0]);
  175. if(len == 0 || len > bufsize){
  176. errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
  177. return "";
  178. }
  179. buf.resize(len);
  180. return buf;
  181. }
  182. std::string CreateTempFile()
  183. {
  184. std::string path = TempPath() + DIR_DELIM "MT_XXXXXX";
  185. _mktemp_s(&path[0], path.size() + 1); // modifies path
  186. HANDLE file = CreateFile(path.c_str(), GENERIC_WRITE, 0, nullptr,
  187. CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
  188. if (file == INVALID_HANDLE_VALUE)
  189. return "";
  190. CloseHandle(file);
  191. return path;
  192. }
  193. #else
  194. /*********
  195. * POSIX *
  196. *********/
  197. #include <sys/types.h>
  198. #include <dirent.h>
  199. #include <sys/stat.h>
  200. #include <sys/wait.h>
  201. #include <unistd.h>
  202. std::vector<DirListNode> GetDirListing(const std::string &pathstring)
  203. {
  204. std::vector<DirListNode> listing;
  205. DIR *dp;
  206. struct dirent *dirp;
  207. if((dp = opendir(pathstring.c_str())) == NULL) {
  208. //infostream<<"Error("<<errno<<") opening "<<pathstring<<std::endl;
  209. return listing;
  210. }
  211. while ((dirp = readdir(dp)) != NULL) {
  212. // NOTE:
  213. // Be very sure to not include '..' in the results, it will
  214. // result in an epic failure when deleting stuff.
  215. if(strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0)
  216. continue;
  217. DirListNode node;
  218. node.name = dirp->d_name;
  219. int isdir = -1; // -1 means unknown
  220. /*
  221. POSIX doesn't define d_type member of struct dirent and
  222. certain filesystems on glibc/Linux will only return
  223. DT_UNKNOWN for the d_type member.
  224. Also we don't know whether symlinks are directories or not.
  225. */
  226. #ifdef _DIRENT_HAVE_D_TYPE
  227. if(dirp->d_type != DT_UNKNOWN && dirp->d_type != DT_LNK)
  228. isdir = (dirp->d_type == DT_DIR);
  229. #endif /* _DIRENT_HAVE_D_TYPE */
  230. /*
  231. Was d_type DT_UNKNOWN, DT_LNK or nonexistent?
  232. If so, try stat().
  233. */
  234. if(isdir == -1) {
  235. struct stat statbuf{};
  236. if (stat((pathstring + "/" + node.name).c_str(), &statbuf))
  237. continue;
  238. isdir = ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
  239. }
  240. node.dir = isdir;
  241. listing.push_back(node);
  242. }
  243. closedir(dp);
  244. return listing;
  245. }
  246. bool CreateDir(const std::string &path)
  247. {
  248. int r = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
  249. if (r == 0) {
  250. return true;
  251. }
  252. // If already exists, return true
  253. if (errno == EEXIST)
  254. return true;
  255. return false;
  256. }
  257. bool PathExists(const std::string &path)
  258. {
  259. struct stat st{};
  260. return (stat(path.c_str(),&st) == 0);
  261. }
  262. bool IsPathAbsolute(const std::string &path)
  263. {
  264. return path[0] == '/';
  265. }
  266. bool IsDir(const std::string &path)
  267. {
  268. struct stat statbuf{};
  269. if(stat(path.c_str(), &statbuf))
  270. return false; // Actually error; but certainly not a directory
  271. return ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
  272. }
  273. bool IsExecutable(const std::string &path)
  274. {
  275. return access(path.c_str(), X_OK) == 0;
  276. }
  277. bool IsDirDelimiter(char c)
  278. {
  279. return c == '/';
  280. }
  281. bool RecursiveDelete(const std::string &path)
  282. {
  283. /*
  284. Execute the 'rm' command directly, by fork() and execve()
  285. */
  286. infostream<<"Removing \""<<path<<"\""<<std::endl;
  287. pid_t child_pid = fork();
  288. if(child_pid == 0)
  289. {
  290. // Child
  291. const char *argv[4] = {
  292. #ifdef __ANDROID__
  293. "/system/bin/rm",
  294. #else
  295. "/bin/rm",
  296. #endif
  297. "-rf",
  298. path.c_str(),
  299. NULL
  300. };
  301. verbosestream<<"Executing '"<<argv[0]<<"' '"<<argv[1]<<"' '"
  302. <<argv[2]<<"'"<<std::endl;
  303. execv(argv[0], const_cast<char**>(argv));
  304. // Execv shouldn't return. Failed.
  305. _exit(1);
  306. }
  307. else
  308. {
  309. // Parent
  310. int child_status;
  311. pid_t tpid;
  312. do{
  313. tpid = wait(&child_status);
  314. }while(tpid != child_pid);
  315. return (child_status == 0);
  316. }
  317. }
  318. bool DeleteSingleFileOrEmptyDirectory(const std::string &path)
  319. {
  320. if (IsDir(path)) {
  321. bool did = (rmdir(path.c_str()) == 0);
  322. if (!did)
  323. errorstream << "rmdir errno: " << errno << ": " << strerror(errno)
  324. << std::endl;
  325. return did;
  326. }
  327. bool did = (unlink(path.c_str()) == 0);
  328. if (!did)
  329. errorstream << "unlink errno: " << errno << ": " << strerror(errno)
  330. << std::endl;
  331. return did;
  332. }
  333. std::string TempPath()
  334. {
  335. /*
  336. Should the environment variables TMPDIR, TMP and TEMP
  337. and the macro P_tmpdir (if defined by stdio.h) be checked
  338. before falling back on /tmp?
  339. Probably not, because this function is intended to be
  340. compatible with lua's os.tmpname which under the default
  341. configuration hardcodes mkstemp("/tmp/lua_XXXXXX").
  342. */
  343. #ifdef __ANDROID__
  344. return porting::path_cache;
  345. #else
  346. return DIR_DELIM "tmp";
  347. #endif
  348. }
  349. std::string CreateTempFile()
  350. {
  351. std::string path = TempPath() + DIR_DELIM "MT_XXXXXX";
  352. int fd = mkstemp(&path[0]); // modifies path
  353. if (fd == -1)
  354. return "";
  355. close(fd);
  356. return path;
  357. }
  358. #endif
  359. /****************************
  360. * portable implementations *
  361. ****************************/
  362. void GetRecursiveDirs(std::vector<std::string> &dirs, const std::string &dir)
  363. {
  364. static const std::set<char> chars_to_ignore = { '_', '.' };
  365. if (dir.empty() || !IsDir(dir))
  366. return;
  367. dirs.push_back(dir);
  368. fs::GetRecursiveSubPaths(dir, dirs, false, chars_to_ignore);
  369. }
  370. std::vector<std::string> GetRecursiveDirs(const std::string &dir)
  371. {
  372. std::vector<std::string> result;
  373. GetRecursiveDirs(result, dir);
  374. return result;
  375. }
  376. void GetRecursiveSubPaths(const std::string &path,
  377. std::vector<std::string> &dst,
  378. bool list_files,
  379. const std::set<char> &ignore)
  380. {
  381. std::vector<DirListNode> content = GetDirListing(path);
  382. for (const auto &n : content) {
  383. std::string fullpath = path + DIR_DELIM + n.name;
  384. if (ignore.count(n.name[0]))
  385. continue;
  386. if (list_files || n.dir)
  387. dst.push_back(fullpath);
  388. if (n.dir)
  389. GetRecursiveSubPaths(fullpath, dst, list_files, ignore);
  390. }
  391. }
  392. bool RecursiveDeleteContent(const std::string &path)
  393. {
  394. infostream<<"Removing content of \""<<path<<"\""<<std::endl;
  395. std::vector<DirListNode> list = GetDirListing(path);
  396. for (const DirListNode &dln : list) {
  397. if(trim(dln.name) == "." || trim(dln.name) == "..")
  398. continue;
  399. std::string childpath = path + DIR_DELIM + dln.name;
  400. bool r = RecursiveDelete(childpath);
  401. if(!r) {
  402. errorstream << "Removing \"" << childpath << "\" failed" << std::endl;
  403. return false;
  404. }
  405. }
  406. return true;
  407. }
  408. bool CreateAllDirs(const std::string &path)
  409. {
  410. std::vector<std::string> tocreate;
  411. std::string basepath = path;
  412. while(!PathExists(basepath))
  413. {
  414. tocreate.push_back(basepath);
  415. basepath = RemoveLastPathComponent(basepath);
  416. if(basepath.empty())
  417. break;
  418. }
  419. for(int i=tocreate.size()-1;i>=0;i--)
  420. if(!CreateDir(tocreate[i]))
  421. return false;
  422. return true;
  423. }
  424. bool CopyFileContents(const std::string &source, const std::string &target)
  425. {
  426. FILE *sourcefile = fopen(source.c_str(), "rb");
  427. if(sourcefile == NULL){
  428. errorstream<<source<<": can't open for reading: "
  429. <<strerror(errno)<<std::endl;
  430. return false;
  431. }
  432. FILE *targetfile = fopen(target.c_str(), "wb");
  433. if(targetfile == NULL){
  434. errorstream<<target<<": can't open for writing: "
  435. <<strerror(errno)<<std::endl;
  436. fclose(sourcefile);
  437. return false;
  438. }
  439. size_t total = 0;
  440. bool retval = true;
  441. bool done = false;
  442. char readbuffer[BUFSIZ];
  443. while(!done){
  444. size_t readbytes = fread(readbuffer, 1,
  445. sizeof(readbuffer), sourcefile);
  446. total += readbytes;
  447. if(ferror(sourcefile)){
  448. errorstream<<source<<": IO error: "
  449. <<strerror(errno)<<std::endl;
  450. retval = false;
  451. done = true;
  452. }
  453. if(readbytes > 0){
  454. fwrite(readbuffer, 1, readbytes, targetfile);
  455. }
  456. if(feof(sourcefile) || ferror(sourcefile)){
  457. // flush destination file to catch write errors
  458. // (e.g. disk full)
  459. fflush(targetfile);
  460. done = true;
  461. }
  462. if(ferror(targetfile)){
  463. errorstream<<target<<": IO error: "
  464. <<strerror(errno)<<std::endl;
  465. retval = false;
  466. done = true;
  467. }
  468. }
  469. infostream<<"copied "<<total<<" bytes from "
  470. <<source<<" to "<<target<<std::endl;
  471. fclose(sourcefile);
  472. fclose(targetfile);
  473. return retval;
  474. }
  475. bool CopyDir(const std::string &source, const std::string &target)
  476. {
  477. if(PathExists(source)){
  478. if(!PathExists(target)){
  479. fs::CreateAllDirs(target);
  480. }
  481. bool retval = true;
  482. std::vector<DirListNode> content = fs::GetDirListing(source);
  483. for (const auto &dln : content) {
  484. std::string sourcechild = source + DIR_DELIM + dln.name;
  485. std::string targetchild = target + DIR_DELIM + dln.name;
  486. if(dln.dir){
  487. if(!fs::CopyDir(sourcechild, targetchild)){
  488. retval = false;
  489. }
  490. }
  491. else {
  492. if(!fs::CopyFileContents(sourcechild, targetchild)){
  493. retval = false;
  494. }
  495. }
  496. }
  497. return retval;
  498. }
  499. return false;
  500. }
  501. bool MoveDir(const std::string &source, const std::string &target)
  502. {
  503. infostream << "Moving \"" << source << "\" to \"" << target << "\"" << std::endl;
  504. // If target exists as empty folder delete, otherwise error
  505. if (fs::PathExists(target)) {
  506. if (rmdir(target.c_str()) != 0) {
  507. errorstream << "MoveDir: target \"" << target
  508. << "\" exists as file or non-empty folder" << std::endl;
  509. return false;
  510. }
  511. }
  512. // Try renaming first which is instant
  513. if (fs::Rename(source, target))
  514. return true;
  515. infostream << "MoveDir: rename not possible, will copy instead" << std::endl;
  516. bool retval = fs::CopyDir(source, target);
  517. if (retval)
  518. retval &= fs::RecursiveDelete(source);
  519. return retval;
  520. }
  521. bool PathStartsWith(const std::string &path, const std::string &prefix)
  522. {
  523. size_t pathsize = path.size();
  524. size_t pathpos = 0;
  525. size_t prefixsize = prefix.size();
  526. size_t prefixpos = 0;
  527. for(;;){
  528. bool delim1 = pathpos == pathsize
  529. || IsDirDelimiter(path[pathpos]);
  530. bool delim2 = prefixpos == prefixsize
  531. || IsDirDelimiter(prefix[prefixpos]);
  532. if(delim1 != delim2)
  533. return false;
  534. if(delim1){
  535. while(pathpos < pathsize &&
  536. IsDirDelimiter(path[pathpos]))
  537. ++pathpos;
  538. while(prefixpos < prefixsize &&
  539. IsDirDelimiter(prefix[prefixpos]))
  540. ++prefixpos;
  541. if(prefixpos == prefixsize)
  542. return true;
  543. if(pathpos == pathsize)
  544. return false;
  545. }
  546. else{
  547. size_t len = 0;
  548. do{
  549. char pathchar = path[pathpos+len];
  550. char prefixchar = prefix[prefixpos+len];
  551. if(FILESYS_CASE_INSENSITIVE){
  552. pathchar = tolower(pathchar);
  553. prefixchar = tolower(prefixchar);
  554. }
  555. if(pathchar != prefixchar)
  556. return false;
  557. ++len;
  558. } while(pathpos+len < pathsize
  559. && !IsDirDelimiter(path[pathpos+len])
  560. && prefixpos+len < prefixsize
  561. && !IsDirDelimiter(
  562. prefix[prefixpos+len]));
  563. pathpos += len;
  564. prefixpos += len;
  565. }
  566. }
  567. }
  568. std::string RemoveLastPathComponent(const std::string &path,
  569. std::string *removed, int count)
  570. {
  571. if(removed)
  572. removed->clear();
  573. size_t remaining = path.size();
  574. for(int i = 0; i < count; ++i){
  575. // strip a dir delimiter
  576. while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
  577. remaining--;
  578. // strip a path component
  579. size_t component_end = remaining;
  580. while(remaining != 0 && !IsDirDelimiter(path[remaining-1]))
  581. remaining--;
  582. size_t component_start = remaining;
  583. // strip a dir delimiter
  584. while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
  585. remaining--;
  586. if(removed){
  587. std::string component = path.substr(component_start,
  588. component_end - component_start);
  589. if(i)
  590. *removed = component + DIR_DELIM + *removed;
  591. else
  592. *removed = component;
  593. }
  594. }
  595. return path.substr(0, remaining);
  596. }
  597. std::string RemoveRelativePathComponents(std::string path)
  598. {
  599. size_t pos = path.size();
  600. size_t dotdot_count = 0;
  601. while (pos != 0) {
  602. size_t component_with_delim_end = pos;
  603. // skip a dir delimiter
  604. while (pos != 0 && IsDirDelimiter(path[pos-1]))
  605. pos--;
  606. // strip a path component
  607. size_t component_end = pos;
  608. while (pos != 0 && !IsDirDelimiter(path[pos-1]))
  609. pos--;
  610. size_t component_start = pos;
  611. std::string component = path.substr(component_start,
  612. component_end - component_start);
  613. bool remove_this_component = false;
  614. if (component == ".") {
  615. remove_this_component = true;
  616. } else if (component == "..") {
  617. remove_this_component = true;
  618. dotdot_count += 1;
  619. } else if (dotdot_count != 0) {
  620. remove_this_component = true;
  621. dotdot_count -= 1;
  622. }
  623. if (remove_this_component) {
  624. while (pos != 0 && IsDirDelimiter(path[pos-1]))
  625. pos--;
  626. if (component_start == 0) {
  627. // We need to remove the delemiter too
  628. path = path.substr(component_with_delim_end, std::string::npos);
  629. } else {
  630. path = path.substr(0, pos) + DIR_DELIM +
  631. path.substr(component_with_delim_end, std::string::npos);
  632. }
  633. if (pos > 0)
  634. pos++;
  635. }
  636. }
  637. if (dotdot_count > 0)
  638. return "";
  639. // remove trailing dir delimiters
  640. pos = path.size();
  641. while (pos != 0 && IsDirDelimiter(path[pos-1]))
  642. pos--;
  643. return path.substr(0, pos);
  644. }
  645. std::string AbsolutePath(const std::string &path)
  646. {
  647. #ifdef _WIN32
  648. char *abs_path = _fullpath(NULL, path.c_str(), MAX_PATH);
  649. #else
  650. char *abs_path = realpath(path.c_str(), NULL);
  651. #endif
  652. if (!abs_path) return "";
  653. std::string abs_path_str(abs_path);
  654. free(abs_path);
  655. return abs_path_str;
  656. }
  657. const char *GetFilenameFromPath(const char *path)
  658. {
  659. const char *filename = strrchr(path, DIR_DELIM_CHAR);
  660. // Consistent with IsDirDelimiter this function handles '/' too
  661. if (DIR_DELIM_CHAR != '/') {
  662. const char *tmp = strrchr(path, '/');
  663. if (tmp && tmp > filename)
  664. filename = tmp;
  665. }
  666. return filename ? filename + 1 : path;
  667. }
  668. bool safeWriteToFile(const std::string &path, const std::string &content)
  669. {
  670. std::string tmp_file = path + ".~mt";
  671. // Write to a tmp file
  672. std::ofstream os(tmp_file.c_str(), std::ios::binary);
  673. if (!os.good())
  674. return false;
  675. os << content;
  676. os.flush();
  677. os.close();
  678. if (os.fail()) {
  679. // Remove the temporary file because writing it failed and it's useless.
  680. remove(tmp_file.c_str());
  681. return false;
  682. }
  683. bool rename_success = false;
  684. // Move the finished temporary file over the real file
  685. #ifdef _WIN32
  686. // When creating the file, it can cause Windows Search indexer, virus scanners and other apps
  687. // to query the file. This can make the move file call below fail.
  688. // We retry up to 5 times, with a 1ms sleep between, before we consider the whole operation failed
  689. int number_attempts = 0;
  690. while (number_attempts < 5) {
  691. rename_success = MoveFileEx(tmp_file.c_str(), path.c_str(),
  692. MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH);
  693. if (rename_success)
  694. break;
  695. sleep_ms(1);
  696. ++number_attempts;
  697. }
  698. #else
  699. // On POSIX compliant systems rename() is specified to be able to swap the
  700. // file in place of the destination file, making this a truly error-proof
  701. // transaction.
  702. rename_success = rename(tmp_file.c_str(), path.c_str()) == 0;
  703. #endif
  704. if (!rename_success) {
  705. warningstream << "Failed to write to file: " << path.c_str() << std::endl;
  706. // Remove the temporary file because moving it over the target file
  707. // failed.
  708. remove(tmp_file.c_str());
  709. return false;
  710. }
  711. return true;
  712. }
  713. #ifndef SERVER
  714. bool extractZipFile(io::IFileSystem *fs, const char *filename, const std::string &destination)
  715. {
  716. // Be careful here not to touch the global file hierarchy in Irrlicht
  717. // since this function needs to be thread-safe!
  718. io::IArchiveLoader *zip_loader = nullptr;
  719. for (u32 i = 0; i < fs->getArchiveLoaderCount(); i++) {
  720. if (fs->getArchiveLoader(i)->isALoadableFileFormat(io::EFAT_ZIP)) {
  721. zip_loader = fs->getArchiveLoader(i);
  722. break;
  723. }
  724. }
  725. if (!zip_loader) {
  726. warningstream << "fs::extractZipFile(): Irrlicht said it doesn't support ZIPs." << std::endl;
  727. return false;
  728. }
  729. irr_ptr<io::IFileArchive> opened_zip(zip_loader->createArchive(filename, false, false));
  730. const io::IFileList* files_in_zip = opened_zip->getFileList();
  731. for (u32 i = 0; i < files_in_zip->getFileCount(); i++) {
  732. std::string fullpath = destination + DIR_DELIM;
  733. fullpath += files_in_zip->getFullFileName(i).c_str();
  734. std::string fullpath_dir = fs::RemoveLastPathComponent(fullpath);
  735. if (files_in_zip->isDirectory(i))
  736. continue; // ignore, we create dirs as necessary
  737. if (!fs::PathExists(fullpath_dir) && !fs::CreateAllDirs(fullpath_dir))
  738. return false;
  739. irr_ptr<io::IReadFile> toread(opened_zip->createAndOpenFile(i));
  740. std::ofstream os(fullpath.c_str(), std::ios::binary);
  741. if (!os.good())
  742. return false;
  743. char buffer[4096];
  744. long total_read = 0;
  745. while (total_read < toread->getSize()) {
  746. long bytes_read = toread->read(buffer, sizeof(buffer));
  747. bool error = true;
  748. if (bytes_read != 0) {
  749. os.write(buffer, bytes_read);
  750. error = os.fail();
  751. }
  752. if (error) {
  753. os.close();
  754. remove(fullpath.c_str());
  755. return false;
  756. }
  757. total_read += bytes_read;
  758. }
  759. }
  760. return true;
  761. }
  762. #endif
  763. bool ReadFile(const std::string &path, std::string &out)
  764. {
  765. std::ifstream is(path, std::ios::binary | std::ios::ate);
  766. if (!is.good()) {
  767. return false;
  768. }
  769. auto size = is.tellg();
  770. out.resize(size);
  771. is.seekg(0);
  772. is.read(&out[0], size);
  773. return !is.fail();
  774. }
  775. bool Rename(const std::string &from, const std::string &to)
  776. {
  777. return rename(from.c_str(), to.c_str()) == 0;
  778. }
  779. } // namespace fs