• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IJHack / QtPass / 45583302534

25 Nov 2026 09:13AM UTC coverage: 94.833% (-0.04%) from 94.876%
45583302534

push

github

web-flow
Content search: read each entry without following a link (#2331)

Content search read each entry by path after a link check, so a pull
that swapped a folder for a link mid-search made it read, decrypt and
match a file outside the store.

Util::readRegularFileUnder(root, path, maxBytes) now reads an entry
without following a link below the store root. On POSIX it opens the
root by name, walks each folder with openat(O_DIRECTORY | O_NOFOLLOW)
and opens the file with O_NOFOLLOW | O_NONBLOCK, then accepts only a
regular file by fstat(). It refuses "..", "." and empty parts and any
path outside the root. On Windows it holds a handle on every folder
from the root down, opened without FILE_SHARE_DELETE so none can be
renamed or replaced while the file is read, and refuses a folder that
is a symbolic link or junction, as the store walk does.

NativeGrep::matchFile() reads the ciphertext this way, hands it to gpg
on stdin and decodes the output with Executor::decodeText(), the same
decoding executeBlocking() applies. ImitatePass::decryptEntry() reads
under the store (or its canonical path) the same way and refuses
anything else.

Scan: ANT-2026-5W0UHRED

Signed-off-by: Anne Jan Brouwer <brouwer@annejan.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

57 of 61 new or added lines in 4 files covered. (93.44%)

3 existing lines in 1 file now uncovered.

10002 of 10547 relevant lines covered (94.83%)

21879.27 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.94
/src/util.cpp
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 <memory>
28
#include <optional>
29
#include <vector>
30

31
#ifdef Q_OS_WIN
32
#include <fcntl.h>
33
#include <io.h>
34
#include <windows.h>
35
#else
36
#include <cerrno>
37
#include <cstdio>
38
#include <dirent.h>
39
#include <fcntl.h>
40
#include <sys/stat.h>
41
#include <sys/time.h>
42
#include <unistd.h>
43
#endif
44

45
#include "qtpasslogging.h"
46

47
QProcessEnvironment Util::_env;
48
bool Util::_envInitialised = false;
49

50
// macOS and Windows: append the usual GPG install directories to PATH.
51
void Util::initialiseEnvironment() {
956 ✔
52
  if (!_envInitialised) {
956 ✔
53
    _env = QProcessEnvironment::systemEnvironment();
6 ✔
54
#ifdef __APPLE__
55
    QString path = _env.value("PATH");
56
    if (!path.contains("/usr/local/MacGPG2/bin") &&
57
        QDir("/usr/local/MacGPG2/bin").exists())
58
      path += ":/usr/local/MacGPG2/bin";
59
    if (!path.contains("/usr/local/bin"))
60
      path += ":/usr/local/bin";
61
    _env.insert("PATH", path);
62
#endif
63
#ifdef Q_OS_WIN
64
    QString path = _env.value("PATH");
65
    if (!path.contains("C:\\Program Files\\WinGPG\\x86") &&
66
        QDir("C:\\Program Files\\WinGPG\\x86").exists())
67
      path += ";C:\\Program Files\\WinGPG\\x86";
68
    if (!path.contains("C:\\Program Files\\GnuPG\\bin") &&
69
        QDir("C:\\Program Files\\GnuPG\\bin").exists())
70
      path += ";C:\\Program Files\\GnuPG\\bin";
71
    _env.insert("PATH", path);
72
#endif
73
    qCDebug(lcQtPass) << _env.value("PATH");
6 ✔
74
    _envInitialised = true;
6 ✔
75
  }
76
}
956 ✔
77

78
auto Util::findPasswordStore() -> QString {
405 ✔
79
  QString path;
405 ✔
80
  initialiseEnvironment();
405 ✔
81
  if (_env.contains("PASSWORD_STORE_DIR")) {
810 ✔
82
    path = Util::expandTilde(_env.value("PASSWORD_STORE_DIR"));
6 ✔
83
  } else {
84
#ifdef Q_OS_WIN
85
    path = QDir(QDir::homePath()).filePath("password-store");
86
#else
87
    path = QDir(QDir::homePath()).filePath(".password-store");
1,206 ✔
88
#endif
89
  }
90
  return Util::normalizeFolderPath(QDir::cleanPath(path));
810 ✔
91
}
92

93
auto Util::expandTilde(const QString &path) -> QString {
12 ✔
94
  if (path == QLatin1String("~")) {
12 ✔
95
    return QDir::homePath();
1 ✔
96
  }
97
  if (path.startsWith(QLatin1String("~/"))) {
11 ✔
98
    return QDir::homePath() + path.mid(1);
10 ✔
99
  }
100
  return path;
101
}
102

103
auto Util::normalizeFolderPath(const QString &path) -> QString {
544 ✔
104
  QString normalizedPath = path;
105
  if (!normalizedPath.endsWith('/')) {
544 ✔
106
    normalizedPath += '/';
525 ✔
107
  }
108
  return normalizedPath;
544 ✔
109
}
110

111
void Util::applyPassProcessDefaults() {
1 ✔
112
  // pass unsets these before it runs git: a GIT_DIR inherited from the
113
  // environment (QtPass started from a git hook, or an IDE terminal) would
114
  // send every commit and push to that repository instead of the store.
115
  for (const char *variable :
11 ✔
116
       {"GIT_DIR", "GIT_WORK_TREE", "GIT_NAMESPACE", "GIT_INDEX_FILE",
117
        "GIT_INDEX_VERSION", "GIT_OBJECT_DIRECTORY", "GIT_COMMON_DIR",
118
        // QtPass sets GIT_LITERAL_PATHSPECS for its git; git refuses a
119
        // pathspec when one of these is set as well.
120
        "GIT_GLOB_PATHSPECS", "GIT_NOGLOB_PATHSPECS", "GIT_ICASE_PATHSPECS"}) {
11 ✔
121
    qunsetenv(variable);
10 ✔
122
  }
123
  Executor::setChildUmask(
1 ✔
124
      passUmask(qEnvironmentVariable("PASSWORD_STORE_UMASK")));
1 ✔
125
}
1 ✔
126

127
auto Util::passUmask(const QString &value) -> int {
11 ✔
128
  // Taken as it is, as bash's umask builtin (which pass hands it to) takes
129
  // it: " 022" is no umask there either. pass then keeps the session's;
130
  // QtPass falls back to 077.
131
  // anchoredPattern(), not ^...$: $ also matches before a final newline.
132
  static const QRegularExpression octal(
133
      QRegularExpression::anchoredPattern(QStringLiteral("[0-7]{1,4}")));
34 ✔
134
  if (!octal.match(value).hasMatch()) {
11 ✔
135
    return 077;
136
  }
137
  return value.toInt(nullptr, 8);
4 ✔
138
}
139

140
auto Util::gitCeiling(const QString &store) -> QString {
1,890 ✔
141
  if (store.isEmpty()) {
1,890 ✔
142
    return {};
×
143
  }
144
  QString path = QFileInfo(store).canonicalFilePath();
1,890 ✔
145
  if (path.isEmpty()) {
1,890 ✔
146
    path = QDir::cleanPath(QDir(store).absolutePath());
×
147
  }
148
  return QFileInfo(path).absolutePath();
1,890 ✔
149
}
150

151
#ifndef Q_OS_WIN
152
namespace {
153
/**
154
 * @brief Open @p path for reading, following a link, but only when it ends
155
 * at a regular file, and never waiting: O_NONBLOCK keeps a FIFO from
156
 * blocking the open until a writer comes, and the open handle is judged
157
 * (fstat), so a FIFO or a device is refused. Unlike Util::openRegularFile(),
158
 * a link is fine: git's own metadata may be one.
159
 * @param path The file.
160
 * @param file Receives the open file on success; untouched otherwise.
161
 * @return Whether @p file is open on a regular file.
162
 */
163
auto openFollowedRegularFile(const QString &path, QFile &file) -> bool {
31 ✔
164
  const int fd = ::open(QFile::encodeName(path).constData(),
31 ✔
165
                        O_RDONLY | O_NONBLOCK | O_CLOEXEC);
166
  if (fd < 0) {
31 ✔
167
    return false;
168
  }
169
  struct stat info{};
31 ✔
170
  if (::fstat(fd, &info) != 0 || !S_ISREG(info.st_mode) ||
62 ✔
171
      !file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
62 ✔
172
    ::close(fd);
×
173
    return false;
×
174
  }
175
  return true;
176
}
177
} // namespace
178
#endif
179

180
auto Util::repositoryPassClimbsTo(const QString &store) -> QString {
44 ✔
181
#ifdef Q_OS_WIN
182
  Q_UNUSED(store);
183
  return {};
184
#else
185
  if (!store.contains(QLatin1Char(':'))) {
44 ✔
186
    return {};
10 ✔
187
  }
188
  // git walks up from the real folder, so the real path is the one to walk,
189
  // and for a store that does not exist yet the one it will have: its
190
  // nearest existing folder resolved, the rest appended. By the raw string:
191
  // QDir and QFileInfo clean a path by name, and "link/.." is the parent
192
  // of the link's target, not the folder the link is in. On macOS the
193
  // temporary folder is under /var, a link to /private/var.
194
  // Absolute as git means it, a leading "/" (Qt would take ":name" for a
195
  // resource path).
196
  QString path =
197
      store.startsWith(u'/') ? store : QDir::currentPath() + u'/' + store;
68 ✔
198
  while (path.size() > 1 && path.endsWith(u'/')) {
37 ✔
199
    path.chop(1);
3 ✔
200
  }
201
  QString rest;
34 ✔
202
  while (!QFileInfo::exists(path)) {
44 ✔
203
    const qsizetype slash = path.lastIndexOf(u'/');
10 ✔
204
    if (slash < 0) {
10 ✔
205
      return {};
×
206
    }
207
    const QString name = path.mid(slash + 1);
10 ✔
208
    rest = rest.isEmpty() ? name : name + u'/' + rest;
24 ✔
209
    path = slash == 0 ? QStringLiteral("/") : path.left(slash);
20 ✔
210
  }
211
  const QString real = QFileInfo(path).canonicalFilePath();
34 ✔
212
  QString start = real.isEmpty() ? QDir::cleanPath(path) : real;
34 ✔
213
  if (!rest.isEmpty()) {
34 ✔
214
    start = QDir::cleanPath(start + u'/' + rest);
8 ✔
215
  }
216
  // The pieces of pass's ceiling as git takes them (setup.c,
217
  // canonicalize_ceiling_entry): relative ones are dropped, the rest
218
  // resolved, one that cannot be resolved is dropped; after an empty piece
219
  // ("::") they are kept exactly as written. A piece can still be a real
220
  // ceiling: "/repo/:vault/.." holds "/repo/".
221
  QString ceiling;
34 ✔
222
  bool afterEmpty = false;
223
  for (const QString &piece :
224
       (store + QStringLiteral("/..")).split(QLatin1Char(':'))) {
139 ✔
225
    if (piece.isEmpty()) {
71 ✔
226
      afterEmpty = true;
227
      continue;
35 ✔
228
    }
229
    if (!piece.startsWith(u'/')) {
69 ✔
230
      continue;
33 ✔
231
    }
232
    const QString entry =
233
        afterEmpty ? piece : QFileInfo(piece).canonicalFilePath();
37 ✔
234
    // git stops below the longest entry the store lies under
235
    // (longest_ancestor_length: "/" is above everything).
236
    const QString under = entry == u'/' ? entry : entry + u'/';
36 ✔
237
    if (!entry.isEmpty() && start.startsWith(under) &&
36 ✔
238
        entry.size() > ceiling.size()) {
239
      ceiling = entry;
4 ✔
240
    }
241
  }
242
  // What git takes for a repository (setup.c, is_git_directory()): HEAD
243
  // naming a ref or an object, objects/ and refs/. An empty or broken .git
244
  // is passed by, as git passes it by.
245
  const auto isGitDirectory = [](const QString &candidate) {
101 ✔
246
    const QDir dir(candidate);
101 ✔
247
    if (!QFileInfo(dir.filePath(QStringLiteral("objects"))).isDir() ||
229 ✔
248
        !QFileInfo(dir.filePath(QStringLiteral("refs"))).isDir()) {
182 ✔
249
      return false;
250
    }
251
    // As git (setup.c, validate_headref()): a HEAD that is a link counts
252
    // when the link text starts with "refs/", without reading what it
253
    // names, and not otherwise. Anything else is read only when it is a
254
    // regular file, without waiting: a HEAD that is a FIFO (a pushed commit
255
    // can carry a link to one, or to a device) blocked the open and the
256
    // read on the GUI thread when Settings opened.
257
    const QString headPath = dir.filePath(QStringLiteral("HEAD"));
54 ✔
258
    if (const QFileInfo headInfo(headPath); headInfo.isSymLink()) {
27 ✔
259
      // The link text as stored (Qt 6.6), not the path it resolves to.
260
      return headInfo.readSymLink().startsWith(QLatin1String("refs/"));
3 ✔
261
    }
27 ✔
262
    QFile head;
24 ✔
263
    if (!openFollowedRegularFile(headPath, head)) {
24 ✔
264
      return false;
265
    }
266
    static const QRegularExpression valid(
267
        QStringLiteral("^(?:ref: refs/|[0-9a-f]{40}\\s*$|[0-9a-f]{64}\\s*$)"));
28 ✔
268
    return valid.match(QString::fromUtf8(head.read(256))).hasMatch();
72 ✔
269
  };
125 ✔
270
  // At each folder, as git: a .git folder that is a repository, or a .git
271
  // file naming one ("gitdir: ..."), is the repository. Any other .git file
272
  // stops git with an error, and pass then commits nothing; a .git folder
273
  // that is no repository is passed by.
274
  enum class Found { Nothing, Repository, Refused };
275
  const auto repositoryAt = [&isGitDirectory](const QString &dir) {
98 ✔
276
    const QString dotGit = QDir(dir).filePath(QStringLiteral(".git"));
196 ✔
277
    const QFileInfo info(dotGit);
98 ✔
278
    if (info.isDir()) {
98 ✔
279
      return isGitDirectory(dotGit) ? Found::Repository : Found::Nothing;
24 ✔
280
    }
281
    if (!info.exists()) {
74 ✔
282
      return Found::Nothing;
283
    }
284
    // The same for a .git file (or a link to one): a FIFO there blocked in
285
    // open().
286
    QFile file;
7 ✔
287
    if (!openFollowedRegularFile(dotGit, file)) {
7 ✔
288
      return Found::Refused;
289
    }
290
    const QString line = QString::fromUtf8(file.readLine(4096)).trimmed();
7 ✔
291
    if (!line.startsWith(QLatin1String("gitdir: "))) {
7 ✔
292
      return Found::Refused;
293
    }
294
    const QString target = line.mid(8);
5 ✔
295
    return isGitDirectory(target.startsWith(u'/') ? target
10 ✔
296
                                                  : QDir(dir).filePath(target))
8 ✔
297
               ? Found::Repository
5 ✔
298
               : Found::Refused;
299
  };
132 ✔
300
  // The store's own repository comes first; only without one does git look
301
  // further up, and never into the ceiling. By name from here: the real
302
  // path holds no link or "..".
303
  for (QString dir = start;;) {
304
    switch (repositoryAt(dir)) {
98 ✔
305
    case Found::Repository:
306
      return dir == start ? QString() : dir;
54 ✔
307
    case Found::Refused:
3 ✔
308
      return {};
3 ✔
309
    case Found::Nothing:
310
      break;
311
    }
312
    // A bare repository: git stops there, and pass, finding no work tree,
313
    // commits nothing.
314
    if (isGitDirectory(dir)) {
72 ✔
315
      return {};
1 ✔
316
    }
317
    const QString up = QFileInfo(dir).absolutePath();
71 ✔
318
    if (up == dir || up == ceiling) {
71 ✔
319
      return {};
7 ✔
320
    }
321
    dir = up;
64 ✔
322
  }
323
#endif
324
}
325

326
namespace {
327
/// setGitOwnerForTests(): who owns "the user's own" store, when set.
328
std::optional<uint> s_gitOwnerForTests;
329
} // namespace
330

331
void Util::setGitOwnerForTests(std::optional<uint> user) {
4 ✔
332
  s_gitOwnerForTests = user;
4 ✔
333
}
4 ✔
334

335
/// setBeforePlacingForTests(): called between staging and the rename.
336
std::function<void(const QString &)> s_beforePlacingForTests;
337

338
void Util::setBeforePlacingForTests(std::function<void(const QString &)> hook) {
3 ✔
339
  s_beforePlacingForTests = std::move(hook);
3 ✔
340
}
3 ✔
341

342
#ifdef Q_OS_UNIX
343
namespace {
344
/**
345
 * @brief Whether git's `safe.directory` trusts the repository at @p root,
346
 * as git's ownership check would judge it in place of ownership.
347
 *
348
 * Read as git reads it: only from system, global and command-line
349
 * configuration (a repository cannot vouch for itself), in order. `*`
350
 * trusts every repository, an empty value forgets the entries before it,
351
 * a path ending in a slash and `*` trusts what lies below it, and any other
352
 * absolute path trusts that one folder, compared after resolving links.
353
 * Relative entries (including git's ".") and paths that do not exist trust
354
 * nothing.
355
 * @param root The store's canonical path.
356
 * @param git The git executable; "git" from PATH when empty.
357
 * @return True when an entry names @p root; false when none does or git
358
 *         cannot be asked.
359
 */
360
auto isSafeDirectory(const QString &root, const QString &git) -> bool {
23 ✔
361
  // Outside any repository, as git reads its protected config: no
362
  // repository's own config, and no includeIf "gitdir:" or "onbranch:"
363
  // that matches (a GIT_DIR, even one that cannot exist, would be matched
364
  // against them, and one that cannot exist makes git config fail). From
365
  // "/", which a user cannot make a repository; a local scope is dropped
366
  // below in any case.
367
  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
23 ✔
368
  env.remove(QStringLiteral("GIT_DIR"));
46 ✔
369
  env.remove(QStringLiteral("GIT_WORK_TREE"));
46 ✔
370
  env.remove(QStringLiteral("GIT_COMMON_DIR"));
46 ✔
371
  // git config alone reads GIT_CONFIG in place of the system and global
372
  // configuration (and reports it as "command"); the ownership check never
373
  // reads it.
374
  env.remove(QStringLiteral("GIT_CONFIG"));
46 ✔
375
  QProcess process;
23 ✔
376
  process.setProcessEnvironment(env);
23 ✔
377
  process.setWorkingDirectory(QStringLiteral("/"));
46 ✔
378
  // Bounded: Git calls wait for this, and a git that never answers trusts
379
  // nothing.
380
  constexpr int kQueryTimeoutMs = 5000;
381
  QString out;
23 ✔
382
  if (Executor::executeBlocking(
184 ✔
383
          process, git.isEmpty() ? QStringLiteral("git") : git,
46 ✔
384
          {QStringLiteral("config"), QStringLiteral("--show-scope"),
23 ✔
385
           QStringLiteral("--type=path"), QStringLiteral("--get-all"),
23 ✔
386
           QStringLiteral("safe.directory")},
23 ✔
387
          QString(), &out, nullptr, nullptr, kQueryTimeoutMs) != 0) {
46 ✔
388
    return false;
389
  }
390
  bool safe = false;
391
  const QStringList lines = out.split(QLatin1Char('\n'));
14 ✔
392
  for (const QString &line : lines) {
47 ✔
393
    const qsizetype tab = line.indexOf(QLatin1Char('\t'));
33 ✔
394
    if (tab < 0) {
33 ✔
395
      continue;
18 ✔
396
    }
397
    const QString scope = line.left(tab);
19 ✔
398
    if (scope != QLatin1String("system") && scope != QLatin1String("global") &&
19 ✔
399
        scope != QLatin1String("command")) {
1 ✔
400
      continue;
×
401
    }
402
    const QString value = line.mid(tab + 1);
19 ✔
403
    if (value.isEmpty()) {
19 ✔
404
      safe = false;
405
    } else if (value == QLatin1String("*")) {
17 ✔
406
      safe = true;
407
    } else if (!QDir::isAbsolutePath(value)) {
13 ✔
408
      continue;
3 ✔
409
    } else if (value.endsWith(QLatin1String("/*"))) {
10 ✔
410
      const QString base = value.chopped(2);
411
      QString prefix = QFileInfo(base.isEmpty() ? QStringLiteral("/") : base)
12 ✔
412
                           .canonicalFilePath();
3 ✔
413
      if (prefix.isEmpty()) {
3 ✔
414
        continue;
415
      }
416
      if (!prefix.endsWith(QLatin1Char('/'))) {
2 ✔
417
        prefix += QLatin1Char('/');
2 ✔
418
      }
419
      safe = safe || root.startsWith(prefix);
2 ✔
420
    } else {
421
      const QString named = QFileInfo(value).canonicalFilePath();
7 ✔
422
      safe = safe || (!named.isEmpty() && named == root);
7 ✔
423
    }
424
  }
425
  return safe;
426
}
23 ✔
427
} // namespace
428
#endif
429

430
auto Util::gitStoreVariables(const QString &store, const QString &git,
1,890 ✔
431
                             std::optional<uint> asUser)
432
    -> QList<std::pair<QString, QString>> {
433
  const QString ceiling = gitCeiling(store);
1,890 ✔
434
  if (ceiling.isEmpty()) {
1,890 ✔
435
    return {};
×
436
  }
437
  QList<std::pair<QString, QString>> vars{
438
      {QStringLiteral("GIT_CEILING_DIRECTORIES"), ceiling}};
5,670 ✔
439
#ifdef Q_OS_WIN
440
  const QChar separator = QLatin1Char(';');
441
#else
442
  const QChar separator = QLatin1Char(':');
443
#endif
444
  // git splits the ceiling list on the separator: "/home/a:b" would be
445
  // "/home/a" and "b", neither of them the parent, and git would climb.
446
  if (ceiling.contains(separator)) {
1,890 ✔
447
    QString root = QFileInfo(store).canonicalFilePath();
28 ✔
448
    if (root.isEmpty()) {
28 ✔
449
      root = QDir::cleanPath(QDir(store).absolutePath());
×
450
    }
451
    QString gitDir = QDir(root).filePath(QStringLiteral(".git"));
56 ✔
452
#ifdef Q_OS_UNIX
453
    // What discovery's ownership check would have looked at: the work tree,
454
    // the .git, and the directory a gitfile names. Not the user's: no
455
    // repository at all, under a path that cannot be created (its parent
456
    // is a device), rather than another user's hooks run as this one.
457
    const uint me = asUser.value_or(
458
        s_gitOwnerForTests.value_or(static_cast<uint>(::geteuid())));
28 ✔
459
    const auto ownedOrMissing = [me](const QString &path) {
33 ✔
460
      const QFileInfo info(path);
33 ✔
461
      return !info.exists() || info.ownerId() == me;
66 ✔
462
    };
33 ✔
463
    bool owned = ownedOrMissing(root) && ownedOrMissing(gitDir);
28 ✔
464
    if (owned && QFileInfo(gitDir).isFile()) {
28 ✔
465
      QFile gitFile(gitDir);
×
466
      if (gitFile.open(QIODevice::ReadOnly)) {
×
467
        const QString line =
468
            QString::fromUtf8(gitFile.readLine(4096)).trimmed();
×
469
        if (line.startsWith(QLatin1String("gitdir:"))) {
×
470
          const QString target = line.mid(7).trimmed();
×
471
          owned = ownedOrMissing(QDir(root).absoluteFilePath(target));
×
472
        }
473
      }
474
    }
×
475
    // Or trusted as git would trust it in place of ownership.
476
    if (!owned && !isSafeDirectory(root, git)) {
28 ✔
477
      gitDir = QStringLiteral("/dev/null/.git");
14 ✔
478
    }
479
#else
480
    // Git for Windows runs the same ownership check during discovery, on
481
    // SIDs, with its own rules for the Administrators group; this pin skips
482
    // it there and does not repeat it (a known gap, #2089).
483
    Q_UNUSED(git);
484
    Q_UNUSED(asUser);
485
#endif
486
    vars.append({QStringLiteral("GIT_DIR"), gitDir});
56 ✔
487
    vars.append({QStringLiteral("GIT_WORK_TREE"), root});
56 ✔
488
  }
489
  return vars;
490
}
1,890 ✔
491

492
auto Util::mkpathForStore(const QString &path) -> bool {
52 ✔
493
  const QString clean = QDir::cleanPath(QDir(path).absolutePath());
104 ✔
494
  if (QFileInfo(clean).isDir()) {
52 ✔
495
    return true;
496
  }
497
  const QString parent = QFileInfo(clean).absolutePath();
30 ✔
498
  if (parent != clean && !mkpathForStore(parent)) {
30 ✔
499
    return false;
500
  }
501
#ifdef Q_OS_UNIX
502
  // The store's umask, as git and gpg get it: a store shared with a group
503
  // (PASSWORD_STORE_UMASK=007) gets group folders, the default owner-only.
504
  const int umask = Executor::childUmask() >= 0 ? Executor::childUmask() : 077;
27 ✔
505
  QFile::Permissions permissions;
506
  const QFile::Permission bits[] = {
27 ✔
507
      QFile::ReadOwner, QFile::WriteOwner, QFile::ExeOwner,
508
      QFile::ReadGroup, QFile::WriteGroup, QFile::ExeGroup,
509
      QFile::ReadOther, QFile::WriteOther, QFile::ExeOther};
510
  for (int i = 0; i < 9; ++i) {
270 ✔
511
    if ((umask & (0400 >> i)) == 0) {
243 ✔
512
      permissions |= bits[i];
87 ✔
513
    }
514
  }
515
  // mkdir() still takes QtPass's own umask off (a session's 022 would drop
516
  // the group's write bit); set the mode exactly afterwards. That only ever
517
  // widens it to what was asked, never past.
518
  const bool made = QDir().mkdir(clean, permissions) &&
54 ✔
519
                    QFile::setPermissions(clean, permissions);
22 ✔
520
#else
521
  // Windows: permissions here would become an ACL of their own, replacing
522
  // the inherited one; the folder takes its parent's, as before.
523
  const bool made = QDir().mkdir(clean);
524
#endif
525
  return made || QFileInfo(clean).isDir();
27 ✔
526
}
527

528
auto Util::findBinaryInPath(const QString &binary) -> QString {
552 ✔
529
  if (binary.isEmpty()) {
552 ✔
530
    return {};
1 ✔
531
  }
532

533
  initialiseEnvironment();
551 ✔
534

535
  const QStringList dirs =
536
      _env.value(QStringLiteral("PATH"))
1,102 ✔
537
          .split(QDir::listSeparator(), Qt::SkipEmptyParts);
551 ✔
538
  QString ret;
551 ✔
539
  if (QDir::fromNativeSeparators(binary).contains(u'/')) {
551 ✔
540
    // An explicit path is not a PATH search: an absolute path is checked
541
    // as-is, a relative one is resolved against the PATH directories. The
542
    // directory-list overload refuses such names, so handle them here.
543
    if (QDir::isAbsolutePath(binary)) {
3 ✔
544
      ret = QStandardPaths::findExecutable(binary);
4 ✔
545
    } else if (!dirs.isEmpty()) {
1 ✔
546
      ret = QStandardPaths::findExecutable(binary, dirs);
2 ✔
547
    }
548
  } else {
549
    ret = findBinaryInPath(binary, dirs);
1,096 ✔
550
  }
551
#ifdef Q_OS_WIN
552
  if (ret.isEmpty()) {
553
    // Cache per-binary WSL lookup result — the wsl --version probe is a
554
    // blocking subprocess that can run several times per session for
555
    // missing binaries; once decided, the answer doesn't change at runtime.
556
    static QHash<QString, QString> wslBinaryCache;
557
    const bool hasWhitespace =
558
        std::any_of(binary.cbegin(), binary.cend(),
559
                    [](const QChar ch) { return ch.isSpace(); });
560
    if (!hasWhitespace) {
561
      auto cached = wslBinaryCache.constFind(binary);
562
      if (cached != wslBinaryCache.constEnd()) {
563
        ret = cached.value();
564
      } else {
565
        QString wslCommand = QStringLiteral("wsl ") + binary;
566
        qCDebug(lcQtPass)
567
            << "Util::findBinaryInPath(): falling back to WSL for binary"
568
            << binary;
569
        QString out, err;
570
        QString cachedResult;
571
        if (Executor::executeBlocking(wslCommand, {"--version"}, &out, &err) ==
572
                0 &&
573
            !out.isEmpty() && err.isEmpty()) {
574
          qCDebug(lcQtPass)
575
              << "Util::findBinaryInPath(): using WSL binary" << wslCommand;
576
          cachedResult = wslCommand;
577
        }
578
        wslBinaryCache.insert(binary, cachedResult);
579
        ret = cachedResult;
580
      }
581
    }
582
  }
583
#endif
584

585
  return ret;
586
}
587

588
// Bare names only: QStandardPaths::findExecutable() returns an absolute binary
589
// without consulting searchPaths, and a relative one with ".." could escape
590
// them.
591
auto Util::findBinaryInPath(const QString &binary,
562 ✔
592
                            const QStringList &searchPaths) -> QString {
593
  if (binary.isEmpty() || QDir::fromNativeSeparators(binary).contains(u'/')) {
1,123 ✔
594
    return {};
4 ✔
595
  }
596
  QStringList dirs;
558 ✔
597
  dirs.reserve(searchPaths.size());
558 ✔
598
  for (const QString &dir : searchPaths) {
8,806 ✔
599
    if (!dir.isEmpty()) {
8,248 ✔
600
      dirs.append(dir);
601
    }
602
  }
603
  if (dirs.isEmpty()) {
558 ✔
604
    // QStandardPaths::findExecutable() treats an empty list as "use PATH".
605
    return {};
4 ✔
606
  }
607
  return QStandardPaths::findExecutable(binary, dirs);
554 ✔
608
}
609

610
auto Util::configIsValid(const AppSettings &s) -> bool {
293 ✔
611
  const QString configFilePath = QDir(s.passStore).filePath(".gpg-id");
586 ✔
612
  if (!QFile(configFilePath).exists()) {
293 ✔
613
    return false;
614
  }
615

616
  const QString executable = s.usePass ? s.passExecutable : s.gpgExecutable;
211 ✔
617

618
  if (const auto wsl = Executor::parseWslCommand(executable)) {
211 ✔
619
    // Probe WSL once per session — availability doesn't change at runtime
620
    // and the executeBlocking call is a blocking subprocess.
621
    static const bool wslAvailable = [&wsl]() {
1 ✔
622
      QString out;
1 ✔
623
      QString err;
1 ✔
624
      return Executor::executeBlocking(wsl->launcher,
3 ✔
625
                                       {QStringLiteral("--version")}, &out,
1 ✔
626
                                       &err) == 0 &&
×
627
             !out.isEmpty() && err.isEmpty();
2 ✔
628
    }();
1 ✔
629
    if (wslAvailable) {
1 ✔
630
      return true;
631
    }
632
  }
633
  return QFile(executable).exists();
211 ✔
634
}
635

636
auto Util::endsWithGpg() -> const QRegularExpression & {
17,301 ✔
637
  static const QRegularExpression expr{R"(\.gpg$)"};
17,308 ✔
638
  return expr;
17,301 ✔
639
}
640

641
// Stops at whitespace, quotes and brackets so a URL on its own line keeps no
642
// line break. file:/// is excluded on purpose (local, not network); the test
643
// relies on that.
644
auto Util::protocolRegex() -> const QRegularExpression & {
158 ✔
645
  static const QRegularExpression regex{
646
      R"(((?:https?|ftp|ssh|sftp|ftps|webdav|webdavs)://[^"\s<>\)\]\[]+))"};
