filesys.cpp 20 KB

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