QtPass Developer documentation
QtPass test coverage
Current view: top level - src/util.cpp (source / functions) Coverage Total Hit
Test: QtPass Lines: 94.9 % 688 653
Test Date: 2026-12-03 23:34:20 Functions: 100.0 % 82 82
Branches: 83.0 % 894 742

             Branch data     Line data    Source code
       1                 :             : // SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
       2                 :             : // SPDX-License-Identifier: GPL-3.0-or-later
       3                 :             : /**
       4                 :             :  * @file
       5                 :             :  * @brief Implements Util; the staged, link-safe store writes
       6                 :             :  * (stageFileReplacing() and its helpers) and the store walk (walkStore())
       7                 :             :  * live here.
       8                 :             :  */
       9                 :             : #include "util.h"
      10                 :             : #include "appsettings.h"
      11                 :             : #include "executor.h"
      12                 :             : #include <QCoreApplication>
      13                 :             : #include <QDebug>
      14                 :             : #include <QDir>
      15                 :             : #include <QFile>
      16                 :             : #include <QFileDevice>
      17                 :             : #include <QFileInfo>
      18                 :             : #include <QHash>
      19                 :             : #include <QRegularExpression>
      20                 :             : #include <QRegularExpressionMatchIterator>
      21                 :             : #include <QScopeGuard>
      22                 :             : #include <QStandardPaths>
      23                 :             : #include <QTemporaryFile>
      24                 :             : #include <QUrl>
      25                 :             : 
      26                 :             : #include <algorithm>
      27                 :             : #include <array>
      28                 :             : #include <cstring>
      29                 :             : #include <memory>
      30                 :             : #include <optional>
      31                 :             : #include <utility>
      32                 :             : #include <vector>
      33                 :             : 
      34                 :             : #ifdef Q_OS_WIN
      35                 :             : #include <fcntl.h>
      36                 :             : #include <io.h>
      37                 :             : #include <windows.h>
      38                 :             : #else
      39                 :             : #include <cerrno>
      40                 :             : #include <cstdio>
      41                 :             : #include <dirent.h>
      42                 :             : #include <fcntl.h>
      43                 :             : #include <sys/stat.h>
      44                 :             : #include <sys/time.h>
      45                 :             : #include <unistd.h>
      46                 :             : #endif
      47                 :             : 
      48                 :             : #include "qtpasslogging.h"
      49                 :             : 
      50                 :             : QProcessEnvironment Util::_env;
      51                 :             : bool Util::_envInitialised = false;
      52                 :             : 
      53                 :             : // macOS and Windows: append the usual GPG install directories to PATH.
      54                 :        1012 : void Util::initialiseEnvironment() {
      55         [ +  + ]:        1012 :   if (!_envInitialised) {
      56                 :           6 :     _env = QProcessEnvironment::systemEnvironment();
      57                 :             : #ifdef __APPLE__
      58                 :             :     QString path = _env.value("PATH");
      59                 :             :     if (!path.contains("/usr/local/MacGPG2/bin") &&
      60                 :             :         QDir("/usr/local/MacGPG2/bin").exists())
      61                 :             :       path += ":/usr/local/MacGPG2/bin";
      62                 :             :     if (!path.contains("/usr/local/bin"))
      63                 :             :       path += ":/usr/local/bin";
      64                 :             :     _env.insert("PATH", path);
      65                 :             : #endif
      66                 :             : #ifdef Q_OS_WIN
      67                 :             :     QString path = _env.value("PATH");
      68                 :             :     if (!path.contains("C:\\Program Files\\WinGPG\\x86") &&
      69                 :             :         QDir("C:\\Program Files\\WinGPG\\x86").exists())
      70                 :             :       path += ";C:\\Program Files\\WinGPG\\x86";
      71                 :             :     if (!path.contains("C:\\Program Files\\GnuPG\\bin") &&
      72                 :             :         QDir("C:\\Program Files\\GnuPG\\bin").exists())
      73                 :             :       path += ";C:\\Program Files\\GnuPG\\bin";
      74                 :             :     _env.insert("PATH", path);
      75                 :             : #endif
      76                 :           6 :     qCDebug(lcQtPass) << _env.value("PATH");
      77                 :           6 :     _envInitialised = true;
      78                 :             :   }
      79                 :        1012 : }
      80                 :             : 
      81                 :         424 : auto Util::findPasswordStore() -> QString {
      82                 :         424 :   QString path;
      83                 :         424 :   initialiseEnvironment();
      84   [ +  +  +  + ]:         848 :   if (_env.contains("PASSWORD_STORE_DIR")) {
      85                 :           6 :     path = Util::expandTilde(_env.value("PASSWORD_STORE_DIR"));
      86                 :             :   } else {
      87                 :             : #ifdef Q_OS_WIN
      88                 :             :     path = QDir(QDir::homePath()).filePath("password-store");
      89                 :             : #else
      90                 :        1263 :     path = QDir(QDir::homePath()).filePath(".password-store");
      91                 :             : #endif
      92                 :             :   }
      93                 :         848 :   return Util::normalizeFolderPath(QDir::cleanPath(path));
      94                 :             : }
      95                 :             : 
      96                 :          12 : auto Util::expandTilde(const QString &path) -> QString {
      97         [ +  + ]:          12 :   if (path == QLatin1String("~")) {
      98                 :           1 :     return QDir::homePath();
      99                 :             :   }
     100         [ +  + ]:          11 :   if (path.startsWith(QLatin1String("~/"))) {
     101                 :          10 :     return QDir::homePath() + path.mid(1);
     102                 :             :   }
     103                 :             :   return path;
     104                 :             : }
     105                 :             : 
     106                 :      145613 : auto Util::isAbsoluteFsPath(const QString &path) -> bool {
     107   [ +  +  +  + ]:      145613 :   return QDir::isAbsolutePath(path) && !path.startsWith(QLatin1Char(':'));
     108                 :             : }
     109                 :             : 
     110                 :        1550 : auto Util::joinPath(const QString &dir, const QString &name) -> QString {
     111         [ +  + ]:        1550 :   if (name.startsWith(QLatin1Char(':'))) {
     112         [ +  + ]:           5 :     return dir.endsWith(QLatin1Char('/')) ? dir + name
     113                 :           6 :                                           : dir + QLatin1Char('/') + name;
     114                 :             :   }
     115                 :        1545 :   return QDir(dir).filePath(name);
     116                 :             : }
     117                 :             : 
     118                 :         602 : auto Util::normalizeFolderPath(const QString &path) -> QString {
     119                 :             :   QString normalizedPath = path;
     120      [ +  +  + ]:         602 :   if (!normalizedPath.endsWith('/')) {
     121                 :         583 :     normalizedPath += '/';
     122                 :             :   }
     123                 :         602 :   return normalizedPath;
     124                 :             : }
     125                 :             : 
     126                 :           1 : void Util::applyPassProcessDefaults() {
     127                 :             :   // pass unsets these before it runs git: a GIT_DIR inherited from the
     128                 :             :   // environment (QtPass started from a git hook, or an IDE terminal) would
     129                 :             :   // send every commit and push to that repository instead of the store.
     130                 :          11 :   for (const char *variable :
     131                 :             :        {"GIT_DIR", "GIT_WORK_TREE", "GIT_NAMESPACE", "GIT_INDEX_FILE",
     132                 :             :         "GIT_INDEX_VERSION", "GIT_OBJECT_DIRECTORY", "GIT_COMMON_DIR",
     133                 :             :         // QtPass sets GIT_LITERAL_PATHSPECS for its git; git refuses a
     134                 :             :         // pathspec when one of these is set as well.
     135         [ +  + ]:          11 :         "GIT_GLOB_PATHSPECS", "GIT_NOGLOB_PATHSPECS", "GIT_ICASE_PATHSPECS"}) {
     136                 :          10 :     qunsetenv(variable);
     137                 :             :   }
     138                 :           1 :   Executor::setChildUmask(
     139                 :           1 :       passUmask(qEnvironmentVariable("PASSWORD_STORE_UMASK")));
     140                 :           1 : }
     141                 :             : 
     142                 :          11 : auto Util::passUmask(const QString &value) -> int {
     143                 :             :   // Taken as it is, as bash's umask builtin (which pass hands it to) takes
     144                 :             :   // it: " 022" is no umask there either. pass then keeps the session's;
     145                 :             :   // QtPass falls back to 077.
     146                 :             :   // anchoredPattern(), not ^...$: $ also matches before a final newline.
     147                 :             :   static const QRegularExpression octal(
     148   [ +  +  +  -  :          35 :       QRegularExpression::anchoredPattern(QStringLiteral("[0-7]{1,4}")));
                   +  + ]
     149      [ +  +  + ]:          11 :   if (!octal.match(value).hasMatch()) {
     150                 :             :     return 077;
     151                 :             :   }
     152                 :           4 :   return value.toInt(nullptr, 8);
     153                 :             : }
     154                 :             : 
     155                 :        3036 : auto Util::gitCeiling(const QString &store) -> QString {
     156         [ -  + ]:        3036 :   if (store.isEmpty()) {
     157                 :           0 :     return {};
     158                 :             :   }
     159                 :        3036 :   QString path = QFileInfo(store).canonicalFilePath();
     160         [ -  + ]:        3036 :   if (path.isEmpty()) {
     161                 :           0 :     path = QDir::cleanPath(QDir(store).absolutePath());
     162                 :             :   }
     163                 :        3036 :   return QFileInfo(path).absolutePath();
     164                 :             : }
     165                 :             : 
     166                 :             : #ifndef Q_OS_WIN
     167                 :             : namespace {
     168                 :             : /**
     169                 :             :  * @brief Open @p path for reading, following a link, but only when it ends
     170                 :             :  * at a regular file, and never waiting: O_NONBLOCK keeps a FIFO from
     171                 :             :  * blocking the open until a writer comes, and the open handle is judged
     172                 :             :  * (fstat), so a FIFO or a device is refused. Unlike Util::openRegularFile(),
     173                 :             :  * a link is fine: git's own metadata may be one.
     174                 :             :  * @param path The file.
     175                 :             :  * @param file Receives the open file on success; untouched otherwise.
     176                 :             :  * @return Whether @p file is open on a regular file.
     177                 :             :  */
     178                 :          31 : auto openFollowedRegularFile(const QString &path, QFile &file) -> bool {
     179                 :          31 :   const int fd = ::open(QFile::encodeName(path).constData(),
     180                 :             :                         O_RDONLY | O_NONBLOCK | O_CLOEXEC);
     181         [ -  + ]:          31 :   if (fd < 0) {
     182                 :             :     return false;
     183                 :             :   }
     184                 :          31 :   struct stat info{};
     185   [ +  -  +  -  :          62 :   if (::fstat(fd, &info) != 0 || !S_ISREG(info.st_mode) ||
                   -  + ]
     186                 :          62 :       !file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
     187                 :           0 :     ::close(fd);
     188                 :           0 :     return false;
     189                 :             :   }
     190                 :             :   return true;
     191                 :             : }
     192                 :             : 
     193                 :             : /**
     194                 :             :  * @brief Where git starts its walk for @p store: the real path of its
     195                 :             :  * nearest existing folder, with the part that does not exist yet appended.
     196                 :             :  * @param store The store as pass gets it (`PASSWORD_STORE_DIR`).
     197                 :             :  * @return The path, or empty when no part of it exists.
     198                 :             :  */
     199                 :          34 : auto gitWalkStart(const QString &store) -> QString {
     200                 :             :   // git walks up from the real folder, so the real path is the one to walk,
     201                 :             :   // and for a store that does not exist yet the one it will have: its
     202                 :             :   // nearest existing folder resolved, the rest appended. By the raw string:
     203                 :             :   // QDir and QFileInfo clean a path by name, and "link/.." is the parent
     204                 :             :   // of the link's target, not the folder the link is in. On macOS the
     205                 :             :   // temporary folder is under /var, a link to /private/var.
     206                 :             :   // Absolute as git means it, a leading "/" (Qt would take ":name" for a
     207                 :             :   // resource path).
     208                 :             :   QString path =
     209   [ +  +  +  +  :          68 :       store.startsWith(u'/') ? store : QDir::currentPath() + u'/' + store;
             +  +  +  -  
                      - ]
     210   [ +  -  +  +  :          37 :   while (path.size() > 1 && path.endsWith(u'/')) {
                      + ]
     211                 :           3 :     path.chop(1);
     212                 :             :   }
     213                 :          34 :   QString rest;
     214      [ +  +  + ]:          44 :   while (!QFileInfo::exists(path)) {
     215                 :          10 :     const qsizetype slash = path.lastIndexOf(u'/');
     216         [ -  + ]:          10 :     if (slash < 0) {
     217                 :           0 :       return {};
     218                 :             :     }
     219                 :          10 :     const QString name = path.mid(slash + 1);
     220   [ +  +  +  +  :          24 :     rest = rest.isEmpty() ? name : name + u'/' + rest;
             +  +  -  - ]
     221   [ -  +  +  -  :          20 :     path = slash == 0 ? QStringLiteral("/") : path.left(slash);
                      + ]
     222                 :             :   }
     223                 :          34 :   const QString real = QFileInfo(path).canonicalFilePath();
     224      [ -  +  - ]:          34 :   const QString start = real.isEmpty() ? QDir::cleanPath(path) : real;
     225   [ +  +  +  +  :          72 :   return rest.isEmpty() ? start : QDir::cleanPath(start + u'/' + rest);
             +  +  +  -  
                      - ]
     226                 :             : }
     227                 :             : 
     228                 :             : /**
     229                 :             :  * @brief The ceiling git stops below when pass runs it for @p store
     230                 :             :  * (`GIT_CEILING_DIRECTORIES=$PREFIX/..`), as git reads that list.
     231                 :             :  * @param store The store as pass gets it.
     232                 :             :  * @param start Where git starts its walk (gitWalkStart()).
     233                 :             :  * @return The longest entry @p start lies under, or empty for none.
     234                 :             :  */
     235                 :          34 : auto passCeilingFor(const QString &store, const QString &start) -> QString {
     236                 :             :   // The pieces of pass's ceiling as git takes them (setup.c,
     237                 :             :   // canonicalize_ceiling_entry): relative ones are dropped, the rest
     238                 :             :   // resolved, one that cannot be resolved is dropped; after an empty piece
     239                 :             :   // ("::") they are kept exactly as written. A piece can still be a real
     240                 :             :   // ceiling: "/repo/:vault/.." holds "/repo/".
     241                 :          34 :   QString ceiling;
     242                 :             :   bool afterEmpty = false;
     243                 :             :   const QStringList pieces =
     244                 :          68 :       (store + QStringLiteral("/..")).split(QLatin1Char(':'));
     245         [ +  + ]:         105 :   for (const QString &piece : pieces) {
     246         [ +  + ]:          71 :     if (piece.isEmpty()) {
     247                 :             :       afterEmpty = true;
     248                 :          35 :       continue;
     249                 :             :     }
     250      [ +  +  + ]:          69 :     if (!piece.startsWith(u'/')) {
     251                 :          33 :       continue;
     252                 :             :     }
     253                 :             :     const QString entry =
     254   [ +  +  +  +  :          37 :         afterEmpty ? piece : QFileInfo(piece).canonicalFilePath();
             +  +  -  - ]
     255                 :             :     // git stops below the longest entry the store lies under
     256                 :             :     // (longest_ancestor_length: "/" is above everything).
     257      [ +  +  + ]:          36 :     const QString under = entry == u'/' ? entry : entry + u'/';
     258   [ +  +  +  +  :          36 :     if (!entry.isEmpty() && start.startsWith(under) &&
                +  +  + ]
     259                 :             :         entry.size() > ceiling.size()) {
     260                 :           4 :       ceiling = entry;
     261                 :             :     }
     262                 :             :   }
     263                 :          34 :   return ceiling;
     264                 :             : }
     265                 :             : 
     266                 :             : /**
     267                 :             :  * @brief Whether git takes @p candidate for a repository (setup.c,
     268                 :             :  * is_git_directory()): HEAD naming a ref or an object, objects/ and refs/.
     269                 :             :  * An empty or broken .git is passed by, as git passes it by.
     270                 :             :  * @param candidate The folder.
     271                 :             :  * @return Whether it is a repository to git.
     272                 :             :  */
     273                 :         101 : auto isGitDirectory(const QString &candidate) -> bool {
     274                 :         101 :   const QDir dir(candidate);
     275   [ +  +  +  +  :         229 :   if (!QFileInfo(dir.filePath(QStringLiteral("objects"))).isDir() ||
          +  +  -  +  +  
                   -  - ]
     276   [ +  +  +  +  :         182 :       !QFileInfo(dir.filePath(QStringLiteral("refs"))).isDir()) {
          +  +  +  +  +  
          -  -  -  -  -  
                -  -  - ]
     277                 :             :     return false;
     278                 :             :   }
     279                 :             :   // As git (setup.c, validate_headref()): a HEAD that is a link counts
     280                 :             :   // when the link text starts with "refs/", without reading what it
     281                 :             :   // names, and not otherwise. Anything else is read only when it is a
     282                 :             :   // regular file, without waiting: a HEAD that is a FIFO (a pushed commit
     283                 :             :   // can carry a link to one, or to a device) blocked the open and the
     284                 :             :   // read on the GUI thread when Settings opened.
     285                 :          54 :   const QString headPath = dir.filePath(QStringLiteral("HEAD"));
     286   [ +  +  +  + ]:          27 :   if (const QFileInfo headInfo(headPath); headInfo.isSymLink()) {
     287                 :             :     // The link text as stored (Qt 6.6), not the path it resolves to.
     288                 :           3 :     return headInfo.readSymLink().startsWith(QLatin1String("refs/"));
     289                 :          27 :   }
     290                 :          24 :   QFile head;
     291      [ +  +  - ]:          24 :   if (!openFollowedRegularFile(headPath, head)) {
     292                 :             :     return false;
     293                 :             :   }
     294                 :             :   static const QRegularExpression valid(
     295   [ +  +  +  -  :          28 :       QStringLiteral("^(?:ref: refs/|[0-9a-f]{40}\\s*$|[0-9a-f]{64}\\s*$)"));
                      + ]
     296                 :          72 :   return valid.match(QString::fromUtf8(head.read(256))).hasMatch();
     297                 :         125 : }
     298                 :             : 
     299                 :             : /// What git finds at one folder of its walk.
     300                 :             : enum class Found {
     301                 :             :   Nothing,    ///< No repository: git goes on up.
     302                 :             :   Repository, ///< A repository: git stops and uses it.
     303                 :             :   Refused     ///< A .git git cannot use: git stops with an error.
     304                 :             : };
     305                 :             : 
     306                 :             : /**
     307                 :             :  * @brief What git finds at @p dir: a .git folder that is a repository,
     308                 :             :  * or a .git file naming one (`gitdir: ...`), is the repository. Any other
     309                 :             :  * .git file stops git with an error, and pass then commits nothing; a .git
     310                 :             :  * folder that is no repository is passed by.
     311                 :             :  * @param dir The folder.
     312                 :             :  * @return What git does there.
     313                 :             :  */
     314                 :          98 : auto repositoryAt(const QString &dir) -> Found {
     315                 :         196 :   const QString dotGit = QDir(dir).filePath(QStringLiteral(".git"));
     316                 :          98 :   const QFileInfo info(dotGit);
     317      [ +  +  + ]:          98 :   if (info.isDir()) {
     318      [ +  +  + ]:          24 :     return isGitDirectory(dotGit) ? Found::Repository : Found::Nothing;
     319                 :             :   }
     320      [ +  +  + ]:          74 :   if (!info.exists()) {
     321                 :             :     return Found::Nothing;
     322                 :             :   }
     323                 :             :   // The same for a .git file (or a link to one): a FIFO there blocked in
     324                 :             :   // open().
     325                 :           7 :   QFile file;
     326      [ +  +  - ]:           7 :   if (!openFollowedRegularFile(dotGit, file)) {
     327                 :             :     return Found::Refused;
     328                 :             :   }
     329                 :           7 :   const QString line = QString::fromUtf8(file.readLine(4096)).trimmed();
     330      [ +  +  + ]:           7 :   if (!line.startsWith(QLatin1String("gitdir: "))) {
     331                 :             :     return Found::Refused;
     332                 :             :   }
     333                 :           5 :   const QString target = line.mid(8);
     334   [ +  +  +  +  :          10 :   return isGitDirectory(target.startsWith(u'/') ? target
                      + ]
     335   [ +  +  +  -  :           8 :                                                 : QDir(dir).filePath(target))
                      - ]
     336         [ +  + ]:           5 :              ? Found::Repository
     337                 :             :              : Found::Refused;
     338                 :          98 : }
     339                 :             : } // namespace
     340                 :             : #endif
     341                 :             : 
     342                 :          46 : auto Util::repositoryPassClimbsTo(const QString &store) -> QString {
     343                 :             : #ifdef Q_OS_WIN
     344                 :             :   Q_UNUSED(store);
     345                 :             :   return {};
     346                 :             : #else
     347         [ +  + ]:          46 :   if (!store.contains(QLatin1Char(':'))) {
     348                 :          12 :     return {};
     349                 :             :   }
     350                 :          34 :   const QString start = gitWalkStart(store);
     351         [ -  + ]:          34 :   if (start.isEmpty()) {
     352                 :           0 :     return {};
     353                 :             :   }
     354                 :          34 :   const QString ceiling = passCeilingFor(store, start);
     355                 :             :   // The store's own repository comes first; only without one does git look
     356                 :             :   // further up, and never into the ceiling. By name from here: the real
     357                 :             :   // path holds no link or "..".
     358                 :             :   for (QString dir = start;;) {
     359   [ +  +  +  + ]:          98 :     switch (repositoryAt(dir)) {
     360                 :             :     case Found::Repository:
     361         [ +  + ]:          54 :       return dir == start ? QString() : std::move(dir);
     362                 :           3 :     case Found::Refused:
     363                 :           3 :       return {};
     364                 :             :     case Found::Nothing:
     365                 :             :       break;
     366                 :             :     }
     367                 :             :     // A bare repository: git stops there, and pass, finding no work tree,
     368                 :             :     // commits nothing.
     369      [ +  +  + ]:          72 :     if (isGitDirectory(dir)) {
     370                 :           1 :       return {};
     371                 :             :     }
     372                 :          71 :     const QString up = QFileInfo(dir).absolutePath();
     373   [ +  +  +  + ]:          71 :     if (up == dir || up == ceiling) {
     374                 :           7 :       return {};
     375                 :             :     }
     376                 :          64 :     dir = up;
     377                 :             :   }
     378                 :             : #endif
     379                 :             : }
     380                 :             : 
     381                 :             : namespace {
     382                 :             : /// setGitOwnerForTests(): who owns "the user's own" store, when set.
     383                 :             : std::optional<uint> s_gitOwnerForTests;
     384                 :             : } // namespace
     385                 :             : 
     386                 :           4 : void Util::setGitOwnerForTests(std::optional<uint> user) {
     387                 :           4 :   s_gitOwnerForTests = user;
     388                 :           4 : }
     389                 :             : 
     390                 :             : /// setBeforePlacingForTests(): called between staging and the rename.
     391                 :             : std::function<void(const QString &)> s_beforePlacingForTests;
     392                 :             : 
     393                 :           3 : void Util::setBeforePlacingForTests(std::function<void(const QString &)> hook) {
     394                 :           3 :   s_beforePlacingForTests = std::move(hook);
     395                 :           3 : }
     396                 :             : 
     397                 :             : #ifdef Q_OS_UNIX
     398                 :             : namespace {
     399                 :             : /**
     400                 :             :  * @brief What git's protected configuration holds for `safe.directory`.
     401                 :             :  * @param git The git executable; "git" from PATH when empty.
     402                 :             :  * @return The entries, one "scope<TAB>value" per line; nothing when git
     403                 :             :  *         cannot be asked.
     404                 :             :  */
     405                 :          23 : auto safeDirectoryEntries(const QString &git) -> std::optional<QString> {
     406                 :             :   // Outside any repository, as git reads its protected config: no
     407                 :             :   // repository's own config, and no includeIf "gitdir:" or "onbranch:"
     408                 :             :   // that matches (a GIT_DIR, even one that cannot exist, would be matched
     409                 :             :   // against them, and one that cannot exist makes git config fail). From
     410                 :             :   // "/", which a user cannot make a repository; a local scope is dropped
     411                 :             :   // by the caller in any case.
     412                 :          23 :   QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
     413                 :          46 :   env.remove(QStringLiteral("GIT_DIR"));
     414                 :          46 :   env.remove(QStringLiteral("GIT_WORK_TREE"));
     415                 :          46 :   env.remove(QStringLiteral("GIT_COMMON_DIR"));
     416                 :             :   // git config alone reads GIT_CONFIG in place of the system and global
     417                 :             :   // configuration (and reports it as "command"); the ownership check never
     418                 :             :   // reads it.
     419                 :          46 :   env.remove(QStringLiteral("GIT_CONFIG"));
     420                 :          23 :   QProcess process;
     421                 :          23 :   process.setProcessEnvironment(env);
     422                 :          46 :   process.setWorkingDirectory(QStringLiteral("/"));
     423                 :             :   // Bounded: Git calls wait for this, and a git that never answers trusts
     424                 :             :   // nothing.
     425                 :             :   constexpr int kQueryTimeoutMs = 5000;
     426                 :          23 :   QString out;
     427   [ +  +  +  -  :         184 :   if (Executor::executeBlocking(
                      - ]
     428   [ +  +  +  +  :          46 :           process, git.isEmpty() ? QStringLiteral("git") : git,
                   -  - ]
     429                 :          23 :           {QStringLiteral("config"), QStringLiteral("--show-scope"),
     430                 :          23 :            QStringLiteral("--type=path"), QStringLiteral("--get-all"),
     431                 :          23 :            QStringLiteral("safe.directory")},
     432         [ +  + ]:          46 :           QString(), &out, nullptr, nullptr, kQueryTimeoutMs) != 0) {
     433                 :           9 :     return std::nullopt;
     434                 :             :   }
     435                 :             :   return out;
     436                 :          23 : }
     437                 :             : 
     438                 :             : /**
     439                 :             :  * @brief Whether one `safe.directory` path names the repository at @p root.
     440                 :             :  * @param value The entry: neither empty nor `*`.
     441                 :             :  * @param root The store's canonical path.
     442                 :             :  * @return True when @p value is an absolute path that is @p root, or ends
     443                 :             :  *         in a slash and `*` and holds @p root below it.
     444                 :             :  */
     445                 :          13 : auto safeDirectoryNames(const QString &value, const QString &root) -> bool {
     446         [ +  + ]:          13 :   if (!QDir::isAbsolutePath(value)) {
     447                 :             :     return false;
     448                 :             :   }
     449         [ +  + ]:          10 :   if (value.endsWith(QLatin1String("/*"))) {
     450                 :             :     const QString base = value.chopped(2);
     451   [ -  +  +  -  :          12 :     QString prefix = QFileInfo(base.isEmpty() ? QStringLiteral("/") : base)
             +  +  +  -  
                      - ]
     452                 :           3 :                          .canonicalFilePath();
     453         [ +  + ]:           3 :     if (prefix.isEmpty()) {
     454                 :             :       return false;
     455                 :             :     }
     456      [ +  +  - ]:           2 :     if (!prefix.endsWith(QLatin1Char('/'))) {
     457                 :           2 :       prefix += QLatin1Char('/');
     458                 :             :     }
     459                 :           2 :     return root.startsWith(prefix);
     460                 :             :   }
     461                 :           7 :   const QString named = QFileInfo(value).canonicalFilePath();
     462         [ +  - ]:           7 :   return !named.isEmpty() && named == root;
     463                 :             : }
     464                 :             : 
     465                 :             : /**
     466                 :             :  * @brief Whether git's `safe.directory` trusts the repository at @p root,
     467                 :             :  * as git's ownership check would judge it in place of ownership.
     468                 :             :  *
     469                 :             :  * Read as git reads it: only from system, global and command-line
     470                 :             :  * configuration (a repository cannot vouch for itself), in order. `*`
     471                 :             :  * trusts every repository, an empty value forgets the entries before it,
     472                 :             :  * a path ending in a slash and `*` trusts what lies below it, and any other
     473                 :             :  * absolute path trusts that one folder, compared after resolving links.
     474                 :             :  * Relative entries (including git's ".") and paths that do not exist trust
     475                 :             :  * nothing.
     476                 :             :  * @param root The store's canonical path.
     477                 :             :  * @param git The git executable; "git" from PATH when empty.
     478                 :             :  * @return True when an entry names @p root; false when none does or git
     479                 :             :  *         cannot be asked.
     480                 :             :  */
     481                 :          23 : auto isSafeDirectory(const QString &root, const QString &git) -> bool {
     482                 :          23 :   const std::optional<QString> out = safeDirectoryEntries(git);
     483         [ +  + ]:          23 :   if (!out) {
     484                 :             :     return false;
     485                 :             :   }
     486                 :             :   bool safe = false;
     487                 :          14 :   const QStringList lines = out->split(QLatin1Char('\n'));
     488         [ +  + ]:          47 :   for (const QString &line : lines) {
     489                 :          33 :     const qsizetype tab = line.indexOf(QLatin1Char('\t'));
     490         [ +  + ]:          33 :     if (tab < 0) {
     491                 :          14 :       continue;
     492                 :             :     }
     493                 :          19 :     const QString scope = line.left(tab);
     494   [ +  -  +  +  :          19 :     if (scope != QLatin1String("system") && scope != QLatin1String("global") &&
                   -  + ]
     495         [ -  + ]:           1 :         scope != QLatin1String("command")) {
     496                 :             :       continue;
     497                 :             :     }
     498                 :          19 :     const QString value = line.mid(tab + 1);
     499         [ +  + ]:          19 :     if (value.isEmpty()) {
     500                 :             :       safe = false;
     501                 :             :     } else {
     502   [ +  -  +  +  :          41 :       safe = safe || value == QLatin1String("*") ||
                   +  + ]
     503                 :          13 :              safeDirectoryNames(value, root);
     504                 :             :     }
     505                 :             :   }
     506                 :             :   return safe;
     507                 :             : }
     508                 :             : } // namespace
     509                 :             : #endif
     510                 :             : 
     511                 :         601 : void Util::requireExplicitBareRepository(QProcessEnvironment &env) {
     512                 :         601 :   const QString key = QStringLiteral("safe.bareRepository");
     513                 :         601 :   const QString value = QStringLiteral("explicit");
     514                 :        1202 :   const QString countText = env.value(QStringLiteral("GIT_CONFIG_COUNT"));
     515                 :         601 :   bool ok = countText.isEmpty();
     516         [ +  + ]:         601 :   int count = countText.isEmpty() ? 0 : countText.toInt(&ok);
     517         [ +  + ]:         601 :   if (!ok || count < 0) {
     518                 :             :     // git refuses to start with a malformed count, so the entries it was
     519                 :             :     // meant to cover never applied: start the list afresh.
     520                 :             :     count = 0;
     521                 :             :   }
     522                 :             :   // Keys and these values are case-insensitive to git; the last entry wins.
     523                 :         601 :   QString last;
     524         [ +  + ]:        1020 :   for (int i = 0; i < count; ++i) {
     525   [ +  +  +  + ]:         838 :     if (env.value(QStringLiteral("GIT_CONFIG_KEY_%1").arg(i))
     526                 :         419 :             .compare(key, Qt::CaseInsensitive) == 0) {
     527                 :         640 :       last = env.value(QStringLiteral("GIT_CONFIG_VALUE_%1").arg(i));
     528                 :             :     }
     529                 :             :   }
     530                 :             :   // git reads GIT_CONFIG_PARAMETERS (`git -c`) after the numbered entries,
     531                 :             :   // so when that names the key at all, explicit must be its last entry. Not
     532                 :             :   // parsed: the string must end in this separate token, which a value
     533                 :             :   // cannot fake (a quote inside one is written '\'', so it never follows a
     534                 :             :   // blank); appending once too often does no harm.
     535                 :        1202 :   const QString parameters = env.value(QStringLiteral("GIT_CONFIG_PARAMETERS"));
     536                 :             :   const QString explicitEntry =
     537                 :         601 :       QStringLiteral("'safe.bareRepository=explicit'");
     538                 :        1202 :   if (parameters.contains(QLatin1String("barerepository"),
     539         [ +  + ]:          16 :                           Qt::CaseInsensitive) &&
     540   [ +  +  +  + ]:         615 :       parameters != explicitEntry &&
     541   [ +  +  +  + ]:         615 :       !parameters.endsWith(QLatin1Char(' ') + explicitEntry)) {
     542                 :          12 :     env.insert(QStringLiteral("GIT_CONFIG_PARAMETERS"),
     543         [ +  + ]:          12 :                parameters + QLatin1Char(' ') + explicitEntry);
     544                 :             :   }
     545         [ +  + ]:         601 :   if (last.compare(value, Qt::CaseInsensitive) == 0) {
     546                 :             :     return;
     547                 :             :   }
     548                 :         568 :   env.insert(QStringLiteral("GIT_CONFIG_KEY_%1").arg(count), key);
     549                 :         568 :   env.insert(QStringLiteral("GIT_CONFIG_VALUE_%1").arg(count), value);
     550                 :         568 :   env.insert(QStringLiteral("GIT_CONFIG_COUNT"), QString::number(count + 1));
     551                 :             : }
     552                 :             : 
     553                 :        3036 : auto Util::gitStoreVariables(const QString &store, const QString &git,
     554                 :             :                              std::optional<uint> asUser)
     555                 :             :     -> QList<std::pair<QString, QString>> {
     556                 :        3036 :   const QString ceiling = gitCeiling(store);
     557         [ -  + ]:        3036 :   if (ceiling.isEmpty()) {
     558                 :           0 :     return {};
     559                 :             :   }
     560                 :             :   QList<std::pair<QString, QString>> vars{
     561                 :        9108 :       {QStringLiteral("GIT_CEILING_DIRECTORIES"), ceiling}};
     562                 :             : #ifdef Q_OS_WIN
     563                 :             :   const QChar separator = QLatin1Char(';');
     564                 :             : #else
     565                 :             :   const QChar separator = QLatin1Char(':');
     566                 :             : #endif
     567                 :             :   // git splits the ceiling list on the separator: "/home/a:b" would be
     568                 :             :   // "/home/a" and "b", neither of them the parent, and git would climb.
     569         [ +  + ]:        3036 :   if (ceiling.contains(separator)) {
     570                 :          28 :     QString root = QFileInfo(store).canonicalFilePath();
     571         [ -  + ]:          28 :     if (root.isEmpty()) {
     572                 :           0 :       root = QDir::cleanPath(QDir(store).absolutePath());
     573                 :             :     }
     574                 :          56 :     QString gitDir = QDir(root).filePath(QStringLiteral(".git"));
     575                 :             : #ifdef Q_OS_UNIX
     576                 :             :     // What discovery's ownership check would have looked at: the work tree,
     577                 :             :     // the .git, and the directory a gitfile names. Not the user's: no
     578                 :             :     // repository at all, under a path that cannot be created (its parent
     579                 :             :     // is a device), rather than another user's hooks run as this one.
     580                 :             :     const uint me = asUser.value_or(
     581                 :          28 :         s_gitOwnerForTests.value_or(static_cast<uint>(::geteuid())));
     582                 :          33 :     const auto ownedOrMissing = [me](const QString &path) {
     583                 :          33 :       const QFileInfo info(path);
     584   [ +  +  +  +  :          66 :       return !info.exists() || info.ownerId() == me;
                   +  + ]
     585                 :          33 :     };
     586   [ +  +  +  +  :          28 :     bool owned = ownedOrMissing(root) && ownedOrMissing(gitDir);
                   -  + ]
     587   [ +  +  -  + ]:          28 :     if (owned && QFileInfo(gitDir).isFile()) {
     588                 :           0 :       QFile gitFile(gitDir);
     589      [ #  #  # ]:           0 :       if (gitFile.open(QIODevice::ReadOnly)) {
     590                 :             :         const QString line =
     591                 :           0 :             QString::fromUtf8(gitFile.readLine(4096)).trimmed();
     592      [ #  #  # ]:           0 :         if (line.startsWith(QLatin1String("gitdir:"))) {
     593                 :           0 :           const QString target = line.mid(7).trimmed();
     594                 :           0 :           owned = ownedOrMissing(QDir(root).absoluteFilePath(target));
     595                 :             :         }
     596                 :             :       }
     597                 :           0 :     }
     598                 :             :     // Or trusted as git would trust it in place of ownership.
     599   [ +  +  +  +  :          28 :     if (!owned && !isSafeDirectory(root, git)) {
                      + ]
     600                 :          14 :       gitDir = QStringLiteral("/dev/null/.git");
     601                 :             :     }
     602                 :             : #else
     603                 :             :     // Git for Windows runs the same ownership check during discovery, on
     604                 :             :     // SIDs, with its own rules for the Administrators group; this pin skips
     605                 :             :     // it there and does not repeat it (a known gap, #2089).
     606                 :             :     Q_UNUSED(git);
     607                 :             :     Q_UNUSED(asUser);
     608                 :             : #endif
     609                 :          56 :     vars.append({QStringLiteral("GIT_DIR"), gitDir});
     610                 :          56 :     vars.append({QStringLiteral("GIT_WORK_TREE"), root});
     611                 :             :   }
     612                 :             :   return vars;
     613                 :        3036 : }
     614                 :             : 
     615                 :          54 : auto Util::mkpathForStore(const QString &path) -> bool {
     616                 :         108 :   const QString clean = QDir::cleanPath(QDir(path).absolutePath());
     617   [ +  +  +  + ]:          54 :   if (QFileInfo(clean).isDir()) {
     618                 :             :     return true;
     619                 :             :   }
     620                 :          31 :   const QString parent = QFileInfo(clean).absolutePath();
     621   [ +  -  +  +  :          31 :   if (parent != clean && !mkpathForStore(parent)) {
                      + ]
     622                 :             :     return false;
     623                 :             :   }
     624                 :             : #ifdef Q_OS_UNIX
     625                 :             :   // The store's umask, as git and gpg get it: a store shared with a group
     626                 :             :   // (PASSWORD_STORE_UMASK=007) gets group folders, the default owner-only.
     627   [ +  +  +  + ]:          28 :   const int umask = Executor::childUmask() >= 0 ? Executor::childUmask() : 077;
     628                 :             :   QFile::Permissions permissions;
     629                 :          28 :   const std::array<QFile::Permission, 9> bits = {
     630                 :             :       QFile::ReadOwner, QFile::WriteOwner, QFile::ExeOwner,
     631                 :             :       QFile::ReadGroup, QFile::WriteGroup, QFile::ExeGroup,
     632                 :             :       QFile::ReadOther, QFile::WriteOther, QFile::ExeOther};
     633         [ +  + ]:         280 :   for (int i = 0; i < 9; ++i) {
     634         [ +  + ]:         252 :     if ((umask & (0400 >> i)) == 0) {
     635                 :          90 :       permissions |= bits[i];
     636                 :             :     }
     637                 :             :   }
     638                 :             :   // mkdir() still takes QtPass's own umask off (a session's 022 would drop
     639                 :             :   // the group's write bit); set the mode exactly afterwards. That only ever
     640                 :             :   // widens it to what was asked, never past.
     641   [ +  +  +  +  :          56 :   const bool made = QDir().mkdir(clean, permissions) &&
                   -  + ]
     642                 :          23 :                     QFile::setPermissions(clean, permissions);
     643                 :             : #else
     644                 :             :   // Windows: permissions here would become an ACL of their own, replacing
     645                 :             :   // the inherited one; the folder takes its parent's, as before.
     646                 :             :   const bool made = QDir().mkdir(clean);
     647                 :             : #endif
     648   [ +  +  +  + ]:          28 :   return made || QFileInfo(clean).isDir();
     649                 :             : }
     650                 :             : 
     651                 :         589 : auto Util::findBinaryInPath(const QString &binary) -> QString {
     652         [ +  + ]:         589 :   if (binary.isEmpty()) {
     653                 :           1 :     return {};
     654                 :             :   }
     655                 :             : 
     656                 :         588 :   initialiseEnvironment();
     657                 :             : 
     658                 :             :   const QStringList dirs =
     659                 :        1176 :       _env.value(QStringLiteral("PATH"))
     660                 :         588 :           .split(QDir::listSeparator(), Qt::SkipEmptyParts);
     661                 :         588 :   QString ret;
     662      [ +  +  + ]:         588 :   if (QDir::fromNativeSeparators(binary).contains(u'/')) {
     663                 :             :     // An explicit path is not a PATH search: an absolute path is checked
     664                 :             :     // as-is, a relative one is resolved against the PATH directories. The
     665                 :             :     // directory-list overload refuses such names, so handle them here.
     666         [ +  + ]:           3 :     if (QDir::isAbsolutePath(binary)) {
     667                 :           4 :       ret = QStandardPaths::findExecutable(binary);
     668         [ +  - ]:           1 :     } else if (!dirs.isEmpty()) {
     669                 :           2 :       ret = QStandardPaths::findExecutable(binary, dirs);
     670                 :             :     }
     671                 :             :   } else {
     672                 :        1170 :     ret = findBinaryInPath(binary, dirs);
     673                 :             :   }
     674                 :             : #ifdef Q_OS_WIN
     675                 :             :   if (ret.isEmpty()) {
     676                 :             :     // Cache per-binary WSL lookup result — the wsl --version probe is a
     677                 :             :     // blocking subprocess that can run several times per session for
     678                 :             :     // missing binaries; once decided, the answer doesn't change at runtime.
     679                 :             :     static QHash<QString, QString> wslBinaryCache;
     680                 :             :     const bool hasWhitespace =
     681                 :             :         std::any_of(binary.cbegin(), binary.cend(),
     682                 :             :                     [](const QChar ch) { return ch.isSpace(); });
     683                 :             :     if (!hasWhitespace) {
     684                 :             :       auto cached = wslBinaryCache.constFind(binary);
     685                 :             :       if (cached != wslBinaryCache.constEnd()) {
     686                 :             :         ret = cached.value();
     687                 :             :       } else {
     688                 :             :         QString wslCommand = QStringLiteral("wsl ") + binary;
     689                 :             :         qCDebug(lcQtPass)
     690                 :             :             << "Util::findBinaryInPath(): falling back to WSL for binary"
     691                 :             :             << binary;
     692                 :             :         QString out, err;
     693                 :             :         QString cachedResult;
     694                 :             :         if (Executor::executeBlocking(wslCommand, {"--version"}, &out, &err) ==
     695                 :             :                 0 &&
     696                 :             :             !out.isEmpty() && err.isEmpty()) {
     697                 :             :           qCDebug(lcQtPass)
     698                 :             :               << "Util::findBinaryInPath(): using WSL binary" << wslCommand;
     699                 :             :           cachedResult = wslCommand;
     700                 :             :         }
     701                 :             :         wslBinaryCache.insert(binary, cachedResult);
     702                 :             :         ret = cachedResult;
     703                 :             :       }
     704                 :             :     }
     705                 :             :   }
     706                 :             : #endif
     707                 :             : 
     708                 :             :   return ret;
     709                 :             : }
     710                 :             : 
     711                 :             : // Bare names only: QStandardPaths::findExecutable() returns an absolute binary
     712                 :             : // without consulting searchPaths, and a relative one with ".." could escape
     713                 :             : // them.
     714                 :         599 : auto Util::findBinaryInPath(const QString &binary,
     715                 :             :                             const QStringList &searchPaths) -> QString {
     716   [ +  +  +  +  :        1197 :   if (binary.isEmpty() || QDir::fromNativeSeparators(binary).contains(u'/')) {
                   +  + ]
     717                 :           4 :     return {};
     718                 :             :   }
     719                 :         595 :   QStringList dirs;
     720                 :         595 :   dirs.reserve(searchPaths.size());
     721         [ +  + ]:        9168 :   for (const QString &dir : searchPaths) {
     722         [ +  + ]:        8573 :     if (!dir.isEmpty()) {
     723                 :             :       dirs.append(dir);
     724                 :             :     }
     725                 :             :   }
     726         [ +  + ]:         595 :   if (dirs.isEmpty()) {
     727                 :             :     // QStandardPaths::findExecutable() treats an empty list as "use PATH".
     728                 :           4 :     return {};
     729                 :             :   }
     730                 :         591 :   return QStandardPaths::findExecutable(binary, dirs);
     731                 :             : }
     732                 :             : 
     733                 :         309 : auto Util::configIsValid(const AppSettings &s) -> bool {
     734                 :         618 :   const QString configFilePath = QDir(s.passStore).filePath(".gpg-id");
     735   [ +  +  +  + ]:         309 :   if (!QFile(configFilePath).exists()) {
     736                 :             :     return false;
     737                 :             :   }
     738                 :             : 
     739         [ +  + ]:         220 :   const QString executable = s.usePass ? s.passExecutable : s.gpgExecutable;
     740                 :             : 
     741      [ +  +  + ]:         220 :   if (const auto wsl = Executor::parseWslCommand(executable)) {
     742                 :             :     // Probe WSL once per session — availability doesn't change at runtime
     743                 :             :     // and the executeBlocking call is a blocking subprocess.
     744                 :           1 :     static const bool wslAvailable = [&wsl]() {
     745                 :           1 :       QString out;
     746                 :           1 :       QString err;
     747   [ +  +  +  -  :           3 :       return Executor::executeBlocking(wsl->launcher,
                      - ]
     748                 :           1 :                                        {QStringLiteral("--version")}, &out,
     749         [ #  # ]:           0 :                                        &err) == 0 &&
     750   [ -  +  -  - ]:           2 :              !out.isEmpty() && err.isEmpty();
     751                 :           1 :     }();
     752         [ -  + ]:           1 :     if (wslAvailable) {
     753                 :             :       return true;
     754                 :             :     }
     755                 :             :   }
     756                 :         220 :   return QFile(executable).exists();
     757                 :             : }
     758                 :             : 
     759                 :      143694 : auto Util::endsWithGpg() -> const QRegularExpression & {
     760                 :      143701 :   static const QRegularExpression expr{R"(\.gpg$)"};
     761                 :      143694 :   return expr;
     762                 :             : }
     763                 :             : 
     764                 :             : // Stops at whitespace, quotes and brackets so a URL on its own line keeps no
     765                 :             : // line break. file:/// is excluded on purpose (local, not network); the test
     766                 :             : // relies on that.
     767                 :         161 : auto Util::protocolRegex() -> const QRegularExpression & {
     768                 :             :   static const QRegularExpression regex{
     769   [ +  +  +  -  :         166 :       R"(((?:https?|ftp|ssh|sftp|ftps|webdav|webdavs)://[^"\s<>\)\]\[]+))"};
                   +  + ]
     770                 :         161 :   return regex;
     771                 :             : }
     772                 :             : 
     773                 :             : namespace {
     774                 :             : /**
     775                 :             :  * @brief Whether @p c ends the scheme or the authority of a URL.
     776                 :             :  * @param c The character.
     777                 :             :  * @return True for '/', '?' and '#'.
     778                 :             :  */
     779                 :             : auto endsUrlPart(QChar c) -> bool {
     780                 :             :   return c == QLatin1Char('/') || c == QLatin1Char('?') ||
     781                 :             :          c == QLatin1Char('#');
     782                 :             : }
     783                 :             : 
     784                 :             : /**
     785                 :             :  * @brief Whether @p c is an ASCII letter.
     786                 :             :  * @param c The character.
     787                 :             :  * @return True for a-z and A-Z.
     788                 :             :  */
     789                 :             : auto isAsciiLetter(QChar c) -> bool {
     790   [ +  +  -  +  :         467 :   return (c >= QLatin1Char('a') && c <= QLatin1Char('z')) ||
          +  -  +  +  -  
                +  +  + ]
     791   [ +  -  -  + ]:           9 :          (c >= QLatin1Char('A') && c <= QLatin1Char('Z'));
     792                 :             : }
     793                 :             : 
     794                 :             : /**
     795                 :             :  * @brief Where the part after a URL's scheme starts, as QUrl finds it.
     796                 :             :  * @param url The candidate URL.
     797                 :             :  * @return The index after the scheme's ':'; 0 when the text before the
     798                 :             :  *         first ':' is no scheme, or no ':' comes before a '/', '?' or '#'.
     799                 :             :  */
     800                 :         124 : auto afterScheme(const QString &url) -> qsizetype {
     801                 :             :   qsizetype colon = -1;
     802         [ +  + ]:         857 :   for (qsizetype i = 0; i < url.size() && !endsUrlPart(url.at(i)); ++i) {
     803         [ +  + ]:         830 :     if (url.at(i) == QLatin1Char(':')) {
     804                 :             :       colon = i;
     805                 :             :       break;
     806                 :             :     }
     807                 :             :   }
     808         [ +  + ]:         124 :   bool scheme = colon > 0 && isAsciiLetter(url.at(0));
     809         [ +  + ]:         494 :   for (qsizetype i = 1; scheme && i < colon; ++i) {
     810                 :             :     const QChar c = url.at(i);
     811                 :             :     scheme =
     812   [ +  +  +  -  :           9 :         isAsciiLetter(c) || (c >= QLatin1Char('0') && c <= QLatin1Char('9')) ||
                   +  + ]
     813   [ +  +  +  + ]:           7 :         c == QLatin1Char('+') || c == QLatin1Char('-') || c == QLatin1Char('.');
     814                 :             :   }
     815         [ +  + ]:         124 :   return scheme ? colon + 1 : 0;
     816                 :             : }
     817                 :             : 
     818                 :             : /**
     819                 :             :  * @brief The length of a URL's authority, found as QUrl finds it.
     820                 :             :  *
     821                 :             :  * QUrl takes the text before the first ':' that comes before any '/', '?'
     822                 :             :  * or '#' as the scheme when it is one (a letter, then letters, digits,
     823                 :             :  * '+', '-' or '.'); the rest starts there, or at the start otherwise. An
     824                 :             :  * authority follows a "//" at that point and runs to the first '/', '?'
     825                 :             :  * or '#'. So "//host" has one too, and a "://" later in the text does not
     826                 :             :  * start it.
     827                 :             :  * @param url The candidate URL.
     828                 :             :  * @return The authority's length, or -1 when there is none.
     829                 :             :  */
     830                 :         124 : auto authorityLength(const QString &url) -> qsizetype {
     831                 :         124 :   const qsizetype hier = afterScheme(url);
     832         [ +  + ]:         248 :   if (url.mid(hier, 2) != QLatin1String("//")) {
     833                 :             :     return -1;
     834                 :             :   }
     835                 :          92 :   qsizetype end = hier + 2;
     836         [ +  + ]:      201621 :   while (end < url.size() && !endsUrlPart(url.at(end))) {
     837                 :      201529 :     ++end;
     838                 :             :   }
     839                 :          92 :   return end - (hier + 2);
     840                 :             : }
     841                 :             : } // namespace
     842                 :             : 
     843                 :         128 : auto Util::isLaunchableWebUrl(const QString &value) -> bool {
     844                 :             :   const QString trimmed = value.trimmed();
     845         [ +  + ]:         128 :   if (trimmed.isEmpty()) {
     846                 :             :     return false;
     847                 :             :   }
     848                 :             :   // Reject control characters first, before QUrl normalisation can hide a
     849                 :             :   // CR/LF/NUL injection into the OS URL handler.
     850         [ +  + ]:      264770 :   for (const QChar &c : trimmed) {
     851                 :             :     if (c == QLatin1Char('\r') || c == QLatin1Char('\n') ||
     852                 :             :         c == QChar(QChar::Null)) {
     853                 :             :       return false;
     854                 :             :     }
     855                 :             :   }
     856                 :             :   // QUrl runs the host through Unicode normalisation, which takes time in
     857                 :             :   // the square of a run of combining marks out of canonical order: one line
     858                 :             :   // of an entry kept the window busy for minutes. A host has at most 253
     859                 :             :   // characters and a port six more, so a longer authority is no web
     860                 :             :   // address anyway.
     861                 :             :   constexpr qsizetype kMaxAuthority = 259;
     862      [ +  +  + ]:         124 :   if (authorityLength(trimmed) > kMaxAuthority) {
     863                 :             :     return false;
     864                 :             :   }
     865                 :         118 :   const QUrl url(trimmed, QUrl::StrictMode);
     866      [ +  +  + ]:         118 :   if (!url.isValid()) {
     867                 :             :     return false;
     868                 :             :   }
     869                 :         103 :   const QString scheme = url.scheme().toLower();
     870   [ +  +  +  + ]:         103 :   if (scheme != QLatin1String("http") && scheme != QLatin1String("https")) {
     871                 :          36 :     return false;
     872                 :             :   }
     873      [ +  +  + ]:         134 :   if (url.host().isEmpty()) {
     874                 :             :     return false;
     875                 :             :   }
     876                 :             :   // Embedded userinfo (user:pass@host) would leak into browser history.
     877   [ +  +  +  +  :         127 :   if (!url.userName().isEmpty() || !url.password().isEmpty()) {
          +  -  +  +  -  
                      - ]
     878                 :             :     return false;
     879                 :             :   }
     880                 :             :   return true;
     881                 :         118 : }
     882                 :             : 
     883                 :             : namespace {
     884                 :             : /**
     885                 :             :  * @brief Whether a character would hide or reorder the text around it.
     886                 :             :  * @param u The UTF-16 code unit.
     887                 :             :  * @return True for C0 controls other than tab, DEL and the C1 controls, the
     888                 :             :  *         line and paragraph separators, and the bidirectional overrides
     889                 :             :  *         and isolates.
     890                 :             :  */
     891                 :    21526795 : auto isDeceptiveChar(char16_t u) -> bool {
     892   [ +  +  +  + ]:    21526742 :   return (u < 0x20 && u != u'\t') || (u >= 0x7f && u <= 0x9f) || u == 0x2028 ||
     893   [ +  +  +  + ]:    43053528 :          u == 0x2029 || (u >= 0x202a && u <= 0x202e) ||
     894         [ +  + ]:    21526727 :          (u >= 0x2066 && u <= 0x2069);
     895                 :             : }
     896                 :             : } // namespace
     897                 :             : 
     898                 :       32347 : auto Util::displayable(const QString &text, bool lineBreaks) -> QString {
     899                 :             :   QString shown = text;
     900         [ +  + ]:    21565216 :   for (qsizetype i = 0; i < shown.size(); ++i) {
     901                 :             :     const char16_t u = shown.at(i).unicode();
     902                 :             :     // A carriage return before a line feed is a Windows line end (git or
     903                 :             :     // gpg output quoted in a message), not a character of its own.
     904                 :             :     const bool lineEnd =
     905   [ +  +  +  +  :    21532869 :         lineBreaks && (u == u'\n' || (u == u'\r' && i + 1 < shown.size() &&
          +  +  +  -  +  
                      + ]
     906                 :             :                                       shown.at(i + 1) == u'\n'));
     907         [ +  + ]:    21526795 :     if (!lineEnd && isDeceptiveChar(u)) {
     908                 :          70 :       shown[i] = QChar(QChar::ReplacementCharacter);
     909                 :             :     }
     910                 :             :   }
     911                 :       32347 :   return shown;
     912                 :             : }
     913                 :             : 
     914                 :         157 : auto Util::linkifyUrls(const QString &text, bool *linked) -> QString {
     915         [ +  + ]:         157 :   if (linked != nullptr) {
     916                 :          61 :     *linked = false;
     917                 :             :   }
     918                 :         157 :   QString html;
     919                 :         157 :   html.reserve(text.size());
     920                 :             :   qsizetype lastIndex = 0;
     921                 :         157 :   QRegularExpressionMatchIterator it = protocolRegex().globalMatch(text);
     922      [ +  +  + ]:         205 :   while (it.hasNext()) {
     923                 :          48 :     const QRegularExpressionMatch match = it.next();
     924                 :          48 :     const QString url = match.captured(0);
     925                 :             :     // Only plain ASCII becomes a link: the link text is the URL as stored,
     926                 :             :     // and a right-to-left letter, a bidi control or a look-alike host in it
     927                 :             :     // makes it read as another address than the one it opens. Such a URL
     928                 :             :     // stays plain text; the open button still takes it.
     929                 :             :     const bool plain = std::all_of(url.cbegin(), url.cend(), [](QChar c) {
     930   [ +  -  +  + ]:        1139 :       return c.unicode() > 0x20 && c.unicode() < 0x7f;
     931                 :             :     });
     932   [ +  +  +  +  :          48 :     if (!plain || !isLaunchableWebUrl(url)) {
                      + ]
     933                 :             :       // Not a web URL (or it carries credentials): leave it in the escaped
     934                 :             :       // plain-text run instead of making it clickable.
     935                 :             :       continue;
     936                 :             :     }
     937                 :          32 :     const qsizetype start = match.capturedStart(0);
     938                 :          32 :     html += text.mid(lastIndex, start - lastIndex).toHtmlEscaped();
     939                 :          32 :     const QString escapedUrl = url.toHtmlEscaped();
     940                 :          64 :     html += QStringLiteral("<a href=\"%1\">%1</a>").arg(escapedUrl);
     941                 :          32 :     lastIndex = match.capturedEnd(0);
     942         [ +  + ]:          32 :     if (linked != nullptr) {
     943                 :          24 :       *linked = true;
     944                 :             :     }
     945                 :          48 :   }
     946                 :         157 :   html += text.mid(lastIndex).toHtmlEscaped();
     947                 :             :   // With a link in it, no bidi embedding, override or isolate control is
     948                 :             :   // drawn: an override earlier in the entry (U+202E) drew the link text
     949                 :             :   // reversed, so it read as another address. Shown as U+FFFD, so the user
     950                 :             :   // sees that something was there; the copy button still copies the value.
     951   [ +  +  +  + ]:         253 :   if (linked != nullptr ? *linked : html.contains(QLatin1String("<a href="))) {
     952         [ +  + ]:        3442 :     for (QChar &c : html) {
     953                 :        3412 :       const char16_t u = c.unicode();
     954         [ +  + ]:        3412 :       if ((u >= 0x202A && u <= 0x202E) || (u >= 0x2066 && u <= 0x2069)) {
     955                 :           1 :         c = QChar(QChar::ReplacementCharacter);
     956                 :             :       }
     957                 :             :     }
     958                 :             :   }
     959                 :         157 :   return html;
     960                 :         157 : }
     961                 :             : 
     962                 :     5345484 : auto Util::isOtherBlockBreak(QChar c) -> bool {
     963                 :     5345484 :   const char16_t u = c.unicode();
     964   [ +  +  +  + ]:     5345484 :   return u == u'\r' || u == 0x2029 || u == 0xFDD0 || u == 0xFDD1;
     965                 :             : }
     966                 :             : 
     967                 :         227 : auto Util::withoutOtherBlockBreaks(QString text) -> QString {
     968         [ +  + ]:      564387 :   for (QChar &c : text) {
     969         [ +  + ]:      564160 :     if (isOtherBlockBreak(c)) {
     970                 :        8002 :       c = QLatin1Char(' ');
     971                 :             :     }
     972                 :             :   }
     973                 :         227 :   return text;
     974                 :             : }
     975                 :             : 
     976                 :         538 : auto Util::hasLongUnbrokenRun(QStringView text) -> bool {
     977                 :             :   qsizetype run = 0;
     978   [ +  +  +  + ]:    11196749 :   for (const QChar c : text) {
     979                 :             :     // A no-break space (U+00A0, U+2007, U+202F) is white space to
     980                 :             :     // isSpace(), but Qt does not wrap at it.
     981                 :             :     const char16_t u = c.unicode();
     982                 :             :     const bool breaks =
     983   [ +  +  +  +  :    11196224 :         c.isSpace() && u != 0x00A0 && u != 0x2007 && u != 0x202F;
                   +  + ]
     984                 :    11126875 :     run = breaks ? 0 : run + 1;
     985         [ +  + ]:    11196224 :     if (run > kMaxUnbrokenRun) {
     986                 :             :       return true;
     987                 :             :     }
     988                 :             :   }
     989                 :             :   return false;
     990                 :             : }
     991                 :             : 
     992                 :       18853 : auto Util::plainToolTip(const QString &text) -> QString {
     993                 :             :   // Escaped, with its white space kept: two names that differ only in it
     994                 :             :   // must not read the same; a long run is cut as everywhere it is kept.
     995                 :       18853 :   return QStringLiteral("<p style=\"white-space: pre-wrap;\">") +
     996                 :       37706 :          boundSpaceRuns(displayable(text, false)).toHtmlEscaped() +
     997                 :       37706 :          QStringLiteral("</p>");
     998                 :             : }
     999                 :             : 
    1000                 :         362 : auto Util::shownName(const QString &name, qsizetype max) -> QString {
    1001                 :         362 :   QString line = displayable(name, false);
    1002                 :         362 :   line.replace(QLatin1Char('\t'), QLatin1Char(' '));
    1003         [ +  + ]:         362 :   if (line.size() <= max) {
    1004                 :         350 :     return line;
    1005                 :             :   }
    1006                 :             :   // Too short for an ellipsis between two ends: the head alone.
    1007         [ +  + ]:          12 :   if (max < 3) {
    1008                 :             :     qsizetype keep = std::max<qsizetype>(max, 0);
    1009   [ +  +  +  + ]:           5 :     if (keep > 0 && line.at(keep - 1).isHighSurrogate()) {
    1010                 :             :       --keep;
    1011                 :             :     }
    1012                 :           5 :     return line.left(keep);
    1013                 :             :   }
    1014                 :           7 :   qsizetype head = max / 3;
    1015         [ +  + ]:           7 :   if (line.at(head - 1).isHighSurrogate()) {
    1016                 :             :     --head;
    1017                 :             :   }
    1018                 :           7 :   qsizetype tail = max - max / 3 - 1;
    1019         [ -  + ]:           7 :   if (line.at(line.size() - tail).isLowSurrogate()) {
    1020                 :           0 :     --tail;
    1021                 :             :   }
    1022                 :          14 :   return line.left(head) + QChar(0x2026) + line.right(tail);
    1023                 :             : }
    1024                 :             : 
    1025                 :             : // One pass, no regex: a pattern such as \s{1001,} retries from every
    1026                 :             : // character of a shorter run, which is quadratic on an entry made of them.
    1027                 :             : // A tab or a line feed ends a run in Qt's layout as well, so it ends one
    1028                 :             : // here; \v and U+0085 do not, so they count.
    1029                 :       19084 : auto Util::boundSpaceRuns(const QString &text) -> QString {
    1030                 :       19084 :   QString bounded;
    1031                 :             :   // Text before this index is in bounded already, or dropped.
    1032                 :             :   qsizetype from = 0;
    1033                 :             :   qsizetype run = 0;
    1034         [ +  + ]:    20772379 :   for (qsizetype i = 0; i < text.size(); ++i) {
    1035                 :             :     const QChar ch = text.at(i);
    1036   [ +  +  +  +  :    20753295 :     if (!ch.isSpace() || ch == QLatin1Char('\t') || ch == QLatin1Char('\n')) {
                   +  + ]
    1037                 :             :       run = 0;
    1038                 :    20599249 :       continue;
    1039                 :             :     }
    1040         [ +  + ]:      154046 :     if (++run <= kMaxSpaceRun) {
    1041                 :       18509 :       continue;
    1042                 :             :     }
    1043         [ +  + ]:      135537 :     if (run == kMaxSpaceRun + 1) {
    1044                 :           6 :       bounded += QStringView(text).sliced(from, i - from);
    1045                 :             :     }
    1046                 :      135537 :     from = i + 1;
    1047                 :             :   }
    1048         [ +  + ]:       19084 :   if (from == 0) {
    1049                 :             :     return text;
    1050                 :             :   }
    1051                 :             :   bounded += QStringView(text).sliced(from);
    1052                 :             :   return bounded;
    1053                 :             : }
    1054                 :             : 
    1055                 :         893 : auto Util::newLinesRegex() -> const QRegularExpression & {
    1056                 :         902 :   static const QRegularExpression regex{"[\r\n]"};
    1057                 :         893 :   return regex;
    1058                 :             : }
    1059                 :             : 
    1060                 :             : // No content heuristics: a line rejected here is erased the next time .gpg-id
    1061                 :             : // is rewritten. A leading `-` is refused because the recipients also go
    1062                 :             : // positionally to `gpg --list-keys`, where it would parse as an option.
    1063                 :        6516 : auto Util::isValidKeyId(const QString &keyId) -> bool {
    1064   [ +  +  +  + ]:        6516 :   return !keyId.isEmpty() && !keyId.startsWith('-');
    1065                 :             : }
    1066                 :             : 
    1067                 :             : namespace {
    1068                 :             : /**
    1069                 :             :  * @brief Whether the walk can see what is in @p dir: read permission to list
    1070                 :             :  * it and, on Unix, search permission to look at what it holds (without it the
    1071                 :             :  * names come, but no entry reads as a file or a folder), and no name Qt
    1072                 :             :  * leaves out of the listing (Util::hasUnreadableName()).
    1073                 :             :  * @param dir An existing directory.
    1074                 :             :  * @return false when the walk would miss what is in it.
    1075                 :             :  */
    1076                 :         266 : auto canList(const QString &dir) -> bool {
    1077                 :             : #ifdef Q_OS_WIN
    1078                 :             :   // Qt answers from the attributes alone unless told to read the ACL.
    1079                 :             :   QNtfsPermissionCheckGuard aclCheck;
    1080                 :             :   return QFileInfo(dir).isReadable();
    1081                 :             : #else
    1082                 :         266 :   const QFileInfo info(dir);
    1083   [ +  +  +  +  :         524 :   return info.isReadable() && info.isExecutable() &&
             +  +  +  + ]
    1084                 :         524 :          !Util::hasUnreadableName(dir);
    1085                 :             : #endif
    1086                 :         266 : }
    1087                 :             : 
    1088                 :             : /**
    1089                 :             :  * @brief Walk @p dir's real, visible directories in sorted pre-order and hand
    1090                 :             :  * every entry to @p visit before any recursion; a directory is entered only
    1091                 :             :  * when @p visit returns true for it. A directory that cannot be read goes to
    1092                 :             :  * @p unlisted, when given: its listing would come back empty, as an empty
    1093                 :             :  * folder's does, and what is in it would be left out without a sign.
    1094                 :             :  */
    1095                 :             : template <typename Visit>
    1096                 :         455 : void walkStore(const QString &dir, Visit visit,
    1097                 :             :                QStringList *unlisted = nullptr) {
    1098                 :             :   // Absolute, so the results are whatever the caller's cwd; not canonical,
    1099                 :             :   // so a linked root keeps the name it was configured under.
    1100                 :        1365 :   QStringList pending{QDir(QDir::cleanPath(dir)).absolutePath()};
    1101         [ +  + ]:        3289 :   while (!pending.isEmpty()) {
    1102                 :        1422 :     const QDir current(pending.takeLast());
    1103   [ +  +  +  -  :        2844 :     if (unlisted != nullptr && current.exists() && !canList(current.path())) {
          +  +  +  +  +  
             +  +  -  - ]
    1104                 :          20 :       qCWarning(lcQtPass) << "Cannot list" << current.path();
    1105                 :          10 :       *unlisted << current.path();
    1106                 :             :       continue;
    1107                 :          10 :     }
    1108                 :             :     // Every entry once, links and hidden entries included, so the decision
    1109                 :             :     // what to do with each is taken here, before any recursion. QDir::System
    1110                 :             :     // keeps dangling links in the listing.
    1111                 :        1412 :     const QFileInfoList entries =
    1112                 :             :         current.entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
    1113                 :             :                                   QDir::System | QDir::NoDotAndDotDot,
    1114                 :             :                               QDir::Name);
    1115                 :        1412 :     QStringList subdirs;
    1116         [ +  + ]:        8561 :     for (const QFileInfo &entry : entries) {
    1117      [ +  +  + ]:        7149 :       if (visit(entry)) {
    1118                 :        1934 :         subdirs << entry.filePath();
    1119                 :             :       }
    1120                 :             :     }
    1121                 :             :     // Pushed last-to-first so the next one taken is the first by name.
    1122         [ +  + ]:        2379 :     for (auto it = subdirs.crbegin(); it != subdirs.crend(); ++it) {
    1123                 :             :       pending << *it;
    1124                 :             :     }
    1125                 :             :   }
    1126                 :         910 : }
    1127                 :             : 
    1128                 :             : /// A symlink or an NTFS junction: never entered, never listed.
    1129                 :      159047 : auto isLink(const QFileInfo &entry) -> bool {
    1130   [ +  +  -  + ]:      159047 :   return entry.isSymLink() || entry.isJunction();
    1131                 :             : }
    1132                 :             : 
    1133                 :             : /// Hidden by attribute, or by the dot convention on every platform: Qt 6.11
    1134                 :             : /// on macOS answers isHidden() from the UF_HIDDEN flag alone once an entry
    1135                 :             : /// was lstat()ed (qfilesystemengine_unix.cpp marks the attribute known there
    1136                 :             : /// without the dot check), and Windows does not consider .stversions hidden
    1137                 :             : /// at all.
    1138                 :        5701 : auto isHiddenEntry(const QFileInfo &entry) -> bool {
    1139   [ +  +  +  +  :       11380 :   return entry.isHidden() || entry.fileName().startsWith(QLatin1Char('.'));
             +  +  -  -  
                      - ]
    1140                 :             : }
    1141                 :             : 
    1142                 :             : /// A real directory that is part of the store: .git, .stversions,
    1143                 :             : /// .Trash-1000 are not, as with QDirIterator without QDir::Hidden.
    1144                 :        7149 : auto isStoreDirectory(const QFileInfo &entry) -> bool {
    1145   [ +  +  +  +  :        7149 :   return !isLink(entry) && entry.isDir() && !isHiddenEntry(entry);
                   +  + ]
    1146                 :             : }
    1147                 :             : } // namespace
    1148                 :             : 
    1149                 :         452 : auto Util::regularFilesUnder(const QString &dir, const QStringList &nameFilters,
    1150                 :             :                              QStringList *skipped, bool hiddenFiles,
    1151                 :             :                              QStringList *unlisted) -> QStringList {
    1152                 :         452 :   QStringList files;
    1153                 :         452 :   walkStore(
    1154                 :             :       dir,
    1155                 :        7069 :       [&](const QFileInfo &entry) {
    1156         [ +  + ]:        7069 :         if (isStoreDirectory(entry)) {
    1157                 :             :           return true;
    1158                 :             :         }
    1159                 :        6124 :         const bool named = QDir::match(nameFilters, entry.fileName());
    1160   [ +  +  +  +  :        6124 :         if (isLink(entry) || (!entry.isDir() && !entry.isFile())) {
                   +  + ]
    1161                 :             :           // A linked directory hides everything behind it; a linked file, or a
    1162                 :             :           // FIFO, socket or device, is only of interest under a name the caller
    1163                 :             :           // asked for.
    1164   [ +  +  +  +  :          75 :           if (skipped != nullptr && (entry.isDir() || named)) {
                   +  + ]
    1165                 :         110 :             qCWarning(lcQtPass) << "Skipping" << entry.filePath()
    1166                 :          55 :                                 << ": not a regular file or directory";
    1167                 :         110 :             *skipped << entry.filePath();
    1168                 :             :           }
    1169                 :          75 :           return false;
    1170                 :             :         }
    1171   [ +  +  +  +  :        6049 :         if (entry.isFile() && named && (hiddenFiles || !isHiddenEntry(entry))) {
             +  +  +  + ]
    1172                 :        9950 :           files << entry.filePath();
    1173                 :             :         }
    1174                 :             :         return false;
    1175                 :             :       },
    1176                 :             :       unlisted);
    1177                 :         452 :   return files;
    1178                 :             : }
    1179                 :             : 
    1180                 :           3 : auto Util::directoriesUnder(const QString &dir) -> QStringList {
    1181                 :           3 :   QStringList dirs;
    1182                 :           3 :   walkStore(dir, [&](const QFileInfo &entry) {
    1183         [ +  + ]:          80 :     if (!isStoreDirectory(entry)) {
    1184                 :             :       return false;
    1185                 :             :     }
    1186                 :          22 :     dirs << entry.filePath();
    1187                 :          22 :     return true;
    1188                 :             :   });
    1189                 :           3 :   return dirs;
    1190                 :             : }
    1191                 :             : 
    1192                 :         449 : auto Util::hasUnreadableName(const QString &dir) -> bool {
    1193                 :             : #ifdef Q_OS_WIN
    1194                 :             :   Q_UNUSED(dir);
    1195                 :             :   return false;
    1196                 :             : #else
    1197                 :             :   // The names as bytes, as readdir() gives them; Qt's own listing has
    1198                 :             :   // already dropped the ones this is looking for.
    1199                 :         449 :   DIR *listing = ::opendir(QFile::encodeName(dir).constData());
    1200         [ +  + ]:         449 :   if (listing == nullptr) {
    1201                 :             :     return false;
    1202                 :             :   }
    1203                 :         446 :   const auto close = qScopeGuard([listing] { ::closedir(listing); });
    1204      [ +  +  + ]:        2282 :   while (const dirent *entry = ::readdir(listing)) {
    1205         [ +  + ]:        1842 :     if (!QByteArrayView(entry->d_name).isValidUtf8()) {
    1206                 :             :       return true;
    1207                 :             :     }
    1208                 :             :   }
    1209                 :             :   return false;
    1210                 :             : #endif
    1211                 :             : }
    1212                 :             : 
    1213                 :      145731 : auto Util::isLinkedFolder(const QString &path) -> bool {
    1214                 :      291462 :   return isLink(QFileInfo(QDir::cleanPath(path)));
    1215                 :             : }
    1216                 :             : 
    1217                 :      141513 : auto Util::isUnderLink(const QString &path, const QString &storeRoot,
    1218                 :             :                        bool includeSelf) -> bool {
    1219                 :             :   // "C:/Store" and "c:/store" are one directory on Windows; a path spelled
    1220                 :             :   // the other way must not skip the walk (as in Pass::getGpgIdPath).
    1221                 :             : #ifdef Q_OS_WIN
    1222                 :             :   constexpr auto cs = Qt::CaseInsensitive;
    1223                 :             : #else
    1224                 :             :   constexpr auto cs = Qt::CaseSensitive;
    1225                 :             : #endif
    1226                 :      141513 :   const QString root = QDir::cleanPath(storeRoot);
    1227                 :             :   // A root of "/" or "C:/" already ends in the separator.
    1228                 :             :   const QString prefix =
    1229   [ +  -  +  + ]:      141513 :       root.endsWith(QLatin1Char('/')) ? root : root + QLatin1Char('/');
    1230                 :             :   const auto isRoot = [&](const QString &p) {
    1231                 :      144865 :     return p.compare(root, cs) == 0;
    1232                 :             :   };
    1233                 :      141513 :   QString current = QDir::cleanPath(path);
    1234      [ +  +  + ]:      141513 :   if (!current.startsWith(prefix, cs)) {
    1235                 :             :     // Not under the store as named: only the entry itself can be judged.
    1236   [ +  -  +  +  :         696 :     return includeSelf && !isRoot(current) && isLinkedFolder(current);
                +  -  + ]
    1237                 :             :   }
    1238         [ +  + ]:      141165 :   if (!includeSelf) {
    1239                 :      280086 :     current = QFileInfo(current).path();
    1240                 :             :   }
    1241   [ +  +  +  +  :      144517 :   for (; !isRoot(current) && current.startsWith(prefix, cs);
                      - ]
    1242         [ +  + ]:        6704 :        current = QFileInfo(current).path()) {
    1243      [ +  +  + ]:        3406 :     if (isLinkedFolder(current)) {
    1244                 :             :       return true;
    1245                 :             :     }
    1246                 :             :   }
    1247                 :             :   return false;
    1248                 :             : }
    1249                 :             : 
    1250                 :             : #ifndef Q_OS_WIN
    1251                 :             : namespace {
    1252                 :             : 
    1253                 :             : /// The filesystem cannot make hard links at all (FAT/exFAT refuse with
    1254                 :             : /// EPERM, some FUSE filesystems with ENOTSUP or ENOSYS).
    1255                 :             : auto hasNoHardLinks(int error) -> bool {
    1256         [ +  - ]:           2 :   return error == EPERM || error == ENOTSUP || error == EOPNOTSUPP ||
    1257                 :             :          error == ENOSYS;
    1258                 :             : }
    1259                 :             : 
    1260                 :             : /// rename() that fails with EEXIST instead of replacing, where the platform
    1261                 :             : /// has one; nothing when neither the platform nor the filesystem does.
    1262                 :           8 : auto renameExclusive(const QByteArray &source, const QByteArray &target)
    1263                 :             :     -> std::optional<bool> {
    1264                 :             : #if defined(__GLIBC__) &&                                                      \
    1265                 :             :     (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 28))
    1266         [ +  + ]:           8 :   if (::renameat2(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(),
    1267                 :             :                   RENAME_NOREPLACE) == 0) {
    1268                 :           2 :     return true;
    1269                 :             :   }
    1270         [ +  + ]:           6 :   if (errno == EINVAL || errno == ENOSYS || hasNoHardLinks(errno)) {
    1271                 :           4 :     return std::nullopt;
    1272                 :             :   }
    1273                 :           2 :   return false;
    1274                 :             : #elif defined(Q_OS_MACOS)
    1275                 :             :   if (::renamex_np(source.constData(), target.constData(), RENAME_EXCL) == 0) {
    1276                 :             :     return true;
    1277                 :             :   }
    1278                 :             :   if (errno == EINVAL || errno == ENOTSUP) {
    1279                 :             :     return std::nullopt;
    1280                 :             :   }
    1281                 :             :   return false;
    1282                 :             : #else
    1283                 :             :   Q_UNUSED(source);
    1284                 :             :   Q_UNUSED(target);
    1285                 :             :   return std::nullopt;
    1286                 :             : #endif
    1287                 :             : }
    1288                 :             : 
    1289                 :             : /**
    1290                 :             :  * @brief Gives @p source the name @p target unless something already has it.
    1291                 :             :  *
    1292                 :             :  * A hard link is the one way every POSIX system can do that in one step:
    1293                 :             :  * linkat() fails with EEXIST rather than replacing. Where the filesystem has
    1294                 :             :  * no hard links, an exclusive rename does it; where that is missing too, the
    1295                 :             :  * name is checked and then renamed, which leaves a short window for another
    1296                 :             :  * writer to create it in between.
    1297                 :             :  */
    1298                 :         130 : auto placeWithoutReplacing(const QByteArray &source, const QByteArray &target)
    1299                 :             :     -> bool {
    1300                 :             :   // linkat() without AT_SYMLINK_FOLLOW follows nothing; link() would, on
    1301                 :             :   // macOS and the BSDs, hard-link whatever a symlink planted under the
    1302                 :             :   // source's name points at.
    1303         [ +  + ]:         130 :   if (::linkat(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(), 0) ==
    1304                 :             :       0) {
    1305         [ +  + ]:         114 :     if (::unlink(source.constData()) == 0) {
    1306                 :             :       return true;
    1307                 :             :     }
    1308                 :             :     // Both names now hold the file. Take the new one away again so the
    1309                 :             :     // caller sees the state it started from, not a success with the source
    1310                 :             :     // still there.
    1311                 :           1 :     const int err = errno;
    1312                 :           1 :     ::unlink(target.constData());
    1313                 :           1 :     errno = err;
    1314                 :           1 :     return false;
    1315                 :             :   }
    1316   [ +  +  +  - ]:          16 :   if (!hasNoHardLinks(errno)) {
    1317                 :             :     return false;
    1318                 :             :   }
    1319         [ +  + ]:           8 :   if (const std::optional<bool> renamed = renameExclusive(source, target)) {
    1320                 :           4 :     return *renamed;
    1321                 :             :   }
    1322                 :           4 :   struct stat st{};
    1323   [ +  +  +  - ]:           4 :   if (::lstat(target.constData(), &st) == 0 || errno != ENOENT) {
    1324                 :           2 :     errno = EEXIST;
    1325                 :           2 :     return false;
    1326                 :             :   }
    1327                 :           2 :   return ::rename(source.constData(), target.constData()) == 0;
    1328                 :             : }
    1329                 :             : 
    1330                 :             : } // namespace
    1331                 :             : #endif
    1332                 :             : 
    1333                 :         345 : auto Util::replaceFile(const QString &from, const QString &to, bool replace)
    1334                 :             :     -> bool {
    1335                 :             : #ifdef Q_OS_WIN
    1336                 :             :   const std::wstring source =
    1337                 :             :       QDir::toNativeSeparators(QFileInfo(from).absoluteFilePath())
    1338                 :             :           .toStdWString();
    1339                 :             :   const std::wstring target =
    1340                 :             :       QDir::toNativeSeparators(QFileInfo(to).absoluteFilePath()).toStdWString();
    1341                 :             :   // WRITE_THROUGH: the new entry is on the device when this returns.
    1342                 :             :   return MoveFileExW(source.c_str(), target.c_str(),
    1343                 :             :                      (replace ? MOVEFILE_REPLACE_EXISTING : 0) |
    1344                 :             :                          MOVEFILE_WRITE_THROUGH) != 0;
    1345                 :             : #else
    1346                 :             :   const QByteArray source = QFile::encodeName(from);
    1347                 :             :   const QByteArray target = QFile::encodeName(to);
    1348         [ +  + ]:         345 :   if (replace) {
    1349         [ +  + ]:         215 :     if (::rename(source.constData(), target.constData()) != 0) {
    1350                 :             :       return false;
    1351                 :             :     }
    1352                 :             :   } else {
    1353         [ +  + ]:         130 :     if (!placeWithoutReplacing(source, target)) {
    1354                 :             :       return false;
    1355                 :             :     }
    1356                 :             :   }
    1357                 :             :   // Sync the directory entry so a crash does not lose the new name. Best
    1358                 :             :   // effort: the bytes are already synced, and some network filesystems
    1359                 :             :   // cannot sync a directory.
    1360                 :         658 :   const int dir = ::open(QFile::encodeName(QFileInfo(to).path()).constData(),
    1361                 :             :                          O_RDONLY | O_DIRECTORY | O_CLOEXEC);
    1362         [ +  - ]:         329 :   if (dir >= 0) {
    1363                 :             :     int rc;
    1364                 :             :     do {
    1365                 :         329 :       rc = ::fsync(dir);
    1366   [ -  +  -  - ]:         329 :     } while (rc != 0 && errno == EINTR);
    1367                 :         329 :     ::close(dir);
    1368                 :             :   }
    1369                 :             :   return true;
    1370                 :             : #endif
    1371                 :             : }
    1372                 :             : 
    1373                 :             : namespace {
    1374                 :             : #ifdef Q_OS_WIN
    1375                 :             : /**
    1376                 :             :  * @brief The attributes of an open handle when it is a file on disk.
    1377                 :             :  * @param handle The open handle.
    1378                 :             :  * @return The attributes; nothing for a directory, a device, anything that
    1379                 :             :  *         is not a disk file, or when they cannot be read.
    1380                 :             :  */
    1381                 :             : auto diskFileAttributes(HANDLE handle) -> std::optional<DWORD> {
    1382                 :             :   BY_HANDLE_FILE_INFORMATION info{};
    1383                 :             :   if (!GetFileInformationByHandle(handle, &info) ||
    1384                 :             :       (info.dwFileAttributes &
    1385                 :             :        (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) != 0 ||
    1386                 :             :       GetFileType(handle) != FILE_TYPE_DISK) {
    1387                 :             :     return std::nullopt;
    1388                 :             :   }
    1389                 :             :   return info.dwFileAttributes;
    1390                 :             : }
    1391                 :             : 
    1392                 :             : /**
    1393                 :             :  * @brief Open the file behind a reparse point that names no other file.
    1394                 :             :  *
    1395                 :             :  * A link, a junction or anything else that names another file is
    1396                 :             :  * refused. Any other reparse point (the placeholder of a cloud
    1397                 :             :  * provider such as OneDrive, whose content is not on disk yet) is
    1398                 :             :  * opened once more through it, so its filter fetches the content, and
    1399                 :             :  * only when that open reaches the very same file.
    1400                 :             :  * @param handle The reparse point itself, open; left open.
    1401                 :             :  * @param native Its native path.
    1402                 :             :  * @return A handle on the file reached through it; INVALID_HANDLE_VALUE
    1403                 :             :  *         when refused.
    1404                 :             :  */
    1405                 :             : auto openThroughReparsePoint(HANDLE handle, const std::wstring &native)
    1406                 :             :     -> HANDLE {
    1407                 :             :   FILE_ATTRIBUTE_TAG_INFO tag{};
    1408                 :             :   if (!GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &tag,
    1409                 :             :                                     sizeof(tag)) ||
    1410                 :             :       IsReparseTagNameSurrogate(tag.ReparseTag)) {
    1411                 :             :     return INVALID_HANDLE_VALUE;
    1412                 :             :   }
    1413                 :             :   HANDLE through =
    1414                 :             :       CreateFileW(native.c_str(), GENERIC_READ,
    1415                 :             :                   FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
    1416                 :             :                   nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
    1417                 :             :   if (through == INVALID_HANDLE_VALUE) {
    1418                 :             :     return INVALID_HANDLE_VALUE;
    1419                 :             :   }
    1420                 :             :   // The 128-bit file ID: the 64-bit index in BY_HANDLE_FILE_INFORMATION
    1421                 :             :   // is not unique on ReFS.
    1422                 :             :   FILE_ID_INFO firstId{};
    1423                 :             :   FILE_ID_INFO throughId{};
    1424                 :             :   const bool same =
    1425                 :             :       GetFileInformationByHandleEx(handle, FileIdInfo, &firstId,
    1426                 :             :                                    sizeof(firstId)) &&
    1427                 :             :       GetFileInformationByHandleEx(through, FileIdInfo, &throughId,
    1428                 :             :                                    sizeof(throughId)) &&
    1429                 :             :       firstId.VolumeSerialNumber == throughId.VolumeSerialNumber &&
    1430                 :             :       std::memcmp(&firstId.FileId, &throughId.FileId, sizeof(firstId.FileId)) ==
    1431                 :             :           0 &&
    1432                 :             :       diskFileAttributes(through).has_value();
    1433                 :             :   if (!same) {
    1434                 :             :     CloseHandle(through);
    1435                 :             :     return INVALID_HANDLE_VALUE;
    1436                 :             :   }
    1437                 :             :   return through;
    1438                 :             : }
    1439                 :             : 
    1440                 :             : /**
    1441                 :             :  * @brief Util::openRegularFile() for Windows.
    1442                 :             :  * @param path The file, as the caller names it.
    1443                 :             :  * @param file Receives the open file on success; untouched otherwise.
    1444                 :             :  * @return Whether @p file is open on a regular file.
    1445                 :             :  */
    1446                 :             : auto openRegularFileNative(const QString &path, QFile &file) -> bool {
    1447                 :             :   // FILE_FLAG_OPEN_REPARSE_POINT opens a symbolic link or junction itself
    1448                 :             :   // rather than its target, so the handle's attributes say what the name
    1449                 :             :   // was at the moment of the open.
    1450                 :             :   const std::wstring native =
    1451                 :             :       QDir::toNativeSeparators(QFileInfo(path).absoluteFilePath())
    1452                 :             :           .toStdWString();
    1453                 :             :   HANDLE handle = CreateFileW(
    1454                 :             :       native.c_str(), GENERIC_READ,
    1455                 :             :       FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
    1456                 :             :       OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
    1457                 :             :   if (handle == INVALID_HANDLE_VALUE) {
    1458                 :             :     return false;
    1459                 :             :   }
    1460                 :             :   const std::optional<DWORD> attributes = diskFileAttributes(handle);
    1461                 :             :   if (!attributes) {
    1462                 :             :     CloseHandle(handle);
    1463                 :             :     return false;
    1464                 :             :   }
    1465                 :             :   if ((*attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
    1466                 :             :     const HANDLE through = openThroughReparsePoint(handle, native);
    1467                 :             :     CloseHandle(handle);
    1468                 :             :     if (through == INVALID_HANDLE_VALUE) {
    1469                 :             :       return false;
    1470                 :             :     }
    1471                 :             :     handle = through;
    1472                 :             :   }
    1473                 :             :   const int fd = _open_osfhandle(reinterpret_cast<intptr_t>(handle),
    1474                 :             :                                  _O_RDONLY | _O_BINARY);
    1475                 :             :   if (fd < 0) {
    1476                 :             :     CloseHandle(handle);
    1477                 :             :     return false;
    1478                 :             :   }
    1479                 :             :   if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
    1480                 :             :     _close(fd);
    1481                 :             :     return false;
    1482                 :             :   }
    1483                 :             :   return true;
    1484                 :             : }
    1485                 :             : #else
    1486                 :             : /**
    1487                 :             :  * @brief Hand an open descriptor to @p file when it is a regular file.
    1488                 :             :  * @param fd The descriptor, opened without following a link; closed here
    1489                 :             :  *        when refused, owned by @p file otherwise.
    1490                 :             :  * @param file Receives the open file on success; untouched otherwise.
    1491                 :             :  * @return Whether @p file is open on a regular file.
    1492                 :             :  */
    1493                 :        1864 : auto adoptRegularFd(int fd, QFile &file) -> bool {
    1494                 :        1864 :   struct stat st{};
    1495   [ +  -  +  + ]:        1864 :   if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
    1496                 :           9 :     ::close(fd);
    1497                 :           9 :     return false;
    1498                 :             :   }
    1499                 :             :   // The descriptor, not the name, is what QFile opens here: the object
    1500                 :             :   // fstat() judged is the object read, so a name swapped between the check
    1501                 :             :   // and the read cannot make it read another file (the file's contents can
    1502                 :             :   // still change; the check is on what kind of file it is). CodeQL's
    1503                 :             :   // check-then-use pattern matcher sees an open after a check and cannot
    1504                 :             :   // tell (its alert on this line is dismissed as a false positive; inline
    1505                 :             :   // suppression comments are not read by the default setup).
    1506         [ -  + ]:        1855 :   if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
    1507                 :           0 :     ::close(fd);
    1508                 :           0 :     return false;
    1509                 :             :   }
    1510                 :             :   return true;
    1511                 :             : }
    1512                 :             : 
    1513                 :             : /**
    1514                 :             :  * @brief Util::openRegularFile() for POSIX.
    1515                 :             :  * @param path The file, as the caller names it.
    1516                 :             :  * @param file Receives the open file on success; untouched otherwise.
    1517                 :             :  * @return Whether @p file is open on a regular file.
    1518                 :             :  */
    1519                 :         684 : auto openRegularFileNative(const QString &path, QFile &file) -> bool {
    1520                 :             :   // O_NOFOLLOW fails with ELOOP on a symbolic link; O_NONBLOCK keeps a FIFO
    1521                 :             :   // from blocking the open until fstat() can refuse it.
    1522                 :         684 :   const int fd = ::open(QFile::encodeName(path).constData(),
    1523                 :             :                         O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
    1524   [ +  +  +  + ]:         738 :   return fd >= 0 && adoptRegularFd(fd, file);
    1525                 :             : }
    1526                 :             : #endif
    1527                 :             : } // namespace
    1528                 :             : 
    1529                 :         684 : auto Util::openRegularFile(const QString &path, QFile &file) -> bool {
    1530                 :         684 :   return openRegularFileNative(path, file);
    1531                 :             : }
    1532                 :             : 
    1533                 :             : namespace {
    1534                 :             : /**
    1535                 :             :  * @brief Read an open regular file whole when it holds at most @p maxBytes.
    1536                 :             :  * @param file Open on a regular file.
    1537                 :             :  * @param maxBytes The most bytes accepted.
    1538                 :             :  * @return The contents; nothing when larger or unreadable.
    1539                 :             :  */
    1540                 :        1295 : auto readOpenFile(QFile &file, qint64 maxBytes) -> std::optional<QByteArray> {
    1541                 :             :   // A regular file's size is reliable, also when sparse: refuse a large one
    1542                 :             :   // before reading anything. One byte past the limit still guards a file
    1543                 :             :   // that grows meanwhile.
    1544         [ +  + ]:        1295 :   if (file.size() > maxBytes) {
    1545                 :          10 :     return std::nullopt;
    1546                 :             :   }
    1547                 :        1285 :   QByteArray bytes = file.read(maxBytes + 1);
    1548   [ +  -  +  -  :        1285 :   if (bytes.size() > maxBytes || file.error() != QFileDevice::NoError) {
                      + ]
    1549                 :           0 :     return std::nullopt;
    1550                 :             :   }
    1551                 :             :   return bytes;
    1552                 :             : }
    1553                 :             : } // namespace
    1554                 :             : 
    1555                 :          80 : auto Util::readRegularFile(const QString &path, qint64 maxBytes)
    1556                 :             :     -> std::optional<QByteArray> {
    1557                 :          80 :   QFile file;
    1558      [ +  +  + ]:          80 :   if (!openRegularFile(path, file)) {
    1559                 :          10 :     return std::nullopt;
    1560                 :             :   }
    1561                 :          70 :   return readOpenFile(file, maxBytes);
    1562                 :          80 : }
    1563                 :             : 
    1564                 :         920 : auto Util::readRegularFileInStore(const QString &store, const QString &path,
    1565                 :             :                                   qint64 maxBytes)
    1566                 :             :     -> std::optional<QByteArray> {
    1567                 :         924 :   const auto under = [&path](const QString &root) {
    1568                 :        1848 :     const QString relative = QDir(root).relativeFilePath(QDir::cleanPath(path));
    1569   [ +  +  -  +  :         924 :     return !root.isEmpty() && !isAbsoluteFsPath(relative) &&
                      - ]
    1570   [ +  -  +  +  :        2772 :            relative != QStringLiteral("..") &&
             +  -  -  - ]
    1571   [ +  +  -  +  :        2772 :            !relative.startsWith(QStringLiteral("../"));
             -  -  -  -  
                      - ]
    1572                 :         920 :   };
    1573                 :         920 :   const QString root = QDir::cleanPath(store);
    1574      [ +  +  + ]:         920 :   if (under(root)) {
    1575                 :         916 :     return readRegularFileUnder(root, path, maxBytes);
    1576                 :             :   }
    1577                 :           4 :   const QString canonical = QFileInfo(root).canonicalFilePath();
    1578      [ +  +  + ]:           4 :   if (under(canonical)) {
    1579                 :           2 :     return readRegularFileUnder(canonical, path, maxBytes);
    1580                 :             :   }
    1581                 :           2 :   return std::nullopt;
    1582                 :             : }
    1583                 :             : 
    1584                 :             : namespace {
    1585                 :             : #ifdef Q_OS_WIN
    1586                 :             : /**
    1587                 :             :  * @brief Open a folder of the way to a file, to hold it in place.
    1588                 :             :  *
    1589                 :             :  * A reparse point that names another place (a symbolic link, a
    1590                 :             :  * junction: what the walk's isLink() leaves out) is refused, as
    1591                 :             :  * openRegularFile() refuses one as the file. A folder with another
    1592                 :             :  * reparse tag, such as a cloud provider's placeholder, is listed by the
    1593                 :             :  * walk and is read through here too.
    1594                 :             :  * @param folder The folder.
    1595                 :             :  * @param isRoot Whether it is the root, which is followed when a link.
    1596                 :             :  * @return The handle, open without FILE_SHARE_DELETE;
    1597                 :             :  *         INVALID_HANDLE_VALUE when refused.
    1598                 :             :  */
    1599                 :             : auto holdFolder(const QString &folder, bool isRoot) -> HANDLE {
    1600                 :             :   const std::wstring native = QDir::toNativeSeparators(folder).toStdWString();
    1601                 :             :   // GENERIC_READ (listing the folder) is data access, so the share mode
    1602                 :             :   // is enforced against a later open for DELETE; attribute access alone
    1603                 :             :   // would not be.
    1604                 :             :   HANDLE handle = CreateFileW(
    1605                 :             :       native.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
    1606                 :             :       OPEN_EXISTING,
    1607                 :             :       FILE_FLAG_BACKUP_SEMANTICS | (isRoot ? 0 : FILE_FLAG_OPEN_REPARSE_POINT),
    1608                 :             :       nullptr);
    1609                 :             :   if (handle == INVALID_HANDLE_VALUE) {
    1610                 :             :     return INVALID_HANDLE_VALUE;
    1611                 :             :   }
    1612                 :             :   FILE_ATTRIBUTE_TAG_INFO info{};
    1613                 :             :   if (!GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &info,
    1614                 :             :                                     sizeof(info)) ||
    1615                 :             :       (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
    1616                 :             :     CloseHandle(handle);
    1617                 :             :     return INVALID_HANDLE_VALUE;
    1618                 :             :   }
    1619                 :             :   const bool link = (info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 &&
    1620                 :             :                     IsReparseTagNameSurrogate(info.ReparseTag);
    1621                 :             :   if (!isRoot && link) {
    1622                 :             :     CloseHandle(handle);
    1623                 :             :     return INVALID_HANDLE_VALUE;
    1624                 :             :   }
    1625                 :             :   return handle;
    1626                 :             : }
    1627                 :             : 
    1628                 :             : /**
    1629                 :             :  * @brief Util::readRegularFileUnder() for Windows, once the path is judged.
    1630                 :             :  * @param cleanRoot The store root, cleaned.
    1631                 :             :  * @param parts The names from the root down to the file.
    1632                 :             :  * @param path The file, spelled under the root.
    1633                 :             :  * @param maxBytes The most bytes accepted.
    1634                 :             :  * @return The contents; nothing when a folder or the file is refused.
    1635                 :             :  */
    1636                 :             : auto readUnderNative(const QString &cleanRoot, const QStringList &parts,
    1637                 :             :                      const QString &path, qint64 maxBytes)
    1638                 :             :     -> std::optional<QByteArray> {
    1639                 :             :   // No openat() here: each folder from the root down is opened by name and
    1640                 :             :   // held open, without FILE_SHARE_DELETE, until the file is read. A folder
    1641                 :             :   // held that way cannot be renamed, removed or replaced by a junction
    1642                 :             :   // meanwhile, so the file is opened through exactly the folders judged.
    1643                 :             :   // The root itself is followed (a linked store is the user's setup).
    1644                 :             :   std::vector<HANDLE> held;
    1645                 :             :   const auto release = qScopeGuard([&held] {
    1646                 :             :     for (HANDLE handle : held) {
    1647                 :             :       CloseHandle(handle);
    1648                 :             :     }
    1649                 :             :   });
    1650                 :             :   QString folder = cleanRoot;
    1651                 :             :   for (qsizetype i = 0; i < parts.size(); ++i) {
    1652                 :             :     const bool isRoot = i == 0;
    1653                 :             :     if (!isRoot) {
    1654                 :             :       folder += QLatin1Char('/') + parts.at(i - 1);
    1655                 :             :     }
    1656                 :             :     const HANDLE handle = holdFolder(folder, isRoot);
    1657                 :             :     if (handle == INVALID_HANDLE_VALUE) {
    1658                 :             :       return std::nullopt;
    1659                 :             :     }
    1660                 :             :     held.push_back(handle);
    1661                 :             :   }
    1662                 :             :   // openRegularFile() refuses a link or junction as the file itself, and
    1663                 :             :   // reads any other reparse point (a cloud placeholder) through.
    1664                 :             :   return Util::readRegularFile(path, maxBytes);
    1665                 :             : }
    1666                 :             : #else
    1667                 :             : /**
    1668                 :             :  * @brief Util::readRegularFileUnder() for POSIX, once the path is judged.
    1669                 :             :  * @param cleanRoot The store root, cleaned.
    1670                 :             :  * @param parts The names from the root down to the file.
    1671                 :             :  * @param path The file, spelled under the root; the walk goes by @p parts.
    1672                 :             :  * @param maxBytes The most bytes accepted.
    1673                 :             :  * @return The contents; nothing when a folder or the file is refused.
    1674                 :             :  */
    1675                 :        1356 : auto readUnderNative(const QString &cleanRoot, const QStringList &parts,
    1676                 :             :                      const QString &path, qint64 maxBytes)
    1677                 :             :     -> std::optional<QByteArray> {
    1678                 :             :   Q_UNUSED(path)
    1679                 :             :   // The root by name, followed if it is a link (the user's setup); below it
    1680                 :             :   // nothing is.
    1681                 :        1356 :   int dir = ::open(QFile::encodeName(cleanRoot).constData(),
    1682                 :             :                    O_RDONLY | O_DIRECTORY | O_CLOEXEC);
    1683         [ -  + ]:        1356 :   if (dir < 0) {
    1684                 :           0 :     return std::nullopt;
    1685                 :             :   }
    1686         [ +  + ]:        1564 :   for (qsizetype i = 0; i + 1 < parts.size(); ++i) {
    1687                 :         217 :     const int next = ::openat(dir, QFile::encodeName(parts.at(i)).constData(),
    1688                 :             :                               O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
    1689                 :         217 :     ::close(dir);
    1690         [ +  + ]:         217 :     if (next < 0) {
    1691                 :           9 :       return std::nullopt;
    1692                 :             :     }
    1693                 :             :     dir = next;
    1694                 :             :   }
    1695                 :             :   // As openRegularFile(): no link, no FIFO left blocking the open.
    1696                 :        1347 :   const int fd = ::openat(dir, QFile::encodeName(parts.constLast()).constData(),
    1697                 :             :                           O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
    1698                 :        1347 :   ::close(dir);
    1699                 :        1347 :   QFile file;
    1700   [ +  +  +  +  :        1347 :   if (fd < 0 || !adoptRegularFd(fd, file)) {
                      + ]
    1701                 :         122 :     return std::nullopt;
    1702                 :             :   }
    1703                 :        1225 :   return readOpenFile(file, maxBytes);
    1704                 :        1347 : }
    1705                 :             : #endif
    1706                 :             : } // namespace
    1707                 :             : 
    1708                 :        1359 : auto Util::readRegularFileUnder(const QString &root, const QString &path,
    1709                 :             :                                 qint64 maxBytes) -> std::optional<QByteArray> {
    1710                 :        1359 :   const QString cleanRoot = QDir::cleanPath(root);
    1711                 :             :   const QString relative =
    1712                 :        2718 :       QDir(cleanRoot).relativeFilePath(QDir::cleanPath(path));
    1713                 :        1359 :   const QStringList parts = relative.split(QLatin1Char('/'));
    1714   [ +  -  +  +  :        2718 :   if (relative.isEmpty() || isAbsoluteFsPath(relative) ||
                      + ]
    1715   [ +  +  +  -  :        2716 :       parts.contains(QStringLiteral("..")) ||
                   +  + ]
    1716   [ +  -  +  +  :        5431 :       parts.contains(QStringLiteral(".")) || parts.contains(QString())) {
             +  +  +  - ]
    1717                 :           3 :     return std::nullopt;
    1718                 :             :   }
    1719                 :        1356 :   return readUnderNative(cleanRoot, parts, path, maxBytes);
    1720                 :             : }
    1721                 :             : 
    1722                 :         328 : auto Util::syncToDisk(QFileDevice &file) -> bool {
    1723         [ +  - ]:         328 :   if (!file.flush()) {
    1724                 :             :     return false;
    1725                 :             :   }
    1726                 :             : #ifdef Q_OS_WIN
    1727                 :             :   const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
    1728                 :             :   return handle != INVALID_HANDLE_VALUE && FlushFileBuffers(handle) != 0;
    1729                 :             : #else
    1730                 :         328 :   return ::fsync(file.handle()) == 0;
    1731                 :             : #endif
    1732                 :             : }
    1733                 :             : 
    1734                 :             : namespace {
    1735                 :             : 
    1736                 :             : /**
    1737                 :             :  * @brief What tells one file object from another on its filesystem: device
    1738                 :             :  * and inode on POSIX, volume serial and file index on Windows.
    1739                 :             :  */
    1740                 :             : struct FileIdentity {
    1741                 :             :   quint64 volume = 0;
    1742                 :             :   quint64 index = 0;
    1743                 :             :   bool known = false;
    1744                 :             : };
    1745                 :             : 
    1746                 :         317 : auto operator==(const FileIdentity &a, const FileIdentity &b) -> bool {
    1747   [ +  -  +  -  :         317 :   return a.known && b.known && a.volume == b.volume && a.index == b.index;
             +  -  +  + ]
    1748                 :             : }
    1749                 :             : 
    1750                 :             : /// The identity of the object @p file is open on, or an unknown one.
    1751                 :         645 : auto identityOf(const QFileDevice &file) -> FileIdentity {
    1752                 :             : #ifdef Q_OS_WIN
    1753                 :             :   const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
    1754                 :             :   BY_HANDLE_FILE_INFORMATION info;
    1755                 :             :   if (handle == INVALID_HANDLE_VALUE ||
    1756                 :             :       GetFileInformationByHandle(handle, &info) == 0) {
    1757                 :             :     return {};
    1758                 :             :   }
    1759                 :             :   // On FAT/exFAT the file ID is the directory entry's offset, which a rename
    1760                 :             :   // can move. They have no hard links either (the swap this catches needs
    1761                 :             :   // one), so the identity is left unknown there.
    1762                 :             :   DWORD flags = 0;
    1763                 :             :   if (GetVolumeInformationByHandleW(handle, nullptr, 0, nullptr, nullptr,
    1764                 :             :                                     &flags, nullptr, 0) == 0 ||
    1765                 :             :       (flags & FILE_SUPPORTS_HARD_LINKS) == 0) {
    1766                 :             :     return {};
    1767                 :             :   }
    1768                 :             :   return {info.dwVolumeSerialNumber,
    1769                 :             :           (static_cast<quint64>(info.nFileIndexHigh) << 32) |
    1770                 :             :               info.nFileIndexLow,
    1771                 :             :           true};
    1772                 :             : #else
    1773                 :         645 :   struct stat st{};
    1774         [ -  + ]:         645 :   if (::fstat(file.handle(), &st) != 0) {
    1775                 :           0 :     return {};
    1776                 :             :   }
    1777                 :         645 :   return {static_cast<quint64>(st.st_dev), static_cast<quint64>(st.st_ino),
    1778                 :         645 :           true};
    1779                 :             : #endif
    1780                 :             : }
    1781                 :             : 
    1782                 :             : /// Put @p text in @p error when there is one; false, for `return fail(...)`.
    1783                 :             : auto fail(QString *error, const QString &text) -> bool {
    1784   [ +  -  +  -  :          22 :   if (error != nullptr) {
                   +  - ]
    1785                 :          22 :     *error = text;
    1786                 :             :   }
    1787                 :             :   return false;
    1788                 :             : }
    1789                 :             : 
    1790                 :             : /// A filled, synced temporary next to its destination.
    1791                 :         328 : struct Staged {
    1792                 :             :   QString path;
    1793                 :             :   FileIdentity identity;
    1794                 :             :   /// POSIX: a descriptor kept open on the temporary until the identity
    1795                 :             :   /// check, so the inode, and with it the number, stays the temporary's.
    1796                 :             :   std::shared_ptr<void> pin;
    1797                 :             : };
    1798                 :             : 
    1799                 :             : /**
    1800                 :             :  * @brief Create the temporary next to @p path (opaque name, exclusive,
    1801                 :             :  * owner-only), fill it through its handle and sync it. The QTemporaryFile
    1802                 :             :  * goes out of scope before the caller renames: it keeps its handle open for
    1803                 :             :  * as long as it lives, and Windows does not rename an open file.
    1804                 :             :  */
    1805                 :         336 : auto stageNextTo(const QString &path, const Util::Filler &fill, QString *why)
    1806                 :             :     -> std::optional<Staged> {
    1807                 :         336 :   Staged staged;
    1808                 :             :   {
    1809                 :         672 :     QTemporaryFile file(QFileInfo(path).path() +
    1810         [ +  + ]:         672 :                         QStringLiteral("/.qtpass-XXXXXX.tmp"));
    1811                 :         336 :     file.setAutoRemove(false);
    1812         [ +  + ]:         336 :     if (!file.open()) {
    1813                 :           8 :       *why = QCoreApplication::translate(
    1814                 :             :                  "Util", "Cannot create a temporary file next to %1: %2")
    1815                 :          16 :                  .arg(path, file.errorString());
    1816                 :           8 :       return std::nullopt;
    1817                 :             :     }
    1818                 :         328 :     staged.path = file.fileName();
    1819                 :             :     // Owner-only: a .gpg-id names the keys a store is encrypted to, an
    1820                 :             :     // entry is an entry. QTemporaryFile creates 0600 already; say so for
    1821                 :             :     // platforms where it may not.
    1822                 :         328 :     file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
    1823                 :         656 :     *why = fill(file);
    1824   [ +  -  +  -  :         328 :     if (why->isEmpty() && !Util::syncToDisk(file)) {
                      + ]
    1825                 :           0 :       *why = QCoreApplication::translate("Util", "Cannot write %1: %2")
    1826                 :           0 :                  .arg(path, file.errorString());
    1827                 :             :     }
    1828                 :         328 :     staged.identity = identityOf(file);
    1829                 :             : #ifndef Q_OS_WIN
    1830                 :             :     // Closed and unlinked by a co-writer before the rename, the temporary's
    1831                 :             :     // inode number would be free, and ext4 hands it to the next file made:
    1832                 :             :     // the very file swapped in would then pass the check below. Windows
    1833                 :             :     // cannot rename an open file, and NTFS does not reuse a file index so.
    1834      [ +  +  - ]:         328 :     if (const int fd = ::dup(file.handle()); fd >= 0) {
    1835                 :             :       staged.pin =
    1836                 :         984 :           std::shared_ptr<void>(nullptr, [fd](void *) { ::close(fd); });
    1837                 :             :     }
    1838                 :             : #endif
    1839                 :         336 :   }
    1840         [ -  + ]:         328 :   if (!why->isEmpty()) {
    1841                 :           0 :     QFile::remove(staged.path);
    1842                 :           0 :     return std::nullopt;
    1843                 :             :   }
    1844                 :         328 :   return staged;
    1845                 :         336 : }
    1846                 :             : 
    1847                 :             : /// Why replaceFile() could not put the temporary under @p path.
    1848                 :           9 : auto placementError(const QString &path, bool replace) -> QString {
    1849         [ +  + ]:           9 :   if (replace) {
    1850                 :           4 :     return QCoreApplication::translate("Util", "Failed to replace %1.")
    1851                 :           2 :         .arg(path);
    1852                 :             :   }
    1853                 :           7 :   const QFileInfo taken(path);
    1854   [ +  +  -  + ]:           8 :   return taken.exists() || taken.isSymLink()
    1855      [ +  +  + ]:           7 :              ? QCoreApplication::translate("Util", "%1 already exists.")
    1856                 :             :                    .arg(path)
    1857                 :           1 :              : QCoreApplication::translate("Util", "Failed to write %1.")
    1858                 :           8 :                    .arg(path);
    1859                 :           7 : }
    1860                 :             : 
    1861                 :             : /**
    1862                 :             :  * @brief Whether what is under @p path is the file that was filled: not a
    1863                 :             :  * link, and not another file (a hard link to something of the user's, say)
    1864                 :             :  * swapped in under the temporary's name. Opened without following, compared
    1865                 :             :  * by identity; only two known identities can prove a swap, otherwise every
    1866                 :             :  * write on such a store would be reported as tampering.
    1867                 :             :  */
    1868                 :         319 : auto isTheFileWritten(const QString &path, const FileIdentity &written)
    1869                 :             :     -> bool {
    1870                 :         319 :   QFile placed;
    1871      [ +  +  + ]:         319 :   if (!Util::openRegularFile(path, placed)) {
    1872                 :             :     return false;
    1873                 :             :   }
    1874                 :         317 :   const FileIdentity there = identityOf(placed);
    1875   [ +  -  -  + ]:         317 :   if (!written.known || !there.known) {
    1876                 :           0 :     qCWarning(lcQtPass) << "Cannot tell whether" << path
    1877                 :           0 :                         << "is the file that was written here";
    1878                 :           0 :     return true;
    1879                 :             :   }
    1880                 :         317 :   return there == written;
    1881                 :         319 : }
    1882                 :             : 
    1883                 :             : } // namespace
    1884                 :             : 
    1885                 :         336 : auto Util::stageFileReplacing(const QString &path, bool replace,
    1886                 :             :                               const Filler &fill, QString *error) -> bool {
    1887                 :         336 :   QString why;
    1888                 :         336 :   const std::optional<Staged> staged = stageNextTo(path, fill, &why);
    1889         [ +  + ]:         336 :   if (!staged) {
    1890                 :             :     return fail(error, why);
    1891                 :             :   }
    1892         [ +  + ]:         328 :   if (s_beforePlacingForTests) {
    1893                 :           1 :     s_beforePlacingForTests(staged->path);
    1894                 :             :   }
    1895      [ +  +  + ]:         328 :   if (!replaceFile(staged->path, path, replace)) {
    1896                 :           9 :     QFile::remove(staged->path);
    1897                 :          18 :     return fail(error, placementError(path, replace));
    1898                 :             :   }
    1899                 :             :   // A mismatch is reported and left: removing by name could take another
    1900                 :             :   // writer's file.
    1901      [ +  +  + ]:         319 :   if (!isTheFileWritten(path, staged->identity)) {
    1902                 :             :     return fail(
    1903                 :             :         error,
    1904                 :           5 :         QCoreApplication::translate(
    1905                 :             :             "Util", "%1 was swapped for another file while it was written.")
    1906                 :          10 :             .arg(path));
    1907                 :             :   }
    1908                 :             :   return true;
    1909                 :             : }
    1910                 :             : 
    1911                 :         124 : auto Util::writeFileReplacing(const QString &path, const QByteArray &bytes,
    1912                 :             :                               bool replace, QString *error) -> bool {
    1913                 :         124 :   return stageFileReplacing(
    1914                 :             :       path, replace,
    1915                 :         246 :       [&path, &bytes](QFileDevice &staged) -> QString {
    1916         [ -  + ]:         122 :         if (staged.write(bytes) != bytes.size()) {
    1917                 :           0 :           return QCoreApplication::translate("Util", "Cannot write %1: %2")
    1918                 :           0 :               .arg(path, staged.errorString());
    1919                 :             :         }
    1920                 :         122 :         return {};
    1921                 :             :       },
    1922                 :         124 :       error);
    1923                 :             : }
    1924                 :             : 
    1925                 :         211 : auto Util::copyFileReplacing(const QString &src, const QString &dst,
    1926                 :             :                              bool replace, QString *error) -> bool {
    1927                 :         211 :   QFile in;
    1928      [ +  +  + ]:         211 :   if (!openRegularFile(src, in)) {
    1929         [ +  - ]:           4 :     if (error)
    1930                 :           8 :       *error = QCoreApplication::translate("Util", "Cannot read %1.").arg(src);
    1931                 :           4 :     return false;
    1932                 :             :   }
    1933                 :         207 :   return stageFileReplacing(
    1934                 :             :       dst, replace,
    1935                 :         615 :       [&src, &dst, &in](QFileDevice &staged) -> QString {
    1936                 :             :         std::array<char, std::size_t{64} * 1024> buf;
    1937                 :             :         for (;;) {
    1938                 :         414 :           const qint64 n = in.read(buf.data(), buf.size());
    1939         [ -  + ]:         414 :           if (n < 0) {
    1940                 :           0 :             return QCoreApplication::translate("Util", "Cannot read %1: %2")
    1941                 :           0 :                 .arg(src, in.errorString());
    1942                 :             :           }
    1943         [ +  + ]:         414 :           if (n == 0) {
    1944                 :         201 :             return {};
    1945                 :             :           }
    1946         [ +  - ]:         213 :           if (staged.write(buf.data(), n) != n) {
    1947                 :           0 :             return QCoreApplication::translate("Util", "Cannot write %1: %2")
    1948                 :           0 :                 .arg(dst, staged.errorString());
    1949                 :             :           }
    1950                 :             :         }
    1951                 :             :       },
    1952                 :             :       error);
    1953                 :         211 : }
    1954                 :             : 
    1955                 :             : namespace {
    1956                 :             : 
    1957                 :             : /// Remove one directory entry that is not a real directory: a link goes as
    1958                 :             : /// the entry itself, never its target (a junction or a directory symlink on
    1959                 :             : /// Windows is a directory entry and goes with rmdir); a read-only file gets
    1960                 :             : /// write access and one more try, as QDir::removeRecursively() does.
    1961                 :          14 : auto removeEntry(const QFileInfo &entry) -> bool {
    1962                 :          14 :   const QString path = entry.filePath();
    1963      [ +  +  + ]:          14 :   if (isLink(entry)) {
    1964   [ +  +  +  +  :           6 :     if (QFile::remove(path) || QDir().rmdir(path)) {
          +  +  +  +  +  
                   -  - ]
    1965                 :             :       return true;
    1966                 :             :     }
    1967                 :           2 :     qCWarning(lcQtPass) << "Could not remove link" << path;
    1968                 :           1 :     return false;
    1969                 :             :   }
    1970      [ +  +  + ]:           9 :   if (QFile::remove(path)) {
    1971                 :             :     return true;
    1972                 :             :   }
    1973                 :           2 :   const QFile::Permissions perms = QFile::permissions(path);
    1974         [ +  - ]:           1 :   if (!perms.testFlag(QFile::WriteUser) &&
    1975   [ +  +  +  +  :           3 :       QFile::setPermissions(path, perms | QFile::WriteUser) &&
                      - ]
    1976                 :           1 :       QFile::remove(path)) {
    1977                 :             :     return true;
    1978                 :             :   }
    1979                 :           4 :   qCWarning(lcQtPass) << "Could not remove" << path;
    1980                 :           2 :   return false;
    1981                 :             : }
    1982                 :             : 
    1983                 :             : } // namespace
    1984                 :             : 
    1985                 :          23 : auto Util::removeTree(const QString &dir) -> bool {
    1986                 :             :   // A trailing separator makes lstat follow a link ("link/" is the target
    1987                 :             :   // directory); the link itself is what this is about.
    1988                 :          23 :   const QString path = QDir::cleanPath(dir);
    1989                 :          23 :   const QFileInfo top(path);
    1990      [ +  +  + ]:          23 :   if (isLink(top)) {
    1991                 :             :     // rm -rf on a link removes the link.
    1992   [ +  +  +  +  :          16 :     return QFile::remove(path) || QDir().rmdir(path);
             +  +  +  -  
                      - ]
    1993                 :             :   }
    1994      [ +  +  + ]:           9 :   if (!top.isDir()) {
    1995                 :             :     return false;
    1996                 :             :   }
    1997                 :             :   bool ok = true;
    1998                 :             :   const QFileInfoList entries =
    1999                 :          16 :       QDir(path).entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
    2000                 :             :                                    QDir::System | QDir::NoDotAndDotDot,
    2001                 :           8 :                                QDir::Name);
    2002         [ +  + ]:          24 :   for (const QFileInfo &entry : entries) {
    2003   [ +  +  +  + ]:          22 :     const bool removed = entry.isDir() && !isLink(entry)
    2004   [ +  +  +  +  :          18 :                              ? removeTree(entry.filePath())
                   -  - ]
    2005                 :          14 :                              : removeEntry(entry);
    2006                 :          16 :     ok = removed && ok;
    2007                 :             :   }
    2008   [ +  +  +  +  :          13 :   return ok && QDir().rmdir(path);
                   +  + ]
    2009                 :          23 : }
        

Generated by: LCOV version 2.0-1