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

IJHack / QtPass / 43475275928

13 Nov 2026 05:41PM UTC coverage: 92.709% (-0.02%) from 92.727%
43475275928

push

github

web-flow
coverage: let lcov ignore inconsistent data on system headers (#2136)

lcov 2.x on the CI runner (gcc 15 headers) fails the coverage job with
"lcov: ERROR: (inconsistent) ...: function ... is not hit but line ... has
a non-zero hit count" on files outside the project (e.g. /usr/include/c++/15
and Qt headers), aborting lcov_prepare before coverage of src/ is produced.

The captures already pass "--ignore-errors unused"; add "inconsistent" the
same way to the capture, extract and combine steps. Only the consistency
check on data that is filtered out anyway (-e src/*) is bypassed; src/
coverage is unchanged.

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

10452 of 11274 relevant lines covered (92.71%)

402.92 hits per line

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

93.62
/src/util.cpp
1
// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3

4
#include "util.h"
5
#include "appsettings.h"
6
#include "executor.h"
7
#include <QCoreApplication>
8
#include <QDebug>
9
#include <QDir>
10
#include <QFile>
11
#include <QFileDevice>
12
#include <QFileInfo>
13
#include <QHash>
14
#include <QRegularExpression>
15
#include <QRegularExpressionMatchIterator>
16
#include <QStandardPaths>
17
#include <QTemporaryFile>
18
#include <QUrl>
19

20
#include <optional>
21

22
#ifdef Q_OS_WIN
23
#include <fcntl.h>
24
#include <io.h>
25
#include <windows.h>
26
#else
27
#include <cerrno>
28
#include <cstdio>
29
#include <fcntl.h>
30
#include <sys/stat.h>
31
#include <sys/time.h>
32
#include <unistd.h>
33
#endif
34

35
#include "qtpasslogging.h"
36

37
QProcessEnvironment Util::_env;
38
bool Util::_envInitialised = false;
39

40
// macOS and Windows: append the usual GPG install directories to PATH.
41
void Util::initialiseEnvironment() {
669 ✔
42
  if (!_envInitialised) {
669 ✔
43
    _env = QProcessEnvironment::systemEnvironment();
6 ✔
44
#ifdef __APPLE__
45
    QString path = _env.value("PATH");
46
    if (!path.contains("/usr/local/MacGPG2/bin") &&
47
        QDir("/usr/local/MacGPG2/bin").exists())
48
      path += ":/usr/local/MacGPG2/bin";
49
    if (!path.contains("/usr/local/bin"))
50
      path += ":/usr/local/bin";
51
    _env.insert("PATH", path);
52
#endif
53
#ifdef Q_OS_WIN
54
    QString path = _env.value("PATH");
55
    if (!path.contains("C:\\Program Files\\WinGPG\\x86") &&
56
        QDir("C:\\Program Files\\WinGPG\\x86").exists())
57
      path += ";C:\\Program Files\\WinGPG\\x86";
58
    if (!path.contains("C:\\Program Files\\GnuPG\\bin") &&
59
        QDir("C:\\Program Files\\GnuPG\\bin").exists())
60
      path += ";C:\\Program Files\\GnuPG\\bin";
61
    _env.insert("PATH", path);
62
#endif
63
    qCDebug(lcQtPass) << _env.value("PATH");
6 ✔
64
    _envInitialised = true;
6 ✔
65
  }
66
}
669 ✔
67

68
auto Util::findPasswordStore() -> QString {
267 ✔
69
  QString path;
267 ✔
70
  initialiseEnvironment();
267 ✔
71
  if (_env.contains("PASSWORD_STORE_DIR")) {
534 ✔
72
    path = Util::expandTilde(_env.value("PASSWORD_STORE_DIR"));
6 ✔
73
  } else {
74
#ifdef Q_OS_WIN
75
    path = QDir(QDir::homePath()).filePath("password-store");
76
#else
77
    path = QDir(QDir::homePath()).filePath(".password-store");
792 ✔
78
#endif
79
  }
80
  return Util::normalizeFolderPath(QDir::cleanPath(path));
534 ✔
81
}
82

83
auto Util::expandTilde(const QString &path) -> QString {
12 ✔
84
  if (path == QLatin1String("~")) {
12 ✔
85
    return QDir::homePath();
1 ✔
86
  }
87
  if (path.startsWith(QLatin1String("~/"))) {
11 ✔
88
    return QDir::homePath() + path.mid(1);
10 ✔
89
  }
90
  return path;
91
}
92

93
auto Util::normalizeFolderPath(const QString &path) -> QString {
387 ✔
94
  QString normalizedPath = path;
95
  if (!normalizedPath.endsWith('/')) {
387 ✔
96
    normalizedPath += '/';
372 ✔
97
  }
98
  return normalizedPath;
387 ✔
99
}
100

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

117
auto Util::passUmask(const QString &value) -> int {
11 ✔
118
  // Taken as it is, as bash's umask builtin (which pass hands it to) takes
119
  // it: " 022" is no umask there either. pass then keeps the session's;
120
  // QtPass falls back to 077.
121
  // anchoredPattern(), not ^...$: $ also matches before a final newline.
122
  static const QRegularExpression octal(
123
      QRegularExpression::anchoredPattern(QStringLiteral("[0-7]{1,4}")));
35 ✔
124
  if (!octal.match(value).hasMatch()) {
11 ✔
125
    return 077;
126
  }
127
  return value.toInt(nullptr, 8);
4 ✔
128
}
129

130
auto Util::gitCeiling(const QString &store) -> QString {
1,072 ✔
131
  if (store.isEmpty()) {
1,072 ✔
132
    return {};
×
133
  }
134
  QString path = QFileInfo(store).canonicalFilePath();
1,072 ✔
135
  if (path.isEmpty()) {
1,072 ✔
136
    path = QDir::cleanPath(QDir(store).absolutePath());
×
137
  }
138
  return QFileInfo(path).absolutePath();
1,072 ✔
139
}
140

141
auto Util::repositoryPassClimbsTo(const QString &store) -> QString {
40 ✔
142
#ifdef Q_OS_WIN
143
  Q_UNUSED(store);
144
  return {};
145
#else
146
  if (!store.contains(QLatin1Char(':'))) {
40 ✔
147
    return {};
10 ✔
148
  }
149
  // git walks up from the real folder, so the real path is the one to walk,
150
  // and for a store that does not exist yet the one it will have: its
151
  // nearest existing folder resolved, the rest appended. By the raw string:
152
  // QDir and QFileInfo clean a path by name, and "link/.." is the parent
153
  // of the link's target, not the folder the link is in. On macOS the
154
  // temporary folder is under /var, a link to /private/var.
155
  // Absolute as git means it, a leading "/" (Qt would take ":name" for a
156
  // resource path).
157
  QString path =
158
      store.startsWith(u'/') ? store : QDir::currentPath() + u'/' + store;
60 ✔
159
  while (path.size() > 1 && path.endsWith(u'/')) {
33 ✔
160
    path.chop(1);
3 ✔
161
  }
162
  QString rest;
30 ✔
163
  while (!QFileInfo::exists(path)) {
40 ✔
164
    const qsizetype slash = path.lastIndexOf(u'/');
10 ✔
165
    if (slash < 0) {
10 ✔
166
      return {};
×
167
    }
168
    const QString name = path.mid(slash + 1);
10 ✔
169
    rest = rest.isEmpty() ? name : name + u'/' + rest;
24 ✔
170
    path = slash == 0 ? QStringLiteral("/") : path.left(slash);
20 ✔
171
  }
172
  const QString real = QFileInfo(path).canonicalFilePath();
30 ✔
173
  QString start = real.isEmpty() ? QDir::cleanPath(path) : real;
30 ✔
174
  if (!rest.isEmpty()) {
30 ✔
175
    start = QDir::cleanPath(start + u'/' + rest);
8 ✔
176
  }
177
  // The pieces of pass's ceiling as git takes them (setup.c,
178
  // canonicalize_ceiling_entry): relative ones are dropped, the rest
179
  // resolved, one that cannot be resolved is dropped; after an empty piece
180
  // ("::") they are kept exactly as written. A piece can still be a real
181
  // ceiling: "/repo/:vault/.." holds "/repo/".
182
  QString ceiling;
30 ✔
183
  bool afterEmpty = false;
184
  for (const QString &piece :
185
       (store + QStringLiteral("/..")).split(QLatin1Char(':'))) {
123 ✔
186
    if (piece.isEmpty()) {
63 ✔
187
      afterEmpty = true;
188
      continue;
31 ✔
189
    }
190
    if (!piece.startsWith(u'/')) {
61 ✔
191
      continue;
29 ✔
192
    }
193
    const QString entry =
194
        afterEmpty ? piece : QFileInfo(piece).canonicalFilePath();
33 ✔
195
    // git stops below the longest entry the store lies under
196
    // (longest_ancestor_length: "/" is above everything).
197
    const QString under = entry == u'/' ? entry : entry + u'/';
32 ✔
198
    if (!entry.isEmpty() && start.startsWith(under) &&
7 ✔
199
        entry.size() > ceiling.size()) {
200
      ceiling = entry;
4 ✔
201
    }
202
  }
203
  // What git takes for a repository (setup.c, is_git_directory()): HEAD
204
  // naming a ref or an object, objects/ and refs/. An empty or broken .git
205
  // is passed by, as git passes it by.
206
  const auto isGitDirectory = [](const QString &candidate) {
81 ✔
207
    const QDir dir(candidate);
81 ✔
208
    if (!QFileInfo(dir.filePath(QStringLiteral("objects"))).isDir() ||
185 ✔
209
        !QFileInfo(dir.filePath(QStringLiteral("refs"))).isDir()) {
150 ✔
210
      return false;
211
    }
212
    QFile head(dir.filePath(QStringLiteral("HEAD")));
46 ✔
213
    if (!head.open(QIODevice::ReadOnly)) {
23 ✔
214
      return false;
215
    }
216
    static const QRegularExpression valid(
217
        QStringLiteral("^(?:ref: refs/|[0-9a-f]{40}\\s*$|[0-9a-f]{64}\\s*$)"));
27 ✔
218
    return valid.match(QString::fromUtf8(head.read(256))).hasMatch();
69 ✔
219
  };
81 ✔
220
  // At each folder, as git: a .git folder that is a repository, or a .git
221
  // file naming one ("gitdir: ..."), is the repository. Any other .git file
222
  // stops git with an error, and pass then commits nothing; a .git folder
223
  // that is no repository is passed by.
224
  enum class Found { Nothing, Repository, Refused };
225
  const auto repositoryAt = [&isGitDirectory](const QString &dir) {
80 ✔
226
    const QString dotGit = QDir(dir).filePath(QStringLiteral(".git"));
160 ✔
227
    const QFileInfo info(dotGit);
80 ✔
228
    if (info.isDir()) {
80 ✔
229
      return isGitDirectory(dotGit) ? Found::Repository : Found::Nothing;
21 ✔
230
    }
231
    if (!info.exists()) {
59 ✔
232
      return Found::Nothing;
233
    }
234
    QFile file(dotGit);
6 ✔
235
    if (!file.open(QIODevice::ReadOnly)) {
6 ✔
236
      return Found::Refused;
237
    }
238
    const QString line = QString::fromUtf8(file.readLine(4096)).trimmed();
6 ✔
239
    if (!line.startsWith(QLatin1String("gitdir: "))) {
6 ✔
240
      return Found::Refused;
241
    }
242
    const QString target = line.mid(8);
4 ✔
243
    return isGitDirectory(target.startsWith(u'/') ? target
8 ✔
244
                                                  : QDir(dir).filePath(target))
7 ✔
245
               ? Found::Repository
4 ✔
246
               : Found::Refused;
247
  };
110 ✔
248
  // The store's own repository comes first; only without one does git look
249
  // further up, and never into the ceiling. By name from here: the real
250
  // path holds no link or "..".
251
  for (QString dir = start;;) {
252
    switch (repositoryAt(dir)) {
80 ✔
253
    case Found::Repository:
254
      return dir == start ? QString() : dir;
48 ✔
255
    case Found::Refused:
3 ✔
256
      return {};
3 ✔
257
    case Found::Nothing:
258
      break;
259
    }
260
    // A bare repository: git stops there, and pass, finding no work tree,
261
    // commits nothing.
262
    if (isGitDirectory(dir)) {
56 ✔
263
      return {};
1 ✔
264
    }
265
    const QString up = QFileInfo(dir).absolutePath();
55 ✔
266
    if (up == dir || up == ceiling) {
55 ✔
267
      return {};
5 ✔
268
    }
269
    dir = up;
50 ✔
270
  }
271
#endif
272
}
273

274
namespace {
275
/// setGitOwnerForTests(): who owns "the user's own" store, when set.
276
std::optional<uint> s_gitOwnerForTests;
277
} // namespace
278

279
void Util::setGitOwnerForTests(std::optional<uint> user) {
4 ✔
280
  s_gitOwnerForTests = user;
4 ✔
281
}
4 ✔
282

283
#ifdef Q_OS_UNIX
284
namespace {
285
/**
286
 * @brief Whether git's `safe.directory` trusts the repository at @p root,
287
 * as git's ownership check would judge it in place of ownership.
288
 *
289
 * Read as git reads it: only from system, global and command-line
290
 * configuration (a repository cannot vouch for itself), in order. `*`
291
 * trusts every repository, an empty value forgets the entries before it,
292
 * a path ending in a slash and `*` trusts what lies below it, and any other
293
 * absolute path trusts that one folder, compared after resolving links.
294
 * Relative entries (including git's ".") and paths that do not exist trust
295
 * nothing.
296
 * @param root The store's canonical path.
297
 * @param git The git executable; "git" from PATH when empty.
298
 * @return True when an entry names @p root; false when none does or git
299
 *         cannot be asked.
300
 */
301
auto isSafeDirectory(const QString &root, const QString &git) -> bool {
23 ✔
302
  // Outside any repository, as git reads its protected config: no
303
  // repository's own config, and no includeIf "gitdir:" or "onbranch:"
304
  // that matches (a GIT_DIR, even one that cannot exist, would be matched
305
  // against them, and one that cannot exist makes git config fail). From
306
  // "/", which a user cannot make a repository; a local scope is dropped
307
  // below in any case.
308
  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
23 ✔
309
  env.remove(QStringLiteral("GIT_DIR"));
46 ✔
310
  env.remove(QStringLiteral("GIT_WORK_TREE"));
46 ✔
311
  env.remove(QStringLiteral("GIT_COMMON_DIR"));
46 ✔
312
  // git config alone reads GIT_CONFIG in place of the system and global
313
  // configuration (and reports it as "command"); the ownership check never
314
  // reads it.
315
  env.remove(QStringLiteral("GIT_CONFIG"));
46 ✔
316
  QProcess process;
23 ✔
317
  process.setProcessEnvironment(env);
23 ✔
318
  process.setWorkingDirectory(QStringLiteral("/"));
46 ✔
319
  // Bounded: Git calls wait for this, and a git that never answers trusts
320
  // nothing.
321
  constexpr int kQueryTimeoutMs = 5000;
322
  QString out;
23 ✔
323
  if (Executor::executeBlocking(
184 ✔
324
          process, git.isEmpty() ? QStringLiteral("git") : git,
46 ✔
325
          {QStringLiteral("config"), QStringLiteral("--show-scope"),
23 ✔
326
           QStringLiteral("--type=path"), QStringLiteral("--get-all"),
23 ✔
327
           QStringLiteral("safe.directory")},
23 ✔
328
          QString(), &out, nullptr, nullptr, kQueryTimeoutMs) != 0) {
46 ✔
329
    return false;
330
  }
331
  bool safe = false;
332
  const QStringList lines = out.split(QLatin1Char('\n'));
14 ✔
333
  for (const QString &line : lines) {
47 ✔
334
    const qsizetype tab = line.indexOf(QLatin1Char('\t'));
33 ✔
335
    if (tab < 0) {
33 ✔
336
      continue;
18 ✔
337
    }
338
    const QString scope = line.left(tab);
19 ✔
339
    if (scope != QLatin1String("system") && scope != QLatin1String("global") &&
19 ✔
340
        scope != QLatin1String("command")) {
1 ✔
341
      continue;
×
342
    }
343
    const QString value = line.mid(tab + 1);
19 ✔
344
    if (value.isEmpty()) {
19 ✔
345
      safe = false;
346
    } else if (value == QLatin1String("*")) {
17 ✔
347
      safe = true;
348
    } else if (!QDir::isAbsolutePath(value)) {
13 ✔
349
      continue;
3 ✔
350
    } else if (value.endsWith(QLatin1String("/*"))) {
10 ✔
351
      const QString base = value.chopped(2);
352
      QString prefix = QFileInfo(base.isEmpty() ? QStringLiteral("/") : base)
12 ✔
353
                           .canonicalFilePath();
3 ✔
354
      if (prefix.isEmpty()) {
3 ✔
355
        continue;
356
      }
357
      if (!prefix.endsWith(QLatin1Char('/'))) {
2 ✔
358
        prefix += QLatin1Char('/');
2 ✔
359
      }
360
      safe = safe || root.startsWith(prefix);
2 ✔
361
    } else {
362
      const QString named = QFileInfo(value).canonicalFilePath();
7 ✔
363
      safe = safe || (!named.isEmpty() && named == root);
7 ✔
364
    }
365
  }
366
  return safe;
367
}
23 ✔
368
} // namespace
369
#endif
370

