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"
45 #define _WIN32_WINNT 0x0501
52 std::vector<DirListNode> GetDirListing(const std::string &pathstring)
54 std::vector<DirListNode> listing;
56 WIN32_FIND_DATA FindFileData;
57 HANDLE hFind = INVALID_HANDLE_VALUE;
60 std::string dirSpec = pathstring + "\\*";
62 // Find the first file in the directory.
63 hFind = FindFirstFile(dirSpec.c_str(), &FindFileData);
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;
73 // Be very sure to not include '..' in the results, it will
74 // result in an epic failure when deleting stuff.
77 node.name = FindFileData.cFileName;
78 node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
79 if (node.name != "." && node.name != "..")
80 listing.push_back(node);
82 // List all the other files in the directory.
83 while (FindNextFile(hFind, &FindFileData) != 0) {
85 node.name = FindFileData.cFileName;
86 node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
87 if(node.name != "." && node.name != "..")
88 listing.push_back(node);
91 dwError = GetLastError();
93 if (dwError != ERROR_NO_MORE_FILES) {
94 errorstream << "GetDirListing: FindNextFile error."
95 << " Error is " << dwError << std::endl;
103 bool CreateDir(const std::string &path)
105 bool r = CreateDirectory(path.c_str(), NULL);
108 if(GetLastError() == ERROR_ALREADY_EXISTS)
113 bool PathExists(const std::string &path)
115 return (GetFileAttributes(path.c_str()) != INVALID_FILE_ATTRIBUTES);
118 bool IsPathAbsolute(const std::string &path)
120 return !PathIsRelative(path.c_str());
123 bool IsDir(const std::string &path)
125 DWORD attr = GetFileAttributes(path.c_str());
126 return (attr != INVALID_FILE_ATTRIBUTES &&
127 (attr & FILE_ATTRIBUTE_DIRECTORY));
130 bool IsDirDelimiter(char c)
132 return c == '/' || c == '\\';
135 bool RecursiveDelete(const std::string &path)
137 infostream << "Recursively deleting \"" << path << "\"" << std::endl;
139 infostream << "RecursiveDelete: Deleting file " << path << std::endl;
140 if (!DeleteFile(path.c_str())) {
141 errorstream << "RecursiveDelete: Failed to delete file "
142 << path << std::endl;
147 infostream << "RecursiveDelete: Deleting content of directory "
148 << path << std::endl;
149 std::vector<DirListNode> content = GetDirListing(path);
150 for (const DirListNode &n: content) {
151 std::string fullpath = path + DIR_DELIM + n.name;
152 if (!RecursiveDelete(fullpath)) {
153 errorstream << "RecursiveDelete: Failed to recurse to "
154 << fullpath << std::endl;
158 infostream << "RecursiveDelete: Deleting directory " << path << std::endl;
159 if (!RemoveDirectory(path.c_str())) {
160 errorstream << "Failed to recursively delete directory "
161 << path << std::endl;
167 bool DeleteSingleFileOrEmptyDirectory(const std::string &path)
169 DWORD attr = GetFileAttributes(path.c_str());
170 bool is_directory = (attr != INVALID_FILE_ATTRIBUTES &&
171 (attr & FILE_ATTRIBUTE_DIRECTORY));
174 bool did = DeleteFile(path.c_str());
179 bool did = RemoveDirectory(path.c_str());
184 std::string TempPath()
186 DWORD bufsize = GetTempPath(0, NULL);
188 errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
193 DWORD len = GetTempPath(bufsize, &buf[0]);
194 if(len == 0 || len > bufsize){
195 errorstream<<"GetTempPath failed, error = "<<GetLastError()<<std::endl;
202 std::string CreateTempFile()
204 std::string path = TempPath() + DIR_DELIM "MT_XXXXXX";
205 _mktemp_s(&path[0], path.size() + 1); // modifies path
206 HANDLE file = CreateFile(path.c_str(), GENERIC_WRITE, 0, nullptr,
207 CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
208 if (file == INVALID_HANDLE_VALUE)
220 #include <sys/types.h>
222 #include <sys/stat.h>
223 #include <sys/wait.h>
226 std::vector<DirListNode> GetDirListing(const std::string &pathstring)
228 std::vector<DirListNode> listing;
232 if((dp = opendir(pathstring.c_str())) == NULL) {
233 //infostream<<"Error("<<errno<<") opening "<<pathstring<<std::endl;
237 while ((dirp = readdir(dp)) != NULL) {
239 // Be very sure to not include '..' in the results, it will
240 // result in an epic failure when deleting stuff.
241 if(strcmp(dirp->d_name, ".") == 0 || strcmp(dirp->d_name, "..") == 0)
245 node.name = dirp->d_name;
247 int isdir = -1; // -1 means unknown
250 POSIX doesn't define d_type member of struct dirent and
251 certain filesystems on glibc/Linux will only return
252 DT_UNKNOWN for the d_type member.
254 Also we don't know whether symlinks are directories or not.
256 #ifdef _DIRENT_HAVE_D_TYPE
257 if(dirp->d_type != DT_UNKNOWN && dirp->d_type != DT_LNK)
258 isdir = (dirp->d_type == DT_DIR);
259 #endif /* _DIRENT_HAVE_D_TYPE */
262 Was d_type DT_UNKNOWN, DT_LNK or nonexistent?
266 struct stat statbuf{};
267 if (stat((pathstring + "/" + node.name).c_str(), &statbuf))
269 isdir = ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
272 listing.push_back(node);
279 bool CreateDir(const std::string &path)
281 int r = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
286 // If already exists, return true
293 bool PathExists(const std::string &path)
296 return (stat(path.c_str(),&st) == 0);
299 bool IsPathAbsolute(const std::string &path)
301 return path[0] == '/';
304 bool IsDir(const std::string &path)
306 struct stat statbuf{};
307 if(stat(path.c_str(), &statbuf))
308 return false; // Actually error; but certainly not a directory
309 return ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
312 bool IsDirDelimiter(char c)
317 bool RecursiveDelete(const std::string &path)
320 Execute the 'rm' command directly, by fork() and execve()
323 infostream<<"Removing \""<<path<<"\""<<std::endl;
325 pid_t child_pid = fork();
330 const char *argv[4] = {
341 verbosestream<<"Executing '"<<argv[0]<<"' '"<<argv[1]<<"' '"
342 <<argv[2]<<"'"<<std::endl;
344 execv(argv[0], const_cast<char**>(argv));
346 // Execv shouldn't return. Failed.
355 tpid = wait(&child_status);
356 }while(tpid != child_pid);
357 return (child_status == 0);
361 bool DeleteSingleFileOrEmptyDirectory(const std::string &path)
364 bool did = (rmdir(path.c_str()) == 0);
366 errorstream << "rmdir errno: " << errno << ": " << strerror(errno)
371 bool did = (unlink(path.c_str()) == 0);
373 errorstream << "unlink errno: " << errno << ": " << strerror(errno)
378 std::string TempPath()
381 Should the environment variables TMPDIR, TMP and TEMP
382 and the macro P_tmpdir (if defined by stdio.h) be checked
383 before falling back on /tmp?
385 Probably not, because this function is intended to be
386 compatible with lua's os.tmpname which under the default
387 configuration hardcodes mkstemp("/tmp/lua_XXXXXX").
391 return porting::path_cache;
393 return DIR_DELIM "tmp";
397 std::string CreateTempFile()
399 std::string path = TempPath() + DIR_DELIM "MT_XXXXXX";
400 int fd = mkstemp(&path[0]); // modifies path
409 /****************************
410 * portable implementations *
411 ****************************/
413 void GetRecursiveDirs(std::vector<std::string> &dirs, const std::string &dir)
415 static const std::set<char> chars_to_ignore = { '_', '.' };
416 if (dir.empty() || !IsDir(dir))
419 fs::GetRecursiveSubPaths(dir, dirs, false, chars_to_ignore);
422 std::vector<std::string> GetRecursiveDirs(const std::string &dir)
424 std::vector<std::string> result;
425 GetRecursiveDirs(result, dir);
429 void GetRecursiveSubPaths(const std::string &path,
430 std::vector<std::string> &dst,
432 const std::set<char> &ignore)
434 std::vector<DirListNode> content = GetDirListing(path);
435 for (const auto &n : content) {
436 std::string fullpath = path + DIR_DELIM + n.name;
437 if (ignore.count(n.name[0]))
439 if (list_files || n.dir)
440 dst.push_back(fullpath);
442 GetRecursiveSubPaths(fullpath, dst, list_files, ignore);
446 bool RecursiveDeleteContent(const std::string &path)
448 infostream<<"Removing content of \""<<path<<"\""<<std::endl;
449 std::vector<DirListNode> list = GetDirListing(path);
450 for (const DirListNode &dln : list) {
451 if(trim(dln.name) == "." || trim(dln.name) == "..")
453 std::string childpath = path + DIR_DELIM + dln.name;
454 bool r = RecursiveDelete(childpath);
456 errorstream << "Removing \"" << childpath << "\" failed" << std::endl;
463 bool CreateAllDirs(const std::string &path)
466 std::vector<std::string> tocreate;
467 std::string basepath = path;
468 while(!PathExists(basepath))
470 tocreate.push_back(basepath);
471 basepath = RemoveLastPathComponent(basepath);
475 for(int i=tocreate.size()-1;i>=0;i--)
476 if(!CreateDir(tocreate[i]))
481 bool CopyFileContents(const std::string &source, const std::string &target)
483 FILE *sourcefile = fopen(source.c_str(), "rb");
484 if(sourcefile == NULL){
485 errorstream<<source<<": can't open for reading: "
486 <<strerror(errno)<<std::endl;
490 FILE *targetfile = fopen(target.c_str(), "wb");
491 if(targetfile == NULL){
492 errorstream<<target<<": can't open for writing: "
493 <<strerror(errno)<<std::endl;
501 char readbuffer[BUFSIZ];
503 size_t readbytes = fread(readbuffer, 1,
504 sizeof(readbuffer), sourcefile);
506 if(ferror(sourcefile)){
507 errorstream<<source<<": IO error: "
508 <<strerror(errno)<<std::endl;
513 fwrite(readbuffer, 1, readbytes, targetfile);
515 if(feof(sourcefile) || ferror(sourcefile)){
516 // flush destination file to catch write errors
521 if(ferror(targetfile)){
522 errorstream<<target<<": IO error: "
523 <<strerror(errno)<<std::endl;
528 infostream<<"copied "<<total<<" bytes from "
529 <<source<<" to "<<target<<std::endl;
535 bool CopyDir(const std::string &source, const std::string &target)
537 if(PathExists(source)){
538 if(!PathExists(target)){
539 fs::CreateAllDirs(target);
542 std::vector<DirListNode> content = fs::GetDirListing(source);
544 for (const auto &dln : content) {
545 std::string sourcechild = source + DIR_DELIM + dln.name;
546 std::string targetchild = target + DIR_DELIM + dln.name;
548 if(!fs::CopyDir(sourcechild, targetchild)){
553 if(!fs::CopyFileContents(sourcechild, targetchild)){
564 bool MoveDir(const std::string &source, const std::string &target)
566 infostream << "Moving \"" << source << "\" to \"" << target << "\"" << std::endl;
568 // If target exists as empty folder delete, otherwise error
569 if (fs::PathExists(target)) {
570 if (rmdir(target.c_str()) != 0) {
571 errorstream << "MoveDir: target \"" << target
572 << "\" exists as file or non-empty folder" << std::endl;
577 // Try renaming first which is instant
578 if (fs::Rename(source, target))
581 infostream << "MoveDir: rename not possible, will copy instead" << std::endl;
582 bool retval = fs::CopyDir(source, target);
584 retval &= fs::RecursiveDelete(source);
588 bool PathStartsWith(const std::string &path, const std::string &prefix)
590 size_t pathsize = path.size();
592 size_t prefixsize = prefix.size();
593 size_t prefixpos = 0;
595 bool delim1 = pathpos == pathsize
596 || IsDirDelimiter(path[pathpos]);
597 bool delim2 = prefixpos == prefixsize
598 || IsDirDelimiter(prefix[prefixpos]);
604 while(pathpos < pathsize &&
605 IsDirDelimiter(path[pathpos]))
607 while(prefixpos < prefixsize &&
608 IsDirDelimiter(prefix[prefixpos]))
610 if(prefixpos == prefixsize)
612 if(pathpos == pathsize)
618 char pathchar = path[pathpos+len];
619 char prefixchar = prefix[prefixpos+len];
620 if(FILESYS_CASE_INSENSITIVE){
621 pathchar = tolower(pathchar);
622 prefixchar = tolower(prefixchar);
624 if(pathchar != prefixchar)
627 } while(pathpos+len < pathsize
628 && !IsDirDelimiter(path[pathpos+len])
629 && prefixpos+len < prefixsize
631 prefix[prefixpos+len]));
638 std::string RemoveLastPathComponent(const std::string &path,
639 std::string *removed, int count)
644 size_t remaining = path.size();
646 for(int i = 0; i < count; ++i){
647 // strip a dir delimiter
648 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
650 // strip a path component
651 size_t component_end = remaining;
652 while(remaining != 0 && !IsDirDelimiter(path[remaining-1]))
654 size_t component_start = remaining;
655 // strip a dir delimiter
656 while(remaining != 0 && IsDirDelimiter(path[remaining-1]))
659 std::string component = path.substr(component_start,
660 component_end - component_start);
662 *removed = component + DIR_DELIM + *removed;
664 *removed = component;
667 return path.substr(0, remaining);
670 std::string RemoveRelativePathComponents(std::string path)
672 size_t pos = path.size();
673 size_t dotdot_count = 0;
675 size_t component_with_delim_end = pos;
676 // skip a dir delimiter
677 while (pos != 0 && IsDirDelimiter(path[pos-1]))
679 // strip a path component
680 size_t component_end = pos;
681 while (pos != 0 && !IsDirDelimiter(path[pos-1]))
683 size_t component_start = pos;
685 std::string component = path.substr(component_start,
686 component_end - component_start);
687 bool remove_this_component = false;
688 if (component == ".") {
689 remove_this_component = true;
690 } else if (component == "..") {
691 remove_this_component = true;
693 } else if (dotdot_count != 0) {
694 remove_this_component = true;
698 if (remove_this_component) {
699 while (pos != 0 && IsDirDelimiter(path[pos-1]))
701 if (component_start == 0) {
702 // We need to remove the delemiter too
703 path = path.substr(component_with_delim_end, std::string::npos);
705 path = path.substr(0, pos) + DIR_DELIM +
706 path.substr(component_with_delim_end, std::string::npos);
713 if (dotdot_count > 0)
716 // remove trailing dir delimiters
718 while (pos != 0 && IsDirDelimiter(path[pos-1]))
720 return path.substr(0, pos);
723 std::string AbsolutePath(const std::string &path)
726 char *abs_path = _fullpath(NULL, path.c_str(), MAX_PATH);
728 char *abs_path = realpath(path.c_str(), NULL);
730 if (!abs_path) return "";
731 std::string abs_path_str(abs_path);
736 const char *GetFilenameFromPath(const char *path)
738 const char *filename = strrchr(path, DIR_DELIM_CHAR);
739 // Consistent with IsDirDelimiter this function handles '/' too
740 if (DIR_DELIM_CHAR != '/') {
741 const char *tmp = strrchr(path, '/');
742 if (tmp && tmp > filename)
745 return filename ? filename + 1 : path;
748 bool safeWriteToFile(const std::string &path, const std::string &content)
750 std::string tmp_file = path + ".~mt";
752 // Write to a tmp file
753 std::ofstream os(tmp_file.c_str(), std::ios::binary);
760 // Remove the temporary file because writing it failed and it's useless.
761 remove(tmp_file.c_str());
765 bool rename_success = false;
767 // Move the finished temporary file over the real file
769 // When creating the file, it can cause Windows Search indexer, virus scanners and other apps
770 // to query the file. This can make the move file call below fail.
771 // We retry up to 5 times, with a 1ms sleep between, before we consider the whole operation failed
772 int number_attempts = 0;
773 while (number_attempts < 5) {
774 rename_success = MoveFileEx(tmp_file.c_str(), path.c_str(),
775 MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH);
782 // On POSIX compliant systems rename() is specified to be able to swap the
783 // file in place of the destination file, making this a truly error-proof
785 rename_success = rename(tmp_file.c_str(), path.c_str()) == 0;
787 if (!rename_success) {
788 warningstream << "Failed to write to file: " << path.c_str() << std::endl;
789 // Remove the temporary file because moving it over the target file
791 remove(tmp_file.c_str());
799 bool extractZipFile(io::IFileSystem *fs, const char *filename, const std::string &destination)
801 // Be careful here not to touch the global file hierarchy in Irrlicht
802 // since this function needs to be thread-safe!
804 io::IArchiveLoader *zip_loader = nullptr;
805 for (u32 i = 0; i < fs->getArchiveLoaderCount(); i++) {
806 if (fs->getArchiveLoader(i)->isALoadableFileFormat(io::EFAT_ZIP)) {
807 zip_loader = fs->getArchiveLoader(i);
812 warningstream << "fs::extractZipFile(): Irrlicht said it doesn't support ZIPs." << std::endl;
816 irr_ptr<io::IFileArchive> opened_zip(zip_loader->createArchive(filename, false, false));
817 const io::IFileList* files_in_zip = opened_zip->getFileList();
819 for (u32 i = 0; i < files_in_zip->getFileCount(); i++) {
820 std::string fullpath = destination + DIR_DELIM;
821 fullpath += files_in_zip->getFullFileName(i).c_str();
822 std::string fullpath_dir = fs::RemoveLastPathComponent(fullpath);
824 if (files_in_zip->isDirectory(i))
825 continue; // ignore, we create dirs as necessary
827 if (!fs::PathExists(fullpath_dir) && !fs::CreateAllDirs(fullpath_dir))
830 irr_ptr<io::IReadFile> toread(opened_zip->createAndOpenFile(i));
832 std::ofstream os(fullpath.c_str(), std::ios::binary);
839 while (total_read < toread->getSize()) {
840 long bytes_read = toread->read(buffer, sizeof(buffer));
842 if (bytes_read != 0) {
843 os.write(buffer, bytes_read);
848 remove(fullpath.c_str());
851 total_read += bytes_read;
859 bool ReadFile(const std::string &path, std::string &out)
861 std::ifstream is(path, std::ios::binary | std::ios::ate);
866 auto size = is.tellg();
869 is.read(&out[0], size);
874 bool Rename(const std::string &from, const std::string &to)
876 return rename(from.c_str(), to.c_str()) == 0;