163 ✔
647
  return regex;
158 ✔
648
}
649

650
namespace {
651
/**
652
 * @brief The length of a URL's authority, found as QUrl finds it.
653
 *
654
 * QUrl takes the text before the first ':' that comes before any '/', '?'
655
 * or '#' as the scheme when it is one (a letter, then letters, digits,
656
 * '+', '-' or '.'); the rest starts there, or at the start otherwise. An
657
 * authority follows a "//" at that point and runs to the first '/', '?'
658
 * or '#'. So "//host" has one too, and a "://" later in the text does not
659
 * start it.
660
 * @param url The candidate URL.
661
 * @return The authority's length, or -1 when there is none.
662
 */
663
auto authorityLength(const QString &url) -> qsizetype {
124 ✔
664
  const auto endsPart = [](QChar c) {
665
    return c == QLatin1Char('/') || c == QLatin1Char('?') ||
666
           c == QLatin1Char('#');
667
  };
668
  const auto isAsciiLetter = [](QChar c) {
669
    return (c >= QLatin1Char('a') && c <= QLatin1Char('z')) ||
467 ✔
670
           (c >= QLatin1Char('A') && c <= QLatin1Char('Z'));
9 ✔
671
  };
672
  qsizetype colon = -1;
673
  for (qsizetype i = 0; i < url.size() && !endsPart(url.at(i)); ++i) {
857 ✔
674
    if (url.at(i) == QLatin1Char(':')) {
830 ✔
675
      colon = i;
676
      break;
677
    }
678
  }
679
  bool scheme = colon > 0 && isAsciiLetter(url.at(0));
124 ✔
680
  for (qsizetype i = 1; scheme && i < colon; ++i) {
494 ✔
681
    const QChar c = url.at(i);
682
    scheme =
683
        isAsciiLetter(c) || (c >= QLatin1Char('0') && c <= QLatin1Char('9')) ||
9 ✔
684
        c == QLatin1Char('+') || c == QLatin1Char('-') || c == QLatin1Char('.');
7 ✔
685
  }
686
  const qsizetype hier = scheme ? colon + 1 : 0;
124 ✔
687
  if (url.mid(hier, 2) != QLatin1String("//")) {
248 ✔
688
    return -1;
689
  }
690
  qsizetype end = hier + 2;
92 ✔
691
  while (end < url.size() && !endsPart(url.at(end))) {
201,621 ✔
692
    ++end;
201,529 ✔
693
  }
694
  return end - (hier + 2);
92 ✔
695
}
696
} // namespace
697

