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