Bitcoin ABC 0.30.5
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 return error("Error while attempting to lock directory %s: %s",
77 fs::PathToString(directory), lock->GetReason());
78 }
79 if (!probe_only) {
80 // Lock successful and we're not just probing, put it into the map
81 dir_locks.emplace(fs::PathToString(pathLockFile), std::move(lock));
82 }
83 return true;
84}
85
86void UnlockDirectory(const fs::path &directory,
87 const std::string &lockfile_name) {
89 dir_locks.erase(fs::PathToString(directory / lockfile_name));
90}
91
94 dir_locks.clear();
95}
96
97bool DirIsWritable(const fs::path &directory) {
98 fs::path tmpFile = GetUniquePath(directory);
99
100 FILE *file = fsbridge::fopen(tmpFile, "a");
101 if (!file) {
102 return false;
103 }
104
105 fclose(file);
106 remove(tmpFile);
107
108 return true;
109}
110
111bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes) {
112 // 50 MiB
113 constexpr uint64_t min_disk_space = 52428800;
114
115 uint64_t free_bytes_available = fs::space(dir).available;
116 return free_bytes_available >= min_disk_space + additional_bytes;
117}
118
119std::streampos GetFileSize(const char *path, std::streamsize max) {
120 std::ifstream file{path, std::ios::binary};
121 file.ignore(max);
122 return file.gcount();
123}
124
125bool FileCommit(FILE *file) {
126 // harmless if redundantly called
127 if (fflush(file) != 0) {
128 LogPrintf("%s: fflush failed: %d\n", __func__, errno);
129 return false;
130 }
131#ifdef WIN32
132 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
133 if (FlushFileBuffers(hFile) == 0) {
134 LogPrintf("%s: FlushFileBuffers failed: %d\n", __func__,
135 GetLastError());
136 return false;
137 }
138#elif defined(MAC_OSX) && defined(F_FULLFSYNC)
139 // Manpage says "value other than -1" is returned on success
140 if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) {
141 LogPrintf("%s: fcntl F_FULLFSYNC failed: %d\n", __func__, errno);
142 return false;
143 }
144#elif HAVE_FDATASYNC
145 // Ignore EINVAL for filesystems that don't support sync
146 if (fdatasync(fileno(file)) != 0 && errno != EINVAL) {
147 LogPrintf("%s: fdatasync failed: %d\n", __func__, errno);
148 return false;
149 }
150#else
151 if (fsync(fileno(file)) != 0 && errno != EINVAL) {
152 LogPrintf("%s: fsync failed: %d\n", __func__, errno);
153 return false;
154 }
155#endif
156 return true;
157}
158
159void DirectoryCommit(const fs::path &dirname) {
160#ifndef WIN32
161 FILE *file = fsbridge::fopen(dirname, "r");
162 if (file) {
163 fsync(fileno(file));
164 fclose(file);
165 }
166#endif
167}
168
169bool TruncateFile(FILE *file, unsigned int length) {
170#if defined(WIN32)
171 return _chsize(_fileno(file), length) == 0;
172#else
173 return ftruncate(fileno(file), length) == 0;
174#endif
175}
176
183#if defined(WIN32)
184 return 8192;
185#else
186 struct rlimit limitFD;
187 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
188 if (limitFD.rlim_cur < (rlim_t)nMinFD) {
189 limitFD.rlim_cur = nMinFD;
190 if (limitFD.rlim_cur > limitFD.rlim_max) {
191 limitFD.rlim_cur = limitFD.rlim_max;
192 }
193 setrlimit(RLIMIT_NOFILE, &limitFD);
194 getrlimit(RLIMIT_NOFILE, &limitFD);
195 }
196 return limitFD.rlim_cur;
197 }
198 // getrlimit failed, assume it's fine.
199 return nMinFD;
200#endif
201}
202
208void AllocateFileRange(FILE *file, unsigned int offset, unsigned int length) {
209#if defined(WIN32)
210 // Windows-specific version.
211 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
212 LARGE_INTEGER nFileSize;
213 int64_t nEndPos = (int64_t)offset + length;
214 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
215 nFileSize.u.HighPart = nEndPos >> 32;
216 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
217 SetEndOfFile(hFile);
218#elif defined(MAC_OSX)
219 // OSX specific version
220 // NOTE: Contrary to other OS versions, the OSX version assumes that
221 // NOTE: offset is the size of the file.
222 fstore_t fst;
223 fst.fst_flags = F_ALLOCATECONTIG;
224 fst.fst_posmode = F_PEOFPOSMODE;
225 fst.fst_offset = 0;
226 // mac os fst_length takes the number of free bytes to allocate,
227 // not the desired file size
228 fst.fst_length = length;
229 fst.fst_bytesalloc = 0;
230 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
231 fst.fst_flags = F_ALLOCATEALL;
232 fcntl(fileno(file), F_PREALLOCATE, &fst);
233 }
234 ftruncate(fileno(file), static_cast<off_t>(offset) + length);
235#elif defined(HAVE_POSIX_FALLOCATE)
236 // Version using posix_fallocate
237 off_t nEndPos = (off_t)offset + length;
238 posix_fallocate(fileno(file), 0, nEndPos);
239#else
240 // Fallback version
241 // TODO: just write one byte per block
242 static const char buf[65536] = {};
243 if (fseek(file, offset, SEEK_SET)) {
244 return;
245 }
246 while (length > 0) {
247 unsigned int now = 65536;
248 if (length < now) {
249 now = length;
250 }
251 // Allowed to fail; this function is advisory anyway.
252 fwrite(buf, 1, now, file);
253 length -= now;
254 }
255#endif
256}
257
258#ifdef WIN32
259fs::path GetSpecialFolderPath(int nFolder, bool fCreate) {
260 WCHAR pszPath[MAX_PATH] = L"";
261
262 if (SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate)) {
263 return fs::path(pszPath);
264 }
265
266 LogPrintf(
267 "SHGetSpecialFolderPathW() failed, could not obtain requested path.\n");
268 return fs::path("");
269}
270#endif
271
272bool RenameOver(fs::path src, fs::path dest) {
273#ifdef WIN32
274 return MoveFileExW(src.wstring().c_str(), dest.wstring().c_str(),
275 MOVEFILE_REPLACE_EXISTING) != 0;
276#else
277 int rc = std::rename(src.c_str(), dest.c_str());
278 return (rc == 0);
279#endif /* WIN32 */
280}
281
288 try {
289 return fs::create_directories(p);
290 } catch (const fs::filesystem_error &) {
291 if (!fs::exists(p) || !fs::is_directory(p)) {
292 throw;
293 }
294 }
295
296 // create_directory didn't create the directory, it had to have existed
297 // already.
298 return false;
299}
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:86
bool DirIsWritable(const fs::path &directory)
Definition: fs_helpers.cpp:97
bool RenameOver(fs::path src, fs::path dest)
Definition: fs_helpers.cpp:272
std::streampos GetFileSize(const char *path, std::streamsize max)
Get the size of a file by scanning it.
Definition: fs_helpers.cpp:119
int RaiseFileDescriptorLimit(int nMinFD)
This function tries to raise the file descriptor limit to the requested number.
Definition: fs_helpers.cpp:182
void DirectoryCommit(const fs::path &dirname)
Sync directory contents.
Definition: fs_helpers.cpp:159
void ReleaseDirectoryLocks()
Release all directory locks.
Definition: fs_helpers.cpp:92
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
Definition: fs_helpers.cpp:287
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:208
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
Definition: fs_helpers.cpp:111
bool TruncateFile(FILE *file, unsigned int length)
Definition: fs_helpers.cpp:169
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:125
fs::path GetUniquePath(const fs::path &base)
Helper function for getting a unique path.
bool error(const char *fmt, const Args &...args)
Definition: logging.h:226
#define LogPrintf(...)
Definition: logging.h:207
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:179
static bool exists(const path &p)
Definition: fs.h:102
static std::string PathToString(const path &path)
Convert path object to byte string.
Definition: fs.h:142
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:30
#define LOCK(cs)
Definition: sync.h:306