Bitcoin Core 31.99.0
P2P Digital Currency
fs_helpers.cpp
Go to the documentation of this file.
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
47static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks GUARDED_BY(cs_dir_locks);
48namespace util {
49LockResult LockDirectory(const fs::path& directory, const fs::path& lockfile_name, bool probe_only)
50{
52 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 if (dir_locks.contains(fs::PathToString(pathLockFile))) {
57 }
58
59 // Create empty lock file if it doesn't exist.
60 if (auto created{fsbridge::fopen(pathLockFile, "a")}) {
61 std::fclose(created);
62 } else {
64 }
65 auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile);
66 if (!lock->TryLock()) {
67 LogError("Error while attempting to lock directory %s: %s\n", fs::PathToString(directory), lock->GetReason());
69 }
70 if (!probe_only) {
71 // Lock successful and we're not just probing, put it into the map
72 dir_locks.emplace(fs::PathToString(pathLockFile), std::move(lock));
73 }
75}
76} // namespace util
77void UnlockDirectory(const fs::path& directory, const fs::path& lockfile_name)
78{
80 dir_locks.erase(fs::PathToString(directory / lockfile_name));
81}
82
84{
86 dir_locks.clear();
87}
88
89bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes)
90{
91 constexpr uint64_t min_disk_space{50_MiB};
92
93 uint64_t free_bytes_available = fs::space(dir).available;
94 return free_bytes_available >= min_disk_space + additional_bytes;
95}
96
97std::streampos GetFileSize(const char* path, std::streamsize max)
98{
99 std::ifstream file{path, std::ios::binary};
100 file.ignore(max);
101 return file.gcount();
102}
103
104bool FileCommit(FILE* file)
105{
106 if (fflush(file) != 0) { // harmless if redundantly called
107 LogError("fflush failed: %s", SysErrorString(errno));
108 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 if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
123 LogError("fdatasync failed: %s", SysErrorString(errno));
124 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
135void DirectoryCommit(const fs::path& dirname)
136{
137#ifndef WIN32
138 FILE* file = fsbridge::fopen(dirname, "r");
139 if (file) {
140 fsync(fileno(file));
141 fclose(file);
142 }
143#endif
144}
145
146bool TruncateFile(FILE* file, unsigned int length)
147{
148#if defined(WIN32)
149 return _chsize(_fileno(file), length) == 0;
150#else
151 return ftruncate(fileno(file), length) == 0;
152#endif
153}
154
160{
161#if defined(WIN32)
162 return 2048;
163#else
164 struct rlimit limitFD;
165 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
166 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
167 limitFD.rlim_cur = nMinFD;
168 if (limitFD.rlim_cur > limitFD.rlim_max)
169 limitFD.rlim_cur = limitFD.rlim_max;
170 setrlimit(RLIMIT_NOFILE, &limitFD);
171 getrlimit(RLIMIT_NOFILE, &limitFD);
172 }
173 return limitFD.rlim_cur;
174 }
175 return nMinFD; // getrlimit failed, assume it's fine
176#endif
177}
178
183void 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 off_t nEndPos = (off_t)offset + length;
213 if (0 == posix_fallocate(fileno(file), 0, nEndPos)) return;
214#endif
215 // Fallback version
216 // TODO: just write one byte per block
217 static const char buf[65536] = {};
218 if (fseek(file, offset, SEEK_SET)) {
219 return;
220 }
221 while (length > 0) {
222 unsigned int now = 65536;
223 if (length < now)
224 now = length;
225 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
226 length -= now;
227 }
228#endif
229}
230
231#ifdef WIN32
232fs::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
245bool RenameOver(fs::path src, fs::path dest)
246{
247 std::error_code error;
248 fs::rename(src, dest, error);
249 return !error;
250}
251
257bool TryCreateDirectories(const fs::path& p)
258{
259 try {
260 return fs::create_directories(p);
261 } catch (const fs::filesystem_error&) {
262 if (!fs::exists(p) || !fs::is_directory(p))
263 throw;
264 }
265
266 // create_directories didn't create the directory, it had to have existed already
267 return false;
268}
269
270std::string PermsToSymbolicString(fs::perms p)
271{
272 std::string perm_str(9, '-');
273
274 auto set_perm = [&](size_t pos, fs::perms required_perm, char letter) {
275 if ((p & required_perm) != fs::perms::none) {
276 perm_str[pos] = letter;
277 }
278 };
279
280 set_perm(0, fs::perms::owner_read, 'r');
281 set_perm(1, fs::perms::owner_write, 'w');
282 set_perm(2, fs::perms::owner_exec, 'x');
283 set_perm(3, fs::perms::group_read, 'r');
284 set_perm(4, fs::perms::group_write, 'w');
285 set_perm(5, fs::perms::group_exec, 'x');
286 set_perm(6, fs::perms::others_read, 'r');
287 set_perm(7, fs::perms::others_write, 'w');
288 set_perm(8, fs::perms::others_exec, 'x');
289
290 return perm_str;
291}
292
293std::optional<fs::perms> InterpretPermString(const std::string& s)
294{
295 if (s == "owner") {
296 return fs::perms::owner_read | fs::perms::owner_write;
297 } else if (s == "group") {
298 return fs::perms::owner_read | fs::perms::owner_write |
299 fs::perms::group_read;
300 } else if (s == "all") {
301 return fs::perms::owner_read | fs::perms::owner_write |
302 fs::perms::group_read |
303 fs::perms::others_read;
304 } else {
305 return std::nullopt;
306 }
307}
308
309#ifdef __APPLE__
310FSType 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
Different type to mark Mutex at global scope.
Definition: sync.h:142
#define MAX_PATH
Definition: compat.h:81
static bool exists(const path &p)
Definition: fs.h:96
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:162
static GlobalMutex cs_dir_locks
Mutex to protect dir_locks.
Definition: fs_helpers.cpp:41
bool RenameOver(fs::path src, fs::path dest)
Rename src to dest.
Definition: fs_helpers.cpp:245
std::streampos GetFileSize(const char *path, std::streamsize max)
Get the size of a file by scanning it.
Definition: fs_helpers.cpp:97
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: fs_helpers.cpp:159
void DirectoryCommit(const fs::path &dirname)
Sync directory contents.
Definition: fs_helpers.cpp:135
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: fs_helpers.cpp:83
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
Definition: fs_helpers.cpp:257
void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length)
this function tries to make a particular range of a file allocated (corresponding to disk space) it i...
Definition: fs_helpers.cpp:183
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: fs_helpers.cpp:89
std::optional< fs::perms > InterpretPermString(const std::string &s)
Interpret a custom permissions level string as fs::perms.
Definition: fs_helpers.cpp:293
bool TruncateFile(FILE *file, unsigned int length)
Definition: fs_helpers.cpp:146
static std::map< std::string, std::unique_ptr< fsbridge::FileLock > > dir_locks GUARDED_BY(cs_dir_locks)
A map that contains all the currently held directory locks.
std::string PermsToSymbolicString(fs::perms p)
Convert fs::perms to symbolic string of the form 'rwxrwxrwx'.
Definition: fs_helpers.cpp:270
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Definition: fs_helpers.cpp:104
void UnlockDirectory(const fs::path &directory, const fs::path &lockfile_name)
Definition: fs_helpers.cpp:77
#define LogError(...)
Definition: log.h:105
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:23
LockResult
Definition: fs_helpers.h:58
LockResult LockDirectory(const fs::path &directory, const fs::path &lockfile_name, bool probe_only)
Definition: fs_helpers.cpp:49
#define LOCK(cs)
Definition: sync.h:268
std::string SysErrorString(int err)
Return system error string from errno value.
Definition: syserror.cpp:18