Bitcoin ABC 0.32.4
P2P Digital Currency
fs_helpers.cpp
Go to the documentation of this file.
1// Copyright (c) 2009-2010 Satoshi Nakamoto
2// Copyright (c) 2009-2023 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 <util/fs_helpers.h>
7
8#if defined(HAVE_CONFIG_H)
9#include <config/bitcoin-config.h>
10#endif
11
12#include <logging.h>
13#include <sync.h>
14#include <tinyformat.h>
15#include <util/fs.h>
16#include <util/getuniquepath.h>
17
18#include <cerrno>
19#include <filesystem>
20#include <fstream>
21#include <map>
22#include <memory>
23#include <string>
24#include <system_error>
25#include <utility>
26
27#ifndef WIN32
28// for posix_fallocate, in config/CMakeLists.txt we check if it is present after
29// this
30#ifdef __linux__
31
32#ifdef _POSIX_C_SOURCE
33#undef _POSIX_C_SOURCE
34#endif
35
36#define _POSIX_C_SOURCE 200112L
37
38#endif // __linux__
39
40#include <fcntl.h>
41#include <sys/resource.h>
42#include <unistd.h>
43#else
44#include <io.h> /* For _get_osfhandle, _chsize */
45#include <shlobj.h> /* For SHGetSpecialFolderPathW */
46#endif // WIN32
47
55static std::map<std::string, std::unique_ptr<fsbridge::FileLock>>
57
58bool LockDirectory(const fs::path &directory, const std::string lockfile_name,
59 bool probe_only) {
61 fs::path pathLockFile = directory / lockfile_name;
62
63 // If a lock for this directory already exists in the map, don't try to
64 // re-lock it
65 if (dir_locks.count(fs::PathToString(pathLockFile))) {
66 return true;
67 }
68
69 // Create empty lock file if it doesn't exist.
70 FILE *file = fsbridge::fopen(pathLockFile, "a");
71 if (file) {
72 fclose(file);
73 }
74 auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile);
75 if (!lock->TryLock()) {
76 LogError("Error while attempting to lock directory %s: %s\n",
77 fs::PathToString(directory), lock->GetReason());
78 return false;
79 }
80 if (!probe_only) {
81 // Lock successful and we're not just probing, put it into the map
82 dir_locks.emplace(fs::PathToString(pathLockFile), std::move(lock));
83 }
84 return true;
85}
86
87void UnlockDirectory(const fs::path &directory,
88 const std::string &lockfile_name) {
90 dir_locks.erase(fs::PathToString(directory / lockfile_name));
91}
92
95 dir_locks.clear();
96}
97
98bool DirIsWritable(const fs::path &directory) {
99 fs::path tmpFile = GetUniquePath(directory);
100
101 FILE *file = fsbridge::fopen(tmpFile, "a");
102 if (!file) {
103 return false;
104 }
105
106 fclose(file);
107 remove(tmpFile);
108
109 return true;
110}
111
112bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes) {
113 // 50 MiB
114 constexpr uint64_t min_disk_space = 52428800;
115
116 uint64_t free_bytes_available = fs::space(dir).available;
117 return free_bytes_available >= min_disk_space + additional_bytes;
118}
119
120std::streampos GetFileSize(const char *path, std::streamsize max) {
121 std::ifstream file{path, std::ios::binary};
122 file.ignore(max);
123 return file.gcount();
124}
125
126bool FileCommit(FILE *file) {
127 // harmless if redundantly called
128 if (fflush(file) != 0) {
129 LogPrintf("%s: fflush failed: %d\n", __func__, errno);
130 return false;
131 }
132#ifdef WIN32
133 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
134 if (FlushFileBuffers(hFile) == 0) {
135 LogPrintf("%s: FlushFileBuffers failed: %d\n", __func__,
136 GetLastError());
137 return false;
138 }
139#elif defined(MAC_OSX) && defined(F_FULLFSYNC)
140 // Manpage says "value other than -1" is returned on success
141 if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) {
142 LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno);
143 return false;
144 }
145#elif HAVE_FDATASYNC
146 // Ignore EINVAL for filesystems that don't support sync
147 if (fdatasync(fileno(file)) != 0 && errno != EINVAL) {
148 LogPrintf("%s: fdatasync failed: %d\n", __func__, errno);
149 return false;
150 }
151#else
152 if (fsync(fileno(file)) != 0 && errno != EINVAL) {
153 LogPrintf("%s: fsync failed: %d\n", __func__, errno);
154 return false;
155 }
156#endif
157 return true;
158}
159
160void DirectoryCommit(const fs::path &dirname) {
161#ifndef WIN32
162 FILE *file = fsbridge::fopen(dirname, "r");
163 if (file) {
164 fsync(fileno(file));
165 fclose(file);
166 }
167#endif
168}
169
170bool TruncateFile(FILE *file, unsigned int length) {
171#if defined(WIN32)
172 return _chsize(_fileno(file), length) == 0;
173#else
174 return ftruncate(fileno(file), length) == 0;
175#endif
176}
177
184#if defined(WIN32)
185 return 8192;
186#else
187 struct rlimit limitFD;
188 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
189 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
190 limitFD.rlim_cur = nMinFD;
191 if (limitFD.rlim_cur > limitFD.rlim_max) {
192 limitFD.rlim_cur = limitFD.rlim_max;
193 }
194 setrlimit(RLIMIT_NOFILE, &limitFD);
195 getrlimit(RLIMIT_NOFILE, &limitFD);
196 }
197 return limitFD.rlim_cur;
198 }
199 // getrlimit failed, assume it's fine.
200 return nMinFD;
201#endif
202}
203
209void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
210#if defined(WIN32)
211 // Windows-specific version.
212 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
213 LARGE_INTEGER nFileSize;
214 int64_t nEndPos = (int64_t)offset + length;
215 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
216 nFileSize.u.HighPart = nEndPos >> 32;
217 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
218 SetEndOfFile(hFile);
219#elif defined(MAC_OSX)
220 // OSX specific version
221 // NOTE: Contrary to other OS versions, the OSX version assumes that
222 // NOTE: offset is the size of the file.
223 fstore_t fst;
224 fst.fst_flags = F_ALLOCATECONTIG;
225 fst.fst_posmode = F_PEOFPOSMODE;
226 fst.fst_offset = 0;
227 // mac os fst_length takes the number of free bytes to allocate,
228 // not the desired file size
229 fst.fst_length = length;
230 fst.fst_bytesalloc = 0;
231 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
232 fst.fst_flags = F_ALLOCATEALL;
233 fcntl(fileno(file), F_PREALLOCATE, &fst);
234 }
235 ftruncate(fileno(file), static_cast<off_t>(offset) + length);
236#elif defined(HAVE_POSIX_FALLOCATE)
237 // Version using posix_fallocate
238 off_t nEndPos = (off_t)offset + length;
239 posix_fallocate(fileno(file), 0, nEndPos);
240#else
241 // Fallback version
242 // TODO: just write one byte per block
243 static const char buf[65536] = {};
244 if (fseek(file, offset, SEEK_SET)) {
245 return;
246 }
247 while (length > 0) {
248 unsigned int now = 65536;
249 if (length < now) {
250 now = length;
251 }
252 // Allowed to fail; this function is advisory anyway.
253 fwrite(buf, 1, now, file);
254 length -= now;
255 }
256#endif
257}
258
259#ifdef WIN32
260fs::path GetSpecialFolderPath(int nFolder, bool fCreate) {
261 WCHAR pszPath[MAX_PATH] = L"";
262
263 if (SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate)) {
264 return fs::path(pszPath);
265 }
266
267 LogPrintf(
268 "SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
269 return fs::path("");
270}
271#endif
272
273bool RenameOver(fs::path src, fs::path dest) {
274#ifdef WIN32
275 return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(),
276 MOVEFILE_REPLACE_EXISTING) != 0;
277#else
278 int rc = std::rename(src.c_str(), dest.c_str());
279 return (rc == 0);
280#endif /* WIN32 */
281}
282
289 try {
290 return fs::create_directories(p);
291 } catch (const fs::filesystem_error &) {
292 if (!fs::exists(p) || !fs::is_directory(p)) {
293 throw;
294 }
295 }
296
297 // create_directory didn't create the directory, it had to have existed
298 // already.
299 return false;
300}
Different type to mark Mutex at global scope.
Definition: sync.h:144
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:30
#define MAX_PATH
Definition: compat.h:70
bool LockDirectory(const fs::path &directory, const std::string lockfile_name, bool probe_only)
Definition: fs_helpers.cpp:58
static GlobalMutex cs_dir_locks
Mutex to protect dir_locks.
Definition: fs_helpers.cpp:49
void UnlockDirectory(const fs::path &directory, const std::string &lockfile_name)
Definition: fs_helpers.cpp:87
bool DirIsWritable(const fs::path &directory)
Definition: fs_helpers.cpp:98
bool RenameOver(fs::path src, fs::path dest)
Definition: fs_helpers.cpp:273
std::streampos GetFileSize(const char *path, std::streamsize max)
Get the size of a file by scanning it.
Definition: fs_helpers.cpp:120
int RaiseFileDescriptorLimit(int nMinFD)
This function tries to raise the file descriptor limit to the requested number.
Definition: fs_helpers.cpp:183
void DirectoryCommit(const fs::path &dirname)
Sync directory contents.
Definition: fs_helpers.cpp:160
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: fs_helpers.cpp:93
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
Definition: fs_helpers.cpp:288
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:209
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: fs_helpers.cpp:112
bool TruncateFile(FILE *file, unsigned int length)
Definition: fs_helpers.cpp:170
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.
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
Definition: fs_helpers.cpp:126
fs::path GetUniquePath(const fs::path &base)
Helper function for getting a unique path.
#define LogError(...)
Definition: logging.h:419
#define LogPrintf(...)
Definition: logging.h:424
static bool create_directories(const std::filesystem::path &p)
Create directory (and if necessary its parents), unless the leaf directory already exists or is a sym...
Definition: fs.h:184
static bool exists(const path &p)
Definition: fs.h:107
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:147
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:30
#define LOCK(cs)
Definition: sync.h:306