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/fs.h>
12#include <util/log.h>
13#include <util/syserror.h>
14
15#include <cerrno>
16#include <fstream>
17#include <map>
18#include <memory>
19#include <optional>
20#include <string>
21#include <system_error>
22#include <utility>
23
24#ifndef WIN32
25#include <fcntl.h>
26#include <sys/resource.h>
27#include <sys/types.h>
28#include <unistd.h>
29#else
30#include <io.h>
31#include <shlobj.h>
32#endif // WIN32
33
34#ifdef __APPLE__
35#include <sys/mount.h>
36#include <sys/param.h>
37#endif
38
46static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks GUARDED_BY(cs_dir_locks);
47namespace util {
48LockResult LockDirectory(const fs::path& directory, const fs::path& lockfile_name, bool probe_only)
49{
51 fs::path pathLockFile = directory / lockfile_name;
52
53 // If a lock for this directory already exists in the map, don't try to re-lock it
54 if (dir_locks.contains(fs::PathToString(pathLockFile))) {
56 }
57
58 // Create empty lock file if it doesn't exist.
59 if (auto created{fsbridge::fopen(pathLockFile, "a")}) {
60 std::fclose(created);
61 } else {
63 }
64 auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile);
65 if (!lock->TryLock()) {
66 LogError("Error while attempting to lock directory %s: %s\n", fs::PathToString(directory), lock->GetReason());
68 }
69 if (!probe_only) {
70 // Lock successful and we're not just probing, put it into the map
71 dir_locks.emplace(fs::PathToString(pathLockFile), std::move(lock));
72 }
74}
75} // namespace util
76void UnlockDirectory(const fs::path& directory, const fs::path& lockfile_name)
77{
79 dir_locks.erase(fs::PathToString(directory / lockfile_name));
80}
81
83{
85 dir_locks.clear();
86}
87
88bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes)
89{
90 constexpr uint64_t min_disk_space = 52428800; // 50 MiB
91
92 uint64_t free_bytes_available = fs::space(dir).available;
93 return free_bytes_available >= min_disk_space + additional_bytes;
94}
95
96std::streampos GetFileSize(const char* path, std::streamsize max)
97{
98 std::ifstream file{path, std::ios::binary};
99 file.ignore(max);
100 return file.gcount();
101}
102
103bool FileCommit(FILE* file)
104{
105 if (fflush(file) != 0) { // harmless if redundantly called
106 LogError("fflush failed: %s", SysErrorString(errno));
107 return false;
108 }
109#ifdef WIN32
110 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
111 if (FlushFileBuffers(hFile) == 0) {
112 LogError("FlushFileBuffers failed: %s", Win32ErrorString(GetLastError()));
113 return false;
114 }
115#elif defined(__APPLE__) && defined(F_FULLFSYNC)
116 if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success
117 LogError("fcntl F_FULLFSYNC failed: %s", SysErrorString(errno));
118 return false;
119 }
120#elif HAVE_FDATASYNC
121 if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
122 LogError("fdatasync failed: %s", SysErrorString(errno));
123 return false;
124 }
125#else
126 if (fsync(fileno(file)) != 0 && errno != EINVAL) {
127 LogError("fsync failed: %s", SysErrorString(errno));
128 return false;
129 }
130#endif
131 return true;
132}
133
134void DirectoryCommit(const fs::path& dirname)
135{
136#ifndef WIN32
137 FILE* file = fsbridge::fopen(dirname, "r");
138 if (file) {
139 fsync(fileno(file));
140 fclose(file);
141 }
142#endif
143}
144
145bool TruncateFile(FILE* file, unsigned int length)
146{
147#if defined(WIN32)
148 return _chsize(_fileno(file), length) == 0;
149#else
150 return ftruncate(fileno(file), length) == 0;
151#endif
152}
153
159{
160#if defined(WIN32)
161 return 2048;
162#else
163 struct rlimit limitFD;
164 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
165 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
166 limitFD.rlim_cur = nMinFD;
167 if (limitFD.rlim_cur > limitFD.rlim_max)
168 limitFD.rlim_cur = limitFD.rlim_max;
169 setrlimit(RLIMIT_NOFILE, &limitFD);
170 getrlimit(RLIMIT_NOFILE, &limitFD);
171 }
172 return limitFD.rlim_cur;
173 }
174 return nMinFD; // getrlimit failed, assume it's fine
175#endif
176}
177
182void AllocateFileRange(FILE* file, unsigned int offset, unsigned int length)
183{
184#if defined(WIN32)
185 // Windows-specific version
186 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
187 LARGE_INTEGER nFileSize;
188 int64_t nEndPos = (int64_t)offset + length;
189 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
190 nFileSize.u.HighPart = nEndPos >> 32;
191 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
192 SetEndOfFile(hFile);
193#elif defined(__APPLE__)
194 // OSX specific version
195 // NOTE: Contrary to other OS versions, the OSX version assumes that
196 // NOTE: offset is the size of the file.
197 fstore_t fst;
198 fst.fst_flags = F_ALLOCATECONTIG;
199 fst.fst_posmode = F_PEOFPOSMODE;
200 fst.fst_offset = 0;
201 fst.fst_length = length; // mac os fst_length takes the # of free bytes to allocate, not desired file size
202 fst.fst_bytesalloc = 0;
203 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
204 fst.fst_flags = F_ALLOCATEALL;
205 fcntl(fileno(file), F_PREALLOCATE, &fst);
206 }
207 ftruncate(fileno(file), static_cast<off_t>(offset) + length);
208#else
209#if defined(HAVE_POSIX_FALLOCATE)
210 // Version using posix_fallocate
211 off_t nEndPos = (off_t)offset + length;
212 if (0 == posix_fallocate(fileno(file), 0, nEndPos)) return;
213#endif
214 // Fallback version
215 // TODO: just write one byte per block
216 static const char buf[65536] = {};
217 if (fseek(file, offset, SEEK_SET)) {
218 return;
219 }
220 while (length > 0) {
221 unsigned int now = 65536;
222 if (length < now)
223 now = length;
224 fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
225 length -= now;
226 }
227#endif
228}
229
230#ifdef WIN32
231fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
232{
233 WCHAR pszPath[MAX_PATH] = L"";
234
235 if (SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate)) {
236 return fs::path(pszPath);
237 }
238
239 LogError("SHGetSpecialFolderPathW() failed, could not obtain requested path.");
240 return fs::path("");
241}
242#endif
243
244bool RenameOver(fs::path src, fs::path dest)
245{
246 std::error_code error;
247 fs::rename(src, dest, error);
248 return !error;
249}
250
256bool TryCreateDirectories(const fs::path& p)
257{
258 try {
259 return fs::create_directories(p);
260 } catch (const fs::filesystem_error&) {
261 if (!fs::exists(p) || !fs::is_directory(p))
262 throw;
263 }
264
265 // create_directories didn't create the directory, it had to have existed already
266 return false;
267}
268
269std::string PermsToSymbolicString(fs::perms p)
270{
271 std::string perm_str(9, '-');
272
273 auto set_perm = [&](size_t pos, fs::perms required_perm, char letter) {
274 if ((p & required_perm) != fs::perms::none) {
275 perm_str[pos] = letter;
276 }
277 };
278
279 set_perm(0, fs::perms::owner_read, 'r');
280 set_perm(1, fs::perms::owner_write, 'w');
281 set_perm(2, fs::perms::owner_exec, 'x');
282 set_perm(3, fs::perms::group_read, 'r');
283 set_perm(4, fs::perms::group_write, 'w');
284 set_perm(5, fs::perms::group_exec, 'x');
285 set_perm(6, fs::perms::others_read, 'r');
286 set_perm(7, fs::perms::others_write, 'w');
287 set_perm(8, fs::perms::others_exec, 'x');
288
289 return perm_str;
290}
291
292std::optional<fs::perms> InterpretPermString(const std::string& s)
293{
294 if (s == "owner") {
295 return fs::perms::owner_read | fs::perms::owner_write;
296 } else if (s == "group") {
297 return fs::perms::owner_read | fs::perms::owner_write |
298 fs::perms::group_read;
299 } else if (s == "all") {
300 return fs::perms::owner_read | fs::perms::owner_write |
301 fs::perms::group_read |
302 fs::perms::others_read;
303 } else {
304 return std::nullopt;
305 }
306}
307
308#ifdef __APPLE__
309FSType GetFilesystemType(const fs::path& path)
310{
311 if (struct statfs fs_info; statfs(path.c_str(), &fs_info)) {
312 return FSType::ERROR;
313 } else if (std::string_view{fs_info.f_fstypename} == "exfat") {
314 return FSType::EXFAT;
315 }
316 return FSType::OTHER;
317}
318#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:40
bool RenameOver(fs::path src, fs::path dest)
Rename src to dest.
Definition: fs_helpers.cpp:244
std::streampos GetFileSize(const char *path, std::streamsize max)
Get the size of a file by scanning it.
Definition: fs_helpers.cpp:96
int RaiseFileDescriptorLimit(int nMinFD)
this function tries to raise the file descriptor limit to the requested number.
Definition: fs_helpers.cpp:158
void DirectoryCommit(const fs::path &dirname)
Sync directory contents.
Definition: fs_helpers.cpp:134
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: fs_helpers.cpp:82
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
Definition: fs_helpers.cpp:256
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:182
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: fs_helpers.cpp:88
std::optional< fs::perms > InterpretPermString(const std::string &s)
Interpret a custom permissions level string as fs::perms.
Definition: fs_helpers.cpp:292
bool TruncateFile(FILE *file, unsigned int length)
Definition: fs_helpers.cpp:145
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:269
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Definition: fs_helpers.cpp:103
void UnlockDirectory(const fs::path &directory, const fs::path &lockfile_name)
Definition: fs_helpers.cpp:76
#define LogError(...)
Definition: log.h:99
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:48
#define LOCK(cs)
Definition: sync.h:268
std::string SysErrorString(int err)
Return system error string from errno value.
Definition: syserror.cpp:18