LCOV - code coverage report
Current view: top level - src/util - fs_helpers.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 73.3 % 105 77
Test Date: 2025-06-01 06:26:32 Functions: 85.7 % 14 12
Branches: 45.5 % 110 50

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

Generated by: LCOV version 2.0-1