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

IJHack / QtPass / 44216600721

18 Nov 2026 01:32AM UTC coverage: 96.372% (-0.02%) from 96.396%
44216600721

Pull #2260

github

web-flow
Merge f2d1e2f22 into 251d7300f
Pull Request #2260: Git commits take only their own paths; tool output stays plain and short

63 of 76 new or added lines in 8 files covered. (82.89%)

28 existing lines in 2 files now uncovered.

9085 of 9427 relevant lines covered (96.37%)

827.66 hits per line

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

94.22
/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

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

44
#include "qtpasslogging.h"
45

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

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

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

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

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

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

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

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

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

287
namespace {
288
/// setGitOwnerForTests(): who owns "the user's own" store, when set.
289
std::optional<uint> s_gitOwnerForTests;
290
} // namespace
291

292
void Util::setGitOwnerForTests(std::optional<uint> user) {
4 ✔
293
  s_gitOwnerForTests = user;
4 ✔
294
}
4 ✔
295

296
/// setBeforePlacingForTests(): called between staging and the rename.
297
std::function<void(const QString &)> s_beforePlacingForTests;
298

299
void Util::setBeforePlacingForTests(std::function<void(const QString &)> hook) {
3 ✔
300
  s_beforePlacingForTests = std::move(hook);
3 ✔
301
}
3 ✔
302

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

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

453
auto Util::mkpathForStore(const QString &path) -> bool {
52 ✔
454
  const QString clean = QDir::cleanPath(QDir(path).absolutePath());
104 ✔
455
  if (QFileInfo(clean).isDir()) {
52 ✔
456
    return true;
457
  }
458
  const QString parent = QFileInfo(clean).absolutePath();
30 ✔
459
  if (parent != clean && !mkpathForStore(parent)) {
30 ✔
460
    return false;
461
  }
462
#ifdef Q_OS_UNIX
463
  // The store's umask, as git and gpg get it: a store shared with a group
464
  // (PASSWORD_STORE_UMASK=007) gets group folders, the default owner-only.
465
  const int umask = Executor::childUmask() >= 0 ? Executor::childUmask() : 077;
27 ✔
466
  QFile::Permissions permissions;
467
  const QFile::Permission bits[] = {
27 ✔
468
      QFile::ReadOwner, QFile::WriteOwner, QFile::ExeOwner,
469
      QFile::ReadGroup, QFile::WriteGroup, QFile::ExeGroup,
470
      QFile::ReadOther, QFile::WriteOther, QFile::ExeOther};
471
  for (int i = 0; i < 9; ++i) {
270 ✔
472
    if ((umask & (0400 >> i)) == 0) {
243 ✔
473
      permissions |= bits[i];
87 ✔
474
    }
475
  }
476
  // mkdir() still takes QtPass's own umask off (a session's 022 would drop
477
  // the group's write bit); set the mode exactly afterwards. That only ever
478
  // widens it to what was asked, never past.
479
  const bool made = QDir().mkdir(clean, permissions) &&
54 ✔
480
                    QFile::setPermissions(clean, permissions);
22 ✔
481
#else
482
  // Windows: permissions here would become an ACL of their own, replacing
483
  // the inherited one; the folder takes its parent's, as before.
484
  const bool made = QDir().mkdir(clean);
485
#endif
486
  return made || QFileInfo(clean).isDir();
27 ✔
487
}
488

489
auto Util::findBinaryInPath(const QString &binary) -> QString {
523 ✔
490
  if (binary.isEmpty()) {
523 ✔
491
    return {};
1 ✔
492
  }
493

494
  initialiseEnvironment();
522 ✔
495

496
  const QStringList dirs =
497
      _env.value(QStringLiteral("PATH"))
1,044 ✔
498
          .split(QDir::listSeparator(), Qt::SkipEmptyParts);
522 ✔
499
  QString ret;
522 ✔
500
  if (QDir::fromNativeSeparators(binary).contains(u'/')) {
522 ✔
501
    // An explicit path is not a PATH search: an absolute path is checked
502
    // as-is, a relative one is resolved against the PATH directories. The
503
    // directory-list overload refuses such names, so handle them here.
504
    if (QDir::isAbsolutePath(binary)) {
3 ✔
505
      ret = QStandardPaths::findExecutable(binary);
4 ✔
506
    } else if (!dirs.isEmpty()) {
1 ✔
507
      ret = QStandardPaths::findExecutable(binary, dirs);
2 ✔
508
    }
509
  } else {
510
    ret = findBinaryInPath(binary, dirs);
1,038 ✔
511
  }
512
#ifdef Q_OS_WIN
513
  if (ret.isEmpty()) {
514
    // Cache per-binary WSL lookup result — the wsl --version probe is a
515
    // blocking subprocess that can run several times per session for
516
    // missing binaries; once decided, the answer doesn't change at runtime.
517
    static QHash<QString, QString> wslBinaryCache;
518
    const bool hasWhitespace =
519
        std::any_of(binary.cbegin(), binary.cend(),
520
                    [](const QChar ch) { return ch.isSpace(); });
521
    if (!hasWhitespace) {
522
      auto cached = wslBinaryCache.constFind(binary);
523
      if (cached != wslBinaryCache.constEnd()) {
524
        ret = cached.value();
525
      } else {
526
        QString wslCommand = QStringLiteral("wsl ") + binary;
527
        qCDebug(lcQtPass)
528
            << "Util::findBinaryInPath(): falling back to WSL for binary"
529
            << binary;
530
        QString out, err;
531
        QString cachedResult;
532
        if (Executor::executeBlocking(wslCommand, {"--version"}, &out, &err) ==
533
                0 &&
534
            !out.isEmpty() && err.isEmpty()) {
535
          qCDebug(lcQtPass)
536
              << "Util::findBinaryInPath(): using WSL binary" << wslCommand;
537
          cachedResult = wslCommand;
538
        }
539
        wslBinaryCache.insert(binary, cachedResult);
540
        ret = cachedResult;
541
      }
542
    }
543
  }
544
#endif
545

546
  return ret;
547
}
548

