3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
21 #include "util/string.h"
44 #define _WIN32_WINNT 0x0501
50 std::vector<DirListNode> GetDirListing(const std::string &pathstring)
52 std::vector<DirListNode> listing;
54 WIN32_FIND_DATA FindFileData;
55 HANDLE hFind = INVALID_HANDLE_VALUE;
58 std::string dirSpec = pathstring + "\\*";
60 // Find the first file in the directory.
61 hFind = FindFirstFile(dirSpec.c_str(), &FindFileData);
63 if (hFind == INVALID_HANDLE_VALUE) {
64 dwError = GetLastError();
65 if (dwError != ERROR_FILE_NOT_FOUND && dwError != ERROR_PATH_NOT_FOUND) {
66 errorstream << "GetDirListing: FindFirstFile error."
67 << " Error is " << dwError << std::endl;
71 // Be very sure to not include '..' in the results, it will
72 // result in an epic failure when deleting stuff.
75 node.name = FindFileData.cFileName;
76 node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
77 if (node.name != "." && node.name != "..")
78 listing.push_back(node);
80 // List all the other files in the directory.
81 while (FindNextFile(hFind, &FindFileData) != 0) {
83 node.name = FindFileData.cFileName;
84 node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
85 if(node.name != "." && node.name != "..")
86 listing.push_back(node);
89 dwError = GetLastError();
91 if (dwError != ERROR_NO_MORE_FILES) {
92 errorstream << "GetDirListing: FindNextFile error."
93 << " Error is " << dwError << std::endl;
101 bool CreateDir(const std::string &path)
103 bool r = CreateDirectory(path.c_str(), NULL);
106 if(GetLastError() == ERROR_ALREADY_EXISTS)
111 bool PathExists(const std::string &path)
113 return (GetFileAttributes(path.c_str()) != INVALID_FILE_ATTRIBUTES);
116 bool IsPathAbsolute(const std::string &path)
118 return !PathIsRelative(path.c_str());
121 bool IsDir(const std::string &path)
123 DWORD attr = GetFileAttributes(path.c_str());
124 return (attr != INVALID_FILE_ATTRIBUTES &&
125 (attr & FILE_ATTRIBUTE_DIRECTORY));
128 bool IsDirDelimiter(char c)
130 return c == '/' || c == '\\';
133 bool RecursiveDelete(const std::string &path)
135 infostream << "Recursively deleting \"" << path << "\"" << std::endl;
137 infostream << "RecursiveDelete: Deleting file " << path << std::endl;
138 if (!DeleteFile(path.c_str())) {
139 errorstream << "RecursiveDelete: Failed to delete file "
140 << path << std::endl;
145 infostream << "RecursiveDelete: Deleting content of directory "
146 << path << std::endl;
147 std::vector<DirListNode> content = GetDirListing(path);
148 for (const DirListNode &n: content) {
149 std::string fullpath = path + DIR_DELIM + n.name;
150 if (!RecursiveDelete(fullpath)) {
151 errorstream << "RecursiveDelete: Failed to recurse to "
152 << fullpath << std::endl;
156 infostream << "RecursiveDelete: Deleting directory " << path << std::endl;
157 if (!RemoveDirectory(path.c_str())) {
158 errorstream << "Failed to recursively delete directory "
159 << path << std::endl;
165 bool DeleteSingleFileOrEmptyDirectory(const std::string &path)
167 DWORD attr = GetFileAttributes(path.c_str());
168 bool is_directory = (attr != INVALID_FILE_ATTRIBUTES &&
169 (attr & FILE_ATTRIBUTE_DIRECTORY));
172 bool did = DeleteFile(path.c_str());
177 bool did = RemoveDirectory(path.c_str());
182 std::string TempPath()
184 DWORD bufsize = GetTempPath(0, NULL);
186 errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
191 DWORD len = GetTempPath(bufsize, &buf[0]);
192 if(len == 0 || len > bufsize){
193 errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
200 std::string CreateTempFile()
202 std::string path = TempPath() + DIR_DELIM "MT_XXXXXX";
203 _mktemp_s(&path[0], path.size() + 1); // modifies path
204 HANDLE file = CreateFile(path.c_str(), GENERIC_WRITE, 0, nullptr,
205 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
206 if (file == INVALID_HANDLE_VALUE)
218 #include <sys/types.h>
220 #include <sys/stat.h>
221 #include <sys/wait.h>
224 std::vector<DirListNode> GetDirListing(const std::string &pathstring)
226 std::vector<DirListNode> listing;
230 if((dp = opendir(pathstring.c_str())) == NULL) {
231 //infostream<<"Error("<<errno<<") opening "<<pathstring<<std::endl;
235 while ((dirp = readdir(dp)) != NULL) {
237 // Be very sure to not include '..' in the results, it will
238 // result in an epic failure when deleting stuff.
239 if(strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0)
243 node.name = dirp->d_name;
245 int isdir = -1; // -1 means unknown
248 POSIX doesn't define d_type member of struct dirent and
249 certain filesystems on glibc/Linux will only return
250 DT_UNKNOWN for the d_type member.
252 Also we don't know whether symlinks are directories or not.
254 #ifdef _DIRENT_HAVE_D_TYPE
255 if(dirp->d_type != DT_UNKNOWN && dirp->d_type != DT_LNK)
256 isdir = (dirp->d_type == DT_DIR);
257 #endif /* _DIRENT_HAVE_D_TYPE */
260 Was d_type DT_UNKNOWN, DT_LNK or nonexistent?
264 struct stat statbuf{};
265 if (stat((pathstring + "/" + node.name).c_str(), &statbuf))
267 isdir = ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
270 listing.push_back(node);
277 bool CreateDir(const std::string &path)
279 int r = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
284 // If already exists, return true
291 bool PathExists(const std::string &path)
294 return (stat(path.c_str(),&st) == 0);
297 bool IsPathAbsolute(const std::string &path)
299 return path[0] == '/';
302 bool IsDir(const std::string &path)
304 struct stat statbuf{};
305 if(stat(path.c_str(), &statbuf))
306 return false; // Actually error; but certainly not a directory
307 return ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
310 bool IsDirDelimiter(char c)
315 bool RecursiveDelete(const std::string &path)
318 Execute the 'rm' command directly, by fork() and execve()
321 infostream<<"Removing \""<<path<<"\""<<std::endl;
323 pid_t child_pid = fork();
328 const char *argv[4] = {
339 verbosestream<<"Executing '"<<argv[0]<<"' '"<<argv[1]<<"' '"
340 <<argv[2]<<"'"<<std::endl;
342 execv(argv[0], const_cast<char**>(argv));
344 // Execv shouldn't return. Failed.
353 tpid = wait(&child_status);
354 }while(tpid != child_pid);
355 return (child_status == 0);
359 bool DeleteSingleFileOrEmptyDirectory(const std::string &path)
362 bool did = (rmdir(path.c_str()) == 0);
364 errorstream << "rmdir errno: " << errno << ": " << strerror(errno)
369 bool did = (unlink(path.c_str()) == 0);
371 errorstream << "unlink errno: " << errno << ": " << strerror(errno)
376 std::string TempPath()
379 Should the environment variables TMPDIR, TMP and TEMP
380 and the macro P_tmpdir (if defined by stdio.h) be checked
381 before falling back on /tmp?
383 Probably not, because this function is intended to be
384 compatible with lua's os.tmpname which under the default
385 configuration hardcodes mkstemp("/tmp/lua_XXXXXX").
389 return porting::path_cache;
391 return DIR_DELIM "tmp";
395 std::string CreateTempFile()
397 std::string path = TempPath() + DIR_DELIM "MT_XXXXXX";
398 int fd = mkstemp(&path[0]); // modifies path
407 /****************************
408 * portable implementations *
409 ****************************/
411 void GetRecursiveDirs(std::vector<std::string> &dirs, const std::string &dir)
413 static const std::set<char> chars_to_ignore = { '_', '.' };
414 if (dir.empty() || !IsDir(dir))
417 fs::GetRecursiveSubPaths(dir, dirs, false, chars_to_ignore);
420 std::vector<std::string> GetRecursiveDirs(const std::string &dir)
422 std::vector<std::string> result;
423 GetRecursiveDirs(result, dir);
427 void GetRecursiveSubPaths(const std::string &path,
428 std::vector<std::string> &dst,
430 const std::set<char> &ignore)
432 std::vector<DirListNode> content = GetDirListing(path);
433 for (const auto &n : content) {
434 std::string fullpath = path + DIR_DELIM + n.name;
435 if (ignore.count(n.name[0]))
437 if (list_files || n.dir)
438 dst.push_back(fullpath);
440 GetRecursiveSubPaths(fullpath, dst, list_files, ignore);
444 bool RecursiveDeleteContent(const std::string &path)
446 infostream<<"Removing content of \""<<path<<"\""<<std::endl;
447 std::vector<DirListNode> list = GetDirListing(path);
448 for (const DirListNode &dln : list) {
449 if(trim(dln.name) == "." || trim(dln.name) == "..")
451 std::string childpath = path + DIR_DELIM + dln.name;
452 bool r = RecursiveDelete(childpath);
454 errorstream << "Removing \"" << childpath << "\" failed" << std::endl;
461 bool CreateAllDirs(const std::string &path)
464 std::vector<std::string> tocreate;
465 std::string basepath = path;
466 while(!PathExists(basepath))
468 tocreate.push_back(basepath);
469 basepath = RemoveLastPathComponent(basepath);
473 for(int i=tocreate.size()-1;i>=0;i--)
474 if(!CreateDir(tocreate[i]))
479 bool CopyFileContents(const std::string &source, const std::string &target)
481 FILE *sourcefile = fopen(source.c_str(), "rb");
482 if(sourcefile == NULL){
483 errorstream<<source<<": can't open for reading: "
484 <<strerror(errno)<<std::endl;
488 FILE *targetfile = fopen(target.c_str(), "wb");
489 if(targetfile == NULL){
490 errorstream<<target<<": can't open for writing: "
491 <<strerror(errno)<<std::endl;
499 char readbuffer[BUFSIZ];
501 size_t readbytes = fread(readbuffer, 1,
502 sizeof(readbuffer), sourcefile);
504 if(ferror(sourcefile)){
505 errorstream<<source<<": IO error: "
506 <<strerror(errno)<<std::endl;
511 fwrite(readbuffer, 1, readbytes, targetfile);
513 if(feof(sourcefile) || ferror(sourcefile)){
514 // flush destination file to catch write errors
519 if(ferror(targetfile)){
520 errorstream<<target<<": IO error: "
521 <<strerror(errno)<<std::endl;
526 infostream<<"copied "<<total<<" bytes from "
527 <<source<<" to "<<target<<std::endl;
533 bool CopyDir(const std::string &source, const std::string &target)
535 if(PathExists(source)){
536 if(!PathExists(target)){
537 fs::CreateAllDirs(target);
540 std::vector<DirListNode> content = fs::GetDirListing(source);
542 for (const auto &dln : content) {
543 std::string sourcechild = source + DIR_DELIM + dln.name;
544 std::string targetchild = target + DIR_DELIM + dln.name;
546 if(!fs::CopyDir(sourcechild, targetchild)){
551 if(!fs::CopyFileContents(sourcechild, targetchild)){
562 bool MoveDir(const std::string &source, const std::string &target)
564 infostream << "Moving \"" << source << "\" to \"" << target << "\"" << std::endl;
566 // If target exists as empty folder delete, otherwise error
567 if (fs::PathExists(target)) {
568 if (rmdir(target.c_str()) != 0) {
569 errorstream << "MoveDir: target \"" << target
570 << "\" exists as file or non-empty folder" << std::endl;
575 // Try renaming first which is instant
576 if (fs::Rename(source, target))
579 infostream << "MoveDir: rename not possible, will copy instead" << std::endl;
580 bool retval = fs::CopyDir(source, target);
582 retval &= fs::RecursiveDelete(source);
586 bool PathStartsWith(const std::string &path, const std::string &prefix)
588 size_t pathsize = path.size();
590 size_t prefixsize = prefix.size();
591 size_t prefixpos = 0;
593 bool delim1 = pathpos == pathsize
594 || IsDirDelimiter(path[pathpos]);
595 bool delim2 = prefixpos == prefixsize
596 || IsDirDelimiter(prefix[prefixpos]);
602 while(pathpos < pathsize &&
603 IsDirDelimiter(path[pathpos]))
605 while(prefixpos < prefixsize &&
606 IsDirDelimiter(prefix[prefixpos]))
608 if(prefixpos == prefixsize)
610 if(pathpos == pathsize)
616 char pathchar = path[pathpos+len];
617 char prefixchar = prefix[prefixpos+len];
618 if(FILESYS_CASE_INSENSITIVE){
619 pathchar = tolower(pathchar);
620 prefixchar = tolower(prefixchar);
622 if(pathchar != prefixchar)
625 } while(pathpos+len < pathsize
626 && !IsDirDelimiter(path[pathpos+len])
627 && prefixpos+len < prefixsize
629 prefix[prefixpos+len]));
636 std::string RemoveLastPathComponent(const std::string &path,
637 std::string *removed, int count)
642 size_t remaining = path.size();
644 for(int i = 0; i < count; ++i){
645 // strip a dir delimiter
646 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
648 // strip a path component
649 size_t component_end = remaining;
650 while(remaining != 0 && !IsDirDelimiter(path[remaining-1]))
652 size_t component_start = remaining;
653 // strip a dir delimiter
654 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
657 std::string component = path.substr(component_start,
658 component_end - component_start);
660 *removed = component + DIR_DELIM + *removed;
662 *removed = component;
665 return path.substr(0, remaining);
668 std::string RemoveRelativePathComponents(std::string path)
670 size_t pos = path.size();
671 size_t dotdot_count = 0;
673 size_t component_with_delim_end = pos;
674 // skip a dir delimiter
675 while (pos != 0 && IsDirDelimiter(path[pos-1]))
677 // strip a path component
678 size_t component_end = pos;
679 while (pos != 0 && !IsDirDelimiter(path[pos-1]))
681 size_t component_start = pos;
683 std::string component = path.substr(component_start,
684 component_end - component_start);
685 bool remove_this_component = false;
686 if (component == ".") {
687 remove_this_component = true;
688 } else if (component == "..") {
689 remove_this_component = true;
691 } else if (dotdot_count != 0) {
692 remove_this_component = true;
696 if (remove_this_component) {
697 while (pos != 0 && IsDirDelimiter(path[pos-1]))
699 if (component_start == 0) {
700 // We need to remove the delemiter too
701 path = path.substr(component_with_delim_end, std::string::npos);
703 path = path.substr(0, pos) + DIR_DELIM +
704 path.substr(component_with_delim_end, std::string::npos);
711 if (dotdot_count > 0)
714 // remove trailing dir delimiters
716 while (pos != 0 && IsDirDelimiter(path[pos-1]))
718 return path.substr(0, pos);
721 std::string AbsolutePath(const std::string &path)
724 char *abs_path = _fullpath(NULL, path.c_str(), MAX_PATH);
726 char *abs_path = realpath(path.c_str(), NULL);
728 if (!abs_path) return "";
729 std::string abs_path_str(abs_path);
734 const char *GetFilenameFromPath(const char *path)
736 const char *filename = strrchr(path, DIR_DELIM_CHAR);
737 // Consistent with IsDirDelimiter this function handles '/' too
738 if (DIR_DELIM_CHAR != '/') {
739 const char *tmp = strrchr(path, '/');
740 if (tmp && tmp > filename)
743 return filename ? filename + 1 : path;
746 bool safeWriteToFile(const std::string &path, const std::string &content)
748 std::string tmp_file = path + ".~mt";
750 // Write to a tmp file
751 std::ofstream os(tmp_file.c_str(), std::ios::binary);
758 // Remove the temporary file because writing it failed and it's useless.
759 remove(tmp_file.c_str());
763 bool rename_success = false;
765 // Move the finished temporary file over the real file
767 // When creating the file, it can cause Windows Search indexer, virus scanners and other apps
768 // to query the file. This can make the move file call below fail.
769 // We retry up to 5 times, with a 1ms sleep between, before we consider the whole operation failed
770 int number_attempts = 0;
771 while (number_attempts < 5) {
772 rename_success = MoveFileEx(tmp_file.c_str(), path.c_str(),
773 MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH);
780 // On POSIX compliant systems rename() is specified to be able to swap the
781 // file in place of the destination file, making this a truly error-proof
783 rename_success = rename(tmp_file.c_str(), path.c_str()) == 0;
785 if (!rename_success) {
786 warningstream << "Failed to write to file: " << path.c_str() << std::endl;
787 // Remove the temporary file because moving it over the target file
789 remove(tmp_file.c_str());
797 bool extractZipFile(io::IFileSystem *fs, const char *filename, const std::string &destination)
799 // Be careful here not to touch the global file hierarchy in Irrlicht
800 // since this function needs to be thread-safe!
802 io::IArchiveLoader *zip_loader = nullptr;
803 for (u32 i = 0; i < fs->getArchiveLoaderCount(); i++) {
804 if (fs->getArchiveLoader(i)->isALoadableFileFormat(io::EFAT_ZIP)) {
805 zip_loader = fs->getArchiveLoader(i);
810 warningstream << "fs::extractZipFile(): Irrlicht said it doesn't support ZIPs." << std::endl;
814 irr_ptr<io::IFileArchive> opened_zip(zip_loader->createArchive(filename, false, false));
815 const io::IFileList* files_in_zip = opened_zip->getFileList();
817 for (u32 i = 0; i < files_in_zip->getFileCount(); i++) {
818 std::string fullpath = destination + DIR_DELIM;
819 fullpath += files_in_zip->getFullFileName(i).c_str();
820 std::string fullpath_dir = fs::RemoveLastPathComponent(fullpath);
822 if (files_in_zip->isDirectory(i))
823 continue; // ignore, we create dirs as necessary
825 if (!fs::PathExists(fullpath_dir) && !fs::CreateAllDirs(fullpath_dir))
828 irr_ptr<io::IReadFile> toread(opened_zip->createAndOpenFile(i));
830 std::ofstream os(fullpath.c_str(), std::ios::binary);
837 while (total_read < toread->getSize()) {
838 long bytes_read = toread->read(buffer, sizeof(buffer));
840 if (bytes_read != 0) {
841 os.write(buffer, bytes_read);
846 remove(fullpath.c_str());
849 total_read += bytes_read;
857 bool ReadFile(const std::string &path, std::string &out)
859 std::ifstream is(path, std::ios::binary | std::ios::ate);
864 auto size = is.tellg();
867 is.read(&out[0], size);
872 bool Rename(const std::string &from, const std::string &to)
874 return rename(from.c_str(), to.c_str()) == 0;