Coverage Report

Created: 2026-05-06 07:53

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/tmp/bitcoin/src/util/fs_helpers.cpp
Line
Count
Source
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
#include <random.h>
10
#include <sync.h>
11
#include <tinyformat.h>
12
#include <util/byte_units.h> // IWYU pragma: keep
13
#include <util/fs.h>
14
#include <util/log.h>
15
#include <util/syserror.h>
16
17
#include <cerrno>
18
#include <fstream>
19
#include <map>
20
#include <memory>
21
#include <optional>
22
#include <stdexcept>
23
#include <string>
24
#include <system_error>
25
#include <utility>
26
27
#ifndef WIN32
28
#include <fcntl.h>
29
#include <sys/resource.h>
30
#include <sys/types.h>
31
#include <unistd.h>
32
#else
33
#include <io.h>
34
#include <shlobj.h>
35
#endif // WIN32
36
37
#ifdef __APPLE__
38
#include <sys/mount.h>
39
#include <sys/param.h>
40
#endif
41
42
/** Mutex to protect dir_locks. */
43
static GlobalMutex cs_dir_locks;
44
/** A map that contains all the currently held directory locks. After
45
 * successful locking, these will be held here until the global destructor
46
 * cleans them up and thus automatically unlocks them, or ReleaseDirectoryLocks
47
 * is called.
48
 */
49
static std::map<std::string, std::unique_ptr<fsbridge::FileLock>> dir_locks GUARDED_BY(cs_dir_locks);
50
namespace util {
51
LockResult LockDirectory(const fs::path& directory, const fs::path& lockfile_name, bool probe_only)
52
4.47k
{
53
4.47k
    LOCK(cs_dir_locks);
54
4.47k
    fs::path pathLockFile = directory / lockfile_name;
55
56
    // If a lock for this directory already exists in the map, don't try to re-lock it
57
4.47k
    if (dir_locks.contains(fs::PathToString(pathLockFile))) {
58
2
        return LockResult::Success;
59
2
    }
60
61
    // Create empty lock file if it doesn't exist.
62
4.47k
    if (auto created{fsbridge::fopen(pathLockFile, "a")}) {
63
4.46k
        std::fclose(created);
64
4.46k
    } else {
65
2
        return LockResult::ErrorWrite;
66
2
    }
67
4.46k
    auto lock = std::make_unique<fsbridge::FileLock>(pathLockFile);
68
4.46k
    if (!lock->TryLock()) {
69
4
        LogError("Error while attempting to lock directory %s: %s\n", fs::PathToString(directory), lock->GetReason());
70
4
        return LockResult::ErrorLock;
71
4
    }
72
4.46k
    if (!probe_only) {
73
        // Lock successful and we're not just probing, put it into the map
74
2.23k
        dir_locks.emplace(fs::PathToString(pathLockFile), std::move(lock));
75
2.23k
    }
76
4.46k
    return LockResult::Success;
77
4.46k
}
78
} // namespace util
79
void UnlockDirectory(const fs::path& directory, const fs::path& lockfile_name)
80
0
{
81
0
    LOCK(cs_dir_locks);
82
0
    dir_locks.erase(fs::PathToString(directory / lockfile_name));
83
0
}
84
85
void ReleaseDirectoryLocks()
86
3
{
87
3
    LOCK(cs_dir_locks);
88
3
    dir_locks.clear();
89
3
}
90
91
bool CheckDiskSpace(const fs::path& dir, uint64_t additional_bytes)
92
10.1k
{
93
10.1k
    constexpr uint64_t min_disk_space{50_MiB};
94
95
10.1k
    uint64_t free_bytes_available = fs::space(dir).available;
96
10.1k
    return free_bytes_available >= min_disk_space + additional_bytes;
97
10.1k
}
98
99
std::streampos GetFileSize(const char* path, std::streamsize max)
100
0
{
101
0
    std::ifstream file{path, std::ios::binary};
102
0
    file.ignore(max);
103
0
    return file.gcount();
104
0
}
105
106
bool FileCommit(FILE* file)
107
9.26k
{
108
9.26k
    if (fflush(file) != 0) { // harmless if redundantly called
109
0
        LogError("fflush failed: %s", SysErrorString(errno));
110
0
        return false;
111
0
    }
112
#ifdef WIN32
113
    HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
114
    if (FlushFileBuffers(hFile) == 0) {
115
        LogError("FlushFileBuffers failed: %s", Win32ErrorString(GetLastError()));
116
        return false;
117
    }
118
#elif defined(__APPLE__) && defined(F_FULLFSYNC)
119
    if (fcntl(fileno(file), F_FULLFSYNC, 0) == -1) { // Manpage says "value other than -1" is returned on success
120
        LogError("fcntl F_FULLFSYNC failed: %s", SysErrorString(errno));
121
        return false;
122
    }
123
#elif HAVE_FDATASYNC
124
9.26k
    if (fdatasync(fileno(file)) != 0 && errno != EINVAL) { // Ignore EINVAL for filesystems that don't support sync
125
0
        LogError("fdatasync failed: %s", SysErrorString(errno));
126
0
        return false;
127
0
    }
128
#else
129
    if (fsync(fileno(file)) != 0 && errno != EINVAL) {
130
        LogError("fsync failed: %s", SysErrorString(errno));
131
        return false;
132
    }
133
#endif
134
9.26k
    return true;
135
9.26k
}
136
137
void DirectoryCommit(const fs::path& dirname)
138
6.76k
{
139
6.76k
#ifndef WIN32
140
6.76k
    FILE* file = fsbridge::fopen(dirname, "r");
141
6.76k
    if (file) {
142
6.76k
        fsync(fileno(file));
143
6.76k
        fclose(file);
144
6.76k
    }
145
6.76k
#endif
146
6.76k
}
147
148
bool TruncateFile(FILE* file, unsigned int length)
149
64
{
150
#if defined(WIN32)
151
    return _chsize(_fileno(file), length) == 0;
152
#else
153
64
    return ftruncate(fileno(file), length) == 0;
154
64
#endif
155
64
}
156
157
/**
158
 * this function tries to raise the file descriptor limit to the requested number.
159
 * It returns the actual file descriptor limit (which may be more or less than nMinFD)
160
 */