549
// Bare names only: QStandardPaths::findExecutable() returns an absolute binary
550
// without consulting searchPaths, and a relative one with ".." could escape
551
// them.
552
auto Util::findBinaryInPath(const QString &binary,
533 ✔
553
                            const QStringList &searchPaths) -> QString {
554
  if (binary.isEmpty() || QDir::fromNativeSeparators(binary).contains(u'/')) {
1,065 ✔
555
    return {};
4 ✔
556
  }
557
  QStringList dirs;
529 ✔
558
  dirs.reserve(searchPaths.size());
529 ✔
559
  for (const QString &dir : searchPaths) {
8,280 ✔
560
    if (!dir.isEmpty()) {
7,751 ✔
561
      dirs.append(dir);
562
    }
563
  }
564
  if (dirs.isEmpty()) {
529 ✔
565
    // QStandardPaths::findExecutable() treats an empty list as "use PATH".
566
    return {};
4 ✔
567
  }
568
  return QStandardPaths::findExecutable(binary, dirs);
525 ✔
569
}
570

571
auto Util::configIsValid(const AppSettings &s) -> bool {
277 ✔
572
  const QString configFilePath = QDir(s.passStore).filePath(".gpg-id");
554 ✔
573
  if (!QFile(configFilePath).exists()) {
277 ✔
574
    return false;
575
  }
576

577
  const QString executable = s.usePass ? s.passExecutable : s.gpgExecutable;
195 ✔
578

579
  if (const auto wsl = Executor::parseWslCommand(executable)) {
195 ✔
580
    // Probe WSL once per session — availability doesn't change at runtime
581
    // and the executeBlocking call is a blocking subprocess.
582
    static const bool wslAvailable = [&wsl]() {
1 ✔
583
      QString out;
1 ✔
584
      QString err;
1 ✔
585
      return Executor::executeBlocking(wsl->launcher,
3 ✔
586
                                       {QStringLiteral("--version")}, &out,
1 ✔
UNCOV
587
                                       &err) == 0 &&
×
588
             !out.isEmpty() && err.isEmpty();
2 ✔
589
    }();
1 ✔
590
    if (wslAvailable) {
1 ✔
591
      return true;
592
    }
593
  }
594
  return QFile(executable).exists();
195 ✔
595
}
596

597
auto Util::endsWithGpg() -> const QRegularExpression & {
15,509 ✔
598
  static const QRegularExpression expr{R"(\.gpg$)"};
15,516 ✔
599
  return expr;
15,509 ✔
600
}
601

602
// Stops at whitespace, quotes and brackets so a URL on its own line keeps no
603
// line break. file:/// is excluded on purpose (local, not network); the test
604
// relies on that.
605
auto Util::protocolRegex() -> const QRegularExpression & {
149 ✔
606
  static const QRegularExpression regex{
607
      R"(((?:https?|ftp|ssh|sftp|ftps|webdav|webdavs)://[^"\s<>\)\]\[]+))"};
154 ✔
608
  return regex;
149 ✔
609
}
610

611
auto Util::isLaunchableWebUrl(const QString &value) -> bool {
117 ✔
612
  const QString trimmed = value.trimmed();
613
  if (trimmed.isEmpty()) {
117 ✔
614
    return false;
615
  }
616
  // Reject control characters first, before QUrl normalisation can hide a
617
  // CR/LF/NUL injection into the OS URL handler.
618
  for (const QChar &c : trimmed) {
4,092 ✔
619
    if (c == QLatin1Char('\r') || c == QLatin1Char('\n') ||
620
        c == QChar(QChar::Null)) {
621
      return false;
622
    }
623
  }
624
  const QUrl url(trimmed, QUrl::StrictMode);
113 ✔
625
  if (!url.isValid()) {
113 ✔
626
    return false;
627
  }
628
  const QString scheme = url.scheme().toLower();
98 ✔
629
  if (scheme != QLatin1String("http") && scheme != QLatin1String("https")) {
98 ✔
630
    return false;
35 ✔
631
  }
632
  if (url.host().isEmpty()) {
126 ✔
633
    return false;
634
  }
635
  // Embedded userinfo (user:pass@host) would leak into browser history.
636
  if (!url.userName().isEmpty() || !url.password().isEmpty()) {
119 ✔
637
    return false;
638
  }
639
  return true;
640
}
113 ✔
641

642
auto Util::displayable(const QString &text, bool lineBreaks) -> QString {
438 ✔
643
  QString shown = text;
644
  for (qsizetype i = 0; i < shown.size(); ++i) {
122,643 ✔
645
    const char16_t u = shown.at(i).unicode();
646
    // A carriage return before a line feed is a Windows line end (git or
647
    // gpg output quoted in a message), not a character of its own.
648
    const bool lineEnd =
649
        lineBreaks && (u == u'\n' || (u == u'\r' && i + 1 < shown.size() &&
122,205 ✔
650
                                      shown.at(i + 1) == u'\n'));
651
    if ((u < 0x20 && u != u'\t' && !lineEnd) || (u >= 0x7f && u <= 0x9f) ||
122,205 ✔
652
        u == 0x2028 || u == 0x2029 || (u >= 0x202a && u <= 0x202e) ||
122,196 ✔
653
        (u >= 0x2066 && u <= 0x2069)) {
122,188 ✔
654
      shown[i] = QChar(QChar::ReplacementCharacter);
19 ✔
655
    }
656
  }
657
  return shown;
438 ✔
658
}
659

