filesys.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768
  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. pid_t child_pid = fork();
  255. if(child_pid == 0)
  256. {
  257. // Child
  258. const char *argv[4] = {
  259. #ifdef __ANDROID__
  260. "/system/bin/rm",
  261. #else
  262. "/bin/rm",
  263. #endif
  264. "-rf",
  265. path.c_str(),
  266. NULL
  267. };
  268. verbosestream<<"Executing '"<<argv[0]<<"' '"<<argv[1]<<"' '"
  269. <<argv[2]<<"'"<<std::endl;
  270. execv(argv[0], const_cast<char**>(argv));
  271. // Execv shouldn't return. Failed.
  272. _exit(1);
  273. }
  274. else
  275. {
  276. // Parent
  277. int child_status;
  278. pid_t tpid;
  279. do{
  280. tpid = wait(&child_status);
  281. }while(tpid != child_pid);
  282. return (child_status == 0);
  283. }
  284. }
  285. bool DeleteSingleFileOrEmptyDirectory(const std::string &path)
  286. {
  287. if (IsDir(path)) {
  288. bool did = (rmdir(path.c_str()) == 0);
  289. if (!did)
  290. errorstream << "rmdir errno: " << errno << ": " << strerror(errno)
  291. << std::endl;
  292. return did;
  293. }
  294. bool did = (unlink(path.c_str()) == 0);
  295. if (!did)
  296. errorstream << "unlink errno: " << errno << ": " << strerror(errno)
  297. << std::endl;
  298. return did;
  299. }
  300. std::string TempPath()
  301. {
  302. /*
  303. Should the environment variables TMPDIR, TMP and TEMP
  304. and the macro P_tmpdir (if defined by stdio.h) be checked
  305. before falling back on /tmp?
  306. Probably not, because this function is intended to be
  307. compatible with lua's os.tmpname which under the default
  308. configuration hardcodes mkstemp("/tmp/lua_XXXXXX").
  309. */
  310. #ifdef __ANDROID__
  311. return g_settings->get("TMPFolder");
  312. #else
  313. return DIR_DELIM "tmp";
  314. #endif
  315. }
  316. #endif
  317. void GetRecursiveDirs(std::vector<std::string> &dirs, const std::string &dir)
  318. {
  319. static const std::set<char> chars_to_ignore = { '_', '.' };
  320. if (dir.empty() || !IsDir(dir))
  321. return;
  322. dirs.push_back(dir);
  323. fs::GetRecursiveSubPaths(dir, dirs, false, chars_to_ignore);
  324. }
  325. std::vector<std::string> GetRecursiveDirs(const std::string &dir)
  326. {
  327. std::vector<std::string> result;
  328. GetRecursiveDirs(result, dir);
  329. return result;
  330. }
  331. void GetRecursiveSubPaths(const std::string &path,
  332. std::vector<std::string> &dst,
  333. bool list_files,
  334. const std::set<char> &ignore)
  335. {
  336. std::vector<DirListNode> content = GetDirListing(path);
  337. for (const auto &n : content) {
  338. std::string fullpath = path + DIR_DELIM + n.name;
  339. if (ignore.count(n.name[0]))
  340. continue;
  341. if (list_files || n.dir)
  342. dst.push_back(fullpath);
  343. if (n.dir)
  344. GetRecursiveSubPaths(fullpath, dst, list_files, ignore);
  345. }
  346. }
  347. bool DeletePaths(const std::vector<std::string> &paths)
  348. {
  349. bool success = true;
  350. // Go backwards to succesfully delete the output of GetRecursiveSubPaths
  351. for(int i=paths.size()-1; i>=0; i--){
  352. const std::string &path = paths[i];
  353. bool did = DeleteSingleFileOrEmptyDirectory(path);
  354. if(!did){
  355. errorstream<<"Failed to delete "<<path<<std::endl;
  356. success = false;
  357. }
  358. }
  359. return success;
  360. }
  361. bool RecursiveDeleteContent(const std::string &path)
  362. {
  363. infostream<<"Removing content of \""<<path<<"\""<<std::endl;
  364. std::vector<DirListNode> list = GetDirListing(path);
  365. for (const DirListNode &dln : list) {
  366. if(trim(dln.name) == "." || trim(dln.name) == "..")
  367. continue;
  368. std::string childpath = path + DIR_DELIM + dln.name;
  369. bool r = RecursiveDelete(childpath);
  370. if(!r) {
  371. errorstream << "Removing \"" << childpath << "\" failed" << std::endl;
  372. return false;
  373. }
  374. }
  375. return true;
  376. }
  377. bool CreateAllDirs(const std::string &path)
  378. {
  379. std::vector<std::string> tocreate;
  380. std::string basepath = path;
  381. while(!PathExists(basepath))
  382. {
  383. tocreate.push_back(basepath);
  384. basepath = RemoveLastPathComponent(basepath);
  385. if(basepath.empty())
  386. break;
  387. }
  388. for(int i=tocreate.size()-1;i>=0;i--)
  389. if(!CreateDir(tocreate[i]))
  390. return false;
  391. return true;
  392. }
  393. bool CopyFileContents(const std::string &source, const std::string &target)
  394. {
  395. FILE *sourcefile = fopen(source.c_str(), "rb");
  396. if(sourcefile == NULL){
  397. errorstream<<source<<": can't open for reading: "
  398. <<strerror(errno)<<std::endl;
  399. return false;
  400. }
  401. FILE *targetfile = fopen(target.c_str(), "wb");
  402. if(targetfile == NULL){
  403. errorstream<<target<<": can't open for writing: "
  404. <<strerror(errno)<<std::endl;
  405. fclose(sourcefile);
  406. return false;
  407. }
  408. size_t total = 0;
  409. bool retval = true;
  410. bool done = false;
  411. char readbuffer[BUFSIZ];
  412. while(!done){
  413. size_t readbytes = fread(readbuffer, 1,
  414. sizeof(readbuffer), sourcefile);
  415. total += readbytes;
  416. if(ferror(sourcefile)){
  417. errorstream<<source<<": IO error: "
  418. <<strerror(errno)<<std::endl;
  419. retval = false;
  420. done = true;
  421. }
  422. if(readbytes > 0){
  423. fwrite(readbuffer, 1, readbytes, targetfile);
  424. }
  425. if(feof(sourcefile) || ferror(sourcefile)){
  426. // flush destination file to catch write errors
  427. // (e.g. disk full)
  428. fflush(targetfile);
  429. done = true;
  430. }
  431. if(ferror(targetfile)){
  432. errorstream<<target<<": IO error: "
  433. <<strerror(errno)<<std::endl;
  434. retval = false;
  435. done = true;
  436. }
  437. }
  438. infostream<<"copied "<<total<<" bytes from "
  439. <<source<<" to "<<target<<std::endl;
  440. fclose(sourcefile);
  441. fclose(targetfile);
  442. return retval;
  443. }
  444. bool CopyDir(const std::string &source, const std::string &target)
  445. {
  446. if(PathExists(source)){
  447. if(!PathExists(target)){
  448. fs::CreateAllDirs(target);
  449. }
  450. bool retval = true;
  451. std::vector<DirListNode> content = fs::GetDirListing(source);
  452. for (const auto &dln : content) {
  453. std::string sourcechild = source + DIR_DELIM + dln.name;
  454. std::string targetchild = target + DIR_DELIM + dln.name;
  455. if(dln.dir){
  456. if(!fs::CopyDir(sourcechild, targetchild)){
  457. retval = false;
  458. }
  459. }
  460. else {
  461. if(!fs::CopyFileContents(sourcechild, targetchild)){
  462. retval = false;
  463. }
  464. }
  465. }
  466. return retval;
  467. }
  468. return false;
  469. }
  470. bool PathStartsWith(const std::string &path, const std::string &prefix)
  471. {
  472. size_t pathsize = path.size();
  473. size_t pathpos = 0;
  474. size_t prefixsize = prefix.size();
  475. size_t prefixpos = 0;
  476. for(;;){
  477. bool delim1 = pathpos == pathsize
  478. || IsDirDelimiter(path[pathpos]);
  479. bool delim2 = prefixpos == prefixsize
  480. || IsDirDelimiter(prefix[prefixpos]);
  481. if(delim1 != delim2)
  482. return false;
  483. if(delim1){
  484. while(pathpos < pathsize &&
  485. IsDirDelimiter(path[pathpos]))
  486. ++pathpos;
  487. while(prefixpos < prefixsize &&
  488. IsDirDelimiter(prefix[prefixpos]))
  489. ++prefixpos;
  490. if(prefixpos == prefixsize)
  491. return true;
  492. if(pathpos == pathsize)
  493. return false;
  494. }
  495. else{
  496. size_t len = 0;
  497. do{
  498. char pathchar = path[pathpos+len];
  499. char prefixchar = prefix[prefixpos+len];
  500. if(FILESYS_CASE_INSENSITIVE){
  501. pathchar = tolower(pathchar);
  502. prefixchar = tolower(prefixchar);
  503. }
  504. if(pathchar != prefixchar)
  505. return false;
  506. ++len;
  507. } while(pathpos+len < pathsize
  508. && !IsDirDelimiter(path[pathpos+len])
  509. && prefixpos+len < prefixsize
  510. && !IsDirDelimiter(
  511. prefix[prefixpos+len]));
  512. pathpos += len;
  513. prefixpos += len;
  514. }
  515. }
  516. }
  517. std::string RemoveLastPathComponent(const std::string &path,
  518. std::string *removed, int count)
  519. {
  520. if(removed)
  521. *removed = "";
  522. size_t remaining = path.size();
  523. for(int i = 0; i < count; ++i){
  524. // strip a dir delimiter
  525. while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
  526. remaining--;
  527. // strip a path component
  528. size_t component_end = remaining;
  529. while(remaining != 0 && !IsDirDelimiter(path[remaining-1]))
  530. remaining--;
  531. size_t component_start = remaining;
  532. // strip a dir delimiter
  533. while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
  534. remaining--;
  535. if(removed){
  536. std::string component = path.substr(component_start,
  537. component_end - component_start);
  538. if(i)
  539. *removed = component + DIR_DELIM + *removed;
  540. else
  541. *removed = component;
  542. }
  543. }
  544. return path.substr(0, remaining);
  545. }
  546. std::string RemoveRelativePathComponents(std::string path)
  547. {
  548. size_t pos = path.size();
  549. size_t dotdot_count = 0;
  550. while (pos != 0) {
  551. size_t component_with_delim_end = pos;
  552. // skip a dir delimiter
  553. while (pos != 0 && IsDirDelimiter(path[pos-1]))
  554. pos--;
  555. // strip a path component
  556. size_t component_end = pos;
  557. while (pos != 0 && !IsDirDelimiter(path[pos-1]))
  558. pos--;
  559. size_t component_start = pos;
  560. std::string component = path.substr(component_start,
  561. component_end - component_start);
  562. bool remove_this_component = false;
  563. if (component == ".") {
  564. remove_this_component = true;
  565. } else if (component == "..") {
  566. remove_this_component = true;
  567. dotdot_count += 1;
  568. } else if (dotdot_count != 0) {
  569. remove_this_component = true;
  570. dotdot_count -= 1;
  571. }
  572. if (remove_this_component) {
  573. while (pos != 0 && IsDirDelimiter(path[pos-1]))
  574. pos--;
  575. if (component_start == 0) {
  576. // We need to remove the delemiter too
  577. path = path.substr(component_with_delim_end, std::string::npos);
  578. } else {
  579. path = path.substr(0, pos) + DIR_DELIM +
  580. path.substr(component_with_delim_end, std::string::npos);
  581. }
  582. if (pos > 0)
  583. pos++;
  584. }
  585. }
  586. if (dotdot_count > 0)
  587. return "";
  588. // remove trailing dir delimiters
  589. pos = path.size();
  590. while (pos != 0 && IsDirDelimiter(path[pos-1]))
  591. pos--;
  592. return path.substr(0, pos);
  593. }
  594. std::string AbsolutePath(const std::string &path)
  595. {
  596. #ifdef _WIN32
  597. char *abs_path = _fullpath(NULL, path.c_str(), MAX_PATH);
  598. #else
  599. char *abs_path = realpath(path.c_str(), NULL);
  600. #endif
  601. if (!abs_path) return "";
  602. std::string abs_path_str(abs_path);
  603. free(abs_path);
  604. return abs_path_str;
  605. }
  606. const char *GetFilenameFromPath(const char *path)
  607. {
  608. const char *filename = strrchr(path, DIR_DELIM_CHAR);
  609. // Consistent with IsDirDelimiter this function handles '/' too
  610. if (DIR_DELIM_CHAR != '/') {
  611. const char *tmp = strrchr(path, '/');
  612. if (tmp && tmp > filename)
  613. filename = tmp;
  614. }
  615. return filename ? filename + 1 : path;
  616. }
  617. bool safeWriteToFile(const std::string &path, const std::string &content)
  618. {
  619. std::string tmp_file = path + ".~mt";
  620. // Write to a tmp file
  621. std::ofstream os(tmp_file.c_str(), std::ios::binary);
  622. if (!os.good())
  623. return false;
  624. os << content;
  625. os.flush();
  626. os.close();
  627. if (os.fail()) {
  628. // Remove the temporary file because writing it failed and it's useless.
  629. remove(tmp_file.c_str());
  630. return false;
  631. }
  632. bool rename_success = false;
  633. // Move the finished temporary file over the real file
  634. #ifdef _WIN32
  635. // When creating the file, it can cause Windows Search indexer, virus scanners and other apps
  636. // to query the file. This can make the move file call below fail.
  637. // We retry up to 5 times, with a 1ms sleep between, before we consider the whole operation failed
  638. int number_attempts = 0;
  639. while (number_attempts < 5) {
  640. rename_success = MoveFileEx(tmp_file.c_str(), path.c_str(),
  641. MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH);
  642. if (rename_success)
  643. break;
  644. sleep_ms(1);
  645. ++number_attempts;
  646. }
  647. #else
  648. // On POSIX compliant systems rename() is specified to be able to swap the
  649. // file in place of the destination file, making this a truly error-proof
  650. // transaction.
  651. rename_success = rename(tmp_file.c_str(), path.c_str()) == 0;
  652. #endif
  653. if (!rename_success) {
  654. warningstream << "Failed to write to file: " << path.c_str() << std::endl;
  655. // Remove the temporary file because moving it over the target file
  656. // failed.
  657. remove(tmp_file.c_str());
  658. return false;
  659. }
  660. return true;
  661. }
  662. bool ReadFile(const std::string &path, std::string &out)
  663. {
  664. std::ifstream is(path, std::ios::binary | std::ios::ate);
  665. if (!is.good()) {
  666. return false;
  667. }
  668. auto size = is.tellg();
  669. out.resize(size);
  670. is.seekg(0);
  671. is.read(&out[0], size);
  672. return true;
  673. }
  674. bool Rename(const std::string &from, const std::string &to)
  675. {
  676. return rename(from.c_str(), to.c_str()) == 0;
  677. }
  678. } // namespace fs