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