660
auto Util::linkifyUrls(const QString &text, bool *linked) -> QString {
145 ✔
661
  if (linked != nullptr) {
145 ✔
662
    *linked = false;
60 ✔
663
  }
664
  QString html;
145 ✔
665
  html.reserve(text.size());
145 ✔
666
  qsizetype lastIndex = 0;
667
  QRegularExpressionMatchIterator it = protocolRegex().globalMatch(text);
145 ✔
668
  while (it.hasNext()) {
193 ✔
669
    const QRegularExpressionMatch match = it.next();
48 ✔
670
    const QString url = match.captured(0);
48 ✔
671
    // Only plain ASCII becomes a link: the link text is the URL as stored,
672
    // and a right-to-left letter, a bidi control or a look-alike host in it
673
    // makes it read as another address than the one it opens. Such a URL
674
    // stays plain text; the open button still takes it.
675
    const bool plain = std::all_of(url.cbegin(), url.cend(), [](QChar c) {
676
      return c.unicode() > 0x20 && c.unicode() < 0x7f;
1,139 ✔
677
    });
678
    if (!plain || !isLaunchableWebUrl(url)) {
48 ✔
679
      // Not a web URL (or it carries credentials): leave it in the escaped
680
      // plain-text run instead of making it clickable.
681
      continue;
682
    }
683
    const qsizetype start = match.capturedStart(0);
32 ✔
684
    html += text.mid(lastIndex, start - lastIndex).toHtmlEscaped();
32 ✔
685
    const QString escapedUrl = url.toHtmlEscaped();
32 ✔
686
    html += QStringLiteral("<a href=\"%1\">%1</a>").arg(escapedUrl);
64 ✔
687
    lastIndex = match.capturedEnd(0);
32 ✔
688
    if (linked != nullptr) {
32 ✔
689
      *linked = true;
24 ✔
690
    }
691
  }
48 ✔
692
  html += text.mid(lastIndex).toHtmlEscaped();
145 ✔
693
  // With a link in it, no bidi embedding, override or isolate control is
694
  // drawn: an override earlier in the entry (U+202E) drew the link text
695
  // reversed, so it read as another address. Shown as U+FFFD, so the user
696
  // sees that something was there; the copy button still copies the value.
697
  if (linked != nullptr ? *linked : html.contains(QLatin1String("<a href="))) {
230 ✔
698
    for (QChar &c : html) {
3,442 ✔
699
      const char16_t u = c.unicode();
3,412 ✔
700
      if ((u >= 0x202A && u <= 0x202E) || (u >= 0x2066 && u <= 0x2069)) {
3,412 ✔
701
        c = QChar(QChar::ReplacementCharacter);
1 ✔
702
      }
703
    }
704
  }
705
  return html;
145 ✔
706
}
145 ✔
707

708
// One pass, no regex: a pattern such as \s{1001,} retries from every
709
// character of a shorter run, which is quadratic on an entry made of them.
710
// A tab or a line feed ends a run in Qt's layout as well, so it ends one
711
// here; \v and U+0085 do not, so they count.
712
auto Util::boundSpaceRuns(const QString &text) -> QString {
210 ✔
713
  QString bounded;
210 ✔
714
  // Text before this index is in bounded already, or dropped.
715
  qsizetype from = 0;
716
  qsizetype run = 0;
717
  for (qsizetype i = 0; i < text.size(); ++i) {
154,053 ✔
718
    const QChar ch = text.at(i);
719
    if (!ch.isSpace() || ch == QLatin1Char('\t') || ch == QLatin1Char('\n')) {
153,843 ✔
720
      run = 0;
721
      continue;
6,821 ✔
722
    }
723
    if (++run <= kMaxSpaceRun) {
147,022 ✔
724
      continue;
11,485 ✔
725
    }
726
    if (run == kMaxSpaceRun + 1) {
135,537 ✔
727
      bounded += QStringView(text).sliced(from, i - from);
6 ✔
728
    }
729
    from = i + 1;
135,537 ✔
730
  }
731
  if (from == 0) {
210 ✔
732
    return text;
733
  }
734
  bounded += QStringView(text).sliced(from);
735
  return bounded;
736
}
737

738
auto Util::newLinesRegex() -> const QRegularExpression & {
326 ✔
739
  static const QRegularExpression regex{"[\r\n]"};
335 ✔
740
  return regex;
326 ✔
741
}
742

743
// No content heuristics: a line rejected here is erased the next time .gpg-id
744
// is rewritten. A leading `-` is refused because the recipients also go
745
// positionally to `gpg --list-keys`, where it would parse as an option.
746
auto Util::isValidKeyId(const QString &keyId) -> bool {
234 ✔
747
  return !keyId.isEmpty() && !keyId.startsWith('-');
234 ✔
748
}
749