698
auto Util::isLaunchableWebUrl(const QString &value) -> bool {
128 ✔
699
  const QString trimmed = value.trimmed();
700
  if (trimmed.isEmpty()) {
128 ✔
701
    return false;
702
  }
703
  // Reject control characters first, before QUrl normalisation can hide a
704
  // CR/LF/NUL injection into the OS URL handler.
705
  for (const QChar &c : trimmed) {
264,770 ✔
706
    if (c == QLatin1Char('\r') || c == QLatin1Char('\n') ||
707
        c == QChar(QChar::Null)) {
708
      return false;
709
    }
710
  }
711
  // QUrl runs the host through Unicode normalisation, which takes time in
712
  // the square of a run of combining marks out of canonical order: one line
713
  // of an entry kept the window busy for minutes. A host has at most 253
714
  // characters and a port six more, so a longer authority is no web
715
  // address anyway.
716
  constexpr qsizetype kMaxAuthority = 259;
717
  if (authorityLength(trimmed) > kMaxAuthority) {
124 ✔
718
    return false;
719
  }
720
  const QUrl url(trimmed, QUrl::StrictMode);
118 ✔
721
  if (!url.isValid()) {
118 ✔
722
    return false;
723
  }
724
  const QString scheme = url.scheme().toLower();
103 ✔
725
  if (scheme != QLatin1String("http") && scheme != QLatin1String("https")) {
103 ✔
726
    return false;
36 ✔
727
  }
728
  if (url.host().isEmpty()) {
134 ✔
729
    return false;
730
  }
731
  // Embedded userinfo (user:pass@host) would leak into browser history.
732
  if (!url.userName().isEmpty() || !url.password().isEmpty()) {
127 ✔
733
    return false;
734
  }
735
  return true;
736
}
118 ✔
737