371
auto Util::gitStoreVariables(const QString &store, const QString &git,
1,072 ✔
372
                             std::optional<uint> asUser)
373
    -> QList<std::pair<QString, QString>> {
374
  const QString ceiling = gitCeiling(store);
1,072 ✔
375
  if (ceiling.isEmpty()) {
1,072 ✔
376
    return {};
×
377
  }
378
  QList<std::pair<QString, QString>> vars{
379
      {QStringLiteral("GIT_CEILING_DIRECTORIES"), ceiling}};
3,216 ✔
380
#ifdef Q_OS_WIN
381
  const QChar separator = QLatin1Char(';');
382
#else
383
  const QChar separator = QLatin1Char(':');
384
#endif
385
  // git splits the ceiling list on the separator: "/home/a:b" would be
386
  // "/home/a" and "b", neither of them the parent, and git would climb.
387
  if (ceiling.contains(separator)) {
1,072 ✔
388
    QString root = QFileInfo(store).canonicalFilePath();
28 ✔
389
    if (root.isEmpty()) {
28 ✔
390
      root = QDir::cleanPath(QDir(store).absolutePath());
×
391
    }
392
    QString gitDir = QDir(root).filePath(QStringLiteral(".git"));
56 ✔
393
#ifdef Q_OS_UNIX
394
    // What discovery's ownership check would have looked at: the work tree,
395
    // the .git, and the directory a gitfile names. Not the user's: no
396
    // repository at all, under a path that cannot be created (its parent
397
    // is a device), rather than another user's hooks run as this one.
398
    const uint me = asUser.value_or(
399
        s_gitOwnerForTests.value_or(static_cast<uint>(::geteuid())));
28 ✔
400
    const auto ownedOrMissing = [me](const QString &path) {
33 ✔
401
      const QFileInfo info(path);
33 ✔
402
      return !info.exists() || info.ownerId() == me;
66 ✔
403
    };
33 ✔
404
    bool owned = ownedOrMissing(root) && ownedOrMissing(gitDir);
28 ✔
405
    if (owned && QFileInfo(gitDir).isFile()) {
28 ✔
406
      QFile gitFile(gitDir);
×
407
      if (gitFile.open(QIODevice::ReadOnly)) {
×
408
        const QString line =
409
            QString::fromUtf8(gitFile.readLine(4096)).trimmed();
×
410
        if (line.startsWith(QLatin1String("gitdir:"))) {
×
411
          const QString target = line.mid(7).trimmed();
×
412
          owned = ownedOrMissing(QDir(root).absoluteFilePath(target));
×
413
        }
414
      }
415
    }
×
416
    // Or trusted as git would trust it in place of ownership.
417
    if (!owned && !isSafeDirectory(root, git)) {
28 ✔
418
      gitDir = QStringLiteral("/dev/null/.git");
14 ✔
419
    }
420
#else
421
    // Git for Windows runs the same ownership check during discovery, on
422
    // SIDs, with its own rules for the Administrators group; this pin skips
423
    // it there and does not repeat it (a known gap, #2089).
424
    Q_UNUSED(git);
425
    Q_UNUSED(asUser);
426
#endif
427
    vars.append({QStringLiteral("GIT_DIR"), gitDir});
56 ✔
428
    vars.append({QStringLiteral("GIT_WORK_TREE"), root});
56 ✔
429
  }
430
  return vars;
431
}
1,072 ✔
432

