filesys.cpp 18 KB

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