552012d2274f84fdceb49f219712401b767ba923
[ardour.git] / libs / pbd / file_utils.cc
1 /*
2     Copyright (C) 2007 Tim Mayberry 
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <algorithm>
21 #include <vector>
22
23 #include <glib.h>
24 #include <glib/gstdio.h>
25
26 #ifdef COMPILER_MINGW
27 #include <io.h> // For W_OK
28 #endif
29
30 #include <glibmm/fileutils.h>
31 #include <glibmm/miscutils.h>
32 #include <glibmm/pattern.h>
33
34 #include <errno.h>
35 #include <string.h> /* strerror */
36
37 /* open() */
38 #include <sys/types.h>
39 #include <sys/stat.h>
40 #include <fcntl.h>
41
42 /* close(), read(), write() */
43 #ifdef COMPILER_MSVC
44 #include <io.h> // Microsoft's nearest equivalent to <unistd.h>
45 #else
46 #include <unistd.h>
47 #endif
48
49 #include "pbd/compose.h"
50 #include "pbd/file_utils.h"
51 #include "pbd/debug.h"
52 #include "pbd/error.h"
53 #include "pbd/pathscanner.h"
54 #include "pbd/stl_delete.h"
55
56 #include "i18n.h"
57
58 using namespace std;
59
60 namespace PBD {
61
62 void
63 get_files_in_directory (const std::string& directory_path, vector<string>& result)
64 {
65         if (!Glib::file_test (directory_path, Glib::FILE_TEST_IS_DIR)) return;
66
67         try
68         {
69                 Glib::Dir dir(directory_path);
70                 std::copy(dir.begin(), dir.end(), std::back_inserter(result));
71         }
72         catch (Glib::FileError& err)
73         {
74                 warning << err.what() << endmsg;
75         }
76 }
77
78 void
79 find_matching_files_in_directory (const std::string& directory,
80                                   const Glib::PatternSpec& pattern,
81                                   vector<std::string>& result)
82 {
83         vector<string> tmp_files;
84
85         get_files_in_directory (directory, tmp_files);
86         result.reserve(tmp_files.size());
87
88         for (vector<string>::iterator file_iter = tmp_files.begin();
89                         file_iter != tmp_files.end();
90                         ++file_iter)
91         {
92                 if (!pattern.match(*file_iter)) continue;
93
94                 std::string full_path(directory);
95                 full_path = Glib::build_filename (full_path, *file_iter);
96
97                 DEBUG_TRACE (
98                         DEBUG::FileUtils,
99                         string_compose("Found file %1\n", full_path)
100                         );
101
102                 result.push_back(full_path);
103         }
104 }
105
106 void
107 find_matching_files_in_directories (const vector<std::string>& paths,
108                                     const Glib::PatternSpec& pattern,
109                                     vector<std::string>& result)
110 {
111         for (vector<std::string>::const_iterator path_iter = paths.begin();
112                         path_iter != paths.end();
113                         ++path_iter)
114         {
115                 find_matching_files_in_directory (*path_iter, pattern, result);
116         }               
117 }
118
119 void
120 find_matching_files_in_search_path (const Searchpath& search_path,
121                                     const Glib::PatternSpec& pattern,
122                                     vector<std::string>& result)
123 {
124         find_matching_files_in_directories (search_path, pattern, result);    
125 }
126
127 bool
128 find_file_in_search_path(const Searchpath& search_path,
129                          const string& filename,
130                          std::string& result)
131 {
132         vector<std::string> tmp;
133         Glib::PatternSpec tmp_pattern(filename);
134
135         find_matching_files_in_search_path (search_path, tmp_pattern, tmp);
136
137         if (tmp.size() == 0)
138         {
139                 DEBUG_TRACE (
140                         DEBUG::FileUtils,
141                         string_compose("No file matching %1 found in Path: %2\n", filename, search_path.to_string())
142                             );
143                 return false;
144         }
145
146         if (tmp.size() != 1)
147         {
148                 DEBUG_TRACE (
149                         DEBUG::FileUtils,
150                         string_compose("Found more that one file matching %1 in Path: %2\n", filename, search_path.to_string())
151                             );
152         }
153
154         result = tmp.front();
155
156         DEBUG_TRACE (
157                 DEBUG::FileUtils,
158                 string_compose("Found file %1 in Path: %2\n", filename, search_path.to_string())
159                     );
160
161         return true;
162 }
163
164 bool
165 copy_file(const std::string & from_path, const std::string & to_path)
166 {
167         if (!Glib::file_test (from_path, Glib::FILE_TEST_EXISTS)) return false;
168
169         int fd_from = -1;
170         int fd_to = -1;
171         char buf[4096]; // BUFSIZ  ??
172         ssize_t nread;
173
174         fd_from = ::open(from_path.c_str(), O_RDONLY);
175         if (fd_from < 0) {
176                 goto copy_error;
177         }
178
179         fd_to = ::open(to_path.c_str(), O_WRONLY | O_CREAT, 0666);
180         if (fd_to < 0) {
181                 goto copy_error;
182         }
183
184         while (nread = ::read(fd_from, buf, sizeof(buf)), nread > 0) {
185                 char *out_ptr = buf;
186                 do {
187                         ssize_t nwritten = ::write(fd_to, out_ptr, nread);
188                         if (nwritten >= 0) {
189                                 nread -= nwritten;
190                                 out_ptr += nwritten;
191                         } else if (errno != EINTR) {
192                                 goto copy_error;
193                         }
194                 } while (nread > 0);
195         }
196
197         if (nread == 0) {
198                 if (::close(fd_to)) {
199                         fd_to = -1;
200                         goto copy_error;
201                 }
202                 ::close(fd_from);
203                 return true;
204         }
205
206 copy_error:
207         int saved_errno = errno;
208
209         if (fd_from >= 0) {
210                 ::close(fd_from);
211         }
212         if (fd_to >= 0) {
213                 ::close(fd_to);
214         }
215
216         error << string_compose (_("Unable to Copy file %1 to %2 (%3)"),
217                         from_path, to_path, strerror(saved_errno))
218                 << endmsg;
219         return false;
220 }
221
222 static
223 bool accept_all_files (string const &, void *)
224 {
225         return true;
226 }
227
228 void
229 copy_files(const std::string & from_path, const std::string & to_dir)
230 {
231         PathScanner scanner;
232         vector<string> files = scanner (from_path, accept_all_files, 0, true, false);
233
234         for (vector<string>::iterator i = files.begin(); i != files.end(); ++i) {
235                 std::string from = Glib::build_filename (from_path, *i);
236                 std::string to = Glib::build_filename (to_dir, *i);
237                 copy_file (from, to);
238         }
239 }
240
241 std::string
242 get_absolute_path (const std::string & p)
243 {
244         if (Glib::path_is_absolute(p)) return p;
245         return Glib::build_filename (Glib::get_current_dir(), p);
246 }
247
248 bool
249 equivalent_paths (const std::string& a, const std::string& b)
250 {
251         GStatBuf bA;
252         int const rA = g_stat (a.c_str(), &bA);
253         GStatBuf bB;
254         int const rB = g_stat (b.c_str(), &bB);
255
256         return (rA == 0 && rB == 0 && bA.st_dev == bB.st_dev && bA.st_ino == bB.st_ino);
257 }
258
259 bool
260 path_is_within (std::string const & haystack, std::string needle)
261 {
262         while (1) {
263                 if (equivalent_paths (haystack, needle)) {
264                         return true;
265                 }
266
267                 needle = Glib::path_get_dirname (needle);
268                 if (needle == "." || needle == "/") {
269                         break;
270                 }
271         }
272
273         return false;
274 }
275
276 bool
277 exists_and_writable (const std::string & p)
278 {
279         /* writable() really reflects the whole folder, but if for any
280            reason the session state file can't be written to, still
281            make us unwritable.
282         */
283
284         GStatBuf statbuf;
285
286         if (g_stat (p.c_str(), &statbuf) != 0) {
287                 /* doesn't exist - not writable */
288                 return false;
289         } else {
290                 if (!(statbuf.st_mode & S_IWUSR)) {
291                         /* exists and is not writable */
292                         return false;
293                 }
294                 /* filesystem may be mounted read-only, so even though file
295                  * permissions permit access, the mount status does not.
296                  * access(2) seems like the best test for this.
297                  */
298                 if (g_access (p.c_str(), W_OK) != 0) {
299                         return false;
300                 }
301         }
302
303         return true;
304 }
305
306 } // namespace PBD