433
auto Util::mkpathForStore(const QString &path) -> bool {
54 ✔
434
  const QString clean = QDir::cleanPath(QDir(path).absolutePath());
108 ✔
435
  if (QFileInfo(clean).isDir()) {
54 ✔
436
    return true;
437
  }
438
  const QString parent = QFileInfo(clean).absolutePath();
31 ✔
439
  if (parent != clean && !mkpathForStore(parent)) {
31 ✔
440
    return false;
441
  }
442
#ifdef Q_OS_UNIX
443
  // The store's umask, as git and gpg get it: a store shared with a group
444
  // (PASSWORD_STORE_UMASK=007) gets group folders, the default owner-only.
445
  const int umask = Executor::childUmask() >= 0 ? Executor::childUmask() : 077;
28 ✔
446
  QFile::Permissions permissions;
447
  const QFile::Permission bits[] = {
28 ✔
448
      QFile::ReadOwner, QFile::WriteOwner, QFile::ExeOwner,
449
      QFile::ReadGroup, QFile::WriteGroup, QFile::ExeGroup,
450
      QFile::ReadOther, QFile::WriteOther, QFile::ExeOther};
451
  for (int i = 0; i < 9; ++i) {
280 ✔
452
    if ((umask & (0400 >> i)) == 0) {
252 ✔
453
      permissions |= bits[i];
90 ✔
454
    }
455
  }
456
  // mkdir() still takes QtPass's own umask off (a session's 022 would drop
457
  // the group's write bit); set the mode exactly afterwards. That only ever
458
  // widens it to what was asked, never past.
459
  const bool made = QDir().mkdir(clean, permissions) &&
56 ✔
460
                    QFile::setPermissions(clean, permissions);
23 ✔
461
#else
462
  // Windows: permissions here would become an ACL of their own, replacing
463
  // the inherited one; the folder takes its parent's, as before.
464
  const bool made = QDir().mkdir(clean);
465
#endif
466
  return made || QFileInfo(clean).isDir();
28 ✔
467
}
468

