Better file/directory removal platform code and utilities
[oweals/minetest.git] / src / filesys.cpp
1 /*
2 Minetest-c55
3 Copyright (C) 2010 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 "strfnd.h"
22 #include <iostream>
23 #include <string.h>
24 #include "log.h"
25
26 namespace fs
27 {
28
29 #ifdef _WIN32 // WINDOWS
30
31 #define _WIN32_WINNT 0x0501
32 #include <windows.h>
33 #include <stdio.h>
34 #include <malloc.h>
35 #include <tchar.h> 
36 #include <wchar.h> 
37 #include <stdio.h>
38
39 #define BUFSIZE MAX_PATH
40
41 std::vector<DirListNode> GetDirListing(std::string pathstring)
42 {
43         std::vector<DirListNode> listing;
44
45         WIN32_FIND_DATA FindFileData;
46         HANDLE hFind = INVALID_HANDLE_VALUE;
47         DWORD dwError;
48         LPTSTR DirSpec;
49         INT retval;
50
51         DirSpec = (LPTSTR) malloc (BUFSIZE);
52
53         if( DirSpec == NULL )
54         {
55           errorstream<<"GetDirListing: Insufficient memory available"<<std::endl;
56           retval = 1;
57           goto Cleanup;
58         }
59
60         // Check that the input is not larger than allowed.
61         if (pathstring.size() > (BUFSIZE - 2))
62         {
63           errorstream<<"GetDirListing: Input directory is too large."<<std::endl;
64           retval = 3;
65           goto Cleanup;
66         }
67
68         //_tprintf (TEXT("Target directory is %s.\n"), pathstring.c_str());
69
70         sprintf(DirSpec, "%s", (pathstring + "\\*").c_str());
71
72         // Find the first file in the directory.
73         hFind = FindFirstFile(DirSpec, &FindFileData);
74
75         if (hFind == INVALID_HANDLE_VALUE) 
76         {
77                 retval = (-1);
78                 goto Cleanup;
79         } 
80         else 
81         {
82                 // NOTE:
83                 // Be very sure to not include '..' in the results, it will
84                 // result in an epic failure when deleting stuff.
85
86                 DirListNode node;
87                 node.name = FindFileData.cFileName;
88                 node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
89                 if(node.name != "." && node.name != "..")
90                         listing.push_back(node);
91
92                 // List all the other files in the directory.
93                 while (FindNextFile(hFind, &FindFileData) != 0) 
94                 {
95                         DirListNode node;
96                         node.name = FindFileData.cFileName;
97                         node.dir = FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
98                         if(node.name != "." && node.name != "..")
99                                 listing.push_back(node);
100                 }
101
102                 dwError = GetLastError();
103                 FindClose(hFind);
104                 if (dwError != ERROR_NO_MORE_FILES) 
105                 {
106                         errorstream<<"GetDirListing: FindNextFile error. Error is "
107                                         <<dwError<<std::endl;
108                         retval = (-1);
109                         goto Cleanup;
110                 }
111         }
112         retval  = 0;
113
114 Cleanup:
115         free(DirSpec);
116
117         if(retval != 0) listing.clear();
118
119         //for(unsigned int i=0; i<listing.size(); i++){
120         //      infostream<<listing[i].name<<(listing[i].dir?" (dir)":" (file)")<<std::endl;
121         //}
122         
123         return listing;
124 }
125
126 bool CreateDir(std::string path)
127 {
128         bool r = CreateDirectory(path.c_str(), NULL);
129         if(r == true)
130                 return true;
131         if(GetLastError() == ERROR_ALREADY_EXISTS)
132                 return true;
133         return false;
134 }
135
136 bool PathExists(std::string path)
137 {
138         return (GetFileAttributes(path.c_str()) != INVALID_FILE_ATTRIBUTES);
139 }
140
141 bool IsDir(std::string path)
142 {
143         DWORD attr = GetFileAttributes(path.c_str());
144         return (attr != INVALID_FILE_ATTRIBUTES &&
145                         (attr & FILE_ATTRIBUTE_DIRECTORY));
146 }
147
148 bool RecursiveDelete(std::string path)
149 {
150         infostream<<"Recursively deleting \""<<path<<"\""<<std::endl;
151
152         DWORD attr = GetFileAttributes(path.c_str());
153         bool is_directory = (attr != INVALID_FILE_ATTRIBUTES &&
154                         (attr & FILE_ATTRIBUTE_DIRECTORY));
155         if(!is_directory)
156         {
157                 infostream<<"RecursiveDelete: Deleting file "<<path<<std::endl;
158                 //bool did = DeleteFile(path.c_str());
159                 bool did = true;
160                 if(!did){
161                         errorstream<<"RecursiveDelete: Failed to delete file "
162                                         <<path<<std::endl;
163                         return false;
164                 }
165         }
166         else
167         {
168                 infostream<<"RecursiveDelete: Deleting content of directory "
169                                 <<path<<std::endl;
170                 std::vector<DirListNode> content = GetDirListing(path);
171                 for(int i=0; i<content.size(); i++){
172                         const DirListNode &n = content[i];
173                         std::string fullpath = path + DIR_DELIM + n.name;
174                         bool did = RecursiveDelete(fullpath);
175                         if(!did){
176                                 errorstream<<"RecursiveDelete: Failed to recurse to "
177                                                 <<fullpath<<std::endl;
178                                 return false;
179                         }
180                 }
181                 infostream<<"RecursiveDelete: Deleting directory "<<path<<std::endl;
182                 //bool did = RemoveDirectory(path.c_str();
183                 bool did = true;
184                 if(!did){
185                         errorstream<<"Failed to recursively delete directory "
186                                         <<path<<std::endl;
187                         return false;
188                 }
189         }
190         return true;
191 }
192
193 bool DeleteSingleFileOrEmptyDirectory(std::string path)
194 {
195         DWORD attr = GetFileAttributes(path.c_str());
196         bool is_directory = (attr != INVALID_FILE_ATTRIBUTES &&
197                         (attr & FILE_ATTRIBUTE_DIRECTORY));
198         if(!is_directory)
199         {
200                 bool did = DeleteFile(path.c_str());
201                 return did;
202         }
203         else
204         {
205                 bool did = RemoveDirectory(path.c_str());
206                 return did;
207         }
208 }
209
210 #else // POSIX
211
212 #include <sys/types.h>
213 #include <dirent.h>
214 #include <errno.h>
215 #include <sys/stat.h>
216 #include <sys/wait.h>
217
218 std::vector<DirListNode> GetDirListing(std::string pathstring)
219 {
220         std::vector<DirListNode> listing;
221
222     DIR *dp;
223     struct dirent *dirp;
224     if((dp  = opendir(pathstring.c_str())) == NULL) {
225                 //infostream<<"Error("<<errno<<") opening "<<pathstring<<std::endl;
226         return listing;
227     }
228
229     while ((dirp = readdir(dp)) != NULL) {
230                 // NOTE:
231                 // Be very sure to not include '..' in the results, it will
232                 // result in an epic failure when deleting stuff.
233                 if(dirp->d_name[0]!='.'){
234                         DirListNode node;
235                         node.name = dirp->d_name;
236                         if(node.name == "." || node.name == "..")
237                                 continue;
238
239                         int isdir = -1; // -1 means unknown
240
241                         /*
242                                 POSIX doesn't define d_type member of struct dirent and
243                                 certain filesystems on glibc/Linux will only return
244                                 DT_UNKNOWN for the d_type member.
245
246                                 Also we don't know whether symlinks are directories or not.
247                         */
248 #ifdef _DIRENT_HAVE_D_TYPE
249                         if(dirp->d_type != DT_UNKNOWN && dirp->d_type != DT_LNK)
250                                 isdir = (dirp->d_type == DT_DIR);
251 #endif /* _DIRENT_HAVE_D_TYPE */
252
253                         /*
254                                 Was d_type DT_UNKNOWN, DT_LNK or nonexistent?
255                                 If so, try stat().
256                         */
257                         if(isdir == -1)
258                         {
259                                 struct stat statbuf;
260                                 if (stat((pathstring + "/" + node.name).c_str(), &statbuf))
261                                         continue;
262                                 isdir = ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
263                         }
264                         node.dir = isdir;
265                         listing.push_back(node);
266                 }
267     }
268     closedir(dp);
269
270         return listing;
271 }
272
273 bool CreateDir(std::string path)
274 {
275         int r = mkdir(path.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
276         if(r == 0)
277         {
278                 return true;
279         }
280         else
281         {
282                 // If already exists, return true
283                 if(errno == EEXIST)
284                         return true;
285                 return false;
286         }
287 }
288
289 bool PathExists(std::string path)
290 {
291         struct stat st;
292         return (stat(path.c_str(),&st) == 0);
293 }
294
295 bool IsDir(std::string path)
296 {
297         struct stat statbuf;
298         if(stat(path.c_str(), &statbuf))
299                 return false; // Actually error; but certainly not a directory
300         return ((statbuf.st_mode & S_IFDIR) == S_IFDIR);
301 }
302
303 bool RecursiveDelete(std::string path)
304 {
305         /*
306                 Execute the 'rm' command directly, by fork() and execve()
307         */
308         
309         infostream<<"Removing \""<<path<<"\""<<std::endl;
310
311         //return false;
312         
313         pid_t child_pid = fork();
314
315         if(child_pid == 0)
316         {
317                 // Child
318                 char argv_data[3][10000];
319                 strcpy(argv_data[0], "/bin/rm");
320                 strcpy(argv_data[1], "-rf");
321                 strncpy(argv_data[2], path.c_str(), 10000);
322                 char *argv[4];
323                 argv[0] = argv_data[0];
324                 argv[1] = argv_data[1];
325                 argv[2] = argv_data[2];
326                 argv[3] = NULL;
327
328                 verbosestream<<"Executing '"<<argv[0]<<"' '"<<argv[1]<<"' '"
329                                 <<argv[2]<<"'"<<std::endl;
330                 
331                 execv(argv[0], argv);
332                 
333                 // Execv shouldn't return. Failed.
334                 _exit(1);
335         }
336         else
337         {
338                 // Parent
339                 int child_status;
340                 pid_t tpid;
341                 do{
342                         tpid = wait(&child_status);
343                         //if(tpid != child_pid) process_terminated(tpid);
344                 }while(tpid != child_pid);
345                 return (child_status == 0);
346         }
347 }
348
349 bool DeleteSingleFileOrEmptyDirectory(std::string path)
350 {
351         if(IsDir(path)){
352                 bool did = (rmdir(path.c_str()) == 0);
353                 if(!did)
354                         errorstream<<"rmdir errno: "<<errno<<": "<<strerror(errno)
355                                         <<std::endl;
356                 return did;
357         } else {
358                 bool did = (unlink(path.c_str()) == 0);
359                 if(!did)
360                         errorstream<<"unlink errno: "<<errno<<": "<<strerror(errno)
361                                         <<std::endl;
362                 return did;
363         }
364 }
365
366 #endif
367
368 void GetRecursiveSubPaths(std::string path, std::vector<std::string> &dst)
369 {
370         std::vector<DirListNode> content = GetDirListing(path);
371         for(unsigned int  i=0; i<content.size(); i++){
372                 const DirListNode &n = content[i];
373                 std::string fullpath = path + DIR_DELIM + n.name;
374                 dst.push_back(fullpath);
375                 GetRecursiveSubPaths(fullpath, dst);
376         }
377 }
378
379 bool DeletePaths(const std::vector<std::string> &paths)
380 {
381         bool success = true;
382         // Go backwards to succesfully delete the output of GetRecursiveSubPaths
383         for(int i=paths.size()-1; i>=0; i--){
384                 const std::string &path = paths[i];
385                 bool did = DeleteSingleFileOrEmptyDirectory(path);
386                 if(!did){
387                         errorstream<<"Failed to delete "<<path<<std::endl;
388                         success = false;
389                 }
390         }
391         return success;
392 }
393
394 bool RecursiveDeleteContent(std::string path)
395 {
396         infostream<<"Removing content of \""<<path<<"\""<<std::endl;
397         std::vector<DirListNode> list = GetDirListing(path);
398         for(unsigned int i=0; i<list.size(); i++)
399         {
400                 if(trim(list[i].name) == "." || trim(list[i].name) == "..")
401                         continue;
402                 std::string childpath = path + DIR_DELIM + list[i].name;
403                 bool r = RecursiveDelete(childpath);
404                 if(r == false)
405                 {
406                         errorstream<<"Removing \""<<childpath<<"\" failed"<<std::endl;
407                         return false;
408                 }
409         }
410         return true;
411 }
412
413 bool CreateAllDirs(std::string path)
414 {
415
416         size_t pos;
417         std::vector<std::string> tocreate;
418         std::string basepath = path;
419         while(!PathExists(basepath))
420         {
421                 tocreate.push_back(basepath);
422                 pos = basepath.rfind(DIR_DELIM_C);
423                 if(pos == std::string::npos)
424                         break;
425                 basepath = basepath.substr(0,pos);
426         }
427         for(int i=tocreate.size()-1;i>=0;i--)
428                 if(!CreateDir(tocreate[i]))
429                         return false;
430         return true;
431 }
432
433 } // namespace fs
434