738
auto Util::displayable(const QString &text, bool lineBreaks) -> QString {
31,819 ✔
739
  QString shown = text;
740
  for (qsizetype i = 0; i < shown.size(); ++i) {
21,542,519 ✔
741
    const char16_t u = shown.at(i).unicode();
742
    // A carriage return before a line feed is a Windows line end (git or
743
    // gpg output quoted in a message), not a character of its own.
744
    const bool lineEnd =
745
        lineBreaks && (u == u'\n' || (u == u'\r' && i + 1 < shown.size() &&
21,510,700 ✔
746
                                      shown.at(i + 1) == u'\n'));
747
    if ((u < 0x20 && u != u'\t' && !lineEnd) || (u >= 0x7f && u <= 0x9f) ||
21,510,700 ✔
748
        u == 0x2028 || u == 0x2029 || (u >= 0x202a && u <= 0x202e) ||
21,510,644 ✔
749
        (u >= 0x2066 && u <= 0x2069)) {
21,510,632 ✔
750
      shown[i] = QChar(QChar::ReplacementCharacter);
70 ✔
751
    }
752
  }
753
  return shown;
31,819 ✔
754
}
755

756
auto Util::linkifyUrls(const QString &text, bool *linked) -> QString {
154 ✔
757
  if (linked != nullptr) {
154 ✔
758
    *linked = false;
61 ✔
759
  }
760
  QString html;
154 ✔
761
  html.reserve(text.size());
154 ✔
762
  qsizetype lastIndex = 0;
763
  QRegularExpressionMatchIterator it = protocolRegex().globalMatch(text);
154 ✔
764
  while (it.hasNext()) {
202 ✔
765
    const QRegularExpressionMatch match = it.next();
48 ✔
766
    const QString url = match.captured(0);
48 ✔
767
    // Only plain ASCII becomes a link: the link text is the URL as stored,
768
    // and a right-to-left letter, a bidi control or a look-alike host in it
769
    // makes it read as another address than the one it opens. Such a URL
770
    // stays plain text; the open button still takes it.
771
    const bool plain = std::all_of(url.cbegin(), url.cend(), [](QChar c) {
772
      return c.unicode() > 0x20 && c.unicode() < 0x7f;
1,139 ✔
773
    });
774
    if (!plain || !isLaunchableWebUrl(url)) {
48 ✔
775
      // Not a web URL (or it carries credentials): leave it in the escaped
776
      // plain-text run instead of making it clickable.
777
      continue;
778
    }
779
    const qsizetype start = match.capturedStart(0);
32 ✔
780
    html += text.mid(lastIndex, start - lastIndex).toHtmlEscaped();
32 ✔
781
    const QString escapedUrl = url.toHtmlEscaped();
32 ✔
782
    html += QStringLiteral("<a href=\"%1\">%1</a>").arg(escapedUrl);
64 ✔
783
    lastIndex = match.capturedEnd(0);
32 ✔
784
    if (linked != nullptr) {
32 ✔
785
      *linked = true;
24 ✔
786
    }
787
  }
48 ✔
788
  html += text.mid(lastIndex).toHtmlEscaped();
154 ✔
789
  // With a link in it, no bidi embedding, override or isolate control is
790
  // drawn: an override earlier in the entry (U+202E) drew the link text
791
  // reversed, so it read as another address. Shown as U+FFFD, so the user
792
  // sees that something was there; the copy button still copies the value.
793
  if (linked != nullptr ? *linked : html.contains(QLatin1String("<a href="))) {
247 ✔
794
    for (QChar &c : html) {
3,442 ✔
795
      const char16_t u = c.unicode();
3,412 ✔
796
      if ((u >= 0x202A && u <= 0x202E) || (u >= 0x2066 && u <= 0x2069)) {
3,412 ✔
797
        c = QChar(QChar::ReplacementCharacter);
1 ✔
798
      }
799
    }
800
  }
801
  return html;
154 ✔
802
}
154 ✔
803

804
auto Util::isOtherBlockBreak(QChar c) -> bool {
5,275,375 ✔
805
  const char16_t u = c.unicode();
5,275,375 ✔
806
  return u == u'\r' || u == 0x2029 || u == 0xFDD0 || u == 0xFDD1;
5,275,375 ✔
807
}
808

