Branch data Line data Source code
1 : : // Copyright (c) 2009-2010 Satoshi Nakamoto
2 : : // Copyright (c) 2009-present The Bitcoin Core developers
3 : : // Distributed under the MIT software license, see the accompanying
4 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 : :
6 : : #include <bitcoin-build-config.h> // IWYU pragma: keep
7 : :
8 : : #include <util/fs_helpers.h>
9 : :
10 : : #include <sync.h>
11 : : #include <util/byte_units.h> // IWYU pragma: keep
12 : : #include <util/fs.h>
13 : : #include <util/log.h>
14 : : #include <util/syserror.h>
15 : :
16 : : #include <cerrno>
17 : : #include <fstream>
18 : : #include <map>
19 : : #include <memory>
20 : : #include <optional>
21 : : #include <string>
22 : : #include <system_error>
23 : : #include <utility>
24 : :
25 : : #ifndef WIN32
26 : : #include <fcntl.h>
27 : : #include <sys/resource.h>
28 : : #include <sys/types.h>
29 : : #include <unistd.h>
30 : : #else
31 : : #include <io.h>
32 : : #include <shlobj.h>
33 : : #endif // WIN32
34 : :
35 : : #ifdef __APPLE__
36 : : #include <sys/mount.h>
37 : : #include <sys/param.h>
38 : : #endif
39 : :
40 : : /** Mutex to protect dir_locks. */
41 : : static GlobalMutex cs_dir_locks;
42 : : /** A map that contains all the currently held directory locks. After
43 : : * successful locking, these will be held here until the global destructor
44 : : * cleans them up and thus automatically unlocks them, or ReleaseDirectoryLocks
45 : : * is called.
46 : : */
47 : : static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks GUARDED_BY(cs_dir_locks);
48 : : namespace util {
49 : 4624 : LockResult LockDirectory(const fs::path& directory, const fs::path& lockfile_name, bool probe_only)
50 : : {
51 : 4624 : LOCK(cs_dir_locks);
52 [ + - + - ]: 9248 : fs::path pathLockFile = directory / lockfile_name;
53 : :
54 : : // If a lock for this directory already exists in the map, don't try to re-lock it
55 [ - + + + ]: 9248 : if (dir_locks.contains(fs::PathToString(pathLockFile))) {
56 : : return LockResult::Success;
57 : : }
58 : :
59 : : // Create empty lock file if it doesn't exist.
60 [ + - + + ]: 4622 : if (auto created{fsbridge::fopen(pathLockFile, "a")}) {
61 [ + - ]: 4620 : std::fclose(created);
62 : : } else {
63 : : return LockResult::ErrorWrite;
64 : : }
65 [ + - ]: 4620 : auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile);
66 [ + - + + ]: 4620 : if (!lock->TryLock()) {
67 [ - + - + : 16 : LogError("Error while attempting to lock directory %s: %s\n", fs::PathToString(directory), lock->GetReason());
+ - ]
68 : 4 : return LockResult::ErrorLock;
69 : : }
70 [ + + ]: 4616 : if (!probe_only) {
71 : : // Lock successful and we're not just probing, put it into the map
72 [ - + + - ]: 6921 : dir_locks.emplace(fs::PathToString(pathLockFile), std::move(lock));
73 : : }
74 : : return LockResult::Success;
75 [ + - ]: 13868 : }
76 : : } // namespace util
77 : 0 : void UnlockDirectory(const fs::path& directory, const fs::path& lockfile_name)
78 : : {
79 : 0 : LOCK(cs_dir_locks);
80 [ # # # # : 0 : dir_locks.erase(fs::PathToString(directory / lockfile_name));
# # # # ]
81 : 0 : }
82 : :
83 : 3 : void ReleaseDirectoryLocks()
84 : : {
85 : 3 : LOCK(cs_dir_locks);
86 [ + - ]: 3 : dir_locks.clear();
87 : 3 : }
88 : :
89 : 11223 : bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes)
90 : : {
91 : 11223 : constexpr uint64_t min_disk_space{50_MiB};
92 : :
93 : 11223 : uint64_t free_bytes_available = fs::space(dir).available;
94 : 11223 : return free_bytes_available >= min_disk_space + additional_bytes;
95 : : }
96 : :
97 : 0 : std::streampos GetFileSize(const char* path, std::streamsize max)
98 : : {
99 : 0 : std::ifstream file{path, std::ios::binary};
100 [ # # ]: 0 : file.ignore(max);
101 : 0 : return file.gcount();
102 : 0 : }
103 : :
104 : 9862 : bool FileCommit(FILE* file)
105 : : {
106 [ - + ]: 9862 : if (fflush(file) != 0) { // harmless if redundantly called
107 [ # # ]: 0 : LogError("fflush failed: %s", SysErrorString(errno));
108 : 0 : return false;
109 : : }
110 : : #ifdef WIN32
111 : : HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
112 : : if (FlushFileBuffers(hFile) == 0) {
113 : : LogError("FlushFileBuffers failed: %s", Win32ErrorString(GetLastError()));
114 : : return false;
115 : : }
116 : : #elif defined(__APPLE__) && defined(F_FULLFSYNC)
117 : : if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success
118 : : LogError("fcntl F_FULLFSYNC failed: %s", SysErrorString(errno));
119 : : return false;
120 : : }
121 : : #elif HAVE_FDATASYNC
122 [ - + - - ]: 9862 : if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
123 [ # # ]: 0 : LogError("fdatasync failed: %s", SysErrorString(errno));
124 : 0 : return false;
125 : : }
126 : : #else
127 : : if (fsync(fileno(file)) != 0 && errno != EINVAL) {
128 : : LogError("fsync failed: %s", SysErrorString(errno));
129 : : return false;
130 : : }
131 : : #endif
132 : : return true;
133 : : }
134 : :
135 : 7243 : void DirectoryCommit(const fs::path& dirname)
136 : : {
137 : : #ifndef WIN32
138 : 7243 : FILE* file = fsbridge::fopen(dirname, "r");
139 [ + - ]: 7243 : if (file) {
140 : 7243 : fsync(fileno(file));
141 : 7243 : fclose(file);
142 : : }
143 : : #endif
144 : 7243 : }
145 : :
146 : 268 : bool TruncateFile(FILE* file, unsigned int length)
147 : : {
148 : : #if defined(WIN32)
149 : : return _chsize(_fileno(file), length) == 0;
150 : : #else
151 : 268 : return ftruncate(fileno(file), length) == 0;
152 : : #endif
153 : : }
154 : :
155 : : /**
156 : : * this function tries to raise the file descriptor limit to the requested number.
157 : : * It returns the actual file descriptor limit (which may be more or less than nMinFD)
158 : : */
159 : 1836 : int RaiseFileDescriptorLimit(int nMinFD)
160 : : {
161 : : #if defined(WIN32)
162 : : return 2048;
163 : : #else
164 : 1836 : struct rlimit limitFD;
165 [ + - ]: 1836 : if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
166 [ - + ]: 1836 : if (limitFD.rlim_cur < (rlim_t)nMinFD) {
167 : 0 : limitFD.rlim_cur = nMinFD;
168 [ # # ]: 0 : if (limitFD.rlim_cur > limitFD.rlim_max)
169 : 0 : limitFD.rlim_cur = limitFD.rlim_max;
170 : 0 : setrlimit(RLIMIT_NOFILE, &limitFD);
171 : 0 : getrlimit(RLIMIT_NOFILE, &limitFD);
172 : : }
173 : 1836 : return limitFD.rlim_cur;
174 : : }
175 : : return nMinFD; // getrlimit failed, assume it's fine
176 : : #endif
177 : : }
178 : :
179 : : /**
180 : : * this function tries to make a particular range of a file allocated (corresponding to disk space)
181 : : * it is advisory, and the range specified in the arguments will never contain live data
182 : : */
183 : 1689 : void AllocateFileRange(FILE* file, unsigned int offset, unsigned int length)
184 : : {
185 : : #if defined(WIN32)
186 : : // Windows-specific version
187 : : HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
188 : : LARGE_INTEGER nFileSize;
189 : : int64_t nEndPos = (int64_t)offset + length;
190 : : nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
191 : : nFileSize.u.HighPart = nEndPos >> 32;
192 : : SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
193 : : SetEndOfFile(hFile);
194 : : #elif defined(__APPLE__)
195 : : // OSX specific version
196 : : // NOTE: Contrary to other OS versions, the OSX version assumes that
197 : : // NOTE: offset is the size of the file.
198 : : fstore_t fst;
199 : : fst.fst_flags = F_ALLOCATECONTIG;
200 : : fst.fst_posmode = F_PEOFPOSMODE;
201 : : fst.fst_offset = 0;
202 : : fst.fst_length = length; // mac os fst_length takes the # of free bytes to allocate, not desired file size
203 : : fst.fst_bytesalloc = 0;
204 : : if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
205 : : fst.fst_flags = F_ALLOCATEALL;
206 : : fcntl(fileno(file), F_PREALLOCATE, &fst);
207 : : }
208 : : ftruncate(fileno(file), static_cast<off_t>(offset) + length);
209 : : #else
210 : : #if defined(HAVE_POSIX_FALLOCATE)
211 : : // Version using posix_fallocate
212 : 1689 : off_t nEndPos = (off_t)offset + length;
213 [ - + ]: 1689 : if (0 == posix_fallocate(fileno(file), 0, nEndPos)) return;
214 : : #endif
215 : : // Fallback version
216 : : // TODO: just write one byte per block
217 : 0 : static const char buf[65536] = {};
218 [ # # ]: 0 : if (fseek(file, offset, SEEK_SET)) {
219 : : return;
220 : : }
221 [ # # ]: 0 : while (length > 0) {
222 : 0 : unsigned int now = 65536;
223 [ # # ]: 0 : if (length < now)
224 : 0 : now = length;
225 : 0 : fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
226 : 0 : length -= now;
227 : : }
228 : : #endif
229 : : }
230 : :
231 : : #ifdef WIN32
232 : : fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
233 : : {
234 : : WCHAR pszPath[MAX_PATH] = L"";
235 : :
236 : : if (SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate)) {
237 : : return fs::path(pszPath);
238 : : }
239 : :
240 : : LogError("SHGetSpecialFolderPathW() failed, could not obtain requested path.");
241 : : return fs::path("");
242 : : }
243 : : #endif
244 : :
245 : 5039 : bool RenameOver(fs::path src, fs::path dest)
246 : : {
247 : 5039 : std::error_code error;
248 : 5039 : fs::rename(src, dest, error);
249 : 5039 : return !error;
250 : : }
251 : :
252 : : /**
253 : : * Ignores exceptions thrown by create_directories if the requested directory exists.
254 : : * Specifically handles case where path p exists, but it wasn't possible for the user to
255 : : * write to the parent directory.
256 : : */
257 : 4316 : bool TryCreateDirectories(const fs::path& p)
258 : : {
259 : 4316 : try {
260 [ + + ]: 4316 : return fs::create_directories(p);
261 [ - + ]: 2 : } catch (const fs::filesystem_error&) {
262 [ + - - + : 2 : if (!fs::exists(p) || !fs::is_directory(p))
- - - - ]
263 : 2 : throw;
264 : 2 : }
265 : :
266 : : // create_directories didn't create the directory, it had to have existed already
267 : 0 : return false;
268 : : }
269 : :
270 : 1134 : std::string PermsToSymbolicString(fs::perms p)
271 : : {
272 [ + - ]: 1134 : std::string perm_str(9, '-');
273 : :
274 : 10206 : auto set_perm = [&](size_t pos, fs::perms required_perm, char letter) {
275 : 10206 : if ((p & required_perm) != fs::perms::none) {
276 : 2271 : perm_str[pos] = letter;
277 : : }
278 : 1134 : };
279 : :
280 [ + - ]: 1134 : set_perm(0, fs::perms::owner_read, 'r');
281 [ + - ]: 1134 : set_perm(1, fs::perms::owner_write, 'w');
282 [ - + ]: 1134 : set_perm(2, fs::perms::owner_exec, 'x');
283 [ + + ]: 1134 : set_perm(3, fs::perms::group_read, 'r');
284 [ - + ]: 1134 : set_perm(4, fs::perms::group_write, 'w');
285 [ - + ]: 1134 : set_perm(5, fs::perms::group_exec, 'x');
286 [ + + ]: 1134 : set_perm(6, fs::perms::others_read, 'r');
287 [ - + ]: 1134 : set_perm(7, fs::perms::others_write, 'w');
288 [ - + ]: 1134 : set_perm(8, fs::perms::others_exec, 'x');
289 : :
290 : 1134 : return perm_str;
291 : : }
292 : :
293 : 3 : std::optional<fs::perms> InterpretPermString(const std::string& s)
294 : : {
295 [ + + ]: 3 : if (s == "owner") {
296 : 1 : return fs::perms::owner_read | fs::perms::owner_write;
297 [ + + ]: 2 : } else if (s == "group") {
298 : 1 : return fs::perms::owner_read | fs::perms::owner_write |
299 : 1 : fs::perms::group_read;
300 [ + - ]: 1 : } else if (s == "all") {
301 : 1 : return fs::perms::owner_read | fs::perms::owner_write |
302 : 1 : fs::perms::group_read |
303 : 1 : fs::perms::others_read;
304 : : } else {
305 : 0 : return std::nullopt;
306 : : }
307 : : }
308 : :
309 : : #ifdef __APPLE__
310 : : FSType GetFilesystemType(const fs::path& path)
311 : : {
312 : : if (struct statfs fs_info; statfs(path.c_str(), &fs_info)) {
313 : : return FSType::ERROR;
314 : : } else if (std::string_view{fs_info.f_fstypename} == "exfat") {
315 : : return FSType::EXFAT;
316 : : }
317 : : return FSType::OTHER;
318 : : }
319 : : #endif
|