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