6#include <bitcoin-build-config.h>
26#include <system_error>
31#include <sys/resource.h>
56 fs::path pathLockFile = directory / lockfile_name;
69 auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile);
70 if (!lock->TryLock()) {
95 constexpr uint64_t min_disk_space{50_MiB};
97 uint64_t free_bytes_available = fs::space(dir).available;
98 return free_bytes_available >= min_disk_space + additional_bytes;
103 std::ifstream file{path, std::ios::binary};
105 return file.gcount();
110 if (fflush(file) != 0) {
115 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
116 if (FlushFileBuffers(hFile) == 0) {
117 LogError(
"FlushFileBuffers failed: %s", Win32ErrorString(GetLastError()));
120#elif defined(__APPLE__) && defined(F_FULLFSYNC)
121 if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) {
126 if (fdatasync(fileno(file)) != 0 && errno != EINVAL) {
131 if (fsync(fileno(file)) != 0 && errno != EINVAL) {
153 return _chsize(_fileno(file), length) == 0;
155 return ftruncate(fileno(file), length) == 0;
165 struct rlimit limitFD;
166 if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
168 if (limitFD.rlim_cur != RLIM_INFINITY && std::cmp_less(limitFD.rlim_cur, min_fd)) {
169 const auto current_limit{limitFD.rlim_cur};
170 static_assert(std::in_range<rlim_t>(std::numeric_limits<int>::max()));
171 limitFD.rlim_cur =
static_cast<rlim_t
>(min_fd);
173 if ((limitFD.rlim_max != RLIM_INFINITY) && (limitFD.rlim_cur > limitFD.rlim_max)) {
174 limitFD.rlim_cur = limitFD.rlim_max;
176 if (current_limit != limitFD.rlim_cur) {
177 setrlimit(RLIMIT_NOFILE, &limitFD);
178 getrlimit(RLIMIT_NOFILE, &limitFD);
186 if (limitFD.rlim_cur == RLIM_INFINITY ||
187 std::cmp_greater_equal(limitFD.rlim_cur, std::numeric_limits<int>::max())) {
188 return std::numeric_limits<int>::max();
190 return static_cast<int>(limitFD.rlim_cur);
204 HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
205 LARGE_INTEGER nFileSize;
206 int64_t nEndPos = (int64_t)offset + length;
207 nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
208 nFileSize.u.HighPart = nEndPos >> 32;
209 SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
211#elif defined(__APPLE__)
216 fst.fst_flags = F_ALLOCATECONTIG;
217 fst.fst_posmode = F_PEOFPOSMODE;
219 fst.fst_length = length;
220 fst.fst_bytesalloc = 0;
221 if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
222 fst.fst_flags = F_ALLOCATEALL;
223 fcntl(fileno(file), F_PREALLOCATE, &fst);
225 ftruncate(fileno(file),
static_cast<off_t
>(offset) + length);
227#if defined(HAVE_POSIX_FALLOCATE)
229 off_t nEndPos = (off_t)offset + length;
230 if (0 == posix_fallocate(fileno(file), 0, nEndPos))
return;
234 static const char buf[65536] = {};
235 if (fseek(file, offset, SEEK_SET)) {
239 unsigned int now = 65536;
242 fwrite(buf, 1, now, file);
249fs::path GetSpecialFolderPath(
int nFolder,
bool fCreate)
253 if (SHGetSpecialFolderPathW(
nullptr, pszPath, nFolder, fCreate)) {
254 return fs::path(pszPath);
257 LogError(
"SHGetSpecialFolderPathW() failed, could not obtain requested path.");
264 std::error_code error;
265 fs::rename(src, dest, error);
277 return fs::create_directories(p);
278 }
catch (
const fs::filesystem_error&) {
289 std::string perm_str(9,
'-');
291 auto set_perm = [&](
size_t pos, fs::perms required_perm,
char letter) {
292 if ((p & required_perm) != fs::perms::none) {
293 perm_str[pos] = letter;
297 set_perm(0, fs::perms::owner_read,
'r');
298 set_perm(1, fs::perms::owner_write,
'w');
299 set_perm(2, fs::perms::owner_exec,
'x');
300 set_perm(3, fs::perms::group_read,
'r');
301 set_perm(4, fs::perms::group_write,
'w');
302 set_perm(5, fs::perms::group_exec,
'x');
303 set_perm(6, fs::perms::others_read,
'r');
304 set_perm(7, fs::perms::others_write,
'w');
305 set_perm(8, fs::perms::others_exec,
'x');
313 return fs::perms::owner_read | fs::perms::owner_write;
314 }
else if (
s ==
"group") {
315 return fs::perms::owner_read | fs::perms::owner_write |
316 fs::perms::group_read;
317 }
else if (
s ==
"all") {
318 return fs::perms::owner_read | fs::perms::owner_write |
319 fs::perms::group_read |
320 fs::perms::others_read;
329 if (!fs::is_directory(dir_path))
throw std::runtime_error(
strprintf(
"Path %s is not a directory",
fs::PathToString(dir_path)));
341 std::fclose(created);
350FSType GetFilesystemType(
const fs::path& path)
352 if (
struct statfs fs_info; statfs(path.c_str(), &fs_info)) {
353 return FSType::ERROR;
354 }
else if (std::string_view{fs_info.f_fstypename} ==
"exfat") {
355 return FSType::EXFAT;
357 return FSType::OTHER;
#define Assert(val)
Identity function.
uint64_t rand64() noexcept
Generate a random 64-bit integer.
Different type to mark Mutex at global scope.
static bool exists(const path &p)
static std::string PathToString(const path &path)
Convert path object to a byte string.
static path PathFromString(const std::string &string)
Convert byte string to path object.
static GlobalMutex cs_dir_locks
Mutex to protect dir_locks.
bool RenameOver(fs::path src, fs::path dest)
Rename src to dest.
std::streampos GetFileSize(const char *path, std::streamsize max)
Get the size of a file by scanning it.
void DirectoryCommit(const fs::path &dirname)
Sync directory contents.
int RaiseFileDescriptorLimit(int min_fd)
Try to raise the file descriptor limit to the requested number.
void ReleaseDirectoryLocks()
Release all directory locks.
bool IsDirWritable(const fs::path &dir_path)
Check if a directory is writable by creating a temporary file on it.
bool TryCreateDirectories(const fs::path &p)
Ignores exceptions thrown by create_directories if the requested directory exists.
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...
bool CheckDiskSpace(const fs::path &dir, uint64_t additional_bytes)
std::optional< fs::perms > InterpretPermString(const std::string &s)
Interpret a custom permissions level string as fs::perms.
bool TruncateFile(FILE *file, unsigned int length)
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'.
bool FileCommit(FILE *file)
Ensure file contents are fully committed to disk, using a platform-specific feature analogous to fsyn...
void UnlockDirectory(const fs::path &directory, const fs::path &lockfile_name)
FILE * fopen(const fs::path &p, const char *mode)
LockResult LockDirectory(const fs::path &directory, const fs::path &lockfile_name, bool probe_only)
std::string SysErrorString(int err)
Return system error string from errno value.