Use stat to check that paths are equivalent
[alexxy/gromacs.git] / src / gromacs / fileio / path.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2011,2012,2013,2014,2015, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements functions in path.h.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_fileio
41  */
42 #include "path.h"
43
44 #include <cctype>
45 #include <cerrno>
46 #include <cstdlib>
47 #include <cstring>
48
49 #include <algorithm>
50
51 #include "config.h"
52
53 #include <sys/stat.h>
54 #ifdef GMX_NATIVE_WINDOWS
55 #include <Windows.h>
56 #include <direct.h>
57 #else
58 #ifdef HAVE_UNISTD_H
59 #include <unistd.h>
60 #endif
61 #endif
62
63 #include "gromacs/fileio/futil.h"
64 #include "gromacs/utility/exceptions.h"
65 #include "gromacs/utility/stringutil.h"
66
67 namespace
68 {
69
70 //! Directory separator to use when joining paths.
71 const char cDirSeparator = '/';
72 //! Directory separators to use when parsing paths.
73 const char cDirSeparators[] = "/\\";
74 /*! \var cPathSeparator
75  * \brief
76  * Separator to use to split the PATH environment variable.
77  *
78  * When reading the PATH environment variable, Unix separates entries
79  * with colon, while windows uses semicolon.
80  */
81 #ifdef GMX_NATIVE_WINDOWS
82 const char cPathSeparator = ';';
83 #else
84 const char cPathSeparator = ':';
85 #endif
86
87 //! Check whether a given character is a directory separator.
88 bool isDirSeparator(char chr)
89 {
90     return std::strchr(cDirSeparators, chr);
91 }
92
93 } // namespace
94
95 namespace gmx
96 {
97
98 /********************************************************************
99  * Path
100  */
101
102 bool Path::containsDirectory(const std::string &path)
103 {
104     return path.find_first_of(cDirSeparators) != std::string::npos;
105 }
106
107 /* Check if the program name begins with "/" on unix/cygwin, or
108  * with "\" or "X:\" on windows. If not, the program name
109  * is relative to the current directory.
110  */
111 bool Path::isAbsolute(const char *path)
112 {
113     if (isDirSeparator(path[0]))
114     {
115         return true;
116     }
117 #ifdef GMX_NATIVE_WINDOWS
118     return path[0] != '\0' && path[1] == ':' && isDirSeparator(path[2]);
119 #else
120     return false;
121 #endif
122 }
123
124 bool Path::isAbsolute(const std::string &path)
125 {
126     return isAbsolute(path.c_str());
127 }
128
129 #ifdef GMX_NATIVE_WINDOWS
130 namespace
131 {
132 struct handle_wrapper
133 {
134     HANDLE handle;
135     handle_wrapper(HANDLE h)
136         : handle(h){}
137     ~handle_wrapper()
138     {
139         if (handle != INVALID_HANDLE_VALUE)
140         {
141             ::CloseHandle(handle);
142         }
143     }
144 };
145 }
146 #endif
147
148 bool Path::isEquivalent(const std::string &path1, const std::string &path2)
149 {
150     //based on boost_1_56_0/libs/filesystem/src/operations.cpp under BSL
151 #ifdef GMX_NATIVE_WINDOWS
152     // Note well: Physical location on external media is part of the
153     // equivalence criteria. If there are no open handles, physical location
154     // can change due to defragmentation or other relocations. Thus handles
155     // must be held open until location information for both paths has
156     // been retrieved.
157
158     // p2 is done first, so any error reported is for p1
159     // FixME: #1635
160     handle_wrapper h2(
161             CreateFile(
162                     path2.c_str(),
163                     0,
164                     FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
165                     0,
166                     OPEN_EXISTING,
167                     FILE_FLAG_BACKUP_SEMANTICS,
168                     0));
169
170     handle_wrapper h1(
171             CreateFile(
172                     path1.c_str(),
173                     0,
174                     FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
175                     0,
176                     OPEN_EXISTING,
177                     FILE_FLAG_BACKUP_SEMANTICS,
178                     0));
179
180     if (h1.handle == INVALID_HANDLE_VALUE
181         || h2.handle == INVALID_HANDLE_VALUE)
182     {
183         // if one is invalid and the other isn't, then they aren't equivalent,
184         // but if both are invalid then it is an error
185         if (h1.handle == INVALID_HANDLE_VALUE
186             && h2.handle == INVALID_HANDLE_VALUE)
187         {
188             GMX_THROW(FileIOError("Path::isEquivalent called with two invalid files"));
189         }
190
191         return false;
192     }
193
194     // at this point, both handles are known to be valid
195
196     BY_HANDLE_FILE_INFORMATION info1, info2;
197
198     if (!GetFileInformationByHandle(h1.handle, &info1))
199     {
200         GMX_THROW(FileIOError("Path::isEquivalent: GetFileInformationByHandle failed"));
201     }
202
203     if (!GetFileInformationByHandle(h2.handle, &info2))
204     {
205         GMX_THROW(FileIOError("Path::isEquivalent: GetFileInformationByHandle failed"));
206     }
207
208     // In theory, volume serial numbers are sufficient to distinguish between
209     // devices, but in practice VSN's are sometimes duplicated, so last write
210     // time and file size are also checked.
211     return
212         info1.dwVolumeSerialNumber == info2.dwVolumeSerialNumber
213         && info1.nFileIndexHigh == info2.nFileIndexHigh
214         && info1.nFileIndexLow == info2.nFileIndexLow
215         && info1.nFileSizeHigh == info2.nFileSizeHigh
216         && info1.nFileSizeLow == info2.nFileSizeLow
217         && info1.ftLastWriteTime.dwLowDateTime
218         == info2.ftLastWriteTime.dwLowDateTime
219         && info1.ftLastWriteTime.dwHighDateTime
220         == info2.ftLastWriteTime.dwHighDateTime;
221 #else
222     struct stat s1, s2;
223     int         e2 = stat(path2.c_str(), &s2);
224     int         e1 = stat(path1.c_str(), &s1);
225
226     if (e1 != 0 || e2 != 0)
227     {
228         // if one is invalid and the other isn't then they aren't equivalent,
229         // but if both are invalid then it is an error.
230         if (e1 != 0 && e2 != 0)
231         {
232             GMX_THROW_WITH_ERRNO(
233                     FileIOError("Path::isEquivalent called with two invalid files"),
234                     "stat", errno);
235         }
236         return false;
237     }
238
239     // both stats now known to be valid
240     return s1.st_dev == s2.st_dev && s1.st_ino == s2.st_ino
241            // According to the POSIX stat specs, "The st_ino and st_dev fields
242            // taken together uniquely identify the file within the system."
243            // Just to be sure, size and mod time are also checked.
244            && s1.st_size == s2.st_size && s1.st_mtime == s2.st_mtime;
245 #endif
246 }
247
248 std::string Path::join(const std::string &path1,
249                        const std::string &path2)
250 {
251     // TODO: Remove extra separators if they are present in the input paths.
252     return path1 + cDirSeparator + path2;
253 }
254
255
256 std::string Path::join(const std::string &path1,
257                        const std::string &path2,
258                        const std::string &path3)
259 {
260     // TODO: Remove extra separators if they are present in the input paths.
261     return path1 + cDirSeparator + path2 + cDirSeparator + path3;
262 }
263
264 std::string Path::getParentPath(const std::string &path)
265 {
266     /* Expects that the path doesn't contain "." or "..". If used on a path for
267      * which this isn't guaranteed realpath needs to be called first. */
268     size_t pos = path.find_last_of(cDirSeparators);
269     if (pos == std::string::npos)
270     {
271         return std::string();
272     }
273     return path.substr(0, pos);
274 }
275
276 std::string Path::getFilename(const std::string &path)
277 {
278     size_t pos = path.find_last_of(cDirSeparators);
279     if (pos == std::string::npos)
280     {
281         return path;
282     }
283     return path.substr(pos+1);
284 }
285
286 std::string Path::normalize(const std::string &path)
287 {
288     std::string result(path);
289     if (DIR_SEPARATOR != '/')
290     {
291         std::replace(result.begin(), result.end(), '/', DIR_SEPARATOR);
292     }
293     return result;
294 }
295
296 bool Path::exists(const char *path)
297 {
298     return gmx_fexist(path);
299 }
300
301 bool Path::exists(const std::string &path)
302 {
303     return exists(path.c_str());
304 }
305
306 std::string Path::getWorkingDirectory()
307 {
308     // TODO: Use exceptions instead of gmx_fatal().
309     char cwd[GMX_PATH_MAX];
310     gmx_getcwd(cwd, sizeof(cwd));
311     return cwd;
312 }
313
314 void Path::splitPathEnvironment(const std::string        &pathEnv,
315                                 std::vector<std::string> *result)
316 {
317     size_t prevPos = 0;
318     size_t separator;
319     do
320     {
321         separator = pathEnv.find(cPathSeparator, prevPos);
322         result->push_back(pathEnv.substr(prevPos, separator - prevPos));
323         prevPos = separator + 1;
324     }
325     while (separator != std::string::npos);
326 }
327
328 std::vector<std::string> Path::getExecutablePaths()
329 {
330     std::vector<std::string> result;
331 #ifdef GMX_NATIVE_WINDOWS
332     // Add the local dir since it is not in the path on Windows.
333     result.push_back("");
334 #endif
335     const char *path = std::getenv("PATH");
336     if (path != NULL)
337     {
338         splitPathEnvironment(path, &result);
339     }
340     return result;
341 }
342
343 std::string Path::resolveSymlinks(const std::string &path)
344 {
345     /* Does not fully resolve the path like realpath/boost::canonical would.
346      * It doesn't resolve path elements (including "." or ".."), but only
347      * resolves the entire path (it does that recursively). */
348     std::string result(path);
349 #ifndef GMX_NATIVE_WINDOWS
350     char        buf[GMX_PATH_MAX];
351     int         length;
352     while ((length = readlink(result.c_str(), buf, sizeof(buf)-1)) > 0)
353     {
354         buf[length] = '\0';
355         if (isAbsolute(buf))
356         {
357             result = buf;
358         }
359         else
360         {
361             result = join(getParentPath(result), buf);
362         }
363     }
364 #endif
365     return result;
366 }
367
368
369 /********************************************************************
370  * Directory
371  */
372
373 int Directory::create(const char *path)
374 {
375     if (Directory::exists(path))
376     {
377         return 0;
378     }
379 #ifdef GMX_NATIVE_WINDOWS
380     if (_mkdir(path))
381 #else
382     if (mkdir(path, S_IRWXU | S_IRWXG | S_IROTH | S_IWOTH) != 0)
383 #endif
384     {
385         // TODO: Proper error handling.
386         return -1;
387     }
388     return 0;
389 }
390
391
392 int Directory::create(const std::string &path)
393 {
394     return create(path.c_str());
395 }
396
397
398 bool Directory::exists(const char *path)
399 {
400     struct stat info;
401     if (stat(path, &info) != 0)
402     {
403         if (errno != ENOENT && errno != ENOTDIR)
404         {
405             // TODO: Proper error handling.
406         }
407         return false;
408     }
409 #ifdef GMX_NATIVE_WINDOWS
410     return ((_S_IFDIR & info.st_mode) != 0);
411 #else
412     return S_ISDIR(info.st_mode);
413 #endif
414 }
415
416
417 bool Directory::exists(const std::string &path)
418 {
419     return exists(path.c_str());
420 }
421
422 } // namespace gmx