750
namespace {
751
/**
752
 * @brief Whether the walk can see what is in @p dir: read permission to list
753
 * it and, on Unix, search permission to look at what it holds (without it the
754
 * names come, but no entry reads as a file or a folder), and no name Qt
755
 * leaves out of the listing (Util::hasUnreadableName()).
756
 * @param dir An existing directory.
757
 * @return false when the walk would miss what is in it.
758
 */
759
auto canList(const QString &dir) -> bool {
183 ✔
760
#ifdef Q_OS_WIN
761
  // Qt answers from the attributes alone unless told to read the ACL.
762
  QNtfsPermissionCheckGuard aclCheck;
763
  return QFileInfo(dir).isReadable();
764
#else
765
  const QFileInfo info(dir);
183 ✔
766
  return info.isReadable() && info.isExecutable() &&
358 ✔
767
         !Util::hasUnreadableName(dir);
358 ✔
768
#endif
769
}
183 ✔
770

771
/**
772
 * @brief Walk @p dir's real, visible directories in sorted pre-order and hand
773
 * every entry to @p visit before any recursion; a directory is entered only
774
 * when @p visit returns true for it. A directory that cannot be read goes to
775
 * @p unlisted, when given: its listing would come back empty, as an empty
776
 * folder's does, and what is in it would be left out without a sign.
777
 */
778
template <typename Visit>
779
void walkStore(const QString &dir, Visit visit,
299 ✔
780
               QStringList *unlisted = nullptr) {
781
  // Absolute, so the results are whatever the caller's cwd; not canonical,
782
  // so a linked root keeps the name it was configured under.
783
  QStringList pending{QDir(QDir::cleanPath(dir)).absolutePath()};
897 ✔
784
  while (!pending.isEmpty()) {
1,169 ✔
785
    const QDir current(pending.takeLast());
440 ✔
786
    if (unlisted != nullptr && current.exists() && !canList(current.path())) {
880 ✔
787
      qCWarning(lcQtPass) << "Cannot list" << current.path();
20 ✔
788
      *unlisted << current.path();
10 ✔
789
      continue;
790
    }
10 ✔
791
    // Every entry once, links and hidden entries included, so the decision
792
    // what to do with each is taken here, before any recursion. QDir::System
793
    // keeps dangling links in the listing.
794
    const QFileInfoList entries =
430 ✔
795
        current.entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
796
                                  QDir::System | QDir::NoDotAndDotDot,
797
                              QDir::Name);
798
    QStringList subdirs;
430 ✔
799
    for (const QFileInfo &entry : entries) {
2,223 ✔
800
      if (visit(entry)) {
1,793 ✔
801
        subdirs << entry.filePath();
282 ✔
802
      }
803
    }
804
    // Pushed last-to-first so the next one taken is the first by name.
805
    for (auto it = subdirs.crbegin(); it != subdirs.crend(); ++it) {
571 ✔
806
      pending << *it;
807
    }
808
  }
809
}
598 ✔
810

811
/// A symlink or an NTFS junction: never entered, never listed.
812
auto isLink(const QFileInfo &entry) -> bool {
16,446 ✔
813
  return entry.isSymLink() || entry.isJunction();
16,446 ✔
814
}
815

816
/// Hidden by attribute, or by the dot convention on every platform: Qt 6.11
817
/// on macOS answers isHidden() from the UF_HIDDEN flag alone once an entry
818
/// was lstat()ed (qfilesystemengine_unix.cpp marks the attribute known there
819
/// without the dot check), and Windows does not consider .stversions hidden
820
/// at all.
821
auto isHiddenEntry(const QFileInfo &entry) -> bool {
967 ✔
822
  return entry.isHidden() || entry.fileName().startsWith(QLatin1Char('.'));
1,917 ✔
823
}
824

825
/// A real directory that is part of the store: .git, .stversions,
826
/// .Trash-1000 are not, as with QDirIterator without QDir::Hidden.
827
auto isStoreDirectory(const QFileInfo &entry) -> bool {
1,793 ✔
828
  return !isLink(entry) && entry.isDir() && !isHiddenEntry(entry);
1,793 ✔
829
}
830
} // namespace
831

832
auto Util::regularFilesUnder(const QString &dir, const QStringList &nameFilters,
296 ✔
833
                             QStringList *skipped, bool hiddenFiles,
834
                             QStringList *unlisted) -> QStringList {
835
  QStringList files;
296 ✔
836
  walkStore(
296 ✔
837
      dir,
838
      [&](const QFileInfo &entry) {
1,718 ✔
839
        if (isStoreDirectory(entry)) {
1,718 ✔
840
          return true;
841
        }
842
        const bool named = QDir::match(nameFilters, entry.fileName());
1,598 ✔
843
        if (isLink(entry) || (!entry.isDir() && !entry.isFile())) {
1,598 ✔
844
          // A linked directory hides everything behind it; a linked file, or a
845
          // FIFO, socket or device, is only of interest under a name the caller
846
          // asked for.
847
          if (skipped != nullptr && (entry.isDir() || named)) {
25 ✔
848
            qCWarning(lcQtPass) << "Skipping" << entry.filePath()
24 ✔
849
                                << ": not a regular file or directory";
12 ✔
850
            *skipped << entry.filePath();
24 ✔
851
          }
852
          return false;
25 ✔
853
        }
854
        if (entry.isFile() && named && (hiddenFiles || !isHiddenEntry(entry))) {
1,573 ✔
855
          files << entry.filePath();
1,728 ✔
856
        }
857
        return false;
858
      },
859
      unlisted);
860
  return files;
296 ✔
861
}
862

863
auto Util::directoriesUnder(const QString &dir) -> QStringList {
3 ✔
864
  QStringList dirs;
3 ✔
865
  walkStore(dir, [&](const QFileInfo &entry) {
3 ✔
866
    if (!isStoreDirectory(entry)) {
75 ✔
867
      return false;
868
    }
869
    dirs << entry.filePath();
21 ✔
870
    return true;
21 ✔
871
  });
872
  return dirs;
3 ✔
873
}
874

875
auto Util::hasUnreadableName(const QString &dir) -> bool {
202 ✔
876
#ifdef Q_OS_WIN
877
  Q_UNUSED(dir);
878
  return false;
879
#else
880
  // The names as bytes, as readdir() gives them; Qt's own listing has
881
  // already dropped the ones this is looking for.
882
  DIR *listing = ::opendir(QFile::encodeName(dir).constData());
202 ✔
883
  if (listing == nullptr) {
202 ✔
884
    return false;
885
  }
886
  const auto close = qScopeGuard([listing] { ::closedir(listing); });
202 ✔
887
  while (const dirent *entry = ::readdir(listing)) {
1,117 ✔
888
    if (!QByteArrayView(entry->d_name).isValidUtf8()) {
920 ✔
889
      return true;
890
    }
891
  }
892
  return false;
893
#endif
894
}
895

896
auto Util::isLinkedFolder(const QString &path) -> bool {
13,012 ✔
897
  return isLink(QFileInfo(QDir::cleanPath(path)));
26,024 ✔
898
}
899