161
int RaiseFileDescriptorLimit(int nMinFD)
162
1.79k
{
163
#if defined(WIN32)
164
    return 2048;
165
#else
166
1.79k
    struct rlimit limitFD;
167
1.79k
    if (getrlimit(RLIMIT_NOFILE, &limitFD) != -1) {
168
1.79k
        if (limitFD.rlim_cur < (rlim_t)nMinFD) {
169
0
            limitFD.rlim_cur = nMinFD;
170
0
            if (limitFD.rlim_cur > limitFD.rlim_max)
171
0
                limitFD.rlim_cur = limitFD.rlim_max;
172
0
            setrlimit(RLIMIT_NOFILE, &limitFD);
173
0
            getrlimit(RLIMIT_NOFILE, &limitFD);
174
0
        }
175
1.79k
        return limitFD.rlim_cur;
176
1.79k
    }
177
0
    return nMinFD; // getrlimit failed, assume it's fine
178
1.79k
#endif
179
1.79k
}
180
181
/**
182
 * this function tries to make a particular range of a file allocated (corresponding to disk space)
183
 * it is advisory, and the range specified in the arguments will never contain live data
184
 */
185
void AllocateFileRange(FILE* file, unsigned int offset, unsigned int length)
186
950
{
187
#if defined(WIN32)
188
    // Windows-specific version
189
    HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(file));
190
    LARGE_INTEGER nFileSize;
191
    int64_t nEndPos = (int64_t)offset + length;
192
    nFileSize.u.LowPart = nEndPos & 0xFFFFFFFF;
193
    nFileSize.u.HighPart = nEndPos >> 32;
194
    SetFilePointerEx(hFile, nFileSize, 0, FILE_BEGIN);
195
    SetEndOfFile(hFile);
196
#elif defined(__APPLE__)
197
    // OSX specific version
198
    // NOTE: Contrary to other OS versions, the OSX version assumes that
199
    // NOTE: offset is the size of the file.
200
    fstore_t fst;
201
    fst.fst_flags = F_ALLOCATECONTIG;
202
    fst.fst_posmode = F_PEOFPOSMODE;
203
    fst.fst_offset = 0;
204
    fst.fst_length = length; // mac os fst_length takes the # of free bytes to allocate, not desired file size
205
    fst.fst_bytesalloc = 0;
206
    if (fcntl(fileno(file), F_PREALLOCATE, &fst) == -1) {
207
        fst.fst_flags = F_ALLOCATEALL;
208
        fcntl(fileno(file), F_PREALLOCATE, &fst);
209
    }
210
    ftruncate(fileno(file), static_cast<off_t>(offset) + length);
211
#else
212
950
#if defined(HAVE_POSIX_FALLOCATE)
213
    // Version using posix_fallocate
214
950
    off_t nEndPos = (off_t)offset + length;
215
950
    if (0 == posix_fallocate(fileno(file), 0, nEndPos)) return;
216
0
#endif
217
    // Fallback version
218
    // TODO: just write one byte per block
219
0
    static const char buf[65536] = {};
220
0
    if (fseek(file, offset, SEEK_SET)) {
221
0
        return;
222
0
    }
223
0
    while (length > 0) {
224
0
        unsigned int now = 65536;
225
0
        if (length < now)
226
0
            now = length;
227
0
        fwrite(buf, 1, now, file); // allowed to fail; this function is advisory anyway
228
0
        length -= now;
229
0
    }
