filesys.cpp 21 KB

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