809
auto Util::withoutOtherBlockBreaks(QString text) -> QString {
223 ✔
810
  for (QChar &c : text) {
494,244 ✔
811
    if (isOtherBlockBreak(c)) {
494,021 ✔
812
      c = QLatin1Char(' ');
8,002 ✔
813
    }
814
  }
815
  return text;
223 ✔
816
}
817

818
auto Util::hasLongUnbrokenRun(QStringView text) -> bool {
328 ✔
819
  qsizetype run = 0;
820
  for (const QChar c : text) {
248,606 ✔
821
    // A no-break space (U+00A0, U+2007, U+202F) is white space to
822
    // isSpace(), but Qt does not wrap at it.
823
    const char16_t u = c.unicode();
824
    const bool breaks =
825
        c.isSpace() && u != 0x00A0 && u != 0x2007 && u != 0x202F;
248,289 ✔
826
    run = breaks ? 0 : run + 1;
211,214 ✔
827
    if (run > kMaxUnbrokenRun) {
248,289 ✔
828
      return true;
829
    }
830
  }
831
  return false;
832
}
833

834
auto Util::plainToolTip(const QString &text) -> QString {
18,853 ✔
835
  // Escaped, with its white space kept: two names that differ only in it
836
  // must not read the same; a long run is cut as everywhere it is kept.
837
  return QStringLiteral("<p style=\"white-space: pre-wrap;\">") +
18,853 ✔
838
         boundSpaceRuns(displayable(text, false)).toHtmlEscaped() +
37,706 ✔
839
         QStringLiteral("</p>");
37,706 ✔
840
}
841

842
auto Util::shownName(const QString &name, qsizetype max) -> QString {
360 ✔
843
  QString line = displayable(name, false);
360 ✔
844
  line.replace(QLatin1Char('\t'), QLatin1Char(' '));
360 ✔
845
  if (line.size() <= max) {
360 ✔
846
    return line;
348 ✔
847
  }
848
  // Too short for an ellipsis between two ends: the head alone.
849
  if (max < 3) {
12 ✔
850
    qsizetype keep = std::max<qsizetype>(max, 0);
851
    if (keep > 0 && line.at(keep - 1).isHighSurrogate()) {
5 ✔
852
      --keep;
853
    }
854
    return line.left(keep);
5 ✔
855
  }
856
  qsizetype head = max / 3;
7 ✔
857
  if (line.at(head - 1).isHighSurrogate()) {
7 ✔
858
    --head;
859
  }
860
  qsizetype tail = max - max / 3 - 1;
7 ✔
861
  if (line.at(line.size() - tail).isLowSurrogate()) {
7 ✔
862
    --tail;
×
863
  }
864
  return line.left(head) + QChar(0x2026) + line.right(tail);
14 ✔
865
}
866

867
// One pass, no regex: a pattern such as \s{1001,} retries from every
868
// character of a shorter run, which is quadratic on an entry made of them.
869
// A tab or a line feed ends a run in Qt's layout as well, so it ends one
870
// here; \v and U+0085 do not, so they count.
871
auto Util::boundSpaceRuns(const QString &text) -> QString {
19,080 ✔
872
  QString bounded;
19,080 ✔
873
  // Text before this index is in bounded already, or dropped.
874
  qsizetype from = 0;
875
  qsizetype run = 0;
876
  for (qsizetype i = 0; i < text.size(); ++i) {
20,702,236 ✔
877
    const QChar ch = text.at(i);
878
    if (!ch.isSpace() || ch == QLatin1Char('\t') || ch == QLatin1Char('\n')) {
20,683,156 ✔
879
      run = 0;
880
      continue;
20,529,111 ✔
881
    }
882
    if (++run <= kMaxSpaceRun) {
154,045 ✔
883
      continue;
18,508 ✔
884
    }
885
    if (run == kMaxSpaceRun + 1) {
135,537 ✔
886
      bounded += QStringView(text).sliced(from, i - from);
6 ✔
887
    }
888
    from = i + 1;
135,537 ✔
889
  }
890
  if (from == 0) {
19,080 ✔
891
    return text;
892
  }
893
  bounded += QStringView(text).sliced(from);
894
  return bounded;
895
}
896

897
auto Util::newLinesRegex() -> const QRegularExpression & {
335 ✔
898
  static const QRegularExpression regex{"[\r\n]"};
343 ✔
899
  return regex;
335 ✔
900
}
901

902
// No content heuristics: a line rejected here is erased the next time .gpg-id
903
// is rewritten. A leading `-` is refused because the recipients also go
904
// positionally to `gpg --list-keys`, where it would parse as an option.
905
auto Util::isValidKeyId(const QString &keyId) -> bool {
6,338 ✔
906
  return !keyId.isEmpty() && !keyId.startsWith('-');
6,338 ✔
907
}
908

909
namespace {
910
/**
911
 * @brief Whether the walk can see what is in @p dir: read permission to list
912
 * it and, on Unix, search permission to look at what it holds (without it the
913
 * names come, but no entry reads as a file or a folder), and no name Qt
914
 * leaves out of the listing (Util::hasUnreadableName()).
915
 * @param dir An existing directory.
916
 * @return false when the walk would miss what is in it.
917
 */
918
auto canList(const QString &dir) -> bool {
211 ✔
919
#ifdef Q_OS_WIN
920
  // Qt answers from the attributes alone unless told to read the ACL.
921
  QNtfsPermissionCheckGuard aclCheck;
922
  return QFileInfo(dir).isReadable();
923
#else
924
  const QFileInfo info(dir);
211 ✔
925
  return info.isReadable() && info.isExecutable() &&
414 ✔
926
         !Util::hasUnreadableName(dir);
414 ✔
927
#endif
928
}
211 ✔
929

930
/**
931
 * @brief Walk @p dir's real, visible directories in sorted pre-order and hand
932
 * every entry to @p visit before any recursion; a directory is entered only
933
 * when @p visit returns true for it. A directory that cannot be read goes to
934
 * @p unlisted, when given: its listing would come back empty, as an empty
935
 * folder's does, and what is in it would be left out without a sign.
936
 */
937
template <typename Visit>
938
void walkStore(const QString &dir, Visit visit,
347 ✔
939
               QStringList *unlisted = nullptr) {
940
  // Absolute, so the results are whatever the caller's cwd; not canonical,
941
  // so a linked root keeps the name it was configured under.
942
  QStringList pending{QDir(QDir::cleanPath(dir)).absolutePath()};
1,041 ✔
943
  while (!pending.isEmpty()) {
2,949 ✔
944
    const QDir current(pending.takeLast());
1,306 ✔
945
    if (unlisted != nullptr && current.exists() && !canList(current.path())) {
2,612 ✔
946
      qCWarning(lcQtPass) << "Cannot list" << current.path();
20 ✔
947
      *unlisted << current.path();
10 ✔
948
      continue;
949
    }
10 ✔
950
    // Every entry once, links and hidden entries included, so the decision
951
    // what to do with each is taken here, before any recursion. QDir::System
952
    // keeps dangling links in the listing.
953
    const QFileInfoList entries =
1,296 ✔
954
        current.entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
955
                                  QDir::System | QDir::NoDotAndDotDot,
956
                              QDir::Name);
957
    QStringList subdirs;
1,296 ✔
958
    for (const QFileInfo &entry : entries) {
8,051 ✔
959
      if (visit(entry)) {
6,755 ✔
960
        subdirs << entry.filePath();
1,918 ✔
961
      }
962
    }
963
    // Pushed last-to-first so the next one taken is the first by name.
964
    for (auto it = subdirs.crbegin(); it != subdirs.crend(); ++it) {
2,255 ✔
965
      pending << *it;
966
    }
967
  }
968
}
694 ✔
969

970
/// A symlink or an NTFS junction: never entered, never listed.
971
auto isLink(const QFileInfo &entry) -> bool {
28,239 ✔
972
  return entry.isSymLink() || entry.isJunction();
28,239 ✔
973
}
974

975
/// Hidden by attribute, or by the dot convention on every platform: Qt 6.11
976
/// on macOS answers isHidden() from the UF_HIDDEN flag alone once an entry
977
/// was lstat()ed (qfilesystemengine_unix.cpp marks the attribute known there
978
/// without the dot check), and Windows does not consider .stversions hidden
979
/// at all.
980
auto isHiddenEntry(const QFileInfo &entry) -> bool {
5,690 ✔
981
  return entry.isHidden() || entry.fileName().startsWith(QLatin1Char('.'));
11,360 ✔
982
}
983

984
/// A real directory that is part of the store: .git, .stversions,
985
/// .Trash-1000 are not, as with QDirIterator without QDir::Hidden.
986
auto isStoreDirectory(const QFileInfo &entry) -> bool {
6,755 ✔
987
  return !isLink(entry) && entry.isDir() && !isHiddenEntry(entry);
6,755 ✔
988
}
989
} // namespace
990

991
auto Util::regularFilesUnder(const QString &dir, const QStringList &nameFilters,
344 ✔
992
                             QStringList *skipped, bool hiddenFiles,
993
                             QStringList *unlisted) -> QStringList {
994
  QStringList files;
344 ✔
995
  walkStore(
344 ✔
996
      dir,
997
      [&](const QFileInfo &entry) {
6,679 ✔
998
        if (isStoreDirectory(entry)) {
6,679 ✔
999
          return true;
1000
        }
1001
        const bool named = QDir::match(nameFilters, entry.fileName());
5,741 ✔
1002
        if (isLink(entry) || (!entry.isDir() && !entry.isFile())) {
5,741 ✔
1003
          // A linked directory hides everything behind it; a linked file, or a
1004
          // FIFO, socket or device, is only of interest under a name the caller
1005
          // asked for.
1006
          if (skipped != nullptr && (entry.isDir() || named)) {
68 ✔
1007
            qCWarning(lcQtPass) << "Skipping" << entry.filePath()
104 ✔
1008
                                << ": not a regular file or directory";
52 ✔
1009
            *skipped << entry.filePath();
104 ✔
1010
          }
1011
          return false;
68 ✔
1012
        }
1013
        if (entry.isFile() && named && (hiddenFiles || !isHiddenEntry(entry))) {
5,673 ✔
1014
          files << entry.filePath();
9,830 ✔
1015
        }
1016
        return false;
1017
      },
1018
      unlisted);
1019
  return files;
344 ✔
1020
}
1021