230
0
#endif
231
0
}
232
233
#ifdef WIN32
234
fs::path GetSpecialFolderPath(int nFolder, bool fCreate)
235
{
236
    WCHAR pszPath[MAX_PATH] = L"";
237
238
    if (SHGetSpecialFolderPathW(nullptr, pszPath, nFolder, fCreate)) {
239
        return fs::path(pszPath);
240
    }
241
242
    LogError("SHGetSpecialFolderPathW() failed, could not obtain requested path.");
243
    return fs::path("");
244
}
245
#endif
246
247
bool RenameOver(fs::path src, fs::path dest)
248
4.85k
{
249
4.85k
    std::error_code error;
250
4.85k
    fs::rename(src, dest, error);
251
4.85k
    return !error;
252
4.85k
}
253
254
/**
255
 * Ignores exceptions thrown by create_directories if the requested directory exists.
256
 * Specifically handles case where path p exists, but it wasn't possible for the user to
257
 * write to the parent directory.
258
 */
259
bool TryCreateDirectories(const fs::path& p)
260
4.15k
{
261
4.15k
    try {
262
4.15k
        return fs::create_directories(p);
263
4.15k
    } catch (const fs::filesystem_error&) {
264
2
        if (!fs::exists(p) || !fs::is_directory(p))
265
2
            throw;
266
2
    }
267
268
    // create_directories didn't create the directory, it had to have existed already
269
0
    return false;
270
4.15k
}
271
272
std::string PermsToSymbolicString(fs::perms p)
273
1.09k
{
274
1.09k
    std::string perm_str(9, '-');
275
276
9.81k
    auto set_perm = [&](size_t pos, fs::perms required_perm, char letter) {
277
9.81k
        if ((p & required_perm) != fs::perms::none) {
278
2.18k
            perm_str[pos] = letter;
279
2.18k
        }
280
9.81k
    };
281
282
1.09k
    set_perm(0, fs::perms::owner_read,   'r');
283
1.09k
    set_perm(1, fs::perms::owner_write,  'w');
284
1.09k
    set_perm(2, fs::perms::owner_exec,   'x');
285
1.09k
    set_perm(3, fs::perms::group_read,   'r');
286
1.09k
    set_perm(4, fs::perms::group_write,  'w');
287
1.09k
    set_perm(5, fs::perms::group_exec,   'x');
288
1.09k
    set_perm(6, fs::perms::others_read,  'r');
289
1.09k
    set_perm(7, fs::perms::others_write, 'w');
290
1.09k
    set_perm(8, fs::perms::others_exec,  'x');
291
292
1.09k
    return perm_str;
293
1.09k
}
294
295
std::optional<fs::perms> InterpretPermString(const std::string& s)
296
3
{
297
3
    if (s == "owner") {
298
1
        return fs::perms::owner_read | fs::perms::owner_write;
299
2
    } else if (s == "group") {
300
1
        return fs::perms::owner_read | fs::perms::owner_write |
301
1
               fs::perms::group_read;
302
1
    } else if (s == "all") {
303
1
        return fs::perms::owner_read | fs::perms::owner_write |
304
1
               fs::perms::group_read |
305
1
               fs::perms::others_read;
306
1
    } else {
307
0
        return std::nullopt;
308
0
    }
309
3
}
310
311
bool IsDirWritable(const fs::path& dir_path)
312
1.07k
{
313
    // Attempt to create a tmp file in the directory
314
1.07k
    if (!fs::is_directory(dir_path)) throw std::runtime_error(strprintf("Path %s is not a directory", fs::PathToString(dir_path)));
315
1.07k
    FastRandomContext rng;
316
1.07k
    const auto tmp = dir_path / fs::PathFromString(strprintf(".tmp_%d", rng.rand64()));
317
318
1.07k
    const char* mode;
319
#ifdef __MINGW64__
320
    mode = "w"; // Temporary workaround for https://github.com/bitcoin/bitcoin/issues/30210
321
#else
322
1.07k
    mode = "wx";
323
1.07k
#endif
324
325
1.07k
    if (const auto created{fsbridge::fopen(tmp, mode)}) {
326
1.07k
        std::fclose(created);
327
1.07k
        std::error_code ec;
328
1.07k
        fs::remove(tmp, ec); // clean up, ignore errors
329
1.07k
        return true;
330
1.07k
    }
331
0
    return false;
332
1.07k
}
333
334
#ifdef __APPLE__
335
FSType GetFilesystemType(const fs::path& path)
336
{
337
    if (struct statfs fs_info; statfs(path.c_str(), &fs_info)) {
338
        return FSType::ERROR;
339
    } else if (std::string_view{fs_info.f_fstypename} == "exfat") {
340
        return FSType::EXFAT;
341
    }
342
    return FSType::OTHER;
343
}
344
#endif