900
auto Util::isUnderLink(const QString &path, const QString &storeRoot,
11,264 ✔
901
                       bool includeSelf) -> bool {
902
  // "C:/Store" and "c:/store" are one directory on Windows; a path spelled
903
  // the other way must not skip the walk (as in Pass::getGpgIdPath).
904
#ifdef Q_OS_WIN
905
  constexpr auto cs = Qt::CaseInsensitive;
906
#else
907
  constexpr auto cs = Qt::CaseSensitive;
908
#endif
909
  const QString root = QDir::cleanPath(storeRoot);
11,264 ✔
910
  // A root of "/" or "C:/" already ends in the separator.
911
  const QString prefix =
912
      root.endsWith(QLatin1Char('/')) ? root : root + QLatin1Char('/');
11,264 ✔
913
  const auto isRoot = [&](const QString &p) {
914
    return p.compare(root, cs) == 0;
12,352 ✔
915
  };
916
  QString current = QDir::cleanPath(path);
11,264 ✔
917
  if (!current.startsWith(prefix, cs)) {
11,264 ✔
918
    // Not under the store as named: only the entry itself can be judged.
919
    return includeSelf && !isRoot(current) && isLinkedFolder(current);
470 ✔
920
  }
921
  if (!includeSelf) {
11,029 ✔
922
    current = QFileInfo(current).path();
20,910 ✔
923
  }
924
  for (; !isRoot(current) && current.startsWith(prefix, cs);
12,117 ✔
925
       current = QFileInfo(current).path()) {
2,176 ✔
926
    if (isLinkedFolder(current)) {
1,134 ✔
927
      return true;
928
    }
929
  }
930
  return false;
931
}
932

933
#ifndef Q_OS_WIN
934
namespace {
935

936
/// The filesystem cannot make hard links at all (FAT/exFAT refuse with
937
/// EPERM, some FUSE filesystems with ENOTSUP or ENOSYS).
938
auto hasNoHardLinks(int error) -> bool {
939
  return error == EPERM || error == ENOTSUP || error == EOPNOTSUPP ||
2 ✔
940
         error == ENOSYS;
941
}
942

943
/// rename() that fails with EEXIST instead of replacing, where the platform
944
/// has one; nothing when neither the platform nor the filesystem does.
945
auto renameExclusive(const QByteArray &source, const QByteArray &target)
8 ✔
946
    -> std::optional<bool> {
947
#if defined(__GLIBC__) &&                                                      \
948
    (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 28))
949
  if (::renameat2(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(),
8 ✔
950
                  RENAME_NOREPLACE) == 0) {
951
    return true;
2 ✔
952
  }
953
  if (errno == EINVAL || errno == ENOSYS || hasNoHardLinks(errno)) {
6 ✔
954
    return std::nullopt;
4 ✔
955
  }
956
  return false;
2 ✔
957
#elif defined(Q_OS_MACOS)
958
  if (::renamex_np(source.constData(), target.constData(), RENAME_EXCL) == 0) {
959
    return true;
960
  }
961
  if (errno == EINVAL || errno == ENOTSUP) {
962
    return std::nullopt;
963
  }
964
  return false;
965
#else
966
  Q_UNUSED(source);
967
  Q_UNUSED(target);
968
  return std::nullopt;
969
#endif
970
}
971

972
/**
973
 * @brief Gives @p source the name @p target unless something already has it.
974
 *
975
 * A hard link is the one way every POSIX system can do that in one step:
976
 * linkat() fails with EEXIST rather than replacing. Where the filesystem has
977
 * no hard links, an exclusive rename does it; where that is missing too, the
978
 * name is checked and then renamed, which leaves a short window for another
979
 * writer to create it in between.
980
 */
981
auto placeWithoutReplacing(const QByteArray &source, const QByteArray &target)
88 ✔
982
    -> bool {
983
  // linkat() without AT_SYMLINK_FOLLOW follows nothing; link() would, on
984
  // macOS and the BSDs, hard-link whatever a symlink planted under the
985
  // source's name points at.
986
  if (::linkat(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(), 0) ==
88 ✔
987
      0) {
988
    ::unlink(source.constData());
73 ✔
989
    return true;
73 ✔
990
  }
991
  if (!hasNoHardLinks(errno)) {
15 ✔
992
    return false;
993
  }
994
  if (const std::optional<bool> renamed = renameExclusive(source, target)) {
8 ✔
995
    return *renamed;
4 ✔
996
  }
997
  struct stat st{};
4 ✔
998
  if (::lstat(target.constData(), &st) == 0 || errno != ENOENT) {
4 ✔
999
    errno = EEXIST;
2 ✔
1000
    return false;
2 ✔
1001
  }
1002
  return ::rename(source.constData(), target.constData()) == 0;
2 ✔
1003
}
1004

1005
} // namespace
1006
#endif
1007