1022
auto Util::directoriesUnder(const QString &dir) -> QStringList {
3 ✔
1023
  QStringList dirs;
3 ✔
1024
  walkStore(dir, [&](const QFileInfo &entry) {
3 ✔
1025
    if (!isStoreDirectory(entry)) {
76 ✔
1026
      return false;
1027
    }
1028
    dirs << entry.filePath();
21 ✔
1029
    return true;
21 ✔
1030
  });
1031
  return dirs;
3 ✔
1032
}
1033

1034
auto Util::hasUnreadableName(const QString &dir) -> bool {
298 ✔
1035
#ifdef Q_OS_WIN
1036
  Q_UNUSED(dir);
1037
  return false;
1038
#else
1039
  // The names as bytes, as readdir() gives them; Qt's own listing has
1040
  // already dropped the ones this is looking for.
1041
  DIR *listing = ::opendir(QFile::encodeName(dir).constData());
298 ✔
1042
  if (listing == nullptr) {
298 ✔
1043
    return false;
1044
  }
1045
  const auto close = qScopeGuard([listing] { ::closedir(listing); });
295 ✔
1046
  while (const dirent *entry = ::readdir(listing)) {
1,490 ✔
1047
    if (!QByteArrayView(entry->d_name).isValidUtf8()) {
1,201 ✔
1048
      return true;
1049
    }
1050
  }
1051
  return false;
1052
#endif
1053
}
1054

1055
auto Util::isLinkedFolder(const QString &path) -> bool {
15,700 ✔
1056
  return isLink(QFileInfo(QDir::cleanPath(path)));
31,400 ✔
1057
}
1058

1059
auto Util::isUnderLink(const QString &path, const QString &storeRoot,
12,660 ✔
1060
                       bool includeSelf) -> bool {
1061
  // "C:/Store" and "c:/store" are one directory on Windows; a path spelled
1062
  // the other way must not skip the walk (as in Pass::getGpgIdPath).
1063
#ifdef Q_OS_WIN
1064
  constexpr auto cs = Qt::CaseInsensitive;
1065
#else
1066
  constexpr auto cs = Qt::CaseSensitive;
1067
#endif
1068
  const QString root = QDir::cleanPath(storeRoot);
12,660 ✔
1069
  // A root of "/" or "C:/" already ends in the separator.
1070
  const QString prefix =
1071
      root.endsWith(QLatin1Char('/')) ? root : root + QLatin1Char('/');
12,660 ✔
1072
  const auto isRoot = [&](const QString &p) {
1073
    return p.compare(root, cs) == 0;
15,218 ✔
1074
  };
1075
  QString current = QDir::cleanPath(path);
12,660 ✔
1076
  if (!current.startsWith(prefix, cs)) {
12,660 ✔
1077
    // Not under the store as named: only the entry itself can be judged.
1078
    return includeSelf && !isRoot(current) && isLinkedFolder(current);
520 ✔
1079
  }
1080
  if (!includeSelf) {
12,400 ✔
1081
    current = QFileInfo(current).path();
23,014 ✔
1082
  }
1083
  for (; !isRoot(current) && current.startsWith(prefix, cs);
14,958 ✔
1084
       current = QFileInfo(current).path()) {
5,116 ✔
1085
    if (isLinkedFolder(current)) {
2,607 ✔
1086
      return true;
1087
    }
1088
  }
1089
  return false;
1090
}
1091

1092
#ifndef Q_OS_WIN
1093
namespace {
1094

1095
/// The filesystem cannot make hard links at all (FAT/exFAT refuse with
1096
/// EPERM, some FUSE filesystems with ENOTSUP or ENOSYS).
1097
auto hasNoHardLinks(int error) -> bool {
1098
  return error == EPERM || error == ENOTSUP || error == EOPNOTSUPP ||
2 ✔
1099
         error == ENOSYS;
1100
}
1101

1102
/// rename() that fails with EEXIST instead of replacing, where the platform
1103
/// has one; nothing when neither the platform nor the filesystem does.
1104
auto renameExclusive(const QByteArray &source, const QByteArray &target)
8 ✔
1105
    -> std::optional<bool> {
1106
#if defined(__GLIBC__) &&                                                      \
1107
    (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 28))
1108
  if (::renameat2(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(),
8 ✔
1109
                  RENAME_NOREPLACE) == 0) {
1110
    return true;
2 ✔
1111
  }
1112
  if (errno == EINVAL || errno == ENOSYS || hasNoHardLinks(errno)) {
6 ✔
1113
    return std::nullopt;
4 ✔
1114
  }
1115
  return false;
2 ✔
1116
#elif defined(Q_OS_MACOS)
1117
  if (::renamex_np(source.constData(), target.constData(), RENAME_EXCL) == 0) {
1118
    return true;
1119
  }
1120
  if (errno == EINVAL || errno == ENOTSUP) {
1121
    return std::nullopt;
1122
  }
1123
  return false;
1124
#else
1125
  Q_UNUSED(source);
1126
  Q_UNUSED(target);
1127
  return std::nullopt;
1128
#endif
1129
}
1130

1131
/**
1132
 * @brief Gives @p source the name @p target unless something already has it.
1133
 *
1134
 * A hard link is the one way every POSIX system can do that in one step:
1135
 * linkat() fails with EEXIST rather than replacing. Where the filesystem has
1136
 * no hard links, an exclusive rename does it; where that is missing too, the
1137
 * name is checked and then renamed, which leaves a short window for another
1138
 * writer to create it in between.
1139
 */
1140
auto placeWithoutReplacing(const QByteArray &source, const QByteArray &target)
110 ✔
1141
    -> bool {
1142
  // linkat() without AT_SYMLINK_FOLLOW follows nothing; link() would, on
1143
  // macOS and the BSDs, hard-link whatever a symlink planted under the
1144
  // source's name points at.
1145
  if (::linkat(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(), 0) ==
110 ✔
1146
      0) {
1147
    ::unlink(source.constData());
95 ✔
1148
    return true;
95 ✔
1149
  }
1150
  if (!hasNoHardLinks(errno)) {
15 ✔
1151
    return false;
1152
  }
1153
  if (const std::optional<bool> renamed = renameExclusive(source, target)) {
8 ✔
1154
    return *renamed;
4 ✔
1155
  }
1156
  struct stat st{};
4 ✔
1157
  if (::lstat(target.constData(), &st) == 0 || errno != ENOENT) {
4 ✔
1158
    errno = EEXIST;
2 ✔
1159
    return false;
2 ✔
1160
  }
1161
  return ::rename(source.constData(), target.constData()) == 0;
2 ✔
1162
}
1163

1164
} // namespace
1165
#endif
1166