469
auto Util::findBinaryInPath(const QString &binary) -> QString {
403 ✔
470
  if (binary.isEmpty()) {
403 ✔
471
    return {};
1 ✔
472
  }
473

474
  initialiseEnvironment();
402 ✔
475

476
  const QStringList dirs =
477
      _env.value(QStringLiteral("PATH"))
804 ✔
478
          .split(QDir::listSeparator(), Qt::SkipEmptyParts);
402 ✔
479
  QString ret;
402 ✔
480
  if (QDir::fromNativeSeparators(binary).contains(u'/')) {
402 ✔
481
    // An explicit path is not a PATH search: an absolute path is checked
482
    // as-is, a relative one is resolved against the PATH directories. The
483
    // directory-list overload refuses such names, so handle them here.
484
    if (QDir::isAbsolutePath(binary)) {
3 ✔
485
      ret = QStandardPaths::findExecutable(binary);
4 ✔
486
    } else if (!dirs.isEmpty()) {
1 ✔
487
      ret = QStandardPaths::findExecutable(binary, dirs);
2 ✔
488
    }
489
  } else {
490
    ret = findBinaryInPath(binary, dirs);
798 ✔
491
  }
492
#ifdef Q_OS_WIN
493
  if (ret.isEmpty()) {
494
    // Cache per-binary WSL lookup result — the wsl --version probe is a
495
    // blocking subprocess that can run several times per session for
496
    // missing binaries; once decided, the answer doesn't change at runtime.
497
    static QHash<QString, QString> wslBinaryCache;
498
    const bool hasWhitespace =
499
        std::any_of(binary.cbegin(), binary.cend(),
500
                    [](const QChar ch) { return ch.isSpace(); });
501
    if (!hasWhitespace) {
502
      auto cached = wslBinaryCache.constFind(binary);
503
      if (cached != wslBinaryCache.constEnd()) {
504
        ret = cached.value();
505
      } else {
506
        QString wslCommand = QStringLiteral("wsl ") + binary;
507
        qCDebug(lcQtPass)
508
            << "Util::findBinaryInPath(): falling back to WSL for binary"
509
            << binary;
510
        QString out, err;
511
        QString cachedResult;
512
        if (Executor::executeBlocking(wslCommand, {"--version"}, &out, &err) ==
513
                0 &&
514
            !out.isEmpty() && err.isEmpty()) {
515
          qCDebug(lcQtPass)
516
              << "Util::findBinaryInPath(): using WSL binary" << wslCommand;
517
          cachedResult = wslCommand;
518
        }
519
        wslBinaryCache.insert(binary, cachedResult);
520
        ret = cachedResult;
521
      }
522
    }
523
  }
524
#endif
525

526
  return ret;
527
}
528

529
// Bare names only: QStandardPaths::findExecutable() returns an absolute binary
530
// without consulting searchPaths, and a relative one with ".." could escape
531
// them.
532
auto Util::findBinaryInPath(const QString &binary,
413 ✔
533
                            const QStringList &searchPaths) -> QString {
534
  if (binary.isEmpty() || QDir::fromNativeSeparators(binary).contains(u'/')) {
825 ✔
535
    return {};
4 ✔
536
  }
537
  QStringList dirs;
409 ✔
538
  dirs.reserve(searchPaths.size());
409 ✔
539
  for (const QString &dir : searchPaths) {
6,042 ✔
540
    if (!dir.isEmpty()) {
5,633 ✔
541
      dirs.append(dir);
542
    }
543
  }
544
  if (dirs.isEmpty()) {
409 ✔
545
    // QStandardPaths::findExecutable() treats an empty list as "use PATH".
546
    return {};
4 ✔
547
  }
548
  return QStandardPaths::findExecutable(binary, dirs);
405 ✔
549
}
550

551
auto Util::configIsValid(const AppSettings &s) -> bool {
210 ✔
552
  const QString configFilePath = QDir(s.passStore).filePath(".gpg-id");
420 ✔
553
  if (!QFile(configFilePath).exists()) {
210 ✔
554
    return false;
555
  }
556

557
  const QString executable = s.usePass ? s.passExecutable : s.gpgExecutable;
135 ✔
558

559
  if (const auto wsl = Executor::parseWslCommand(executable)) {
135 ✔
560
    // Probe WSL once per session — availability doesn't change at runtime
561
    // and the executeBlocking call is a blocking subprocess.
562
    static const bool wslAvailable = [&wsl]() {
1 ✔
563
      QString out;
1 ✔
564
      QString err;
1 ✔
565
      return Executor::executeBlocking(wsl->launcher,
3 ✔
566
                                       {QStringLiteral("--version")}, &out,
1 ✔
567
                                       &err) == 0 &&
×
568
             !out.isEmpty() && err.isEmpty();
2 ✔
569
    }();
1 ✔
570
    if (wslAvailable) {
1 ✔
571
      return true;
572
    }
573
  }
574
  return QFile(executable).exists();
135 ✔
575
}
576

577
auto Util::endsWithGpg() -> const QRegularExpression & {
7,179 ✔
578
  static const QRegularExpression expr{R"(\.gpg$)"};
7,186 ✔
579
  return expr;
7,179 ✔
580
}
581

582
// Stops at whitespace, quotes and brackets so a URL on its own line keeps no
583
// line break. file:/// is excluded on purpose (local, not network); the test
584
// relies on that.
585
auto Util::protocolRegex() -> const QRegularExpression & {
161 ✔
586
  static const QRegularExpression regex{
587
      R"(((?:https?|ftp|ssh|sftp|ftps|webdav|webdavs)://[^"\s<>\)\]\[]+))"};
166 ✔
588
  return regex;
161 ✔
589
}
590

591
auto Util::isLaunchableWebUrl(const QString &value) -> bool {
108 ✔
592
  const QString trimmed = value.trimmed();
593
  if (trimmed.isEmpty()) {
108 ✔
594
    return false;
595
  }
596
  // Reject control characters first, before QUrl normalisation can hide a
597
  // CR/LF/NUL injection into the OS URL handler.
598
  for (const QChar &c : trimmed) {
2,346 ✔
599
    if (c == QLatin1Char('\r') || c == QLatin1Char('\n') ||
600
        c == QChar(QChar::Null)) {
601
      return false;
602
    }
603
  }
604
  const QUrl url(trimmed, QUrl::StrictMode);
104 ✔
605
  if (!url.isValid()) {
104 ✔
606
    return false;
607
  }
608
  const QString scheme = url.scheme().toLower();
91 ✔
609
  if (scheme != QLatin1String("http") && scheme != QLatin1String("https")) {
91 ✔
610
    return false;
34 ✔
611
  }
612
  if (url.host().isEmpty()) {
114 ✔
613
    return false;
614
  }
615
  // Embedded userinfo (user:pass@host) would leak into browser history.
616
  if (!url.userName().isEmpty() || !url.password().isEmpty()) {
107 ✔
617
    return false;
618
  }
619
  return true;
620
}
104 ✔
621

622
auto Util::linkifyUrls(const QString &text, bool *linked) -> QString {
157 ✔
623
  if (linked != nullptr) {
157 ✔
624
    *linked = false;
110 ✔
625
  }
626
  QString html;
157 ✔
627
  html.reserve(text.size());
157 ✔
628
  qsizetype lastIndex = 0;
629
  QRegularExpressionMatchIterator it = protocolRegex().globalMatch(text);
157 ✔
630
  while (it.hasNext()) {
198 ✔
631
    const QRegularExpressionMatch match = it.next();
41 ✔
632
    const QString url = match.captured(0);
41 ✔
633
    if (!isLaunchableWebUrl(url)) {
41 ✔
634
      // Not a web URL (or it carries credentials): leave it in the escaped
635
      // plain-text run instead of making it clickable.
636
      continue;
637
    }
638
    const qsizetype start = match.capturedStart(0);
28 ✔
639
    html += text.mid(lastIndex, start - lastIndex).toHtmlEscaped();
28 ✔
640
    const QString escapedUrl = url.toHtmlEscaped();
28 ✔
641
    html += QStringLiteral("<a href=\"%1\">%1</a>").arg(escapedUrl);
56 ✔
642
    lastIndex = match.capturedEnd(0);
28 ✔
643
    if (linked != nullptr) {
28 ✔
644
      *linked = true;
22 ✔
645
    }
646
  }
41 ✔
647
  html += text.mid(lastIndex).toHtmlEscaped();
157 ✔
648
  return html;
157 ✔
649
}
157 ✔
650

651
auto Util::newLinesRegex() -> const QRegularExpression & {
254 ✔
652
  static const QRegularExpression regex{"[\r\n]"};
263 ✔
653
  return regex;
254 ✔
654
}
655

656
// No content heuristics: a line rejected here is erased the next time .gpg-id
657
// is rewritten. A leading `-` is refused because the recipients also go
658
// positionally to `gpg --list-keys`, where it would parse as an option.
659
auto Util::isValidKeyId(const QString &keyId) -> bool {
189 ✔
660
  return !keyId.isEmpty() && !keyId.startsWith('-');
189 ✔
661
}
662

663
namespace {
664
/**
665
 * @brief Walk @p dir's real, visible directories in sorted pre-order and hand
666
 * every entry to @p visit before any recursion; a directory is entered only
667
 * when @p visit returns true for it.
668
 */
669
template <typename Visit> void walkStore(const QString &dir, Visit visit) {
206 ✔
670
  // Absolute, so the results are whatever the caller's cwd; not canonical,
671
  // so a linked root keeps the name it was configured under.
672
  QStringList pending{QDir(QDir::cleanPath(dir)).absolutePath()};
618 ✔
673
  while (!pending.isEmpty()) {
748 ✔
674
    const QDir current(pending.takeLast());
271 ✔
675
    // Every entry once, links and hidden entries included, so the decision
676
    // what to do with each is taken here, before any recursion. QDir::System
677
    // keeps dangling links in the listing.
678
    const QFileInfoList entries =
271 ✔
679
        current.entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
680
                                  QDir::System | QDir::NoDotAndDotDot,
681
                              QDir::Name);
682
    QStringList subdirs;
271 ✔
683
    for (const QFileInfo &entry : entries) {
1,502 ✔
684
      if (visit(entry)) {
1,231 ✔
685
        subdirs << entry.filePath();
130 ✔
686
      }
687
    }
688
    // Pushed last-to-first so the next one taken is the first by name.
689
    for (auto it = subdirs.crbegin(); it != subdirs.crend(); ++it) {
336 ✔
690
      pending << *it;
691
    }
692
  }
693
}
412 ✔
694

695
/// A symlink or an NTFS junction: never entered, never listed.
696
auto isLink(const QFileInfo &entry) -> bool {
3,308 ✔
697
  return entry.isSymLink() || entry.isJunction();
3,308 ✔
698
}
699

700
/// Hidden by attribute, or by the dot convention on every platform: Qt 6.11
701
/// on macOS answers isHidden() from the UF_HIDDEN flag alone once an entry
702
/// was lstat()ed (qfilesystemengine_unix.cpp marks the attribute known there
703
/// without the dot check), and Windows does not consider .stversions hidden
704
/// at all.
705
auto isHiddenEntry(const QFileInfo &entry) -> bool {
623 ✔
706
  return entry.isHidden() || entry.fileName().startsWith(QLatin1Char('.'));
1,231 ✔
707
}
708

709
/// A real directory that is part of the store: .git, .stversions,
710
/// .Trash-1000 are not, as with QDirIterator without QDir::Hidden.
711
auto isStoreDirectory(const QFileInfo &entry) -> bool {
1,231 ✔
712
  return !isLink(entry) && entry.isDir() && !isHiddenEntry(entry);
1,231 ✔
713
}
714
} // namespace
715

716
auto Util::regularFilesUnder(const QString &dir, const QStringList &nameFilters,
203 ✔
717
                             QStringList *skipped, bool hiddenFiles)
718
    -> QStringList {
719
  QStringList files;
203 ✔
720
  walkStore(dir, [&](const QFileInfo &entry) {
203 ✔
721
    if (isStoreDirectory(entry)) {
1,176 ✔
722
      return true;
723
    }
724
    const bool named = QDir::match(nameFilters, entry.fileName());
1,129 ✔
725
    if (isLink(entry) || (!entry.isDir() && !entry.isFile())) {
1,129 ✔
726
      // A linked directory hides everything behind it; a linked file, or a
727
      // FIFO, socket or device, is only of interest under a name the caller
728
      // asked for.
729
      if (skipped != nullptr && (entry.isDir() || named)) {
25 ✔
730
        qCWarning(lcQtPass) << "Skipping" << entry.filePath()
24 ✔
731
                            << ": not a regular file or directory";
12 ✔
732
        *skipped << entry.filePath();
24 ✔
733
      }
734
      return false;
25 ✔
735
    }
736
    if (entry.isFile() && named && (hiddenFiles || !isHiddenEntry(entry))) {
1,104 ✔
737
      files << entry.filePath();
1,126 ✔
738
    }
739
    return false;
740
  });
741
  return files;
203 ✔
742
}
743

744
auto Util::directoriesUnder(const QString &dir) -> QStringList {
3 ✔
745
  QStringList dirs;
3 ✔
746
  walkStore(dir, [&](const QFileInfo &entry) {
3 ✔
747
    if (!isStoreDirectory(entry)) {
55 ✔
748
      return false;
749
    }
750
    dirs << entry.filePath();
18 ✔
751
    return true;
18 ✔
752
  });
753
  return dirs;
3 ✔
754
}
755

756
auto Util::isLinkedFolder(const QString &path) -> bool {
911 ✔
757
  return isLink(QFileInfo(QDir::cleanPath(path)));
1,822 ✔
758
}
759

760
auto Util::isUnderLink(const QString &path, const QString &storeRoot,
607 ✔
761
                       bool includeSelf) -> bool {
762
  // "C:/Store" and "c:/store" are one directory on Windows; a path spelled
763
  // the other way must not skip the walk (as in Pass::getGpgIdPath).
764
#ifdef Q_OS_WIN
765
  constexpr auto cs = Qt::CaseInsensitive;
766
#else
767
  constexpr auto cs = Qt::CaseSensitive;
768
#endif
769
  const QString root = QDir::cleanPath(storeRoot);
607 ✔
770
  // A root of "/" or "C:/" already ends in the separator.
771
  const QString prefix =
772
      root.endsWith(QLatin1Char('/')) ? root : root + QLatin1Char('/');
607 ✔
773
  const auto isRoot = [&](const QString &p) {
774
    return p.compare(root, cs) == 0;
1,047 ✔
775
  };
776
  QString current = QDir::cleanPath(path);
607 ✔
777
  if (!current.startsWith(prefix, cs)) {
607 ✔
778
    // Not under the store as named: only the entry itself can be judged.
779
    return includeSelf && !isRoot(current) && isLinkedFolder(current);
402 ✔
780
  }
781
  if (!includeSelf) {
406 ✔
782
    current = QFileInfo(current).path();
56 ✔
783
  }
784
  for (; !isRoot(current) && current.startsWith(prefix, cs);
846 ✔
785
       current = QFileInfo(current).path()) {
880 ✔
786
    if (isLinkedFolder(current)) {
477 ✔
787
      return true;
788
    }
789
  }
790
  return false;
791
}
792

793
#ifndef Q_OS_WIN
794
namespace {
795

796
/// The filesystem cannot make hard links at all (FAT/exFAT refuse with
797
/// EPERM, some FUSE filesystems with ENOTSUP or ENOSYS).
798
auto hasNoHardLinks(int error) -> bool {
799
  return error == EPERM || error == ENOTSUP || error == EOPNOTSUPP ||
2 ✔
800
         error == ENOSYS;
801
}
802

803
/// rename() that fails with EEXIST instead of replacing, where the platform
804
/// has one; nothing when neither the platform nor the filesystem does.
805
auto renameExclusive(const QByteArray &source, const QByteArray &target)
8 ✔
806
    -> std::optional<bool> {
807
#if defined(__GLIBC__) &&                                                      \
808
    (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 28))
809
  if (::renameat2(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(),
8 ✔
810
                  RENAME_NOREPLACE) == 0) {
811
    return true;
2 ✔
812
  }
813
  if (errno == EINVAL || errno == ENOSYS || hasNoHardLinks(errno)) {
6 ✔
814
    return std::nullopt;
4 ✔
815
  }
816
  return false;
2 ✔
817
#elif defined(Q_OS_MACOS)
818
  if (::renamex_np(source.constData(), target.constData(), RENAME_EXCL) == 0) {
819
    return true;
820
  }
821
  if (errno == EINVAL || errno == ENOTSUP) {
822
    return std::nullopt;
823
  }
824
  return false;
825
#else
826
  Q_UNUSED(source);
827
  Q_UNUSED(target);
828
  return std::nullopt;
829
#endif
830
}
831

832
/**
833
 * @brief Gives @p source the name @p target unless something already has it.
834
 *
835
 * A hard link is the one way every POSIX system can do that in one step:
836
 * linkat() fails with EEXIST rather than replacing. Where the filesystem has
837
 * no hard links, an exclusive rename does it; where that is missing too, the
838
 * name is checked and then renamed, which leaves a short window for another
839
 * writer to create it in between.
840
 */
841
auto placeWithoutReplacing(const QByteArray &source, const QByteArray &target)
87 ✔
842
    -> bool {
843
  // linkat() without AT_SYMLINK_FOLLOW follows nothing; link() would, on
844
  // macOS and the BSDs, hard-link whatever a symlink planted under the
845
  // source's name points at.
846
  if (::linkat(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(), 0) ==
87 ✔
847
      0) {
848
    ::unlink(source.constData());
72 ✔
849
    return true;
72 ✔
850
  }
851
  if (!hasNoHardLinks(errno)) {
15 ✔
852
    return false;
853
  }
854
  if (const std::optional<bool> renamed = renameExclusive(source, target)) {
8 ✔
855
    return *renamed;
4 ✔
856
  }
857
  struct stat st{};
4 ✔
858
  if (::lstat(target.constData(), &st) == 0 || errno != ENOENT) {
4 ✔
859
    errno = EEXIST;
2 ✔
860
    return false;
2 ✔
861
  }
862
  return ::rename(source.constData(), target.constData()) == 0;
2 ✔
863
}
864

865
} // namespace
866
#endif
867

868
auto Util::replaceFile(const QString &from, const QString &to, bool replace)
226 ✔
869
    -> bool {
870
#ifdef Q_OS_WIN
871
  const std::wstring source =
872
      QDir::toNativeSeparators(QFileInfo(from).absoluteFilePath())
873
          .toStdWString();
874
  const std::wstring target =
875
      QDir::toNativeSeparators(QFileInfo(to).absoluteFilePath()).toStdWString();
876
  // WRITE_THROUGH: the new entry is on the device when this returns.
877
  return MoveFileExW(source.c_str(), target.c_str(),
878
                     (replace ? MOVEFILE_REPLACE_EXISTING : 0) |
879
                         MOVEFILE_WRITE_THROUGH) != 0;
880
#else
881
  const QByteArray source = QFile::encodeName(from);
882
  const QByteArray target = QFile::encodeName(to);
883
  if (replace) {
226 ✔
884
    if (::rename(source.constData(), target.constData()) != 0) {
139 ✔
885
      return false;
886
    }
887
  } else {
888
    if (!placeWithoutReplacing(source, target)) {
87 ✔
889
      return false;
890
    }
891
  }
892
  // Sync the directory entry so a crash does not lose the new name. Best
893
  // effort: the bytes are already synced, and some network filesystems
894
  // cannot sync a directory.
895
  const int dir = ::open(QFile::encodeName(QFileInfo(to).path()).constData(),
426 ✔
896
                         O_RDONLY | O_DIRECTORY | O_CLOEXEC);
897
  if (dir >= 0) {
213 ✔
898
    int rc;
899
    do {
900
      rc = ::fsync(dir);
213 ✔
901
    } while (rc != 0 && errno == EINTR);
213 ✔
902
    ::close(dir);
213 ✔
903
  }
904
  return true;
905
#endif
906
}
907

908
auto Util::openRegularFile(const QString &path, QFile &file) -> bool {
747 ✔
909
#ifdef Q_OS_WIN
910
  // FILE_FLAG_OPEN_REPARSE_POINT opens a symbolic link or junction itself
911
  // rather than its target, so the handle's attributes say what the name
912
  // was at the moment of the open.
913
  const std::wstring native =
914
      QDir::toNativeSeparators(QFileInfo(path).absoluteFilePath())
915
          .toStdWString();
916
  HANDLE handle = CreateFileW(
917
      native.c_str(), GENERIC_READ,
918
      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
919
      OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
920
  if (handle == INVALID_HANDLE_VALUE) {
921
    return false;
922
  }
923
  BY_HANDLE_FILE_INFORMATION info{};
924
  if (!GetFileInformationByHandle(handle, &info) ||
925
      (info.dwFileAttributes &
926
       (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY |
927
        FILE_ATTRIBUTE_DEVICE)) != 0 ||
928
      GetFileType(handle) != FILE_TYPE_DISK) {
929
    CloseHandle(handle);
930
    return false;
931
  }
932
  const int fd = _open_osfhandle(reinterpret_cast<intptr_t>(handle),
933
                                 _O_RDONLY | _O_BINARY);
934
  if (fd < 0) {
935
    CloseHandle(handle);
936
    return false;
937
  }
938
  if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
939
    _close(fd);
940
    return false;
941
  }
942
  return true;
943
#else
944
  // O_NOFOLLOW fails with ELOOP on a symbolic link; O_NONBLOCK keeps a FIFO
945
  // from blocking the open until fstat() can refuse it.
946
  const int fd = ::open(QFile::encodeName(path).constData(),
747 ✔
947
                        O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
948
  if (fd < 0) {
747 ✔
949
    return false;
950
  }
951
  struct stat st{};
696 ✔
952
  if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
696 ✔
953
    ::close(fd);
7 ✔
954
    return false;
7 ✔
955
  }
956
  // The descriptor, not the name, is what QFile opens here: the object
957
  // fstat() judged is the object read. CodeQL's check-then-use pattern
958
  // matcher sees an open after a check and cannot tell.
959
  if (!file.open(fd, QIODevice::ReadOnly, // codeql[cpp/toctou-race-condition]
689 ✔
960
                 QFileDevice::AutoCloseHandle)) {
961
    ::close(fd);
×
962
    return false;
×
963
  }
964
  return true;
965
#endif
966
}
967

968
auto Util::readRegularFile(const QString &path, qint64 maxBytes)
235 ✔
969
    -> std::optional<QByteArray> {
970
  QFile file;
235 ✔
971
  if (!openRegularFile(path, file)) {
235 ✔
972
    return std::nullopt;
11 ✔
973
  }
974
  // A regular file's size is reliable, also when sparse: refuse a large one
975
  // before reading anything. One byte past the limit still guards a file
976
  // that grows meanwhile.
977
  if (file.size() > maxBytes) {
224 ✔
978
    return std::nullopt;
3 ✔
979
  }
980
  QByteArray bytes = file.read(maxBytes + 1);
221 ✔
981
  if (bytes.size() > maxBytes || file.error() != QFileDevice::NoError) {
221 ✔
982
    return std::nullopt;
×
983
  }
984
  return bytes;
985
}
235 ✔
986

987
auto Util::syncToDisk(QFileDevice &file) -> bool {
215 ✔
988
  if (!file.flush()) {
215 ✔
989
    return false;
990
  }
991
#ifdef Q_OS_WIN
992
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
993
  return handle != INVALID_HANDLE_VALUE && FlushFileBuffers(handle) != 0;
994
#else
995
  return ::fsync(file.handle()) == 0;
215 ✔
996
#endif
997
}
998

999
namespace {
1000

1001
/**
1002
 * @brief What tells one file object from another on its filesystem: device
1003
 * and inode on POSIX, volume serial and file index on Windows.
1004
 */
1005
struct FileIdentity {
1006
  quint64 volume = 0;
1007
  quint64 index = 0;
1008
  bool known = false;
1009
};
1010

1011
auto operator==(const FileIdentity &a, const FileIdentity &b) -> bool {
204 ✔
1012
  return a.known && b.known && a.volume == b.volume && a.index == b.index;
204 ✔
1013
}
1014

1015
/// The identity of the object @p file is open on, or an unknown one.
1016
auto identityOf(const QFileDevice &file) -> FileIdentity {
419 ✔
1017
#ifdef Q_OS_WIN
1018
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1019
  BY_HANDLE_FILE_INFORMATION info;
1020
  if (handle == INVALID_HANDLE_VALUE ||
1021
      GetFileInformationByHandle(handle, &info) == 0) {
1022
    return {};
1023
  }
1024
  // On FAT/exFAT the file ID is the directory entry's offset, which a rename
1025
  // can move. They have no hard links either (the swap this catches needs
1026
  // one), so the identity is left unknown there.
1027
  DWORD flags = 0;
1028
  if (GetVolumeInformationByHandleW(handle, nullptr, 0, nullptr, nullptr,
1029
                                    &flags, nullptr, 0) == 0 ||
1030
      (flags & FILE_SUPPORTS_HARD_LINKS) == 0) {
1031
    return {};
1032
  }
1033
  return {info.dwVolumeSerialNumber,
1034
          (static_cast<quint64>(info.nFileIndexHigh) << 32) |
1035
              info.nFileIndexLow,
1036
          true};
1037
#else
1038
  struct stat st{};
419 ✔
1039
  if (::fstat(file.handle(), &st) != 0) {
419 ✔
1040
    return {};
×
1041
  }
1042
  return {static_cast<quint64>(st.st_dev), static_cast<quint64>(st.st_ino),
419 ✔
1043
          true};
419 ✔
1044
#endif
1045
}
1046

1047
/// Put @p text in @p error when there is one; false, for `return fail(...)`.
1048
auto fail(QString *error, const QString &text) -> bool {
1049
  if (error != nullptr) {
21 ✔
1050
    *error = text;
21 ✔
1051
  }
1052
  return false;
1053
}
1054

1055
/// A filled, synced temporary next to its destination.
1056
struct Staged {
653 ✔
1057
  QString path;
1058
  FileIdentity identity;
1059
};
1060

1061
/**
1062
 * @brief Create the temporary next to @p path (opaque name, exclusive,
1063
 * owner-only), fill it through its handle and sync it. The QTemporaryFile
1064
 * goes out of scope before the caller renames: it keeps its handle open for
1065
 * as long as it lives, and Windows does not rename an open file.
1066
 */
1067
auto stageNextTo(const QString &path, const Util::Filler &fill, QString *why)
223 ✔
1068
    -> std::optional<Staged> {
1069
  Staged staged;
223 ✔
1070
  {
1071
    QTemporaryFile file(QFileInfo(path).path() +
446 ✔
1072
                        QStringLiteral("/.qtpass-XXXXXX.tmp"));
446 ✔
1073
    file.setAutoRemove(false);
223 ✔
1074
    if (!file.open()) {
223 ✔
1075
      *why = QCoreApplication::translate(
8 ✔
1076
                 "Util", "Cannot create a temporary file next to %1: %2")
1077
                 .arg(path, file.errorString());
16 ✔
1078
      return std::nullopt;
8 ✔
1079
    }
1080
    staged.path = file.fileName();
215 ✔
1081
    // Owner-only: a .gpg-id names the keys a store is encrypted to, an
1082
    // entry is an entry. QTemporaryFile creates 0600 already; say so for
1083
    // platforms where it may not.
1084
    file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
215 ✔
1085
    *why = fill(file);
430 ✔
1086
    if (why->isEmpty() && !Util::syncToDisk(file)) {
215 ✔
1087
      *why = QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1088
                 .arg(path, file.errorString());
×
1089
    }
1090
    staged.identity = identityOf(file);
215 ✔
1091
  }
223 ✔
1092
  if (!why->isEmpty()) {
215 ✔
1093
    QFile::remove(staged.path);
×
1094
    return std::nullopt;
×
1095
  }
1096
  return staged;
1097
}
1098

1099
/// Why replaceFile() could not put the temporary under @p path.
1100
auto placementError(const QString &path, bool replace) -> QString {
9 ✔
1101
  if (replace) {
9 ✔
1102
    return QCoreApplication::translate("Util", "Failed to replace %1.")
4 ✔
1103
        .arg(path);
2 ✔
1104
  }
1105
  const QFileInfo taken(path);
7 ✔
1106
  return taken.exists() || taken.isSymLink()
8 ✔
1107
             ? QCoreApplication::translate("Util", "%1 already exists.")
7 ✔
1108
                   .arg(path)
1109
             : QCoreApplication::translate("Util", "Failed to write %1.")
1 ✔
1110
                   .arg(path);
8 ✔
1111
}
7 ✔
1112

1113
/**
1114
 * @brief Whether what is under @p path is the file that was filled: not a
1115
 * link, and not another file (a hard link to something of the user's, say)
1116
 * swapped in under the temporary's name. Opened without following, compared
1117
 * by identity; only two known identities can prove a swap, otherwise every
1118
 * write on such a store would be reported as tampering.
1119
 */
1120
auto isTheFileWritten(const QString &path, const FileIdentity &written)
206 ✔
1121
    -> bool {
1122
  QFile placed;
206 ✔
1123
  if (!Util::openRegularFile(path, placed)) {
206 ✔
1124
    return false;
1125
  }
1126
  const FileIdentity there = identityOf(placed);
204 ✔
1127
  if (!written.known || !there.known) {
204 ✔
1128
    qCWarning(lcQtPass) << "Cannot tell whether" << path
×
1129
                        << "is the file that was written here";
×
1130
    return true;
×
1131
  }
1132
  return there == written;
204 ✔
1133
}
206 ✔
1134

1135
} // namespace
1136

1137
auto Util::stageFileReplacing(const QString &path, bool replace,
223 ✔
1138
                              const Filler &fill, QString *error) -> bool {
1139
  QString why;
223 ✔
1140
  const std::optional<Staged> staged = stageNextTo(path, fill, &why);
223 ✔
1141
  if (!staged) {
223 ✔
1142
    return fail(error, why);
1143
  }
1144
  if (!replaceFile(staged->path, path, replace)) {
215 ✔
1145
    QFile::remove(staged->path);
9 ✔
1146
    return fail(error, placementError(path, replace));
18 ✔
1147
  }
1148
  // A mismatch is reported and left: removing by name could take another
1149
  // writer's file.
1150
  if (!isTheFileWritten(path, staged->identity)) {
206 ✔
1151
    return fail(
1152
        error,
1153
        QCoreApplication::translate(
4 ✔
1154
            "Util", "%1 was swapped for another file while it was written.")
1155
            .arg(path));
8 ✔
1156
  }
1157
  return true;
1158
}
1159

1160
auto Util::writeFileReplacing(const QString &path, const QByteArray &bytes,
106 ✔
1161
                              bool replace, QString *error) -> bool {
1162
  return stageFileReplacing(
106 ✔
1163
      path, replace,
1164
      [&path, &bytes](QFileDevice &staged) -> QString {
210 ✔
1165
        if (staged.write(bytes) != bytes.size()) {
104 ✔
1166
          return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1167
              .arg(path, staged.errorString());
×
1168
        }
1169
        return {};
104 ✔
1170
      },
1171
      error);
106 ✔
1172
}
1173

1174
auto Util::copyFileReplacing(const QString &src, const QString &dst,
116 ✔
1175
                             bool replace, QString *error) -> bool {
1176
  QFile in;
116 ✔
1177
  if (!openRegularFile(src, in)) {
116 ✔
1178
    if (error)
4 ✔
1179
      *error = QCoreApplication::translate("Util", "Cannot read %1.").arg(src);
8 ✔
1180
    return false;
4 ✔
1181
  }
1182
  return stageFileReplacing(
112 ✔
1183
      dst, replace,
1184
      [&src, &dst, &in](QFileDevice &staged) -> QString {
330 ✔
1185
        char buf[64 * 1024];
1186
        for (;;) {
1187
          const qint64 n = in.read(buf, sizeof buf);
224 ✔
1188
          if (n < 0) {
224 ✔
1189
            return QCoreApplication::translate("Util", "Cannot read %1: %2")
×
1190
                .arg(src, in.errorString());
×
1191
          }
1192
          if (n == 0) {
224 ✔
1193
            return {};
106 ✔
1194
          }
1195
          if (staged.write(buf, n) != n) {
118 ✔
1196
            return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1197
                .arg(dst, staged.errorString());
×
1198
          }
1199
        }
1200
      },
1201
      error);
1202
}
116 ✔
1203

1204
namespace {
1205

1206
/// Remove one directory entry that is not a real directory: a link goes as
1207
/// the entry itself, never its target (a junction or a directory symlink on
1208
/// Windows is a directory entry and goes with rmdir); a read-only file gets
1209
/// write access and one more try, as QDir::removeRecursively() does.
1210
auto removeEntry(const QFileInfo &entry) -> bool {
11 ✔
1211
  const QString path = entry.filePath();
11 ✔
1212
  if (isLink(entry)) {
11 ✔
1213
    if (QFile::remove(path) || QDir().rmdir(path)) {
6 ✔
1214
      return true;
1215
    }
1216
    qCWarning(lcQtPass) << "Could not remove link" << path;
2 ✔
1217
    return false;
1 ✔
1218
  }
1219
  if (QFile::remove(path)) {
6 ✔
1220
    return true;
1221
  }
1222
  const QFile::Permissions perms = QFile::permissions(path);
1 ✔
1223
  if (!perms.testFlag(QFile::WriteUser) &&
1 ✔
1224
      QFile::setPermissions(path, perms | QFile::WriteUser) &&
2 ✔
1225
      QFile::remove(path)) {
1 ✔
1226
    return true;
1227
  }
1228
  qCWarning(lcQtPass) << "Could not remove" << path;
2 ✔
1229
  return false;
1 ✔
1230
}
1231

1232
} // namespace
1233

1234
auto Util::removeTree(const QString &dir) -> bool {
21 ✔
1235
  // A trailing separator makes lstat follow a link ("link/" is the target
1236
  // directory); the link itself is what this is about.
1237
  const QString path = QDir::cleanPath(dir);
21 ✔
1238
  const QFileInfo top(path);
21 ✔
1239
  if (isLink(top)) {
21 ✔
1240
    // rm -rf on a link removes the link.
1241
    return QFile::remove(path) || QDir().rmdir(path);
16 ✔
1242
  }
1243
  if (!top.isDir()) {
7 ✔
1244
    return false;
1245
  }
1246
  bool ok = true;
1247
  const QFileInfoList entries =
1248
      QDir(path).entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
12 ✔
1249
                                   QDir::System | QDir::NoDotAndDotDot,
1250
                               QDir::Name);
6 ✔
1251
  for (const QFileInfo &entry : entries) {
18 ✔
1252
    const bool removed = entry.isDir() && !isLink(entry)
17 ✔
1253
                             ? removeTree(entry.filePath())
13 ✔
1254
                             : removeEntry(entry);
11 ✔
1255
    ok = removed && ok;
12 ✔
1256
  }
1257
  return ok && QDir().rmdir(path);
11 ✔
1258
}
21 ✔
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