1008
auto Util::replaceFile(const QString &from, const QString &to, bool replace)
245 ✔
1009
    -> bool {
1010
#ifdef Q_OS_WIN
1011
  const std::wstring source =
1012
      QDir::toNativeSeparators(QFileInfo(from).absoluteFilePath())
1013
          .toStdWString();
1014
  const std::wstring target =
1015
      QDir::toNativeSeparators(QFileInfo(to).absoluteFilePath()).toStdWString();
1016
  // WRITE_THROUGH: the new entry is on the device when this returns.
1017
  return MoveFileExW(source.c_str(), target.c_str(),
1018
                     (replace ? MOVEFILE_REPLACE_EXISTING : 0) |
1019
                         MOVEFILE_WRITE_THROUGH) != 0;
1020
#else
1021
  const QByteArray source = QFile::encodeName(from);
1022
  const QByteArray target = QFile::encodeName(to);
1023
  if (replace) {
245 ✔
1024
    if (::rename(source.constData(), target.constData()) != 0) {
157 ✔
1025
      return false;
1026
    }
1027
  } else {
1028
    if (!placeWithoutReplacing(source, target)) {
88 ✔
1029
      return false;
1030
    }
1031
  }
1032
  // Sync the directory entry so a crash does not lose the new name. Best
1033
  // effort: the bytes are already synced, and some network filesystems
1034
  // cannot sync a directory.
1035
  const int dir = ::open(QFile::encodeName(QFileInfo(to).path()).constData(),
462 ✔
1036
                         O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1037
  if (dir >= 0) {
231 ✔
1038
    int rc;
1039
    do {
1040
      rc = ::fsync(dir);
231 ✔
1041
    } while (rc != 0 && errno == EINTR);
231 ✔
1042
    ::close(dir);
231 ✔
1043
  }
1044
  return true;
1045
#endif
1046
}
1047

1048
auto Util::openRegularFile(const QString &path, QFile &file) -> bool {
864 ✔
1049
#ifdef Q_OS_WIN
1050
  // FILE_FLAG_OPEN_REPARSE_POINT opens a symbolic link or junction itself
1051
  // rather than its target, so the handle's attributes say what the name
1052
  // was at the moment of the open.
1053
  const std::wstring native =
1054
      QDir::toNativeSeparators(QFileInfo(path).absoluteFilePath())
1055
          .toStdWString();
1056
  HANDLE handle = CreateFileW(
1057
      native.c_str(), GENERIC_READ,
1058
      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
1059
      OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
1060
  if (handle == INVALID_HANDLE_VALUE) {
1061
    return false;
1062
  }
1063
  BY_HANDLE_FILE_INFORMATION info{};
1064
  if (!GetFileInformationByHandle(handle, &info) ||
1065
      (info.dwFileAttributes &
1066
       (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY |
1067
        FILE_ATTRIBUTE_DEVICE)) != 0 ||
1068
      GetFileType(handle) != FILE_TYPE_DISK) {
1069
    CloseHandle(handle);
1070
    return false;
1071
  }
1072
  const int fd = _open_osfhandle(reinterpret_cast<intptr_t>(handle),
1073
                                 _O_RDONLY | _O_BINARY);
1074
  if (fd < 0) {
1075
    CloseHandle(handle);
1076
    return false;
1077
  }
1078
  if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
1079
    _close(fd);
1080
    return false;
1081
  }
1082
  return true;
1083
#else
1084
  // O_NOFOLLOW fails with ELOOP on a symbolic link; O_NONBLOCK keeps a FIFO
1085
  // from blocking the open until fstat() can refuse it.
1086
  const int fd = ::open(QFile::encodeName(path).constData(),
864 ✔
1087
                        O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
1088
  if (fd < 0) {
864 ✔
1089
    return false;
1090
  }
1091
  struct stat st{};
810 ✔
1092
  if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
810 ✔
1093
    ::close(fd);
7 ✔
1094
    return false;
7 ✔
1095
  }
1096
  // The descriptor, not the name, is what QFile opens here: the object
1097
  // fstat() judged is the object read. CodeQL's check-then-use pattern
1098
  // matcher sees an open after a check and cannot tell.
1099
  if (!file.open(fd, QIODevice::ReadOnly, // codeql[cpp/toctou-race-condition]
803 ✔
1100
                 QFileDevice::AutoCloseHandle)) {
UNCOV
1101
    ::close(fd);
×
UNCOV
1102
    return false;
×
1103
  }
1104
  return true;
1105
#endif
1106
}
1107

1108
auto Util::readRegularFile(const QString &path, qint64 maxBytes)
284 ✔
1109
    -> std::optional<QByteArray> {
1110
  QFile file;
284 ✔
1111
  if (!openRegularFile(path, file)) {
284 ✔
1112
    return std::nullopt;
10 ✔
1113
  }
1114
  // A regular file's size is reliable, also when sparse: refuse a large one
1115
  // before reading anything. One byte past the limit still guards a file
1116
  // that grows meanwhile.
1117
  if (file.size() > maxBytes) {
274 ✔
1118
    return std::nullopt;
3 ✔
1119
  }
1120
  QByteArray bytes = file.read(maxBytes + 1);
271 ✔
1121
  if (bytes.size() > maxBytes || file.error() != QFileDevice::NoError) {
271 ✔
UNCOV
1122
    return std::nullopt;
×
1123
  }
1124
  return bytes;
1125
}
284 ✔
1126

1127
auto Util::syncToDisk(QFileDevice &file) -> bool {
231 ✔
1128
  if (!file.flush()) {
231 ✔
1129
    return false;
1130
  }
1131
#ifdef Q_OS_WIN
1132
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1133
  return handle != INVALID_HANDLE_VALUE && FlushFileBuffers(handle) != 0;
1134
#else
1135
  return ::fsync(file.handle()) == 0;
231 ✔
1136
#endif
1137
}
1138

1139
namespace {
1140

1141
/**
1142
 * @brief What tells one file object from another on its filesystem: device
1143
 * and inode on POSIX, volume serial and file index on Windows.
1144
 */
1145
struct FileIdentity {
1146
  quint64 volume = 0;
1147
  quint64 index = 0;
1148
  bool known = false;
1149
};
1150

1151
auto operator==(const FileIdentity &a, const FileIdentity &b) -> bool {
220 ✔
1152
  return a.known && b.known && a.volume == b.volume && a.index == b.index;
220 ✔
1153
}
1154

1155
/// The identity of the object @p file is open on, or an unknown one.
1156
auto identityOf(const QFileDevice &file) -> FileIdentity {
451 ✔
1157
#ifdef Q_OS_WIN
1158
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1159
  BY_HANDLE_FILE_INFORMATION info;
1160
  if (handle == INVALID_HANDLE_VALUE ||
1161
      GetFileInformationByHandle(handle, &info) == 0) {
1162
    return {};
1163
  }
1164
  // On FAT/exFAT the file ID is the directory entry's offset, which a rename
1165
  // can move. They have no hard links either (the swap this catches needs
1166
  // one), so the identity is left unknown there.
1167
  DWORD flags = 0;
1168
  if (GetVolumeInformationByHandleW(handle, nullptr, 0, nullptr, nullptr,
1169
                                    &flags, nullptr, 0) == 0 ||
1170
      (flags & FILE_SUPPORTS_HARD_LINKS) == 0) {
1171
    return {};
1172
  }
1173
  return {info.dwVolumeSerialNumber,
1174
          (static_cast<quint64>(info.nFileIndexHigh) << 32) |
1175
              info.nFileIndexLow,
1176
          true};
1177
#else
1178
  struct stat st{};
451 ✔
1179
  if (::fstat(file.handle(), &st) != 0) {
451 ✔
UNCOV
1180
    return {};
×
1181
  }
1182
  return {static_cast<quint64>(st.st_dev), static_cast<quint64>(st.st_ino),
451 ✔
1183
          true};
451 ✔
1184
#endif
1185
}
1186

1187
/// Put @p text in @p error when there is one; false, for `return fail(...)`.
1188
auto fail(QString *error, const QString &text) -> bool {
1189
  if (error != nullptr) {
22 ✔
1190
    *error = text;
22 ✔
1191
  }
1192
  return false;
1193
}
1194

1195
/// A filled, synced temporary next to its destination.
1196
struct Staged {
231 ✔
1197
  QString path;
1198
  FileIdentity identity;
1199
  /// POSIX: a descriptor kept open on the temporary until the identity
1200
  /// check, so the inode, and with it the number, stays the temporary's.
1201
  std::shared_ptr<void> pin;
1202
};
1203

1204
/**
1205
 * @brief Create the temporary next to @p path (opaque name, exclusive,
1206
 * owner-only), fill it through its handle and sync it. The QTemporaryFile
1207
 * goes out of scope before the caller renames: it keeps its handle open for
1208
 * as long as it lives, and Windows does not rename an open file.
1209
 */
1210
auto stageNextTo(const QString &path, const Util::Filler &fill, QString *why)
239 ✔
1211
    -> std::optional<Staged> {
1212
  Staged staged;
239 ✔
1213
  {
1214
    QTemporaryFile file(QFileInfo(path).path() +
478 ✔
1215
                        QStringLiteral("/.qtpass-XXXXXX.tmp"));
478 ✔
1216
    file.setAutoRemove(false);
239 ✔
1217
    if (!file.open()) {
239 ✔
1218
      *why = QCoreApplication::translate(
8 ✔
1219
                 "Util", "Cannot create a temporary file next to %1: %2")
1220
                 .arg(path, file.errorString());
16 ✔
1221
      return std::nullopt;
8 ✔
1222
    }
1223
    staged.path = file.fileName();
231 ✔
1224
    // Owner-only: a .gpg-id names the keys a store is encrypted to, an
1225
    // entry is an entry. QTemporaryFile creates 0600 already; say so for
1226
    // platforms where it may not.
1227
    file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
231 ✔
1228
    *why = fill(file);
462 ✔
1229
    if (why->isEmpty() && !Util::syncToDisk(file)) {
231 ✔
UNCOV
1230
      *why = QCoreApplication::translate("Util", "Cannot write %1: %2")
×
UNCOV
1231
                 .arg(path, file.errorString());
×
1232
    }
1233
    staged.identity = identityOf(file);
231 ✔
1234
#ifndef Q_OS_WIN
1235
    // Closed and unlinked by a co-writer before the rename, the temporary's
1236
    // inode number would be free, and ext4 hands it to the next file made:
1237
    // the very file swapped in would then pass the check below. Windows
1238
    // cannot rename an open file, and NTFS does not reuse a file index so.
1239
    if (const int fd = ::dup(file.handle()); fd >= 0) {
231 ✔
1240
      staged.pin =
1241
          std::shared_ptr<void>(nullptr, [fd](void *) { ::close(fd); });
693 ✔
1242
    }
1243
#endif
1244
  }
239 ✔
1245
  if (!why->isEmpty()) {
231 ✔
UNCOV
1246
    QFile::remove(staged.path);
×
UNCOV
1247
    return std::nullopt;
×
1248
  }
1249
  return staged;
231 ✔
1250
}
239 ✔
1251

1252
/// Why replaceFile() could not put the temporary under @p path.
1253
auto placementError(const QString &path, bool replace) -> QString {
9 ✔
1254
  if (replace) {
9 ✔
1255
    return QCoreApplication::translate("Util", "Failed to replace %1.")
4 ✔
1256
        .arg(path);
2 ✔
1257
  }
1258
  const QFileInfo taken(path);
7 ✔
1259
  return taken.exists() || taken.isSymLink()
8 ✔
1260
             ? QCoreApplication::translate("Util", "%1 already exists.")
7 ✔
1261
                   .arg(path)
1262
             : QCoreApplication::translate("Util", "Failed to write %1.")
1 ✔
1263
                   .arg(path);
8 ✔
1264
}
7 ✔
1265

1266
/**
1267
 * @brief Whether what is under @p path is the file that was filled: not a
1268
 * link, and not another file (a hard link to something of the user's, say)
1269
 * swapped in under the temporary's name. Opened without following, compared
1270
 * by identity; only two known identities can prove a swap, otherwise every
1271
 * write on such a store would be reported as tampering.
1272
 */
1273
auto isTheFileWritten(const QString &path, const FileIdentity &written)
222 ✔
1274
    -> bool {
1275
  QFile placed;
222 ✔
1276
  if (!Util::openRegularFile(path, placed)) {
222 ✔
1277
    return false;
1278
  }
1279
  const FileIdentity there = identityOf(placed);
220 ✔
1280
  if (!written.known || !there.known) {
220 ✔
UNCOV
1281
    qCWarning(lcQtPass) << "Cannot tell whether" << path
×
UNCOV
1282
                        << "is the file that was written here";
×
UNCOV
1283
    return true;
×
1284
  }
1285
  return there == written;
220 ✔
1286
}
222 ✔
1287

1288
} // namespace
1289

1290
auto Util::stageFileReplacing(const QString &path, bool replace,
239 ✔
1291
                              const Filler &fill, QString *error) -> bool {
1292
  QString why;
239 ✔
1293
  const std::optional<Staged> staged = stageNextTo(path, fill, &why);
239 ✔
1294
  if (!staged) {
239 ✔
1295
    return fail(error, why);
1296
  }
1297
  if (s_beforePlacingForTests) {
231 ✔
1298
    s_beforePlacingForTests(staged->path);
1 ✔
1299
  }
1300
  if (!replaceFile(staged->path, path, replace)) {
231 ✔
1301
    QFile::remove(staged->path);
9 ✔
1302
    return fail(error, placementError(path, replace));
18 ✔
1303
  }
1304
  // A mismatch is reported and left: removing by name could take another
1305
  // writer's file.
1306
  if (!isTheFileWritten(path, staged->identity)) {
222 ✔
1307
    return fail(
1308
        error,
1309
        QCoreApplication::translate(
5 ✔
1310
            "Util", "%1 was swapped for another file while it was written.")
1311
            .arg(path));
10 ✔
1312
  }
1313
  return true;
1314
}
1315

1316
auto Util::writeFileReplacing(const QString &path, const QByteArray &bytes,
106 ✔
1317
                              bool replace, QString *error) -> bool {
1318
  return stageFileReplacing(
106 ✔
1319
      path, replace,
1320
      [&path, &bytes](QFileDevice &staged) -> QString {
210 ✔
1321
        if (staged.write(bytes) != bytes.size()) {
104 ✔
UNCOV
1322
          return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
UNCOV
1323
              .arg(path, staged.errorString());
×
1324
        }
1325
        return {};
104 ✔
1326
      },
1327
      error);
106 ✔
1328
}
1329

1330
auto Util::copyFileReplacing(const QString &src, const QString &dst,
132 ✔
1331
                             bool replace, QString *error) -> bool {
1332
  QFile in;
132 ✔
1333
  if (!openRegularFile(src, in)) {
132 ✔
1334
    if (error)
4 ✔
1335
      *error = QCoreApplication::translate("Util", "Cannot read %1.").arg(src);
8 ✔
1336
    return false;
4 ✔
1337
  }
1338
  return stageFileReplacing(
128 ✔
1339
      dst, replace,
1340
      [&src, &dst, &in](QFileDevice &staged) -> QString {
378 ✔
1341
        char buf[64 * 1024];
1342
        for (;;) {
1343
          const qint64 n = in.read(buf, sizeof buf);
256 ✔
1344
          if (n < 0) {
256 ✔
UNCOV
1345
            return QCoreApplication::translate("Util", "Cannot read %1: %2")
×
UNCOV
1346
                .arg(src, in.errorString());
×
1347
          }
1348
          if (n == 0) {
256 ✔
1349
            return {};
122 ✔
1350
          }
1351
          if (staged.write(buf, n) != n) {
134 ✔
UNCOV
1352
            return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1353
                .arg(dst, staged.errorString());
×
1354
          }
1355
        }
1356
      },
1357
      error);
1358
}
132 ✔
1359

1360
namespace {
1361

1362
/// Remove one directory entry that is not a real directory: a link goes as
1363
/// the entry itself, never its target (a junction or a directory symlink on
1364
/// Windows is a directory entry and goes with rmdir); a read-only file gets
1365
/// write access and one more try, as QDir::removeRecursively() does.
1366
auto removeEntry(const QFileInfo &entry) -> bool {
14 ✔
1367
  const QString path = entry.filePath();
14 ✔
1368
  if (isLink(entry)) {
14 ✔
1369
    if (QFile::remove(path) || QDir().rmdir(path)) {
6 ✔
1370
      return true;
1371
    }
1372
    qCWarning(lcQtPass) << "Could not remove link" << path;
2 ✔
1373
    return false;
1 ✔
1374
  }
1375
  if (QFile::remove(path)) {
9 ✔
1376
    return true;
1377
  }
1378
  const QFile::Permissions perms = QFile::permissions(path);
2 ✔
1379
  if (!perms.testFlag(QFile::WriteUser) &&
1 ✔
1380
      QFile::setPermissions(path, perms | QFile::WriteUser) &&
3 ✔
1381
      QFile::remove(path)) {
1 ✔
1382
    return true;
1383
  }
1384
  qCWarning(lcQtPass) << "Could not remove" << path;
4 ✔
1385
  return false;
2 ✔
1386
}
1387

1388
} // namespace
1389

1390
auto Util::removeTree(const QString &dir) -> bool {
23 ✔
1391
  // A trailing separator makes lstat follow a link ("link/" is the target
1392
  // directory); the link itself is what this is about.
1393
  const QString path = QDir::cleanPath(dir);
23 ✔
1394
  const QFileInfo top(path);
23 ✔
1395
  if (isLink(top)) {
23 ✔
1396
    // rm -rf on a link removes the link.
1397
    return QFile::remove(path) || QDir().rmdir(path);
16 ✔
1398
  }
1399
  if (!top.isDir()) {
9 ✔
1400
    return false;
1401
  }
1402
  bool ok = true;
1403
  const QFileInfoList entries =
1404
      QDir(path).entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
16 ✔
1405
                                   QDir::System | QDir::NoDotAndDotDot,
1406
                               QDir::Name);
8 ✔
1407
  for (const QFileInfo &entry : entries) {
24 ✔
1408
    const bool removed = entry.isDir() && !isLink(entry)
22 ✔
1409
                             ? removeTree(entry.filePath())
18 ✔
1410
                             : removeEntry(entry);
14 ✔
1411
    ok = removed && ok;
16 ✔
1412
  }
1413
  return ok && QDir().rmdir(path);
13 ✔
1414
}
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