1167
auto Util::replaceFile(const QString &from, const QString &to, bool replace)
286 ✔
1168
    -> bool {
1169
#ifdef Q_OS_WIN
1170
  const std::wstring source =
1171
      QDir::toNativeSeparators(QFileInfo(from).absoluteFilePath())
1172
          .toStdWString();
1173
  const std::wstring target =
1174
      QDir::toNativeSeparators(QFileInfo(to).absoluteFilePath()).toStdWString();
1175
  // WRITE_THROUGH: the new entry is on the device when this returns.
1176
  return MoveFileExW(source.c_str(), target.c_str(),
1177
                     (replace ? MOVEFILE_REPLACE_EXISTING : 0) |
1178
                         MOVEFILE_WRITE_THROUGH) != 0;
1179
#else
1180
  const QByteArray source = QFile::encodeName(from);
1181
  const QByteArray target = QFile::encodeName(to);
1182
  if (replace) {
286 ✔
1183
    if (::rename(source.constData(), target.constData()) != 0) {
176 ✔
1184
      return false;
1185
    }
1186
  } else {
1187
    if (!placeWithoutReplacing(source, target)) {
110 ✔
1188
      return false;
1189
    }
1190
  }
1191
  // Sync the directory entry so a crash does not lose the new name. Best
1192
  // effort: the bytes are already synced, and some network filesystems
1193
  // cannot sync a directory.
1194
  const int dir = ::open(QFile::encodeName(QFileInfo(to).path()).constData(),
544 ✔
1195
                         O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1196
  if (dir >= 0) {
272 ✔
1197
    int rc;
1198
    do {
1199
      rc = ::fsync(dir);
272 ✔
1200
    } while (rc != 0 && errno == EINTR);
272 ✔
1201
    ::close(dir);
272 ✔
1202
  }
1203
  return true;
1204
#endif
1205
}
1206

1207
auto Util::openRegularFile(const QString &path, QFile &file) -> bool {
1,079 ✔
1208
#ifdef Q_OS_WIN
1209
  // FILE_FLAG_OPEN_REPARSE_POINT opens a symbolic link or junction itself
1210
  // rather than its target, so the handle's attributes say what the name
1211
  // was at the moment of the open.
1212
  const std::wstring native =
1213
      QDir::toNativeSeparators(QFileInfo(path).absoluteFilePath())
1214
          .toStdWString();
1215
  HANDLE handle = CreateFileW(
1216
      native.c_str(), GENERIC_READ,
1217
      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
1218
      OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
1219
  if (handle == INVALID_HANDLE_VALUE) {
1220
    return false;
1221
  }
1222
  BY_HANDLE_FILE_INFORMATION info{};
1223
  if (!GetFileInformationByHandle(handle, &info) ||
1224
      (info.dwFileAttributes &
1225
       (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY |
1226
        FILE_ATTRIBUTE_DEVICE)) != 0 ||
1227
      GetFileType(handle) != FILE_TYPE_DISK) {
1228
    CloseHandle(handle);
1229
    return false;
1230
  }
1231
  const int fd = _open_osfhandle(reinterpret_cast<intptr_t>(handle),
1232
                                 _O_RDONLY | _O_BINARY);
1233
  if (fd < 0) {
1234
    CloseHandle(handle);
1235
    return false;
1236
  }
1237
  if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
1238
    _close(fd);
1239
    return false;
1240
  }
1241
  return true;
1242
#else
1243
  // O_NOFOLLOW fails with ELOOP on a symbolic link; O_NONBLOCK keeps a FIFO
1244
  // from blocking the open until fstat() can refuse it.
1245
  const int fd = ::open(QFile::encodeName(path).constData(),
1,079 ✔
1246
                        O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
1247
  if (fd < 0) {
1,079 ✔
1248
    return false;
1249
  }
1250
  struct stat st{};
981 ✔
1251
  if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
981 ✔
1252
    ::close(fd);
7 ✔
1253
    return false;
7 ✔
1254
  }
1255
  // The descriptor, not the name, is what QFile opens here: the object
1256
  // fstat() judged is the object read. CodeQL's check-then-use pattern
1257
  // matcher sees an open after a check and cannot tell.
1258
  if (!file.open(fd, QIODevice::ReadOnly, // codeql[cpp/toctou-race-condition]
974 ✔
1259
                 QFileDevice::AutoCloseHandle)) {
1260
    ::close(fd);
×
1261
    return false;
×
1262
  }
1263
  return true;
1264
#endif
1265
}
1266

1267
namespace {
1268
/**
1269
 * @brief Read an open regular file whole when it holds at most @p maxBytes.
1270
 * @param file Open on a regular file.
1271
 * @param maxBytes The most bytes accepted.
1272
 * @return The contents; nothing when larger or unreadable.
1273
 */
1274
auto readOpenFile(QFile &file, qint64 maxBytes) -> std::optional<QByteArray> {
926 ✔
1275
  // A regular file's size is reliable, also when sparse: refuse a large one
1276
  // before reading anything. One byte past the limit still guards a file
1277
  // that grows meanwhile.
1278
  if (file.size() > maxBytes) {
926 ✔
1279
    return std::nullopt;
5 ✔
1280
  }
1281
  QByteArray bytes = file.read(maxBytes + 1);
921 ✔
1282
  if (bytes.size() > maxBytes || file.error() != QFileDevice::NoError) {
921 ✔
1283
    return std::nullopt;
×
1284
  }
1285
  return bytes;
1286
}
1287
} // namespace
1288

1289
auto Util::readRegularFile(const QString &path, qint64 maxBytes)
430 ✔
1290
    -> std::optional<QByteArray> {
1291
  QFile file;
430 ✔
1292
  if (!openRegularFile(path, file)) {
430 ✔
1293
    return std::nullopt;
47 ✔
1294
  }
1295
  return readOpenFile(file, maxBytes);
383 ✔
1296
}
430 ✔
1297

1298
auto Util::readRegularFileUnder(const QString &root, const QString &path,
556 ✔
1299
                                qint64 maxBytes) -> std::optional<QByteArray> {
1300
  const QString cleanRoot = QDir::cleanPath(root);
556 ✔
1301
  const QString relative =
1302
      QDir(cleanRoot).relativeFilePath(QDir::cleanPath(path));
1,112 ✔
1303
  const QStringList parts = relative.split(QLatin1Char('/'));
556 ✔
1304
  if (relative.isEmpty() || QDir::isAbsolutePath(relative) ||
1,112 ✔
1305
      parts.contains(QStringLiteral("..")) ||
1,110 ✔
1306
      parts.contains(QStringLiteral(".")) || parts.contains(QString())) {
2,219 ✔
1307
    return std::nullopt;
3 ✔
1308
  }
1309
#ifdef Q_OS_WIN
1310
  // No openat() here: each folder from the root down is opened by name and
1311
  // held open, without FILE_SHARE_DELETE, until the file is read. A folder
1312
  // held that way cannot be renamed, removed or replaced by a junction
1313
  // meanwhile, so the file is opened through exactly the folders judged.
1314
  // The root itself is followed (a linked store is the user's setup).
1315
  std::vector<HANDLE> held;
1316
  const auto release = qScopeGuard([&held] {
1317
    for (HANDLE handle : held) {
1318
      CloseHandle(handle);
1319
    }
1320
  });
1321
  QString folder = cleanRoot;
1322
  for (qsizetype i = 0; i < parts.size(); ++i) {
1323
    const bool isRoot = i == 0;
1324
    if (!isRoot) {
1325
      folder += QLatin1Char('/') + parts.at(i - 1);
1326
    }
1327
    const std::wstring native = QDir::toNativeSeparators(folder).toStdWString();
1328
    // GENERIC_READ (listing the folder) is data access, so the share mode
1329
    // is enforced against a later open for DELETE; attribute access alone
1330
    // would not be.
1331
    HANDLE handle =
1332
        CreateFileW(native.c_str(), GENERIC_READ,
1333
                    FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
1334
                    FILE_FLAG_BACKUP_SEMANTICS |
1335
                        (isRoot ? 0 : FILE_FLAG_OPEN_REPARSE_POINT),
1336
                    nullptr);
1337
    if (handle == INVALID_HANDLE_VALUE) {
1338
      return std::nullopt;
1339
    }
1340
    held.push_back(handle);
1341
    // A link is what the walk (isLink(): QFileInfo::isSymLink() or
1342
    // isJunction()) leaves out: a symbolic link or a junction. A folder with
1343
    // another reparse tag, such as a cloud provider's placeholder, is listed
1344
    // by the walk and is read through here too.
1345
    FILE_ATTRIBUTE_TAG_INFO info{};
1346
    if (!GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &info,
1347
                                      sizeof(info)) ||
1348
        (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
1349
      return std::nullopt;
1350
    }
1351
    const bool link =
1352
        (info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 &&
1353
        (info.ReparseTag == IO_REPARSE_TAG_SYMLINK ||
1354
         info.ReparseTag == IO_REPARSE_TAG_MOUNT_POINT);
1355
    if (!isRoot && link) {
1356
      return std::nullopt;
1357
    }
1358
  }
1359
  // openRegularFile() refuses a reparse point as the file itself.
1360
  return readRegularFile(path, maxBytes);
1361
#else
1362
  // The root by name, followed if it is a link (the user's setup); below it
1363
  // nothing is.
1364
  int dir = ::open(QFile::encodeName(cleanRoot).constData(),
553 ✔
1365
                   O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1366
  if (dir < 0) {
553 ✔
NEW
1367
    return std::nullopt;
×
1368
  }
1369
  for (qsizetype i = 0; i + 1 < parts.size(); ++i) {
599 ✔
1370
    const int next = ::openat(dir, QFile::encodeName(parts.at(i)).constData(),
51 ✔
1371
                              O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
1372
    ::close(dir);
51 ✔
1373
    if (next < 0) {
51 ✔
1374
      return std::nullopt;
5 ✔
1375
    }
1376
    dir = next;
1377
  }
1378
  // As openRegularFile(): no link, no FIFO left blocking the open.
NEW
1379
  const int fd = ::openat(dir, QFile::encodeName(parts.constLast()).constData(),
×
1380
                          O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
1381
  ::close(dir);
548 ✔
1382
  if (fd < 0) {
548 ✔
1383
    return std::nullopt;
3 ✔
1384
  }
1385
  struct stat st{};
545 ✔
1386
  if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
545 ✔
1387
    ::close(fd);
2 ✔
1388
    return std::nullopt;
2 ✔
1389
  }
1390
  QFile file;
543 ✔
1391
  if (!file.open(fd, QIODevice::ReadOnly, // codeql[cpp/toctou-race-condition]
543 ✔
1392
                 QFileDevice::AutoCloseHandle)) {
NEW
1393
    ::close(fd);
×
NEW
1394
    return std::nullopt;
×
1395
  }
1396
  return readOpenFile(file, maxBytes);
543 ✔
1397
#endif
1398
}
543 ✔
1399

1400
auto Util::syncToDisk(QFileDevice &file) -> bool {
272 ✔
1401
  if (!file.flush()) {
272 ✔
1402
    return false;
1403
  }
1404
#ifdef Q_OS_WIN
1405
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1406
  return handle != INVALID_HANDLE_VALUE && FlushFileBuffers(handle) != 0;
1407
#else
1408
  return ::fsync(file.handle()) == 0;
272 ✔
1409
#endif
1410
}
1411

1412
namespace {
1413

1414
/**
1415
 * @brief What tells one file object from another on its filesystem: device
1416
 * and inode on POSIX, volume serial and file index on Windows.
1417
 */
1418
struct FileIdentity {
1419
  quint64 volume = 0;
1420
  quint64 index = 0;
1421
  bool known = false;
1422
};
1423

1424
auto operator==(const FileIdentity &a, const FileIdentity &b) -> bool {
261 ✔
1425
  return a.known && b.known && a.volume == b.volume && a.index == b.index;
261 ✔
1426
}
1427

1428
/// The identity of the object @p file is open on, or an unknown one.
1429
auto identityOf(const QFileDevice &file) -> FileIdentity {
533 ✔
1430
#ifdef Q_OS_WIN
1431
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1432
  BY_HANDLE_FILE_INFORMATION info;
1433
  if (handle == INVALID_HANDLE_VALUE ||
1434
      GetFileInformationByHandle(handle, &info) == 0) {
1435
    return {};
1436
  }
1437
  // On FAT/exFAT the file ID is the directory entry's offset, which a rename
1438
  // can move. They have no hard links either (the swap this catches needs
1439
  // one), so the identity is left unknown there.
1440
  DWORD flags = 0;
1441
  if (GetVolumeInformationByHandleW(handle, nullptr, 0, nullptr, nullptr,
1442
                                    &flags, nullptr, 0) == 0 ||
1443
      (flags & FILE_SUPPORTS_HARD_LINKS) == 0) {
1444
    return {};
1445
  }
1446
  return {info.dwVolumeSerialNumber,
1447
          (static_cast<quint64>(info.nFileIndexHigh) << 32) |
1448
              info.nFileIndexLow,
1449
          true};
1450
#else
1451
  struct stat st{};
533 ✔
1452
  if (::fstat(file.handle(), &st) != 0) {
533 ✔
1453
    return {};
×
1454
  }
1455
  return {static_cast<quint64>(st.st_dev), static_cast<quint64>(st.st_ino),
533 ✔
1456
          true};
533 ✔
1457
#endif
1458
}
1459

1460
/// Put @p text in @p error when there is one; false, for `return fail(...)`.
1461
auto fail(QString *error, const QString &text) -> bool {
1462
  if (error != nullptr) {
22 ✔
1463
    *error = text;
22 ✔
1464
  }
1465
  return false;
1466
}
1467

1468
/// A filled, synced temporary next to its destination.
1469
struct Staged {
272 ✔
1470
  QString path;
1471
  FileIdentity identity;
1472
  /// POSIX: a descriptor kept open on the temporary until the identity
1473
  /// check, so the inode, and with it the number, stays the temporary's.
1474
  std::shared_ptr<void> pin;
1475
};
1476

1477
/**
1478
 * @brief Create the temporary next to @p path (opaque name, exclusive,
1479
 * owner-only), fill it through its handle and sync it. The QTemporaryFile
1480
 * goes out of scope before the caller renames: it keeps its handle open for
1481
 * as long as it lives, and Windows does not rename an open file.
1482
 */
1483
auto stageNextTo(const QString &path, const Util::Filler &fill, QString *why)
280 ✔
1484
    -> std::optional<Staged> {
1485
  Staged staged;
280 ✔
1486
  {
1487
    QTemporaryFile file(QFileInfo(path).path() +
560 ✔
1488
                        QStringLiteral("/.qtpass-XXXXXX.tmp"));
560 ✔
1489
    file.setAutoRemove(false);
280 ✔
1490
    if (!file.open()) {
280 ✔
1491
      *why = QCoreApplication::translate(
8 ✔
1492
                 "Util", "Cannot create a temporary file next to %1: %2")
1493
                 .arg(path, file.errorString());
16 ✔
1494
      return std::nullopt;
8 ✔
1495
    }
1496
    staged.path = file.fileName();
272 ✔
1497
    // Owner-only: a .gpg-id names the keys a store is encrypted to, an
1498
    // entry is an entry. QTemporaryFile creates 0600 already; say so for
1499
    // platforms where it may not.
1500
    file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
272 ✔
1501
    *why = fill(file);
544 ✔
1502
    if (why->isEmpty() && !Util::syncToDisk(file)) {
272 ✔
1503
      *why = QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1504
                 .arg(path, file.errorString());
×
1505
    }
1506
    staged.identity = identityOf(file);
272 ✔
1507
#ifndef Q_OS_WIN
1508
    // Closed and unlinked by a co-writer before the rename, the temporary's
1509
    // inode number would be free, and ext4 hands it to the next file made:
1510
    // the very file swapped in would then pass the check below. Windows
1511
    // cannot rename an open file, and NTFS does not reuse a file index so.
1512
    if (const int fd = ::dup(file.handle()); fd >= 0) {
272 ✔
1513
      staged.pin =
1514
          std::shared_ptr<void>(nullptr, [fd](void *) { ::close(fd); });
816 ✔
1515
    }
1516
#endif
1517
  }
280 ✔
1518
  if (!why->isEmpty()) {
272 ✔
1519
    QFile::remove(staged.path);
×
1520
    return std::nullopt;
×
1521
  }
1522
  return staged;
272 ✔
1523
}
280 ✔
1524

1525
/// Why replaceFile() could not put the temporary under @p path.
1526
auto placementError(const QString &path, bool replace) -> QString {
9 ✔
1527
  if (replace) {
9 ✔
1528
    return QCoreApplication::translate("Util", "Failed to replace %1.")
4 ✔
1529
        .arg(path);
2 ✔
1530
  }
1531
  const QFileInfo taken(path);
7 ✔
1532
  return taken.exists() || taken.isSymLink()
8 ✔
1533
             ? QCoreApplication::translate("Util", "%1 already exists.")
7 ✔
1534
                   .arg(path)
1535
             : QCoreApplication::translate("Util", "Failed to write %1.")
1 ✔
1536
                   .arg(path);
8 ✔
1537
}
7 ✔
1538

1539
/**
1540
 * @brief Whether what is under @p path is the file that was filled: not a
1541
 * link, and not another file (a hard link to something of the user's, say)
1542
 * swapped in under the temporary's name. Opened without following, compared
1543
 * by identity; only two known identities can prove a swap, otherwise every
1544
 * write on such a store would be reported as tampering.
1545
 */
1546
auto isTheFileWritten(const QString &path, const FileIdentity &written)
263 ✔
1547
    -> bool {
1548
  QFile placed;
263 ✔
1549
  if (!Util::openRegularFile(path, placed)) {
263 ✔
1550
    return false;
1551
  }
1552
  const FileIdentity there = identityOf(placed);
261 ✔
1553
  if (!written.known || !there.known) {
261 ✔
1554
    qCWarning(lcQtPass) << "Cannot tell whether" << path
×
1555
                        << "is the file that was written here";
×
1556
    return true;
×
1557
  }
1558
  return there == written;
261 ✔
1559
}
263 ✔
1560

1561
} // namespace
1562

1563
auto Util::stageFileReplacing(const QString &path, bool replace,
280 ✔
1564
                              const Filler &fill, QString *error) -> bool {
1565
  QString why;
280 ✔
1566
  const std::optional<Staged> staged = stageNextTo(path, fill, &why);
280 ✔
1567
  if (!staged) {
280 ✔
1568
    return fail(error, why);
1569
  }
1570
  if (s_beforePlacingForTests) {
272 ✔
1571
    s_beforePlacingForTests(staged->path);
1 ✔
1572
  }
1573
  if (!replaceFile(staged->path, path, replace)) {
272 ✔
1574
    QFile::remove(staged->path);
9 ✔
1575
    return fail(error, placementError(path, replace));
18 ✔
1576
  }
1577
  // A mismatch is reported and left: removing by name could take another
1578
  // writer's file.
1579
  if (!isTheFileWritten(path, staged->identity)) {
263 ✔
1580
    return fail(
1581
        error,
1582
        QCoreApplication::translate(
5 ✔
1583
            "Util", "%1 was swapped for another file while it was written.")
1584
            .arg(path));
10 ✔
1585
  }
1586
  return true;
1587
}
1588

1589
auto Util::writeFileReplacing(const QString &path, const QByteArray &bytes,
110 ✔
1590
                              bool replace, QString *error) -> bool {
1591
  return stageFileReplacing(
110 ✔
1592
      path, replace,
1593
      [&path, &bytes](QFileDevice &staged) -> QString {
218 ✔
1594
        if (staged.write(bytes) != bytes.size()) {
108 ✔
1595
          return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1596
              .arg(path, staged.errorString());
×
1597
        }
1598
        return {};
108 ✔
1599
      },
1600
      error);
110 ✔
1601
}
1602

1603
auto Util::copyFileReplacing(const QString &src, const QString &dst,
169 ✔
1604
                             bool replace, QString *error) -> bool {
1605
  QFile in;
169 ✔
1606
  if (!openRegularFile(src, in)) {
169 ✔
1607
    if (error)
4 ✔
1608
      *error = QCoreApplication::translate("Util", "Cannot read %1.").arg(src);
8 ✔
1609
    return false;
4 ✔
1610
  }
1611
  return stageFileReplacing(
165 ✔
1612
      dst, replace,
1613
      [&src, &dst, &in](QFileDevice &staged) -> QString {
489 ✔
1614
        char buf[64 * 1024];
1615
        for (;;) {
1616
          const qint64 n = in.read(buf, sizeof buf);
330 ✔
1617
          if (n < 0) {
330 ✔
1618
            return QCoreApplication::translate("Util", "Cannot read %1: %2")
×
1619
                .arg(src, in.errorString());
×
1620
          }
1621
          if (n == 0) {
330 ✔
1622
            return {};
159 ✔
1623
          }
1624
          if (staged.write(buf, n) != n) {
171 ✔
1625
            return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1626
                .arg(dst, staged.errorString());
×
1627
          }
1628
        }
1629
      },
1630
      error);
1631
}
169 ✔
1632

1633
namespace {
1634

1635
/// Remove one directory entry that is not a real directory: a link goes as
1636
/// the entry itself, never its target (a junction or a directory symlink on
1637
/// Windows is a directory entry and goes with rmdir); a read-only file gets
1638
/// write access and one more try, as QDir::removeRecursively() does.
1639
auto removeEntry(const QFileInfo &entry) -> bool {
14 ✔
1640
  const QString path = entry.filePath();
14 ✔
1641
  if (isLink(entry)) {
14 ✔
1642
    if (QFile::remove(path) || QDir().rmdir(path)) {
6 ✔
1643
      return true;
1644
    }
1645
    qCWarning(lcQtPass) << "Could not remove link" << path;
2 ✔
1646
    return false;
1 ✔
1647
  }
1648
  if (QFile::remove(path)) {
9 ✔
1649
    return true;
1650
  }
1651
  const QFile::Permissions perms = QFile::permissions(path);
2 ✔
1652
  if (!perms.testFlag(QFile::WriteUser) &&
1 ✔
1653
      QFile::setPermissions(path, perms | QFile::WriteUser) &&
3 ✔
1654
      QFile::remove(path)) {
1 ✔
1655
    return true;
1656
  }
1657
  qCWarning(lcQtPass) << "Could not remove" << path;
4 ✔
1658
  return false;
2 ✔
1659
}
1660

1661
} // namespace
1662

1663
auto Util::removeTree(const QString &dir) -> bool {
23 ✔
1664
  // A trailing separator makes lstat follow a link ("link/" is the target
1665
  // directory); the link itself is what this is about.
1666
  const QString path = QDir::cleanPath(dir);
23 ✔
1667
  const QFileInfo top(path);
23 ✔
1668
  if (isLink(top)) {
23 ✔
1669
    // rm -rf on a link removes the link.
1670
    return QFile::remove(path) || QDir().rmdir(path);
16 ✔
1671
  }
1672
  if (!top.isDir()) {
9 ✔
1673
    return false;
1674
  }
1675
  bool ok = true;
1676
  const QFileInfoList entries =
1677
      QDir(path).entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
16 ✔
1678
                                   QDir::System | QDir::NoDotAndDotDot,
1679
                               QDir::Name);
8 ✔
1680
  for (const QFileInfo &entry : entries) {
24 ✔
1681
    const bool removed = entry.isDir() && !isLink(entry)
22 ✔
1682
                             ? removeTree(entry.filePath())
18 ✔
1683
                             : removeEntry(entry);
14 ✔
1684
    ok = removed && ok;
16 ✔
1685
  }
1686
  return ok && QDir().rmdir(path);
13 ✔
1687
}
23 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc