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

IJHack / QtPass / 46541594595

01 Dec 2026 12:00AM UTC coverage: 94.541% (-0.02%) from 94.557%
46541594595

push

github

web-flow
Split Util::repositoryPassClimbsTo and ImitatePass::finishReencrypt (#2424)

Third batch for #2157 (lizard CCN 39 and 37). The code and its comments
move into helpers:

- util.cpp, file-local next to openFollowedRegularFile(): gitWalkStart()
  (the real path git walks from), passCeilingFor() (pass's
  GIT_CEILING_DIRECTORIES as git reads it), and the former lambdas
  isGitDirectory() and repositoryAt(), with the Found enum at namespace
  scope.
- ImitatePass: reportFailedEntries(), settleAutoPushHold() (the removed-
  reader record and the auto-push hold, returning whether an entry is
  still read by someone removed), reportReencryptOutcome() (status line
  and the push after a run) and rememberUnexpected().

No behaviour change. repositoryPassClimbsTo 39 -> 12, finishReencrypt
37 -> 13; every new helper is below 15.

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

78 of 79 new or added lines in 2 files covered. (98.73%)

3 existing lines in 1 file now uncovered.

11378 of 12035 relevant lines covered (94.54%)

24057.33 hits per line

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

94.27
/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 <cstring>
28
#include <memory>
29
#include <optional>
30
#include <vector>
31

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

46
#include "qtpasslogging.h"
47

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

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

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

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

104
auto Util::isAbsoluteFsPath(const QString &path) -> bool {
144,449 ✔
105
  return QDir::isAbsolutePath(path) && !path.startsWith(QLatin1Char(':'));
144,449 ✔
106
}
107

108
auto Util::joinPath(const QString &dir, const QString &name) -> QString {
1,421 ✔
109
  if (name.startsWith(QLatin1Char(':'))) {
1,421 ✔
110
    return dir.endsWith(QLatin1Char('/')) ? dir + name
5 ✔
111
                                          : dir + QLatin1Char('/') + name;
6 ✔
112
  }
113
  return QDir(dir).filePath(name);
1,416 ✔
114
}
115

116
auto Util::normalizeFolderPath(const QString &path) -> QString {
588 ✔
117
  QString normalizedPath = path;
118
  if (!normalizedPath.endsWith('/')) {
588 ✔
119
    normalizedPath += '/';
569 ✔
120
  }
121
  return normalizedPath;
588 ✔
122
}
123

124
void Util::applyPassProcessDefaults() {
1 ✔
125
  // pass unsets these before it runs git: a GIT_DIR inherited from the
126
  // environment (QtPass started from a git hook, or an IDE terminal) would
127
  // send every commit and push to that repository instead of the store.
128
  for (const char *variable :
11 ✔
129
       {"GIT_DIR", "GIT_WORK_TREE", "GIT_NAMESPACE", "GIT_INDEX_FILE",
130
        "GIT_INDEX_VERSION", "GIT_OBJECT_DIRECTORY", "GIT_COMMON_DIR",
131
        // QtPass sets GIT_LITERAL_PATHSPECS for its git; git refuses a
132
        // pathspec when one of these is set as well.
133
        "GIT_GLOB_PATHSPECS", "GIT_NOGLOB_PATHSPECS", "GIT_ICASE_PATHSPECS"}) {
11 ✔
134
    qunsetenv(variable);
10 ✔
135
  }
136
  Executor::setChildUmask(
1 ✔
137
      passUmask(qEnvironmentVariable("PASSWORD_STORE_UMASK")));
1 ✔
138
}
1 ✔
139

140
auto Util::passUmask(const QString &value) -> int {
11 ✔
141
  // Taken as it is, as bash's umask builtin (which pass hands it to) takes
142
  // it: " 022" is no umask there either. pass then keeps the session's;
143
  // QtPass falls back to 077.
144
  // anchoredPattern(), not ^...$: $ also matches before a final newline.
145
  static const QRegularExpression octal(
146
      QRegularExpression::anchoredPattern(QStringLiteral("[0-7]{1,4}")));
35 ✔
147
  if (!octal.match(value).hasMatch()) {
11 ✔
148
    return 077;
149
  }
150
  return value.toInt(nullptr, 8);
4 ✔
151
}
152

153
auto Util::gitCeiling(const QString &store) -> QString {
2,599 ✔
154
  if (store.isEmpty()) {
2,599 ✔
155
    return {};
×
156
  }
157
  QString path = QFileInfo(store).canonicalFilePath();
2,599 ✔
158
  if (path.isEmpty()) {
2,599 ✔
159
    path = QDir::cleanPath(QDir(store).absolutePath());
×
160
  }
161
  return QFileInfo(path).absolutePath();
2,599 ✔
162
}
163

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

191
/**
192
 * @brief Where git starts its walk for @p store: the real path of its
193
 * nearest existing folder, with the part that does not exist yet appended.
194
 * @param store The store as pass gets it (`PASSWORD_STORE_DIR`).
195
 * @return The path, or empty when no part of it exists.
196
 */
197
auto gitWalkStart(const QString &store) -> QString {
34 ✔
198
  // git walks up from the real folder, so the real path is the one to walk,
199
  // and for a store that does not exist yet the one it will have: its
200
  // nearest existing folder resolved, the rest appended. By the raw string:
201
  // QDir and QFileInfo clean a path by name, and "link/.." is the parent
202
  // of the link's target, not the folder the link is in. On macOS the
203
  // temporary folder is under /var, a link to /private/var.
204
  // Absolute as git means it, a leading "/" (Qt would take ":name" for a
205
  // resource path).
206
  QString path =
207
      store.startsWith(u'/') ? store : QDir::currentPath() + u'/' + store;
68 ✔
208
  while (path.size() > 1 && path.endsWith(u'/')) {
37 ✔
209
    path.chop(1);
3 ✔
210
  }
211
  QString rest;
34 ✔
212
  while (!QFileInfo::exists(path)) {
44 ✔
213
    const qsizetype slash = path.lastIndexOf(u'/');
10 ✔
214
    if (slash < 0) {
10 ✔
215
      return {};
×
216
    }
217
    const QString name = path.mid(slash + 1);
10 ✔
218
    rest = rest.isEmpty() ? name : name + u'/' + rest;
24 ✔
219
    path = slash == 0 ? QStringLiteral("/") : path.left(slash);
20 ✔
220
  }
221
  const QString real = QFileInfo(path).canonicalFilePath();
34 ✔
222
  const QString start = real.isEmpty() ? QDir::cleanPath(path) : real;
34 ✔
223
  return rest.isEmpty() ? start : QDir::cleanPath(start + u'/' + rest);
72 ✔
224
}
225

226
/**
227
 * @brief The ceiling git stops below when pass runs it for @p store
228
 * (`GIT_CEILING_DIRECTORIES=$PREFIX/..`), as git reads that list.
229
 * @param store The store as pass gets it.
230
 * @param start Where git starts its walk (gitWalkStart()).
231
 * @return The longest entry @p start lies under, or empty for none.
232
 */
233
auto passCeilingFor(const QString &store, const QString &start) -> QString {
34 ✔
234
  // The pieces of pass's ceiling as git takes them (setup.c,
235
  // canonicalize_ceiling_entry): relative ones are dropped, the rest
236
  // resolved, one that cannot be resolved is dropped; after an empty piece
237
  // ("::") they are kept exactly as written. A piece can still be a real
238
  // ceiling: "/repo/:vault/.." holds "/repo/".
239
  QString ceiling;
34 ✔
240
  bool afterEmpty = false;
241
  for (const QString &piece :
242
       (store + QStringLiteral("/..")).split(QLatin1Char(':'))) {
173 ✔
243
    if (piece.isEmpty()) {
71 ✔
244
      afterEmpty = true;
245
      continue;
35 ✔
246
    }
247
    if (!piece.startsWith(u'/')) {
69 ✔
248
      continue;
33 ✔
249
    }
250
    const QString entry =
251
        afterEmpty ? piece : QFileInfo(piece).canonicalFilePath();
37 ✔
252
    // git stops below the longest entry the store lies under
253
    // (longest_ancestor_length: "/" is above everything).
254
    const QString under = entry == u'/' ? entry : entry + u'/';
36 ✔
255
    if (!entry.isEmpty() && start.startsWith(under) &&
36 ✔
256
        entry.size() > ceiling.size()) {
257
      ceiling = entry;
4 ✔
258
    }
259
  }
260
  return ceiling;
34 ✔
261
}
262

263
/**
264
 * @brief Whether git takes @p candidate for a repository (setup.c,
265
 * is_git_directory()): HEAD naming a ref or an object, objects/ and refs/.
266
 * An empty or broken .git is passed by, as git passes it by.
267
 * @param candidate The folder.
268
 * @return Whether it is a repository to git.
269
 */
270
auto isGitDirectory(const QString &candidate) -> bool {
101 ✔
271
  const QDir dir(candidate);
101 ✔
272
  if (!QFileInfo(dir.filePath(QStringLiteral("objects"))).isDir() ||
229 ✔
273
      !QFileInfo(dir.filePath(QStringLiteral("refs"))).isDir()) {
182 ✔
274
    return false;
275
  }
276
  // As git (setup.c, validate_headref()): a HEAD that is a link counts
277
  // when the link text starts with "refs/", without reading what it
278
  // names, and not otherwise. Anything else is read only when it is a
279
  // regular file, without waiting: a HEAD that is a FIFO (a pushed commit
280
  // can carry a link to one, or to a device) blocked the open and the
281
  // read on the GUI thread when Settings opened.
282
  const QString headPath = dir.filePath(QStringLiteral("HEAD"));
54 ✔
283
  if (const QFileInfo headInfo(headPath); headInfo.isSymLink()) {
27 ✔
284
    // The link text as stored (Qt 6.6), not the path it resolves to.
285
    return headInfo.readSymLink().startsWith(QLatin1String("refs/"));
3 ✔
286
  }
27 ✔
287
  QFile head;
24 ✔
288
  if (!openFollowedRegularFile(headPath, head)) {
24 ✔
289
    return false;
290
  }
291
  static const QRegularExpression valid(
292
      QStringLiteral("^(?:ref: refs/|[0-9a-f]{40}\\s*$|[0-9a-f]{64}\\s*$)"));
28 ✔
293
  return valid.match(QString::fromUtf8(head.read(256))).hasMatch();
72 ✔
294
}
125 ✔
295

296
/// What git finds at one folder of its walk.
297
enum class Found {
298
  Nothing,    ///< No repository: git goes on up.
299
  Repository, ///< A repository: git stops and uses it.
300
  Refused     ///< A .git git cannot use: git stops with an error.
301
};
302

303
/**
304
 * @brief What git finds at @p dir: a .git folder that is a repository,
305
 * or a .git file naming one (`gitdir: ...`), is the repository. Any other
306
 * .git file stops git with an error, and pass then commits nothing; a .git
307
 * folder that is no repository is passed by.
308
 * @param dir The folder.
309
 * @return What git does there.
310
 */
311
auto repositoryAt(const QString &dir) -> Found {
98 ✔
312
  const QString dotGit = QDir(dir).filePath(QStringLiteral(".git"));
196 ✔
313
  const QFileInfo info(dotGit);
98 ✔
314
  if (info.isDir()) {
98 ✔
315
    return isGitDirectory(dotGit) ? Found::Repository : Found::Nothing;
24 ✔
316
  }
317
  if (!info.exists()) {
74 ✔
318
    return Found::Nothing;
319
  }
320
  // The same for a .git file (or a link to one): a FIFO there blocked in
321
  // open().
322
  QFile file;
7 ✔
323
  if (!openFollowedRegularFile(dotGit, file)) {
7 ✔
324
    return Found::Refused;
325
  }
326
  const QString line = QString::fromUtf8(file.readLine(4096)).trimmed();
7 ✔
327
  if (!line.startsWith(QLatin1String("gitdir: "))) {
7 ✔
328
    return Found::Refused;
329
  }
330
  const QString target = line.mid(8);
5 ✔
331
  return isGitDirectory(target.startsWith(u'/') ? target
10 ✔
332
                                                : QDir(dir).filePath(target))
8 ✔
333
             ? Found::Repository
5 ✔
334
             : Found::Refused;
335
}
98 ✔
336
} // namespace
337
#endif
338

339
auto Util::repositoryPassClimbsTo(const QString &store) -> QString {
44 ✔
340
#ifdef Q_OS_WIN
341
  Q_UNUSED(store);
342
  return {};
343
#else
344
  if (!store.contains(QLatin1Char(':'))) {
44 ✔
345
    return {};
10 ✔
346
  }
347
  const QString start = gitWalkStart(store);
34 ✔
348
  if (start.isEmpty()) {
34 ✔
NEW
349
    return {};
×
350
  }
351
  const QString ceiling = passCeilingFor(store, start);
34 ✔
352
  // The store's own repository comes first; only without one does git look
353
  // further up, and never into the ceiling. By name from here: the real
354
  // path holds no link or "..".
355
  for (QString dir = start;;) {
356
    switch (repositoryAt(dir)) {
98 ✔
357
    case Found::Repository:
358
      return dir == start ? QString() : dir;
54 ✔
359
    case Found::Refused:
3 ✔
360
      return {};
3 ✔
361
    case Found::Nothing:
362
      break;
363
    }
364
    // A bare repository: git stops there, and pass, finding no work tree,
365
    // commits nothing.
366
    if (isGitDirectory(dir)) {
72 ✔
367
      return {};
1 ✔
368
    }
369
    const QString up = QFileInfo(dir).absolutePath();
71 ✔
370
    if (up == dir || up == ceiling) {
71 ✔
371
      return {};
7 ✔
372
    }
373
    dir = up;
64 ✔
374
  }
375
#endif
376
}
377

378
namespace {
379
/// setGitOwnerForTests(): who owns "the user's own" store, when set.
380
std::optional<uint> s_gitOwnerForTests;
381
} // namespace
382

383
void Util::setGitOwnerForTests(std::optional<uint> user) {
4 ✔
384
  s_gitOwnerForTests = user;
4 ✔
385
}
4 ✔
386

387
/// setBeforePlacingForTests(): called between staging and the rename.
388
std::function<void(const QString &)> s_beforePlacingForTests;
389

390
void Util::setBeforePlacingForTests(std::function<void(const QString &)> hook) {
3 ✔
391
  s_beforePlacingForTests = std::move(hook);
3 ✔
392
}
3 ✔
393

394
#ifdef Q_OS_UNIX
395
namespace {
396
/**
397
 * @brief Whether git's `safe.directory` trusts the repository at @p root,
398
 * as git's ownership check would judge it in place of ownership.
399
 *
400
 * Read as git reads it: only from system, global and command-line
401
 * configuration (a repository cannot vouch for itself), in order. `*`
402
 * trusts every repository, an empty value forgets the entries before it,
403
 * a path ending in a slash and `*` trusts what lies below it, and any other
404
 * absolute path trusts that one folder, compared after resolving links.
405
 * Relative entries (including git's ".") and paths that do not exist trust
406
 * nothing.
407
 * @param root The store's canonical path.
408
 * @param git The git executable; "git" from PATH when empty.
409
 * @return True when an entry names @p root; false when none does or git
410
 *         cannot be asked.
411
 */
412
auto isSafeDirectory(const QString &root, const QString &git) -> bool {
23 ✔
413
  // Outside any repository, as git reads its protected config: no
414
  // repository's own config, and no includeIf "gitdir:" or "onbranch:"
415
  // that matches (a GIT_DIR, even one that cannot exist, would be matched
416
  // against them, and one that cannot exist makes git config fail). From
417
  // "/", which a user cannot make a repository; a local scope is dropped
418
  // below in any case.
419
  QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
23 ✔
420
  env.remove(QStringLiteral("GIT_DIR"));
46 ✔
421
  env.remove(QStringLiteral("GIT_WORK_TREE"));
46 ✔
422
  env.remove(QStringLiteral("GIT_COMMON_DIR"));
46 ✔
423
  // git config alone reads GIT_CONFIG in place of the system and global
424
  // configuration (and reports it as "command"); the ownership check never
425
  // reads it.
426
  env.remove(QStringLiteral("GIT_CONFIG"));
46 ✔
427
  QProcess process;
23 ✔
428
  process.setProcessEnvironment(env);
23 ✔
429
  process.setWorkingDirectory(QStringLiteral("/"));
46 ✔
430
  // Bounded: Git calls wait for this, and a git that never answers trusts
431
  // nothing.
432
  constexpr int kQueryTimeoutMs = 5000;
433
  QString out;
23 ✔
434
  if (Executor::executeBlocking(
184 ✔
435
          process, git.isEmpty() ? QStringLiteral("git") : git,
46 ✔
436
          {QStringLiteral("config"), QStringLiteral("--show-scope"),
23 ✔
437
           QStringLiteral("--type=path"), QStringLiteral("--get-all"),
23 ✔
438
           QStringLiteral("safe.directory")},
23 ✔
439
          QString(), &out, nullptr, nullptr, kQueryTimeoutMs) != 0) {
46 ✔
440
    return false;
441
  }
442
  bool safe = false;
443
  const QStringList lines = out.split(QLatin1Char('\n'));
14 ✔
444
  for (const QString &line : lines) {
47 ✔
445
    const qsizetype tab = line.indexOf(QLatin1Char('\t'));
33 ✔
446
    if (tab < 0) {
33 ✔
447
      continue;
18 ✔
448
    }
449
    const QString scope = line.left(tab);
19 ✔
450
    if (scope != QLatin1String("system") && scope != QLatin1String("global") &&
19 ✔
451
        scope != QLatin1String("command")) {
1 ✔
452
      continue;
×
453
    }
454
    const QString value = line.mid(tab + 1);
19 ✔
455
    if (value.isEmpty()) {
19 ✔
456
      safe = false;
457
    } else if (value == QLatin1String("*")) {
17 ✔
458
      safe = true;
459
    } else if (!QDir::isAbsolutePath(value)) {
13 ✔
460
      continue;
3 ✔
461
    } else if (value.endsWith(QLatin1String("/*"))) {
10 ✔
462
      const QString base = value.chopped(2);
463
      QString prefix = QFileInfo(base.isEmpty() ? QStringLiteral("/") : base)
12 ✔
464
                           .canonicalFilePath();
3 ✔
465
      if (prefix.isEmpty()) {
3 ✔
466
        continue;
467
      }
468
      if (!prefix.endsWith(QLatin1Char('/'))) {
2 ✔
469
        prefix += QLatin1Char('/');
2 ✔
470
      }
471
      safe = safe || root.startsWith(prefix);
2 ✔
472
    } else {
473
      const QString named = QFileInfo(value).canonicalFilePath();
7 ✔
474
      safe = safe || (!named.isEmpty() && named == root);
7 ✔
475
    }
476
  }
477
  return safe;
478
}
23 ✔
479
} // namespace
480
#endif
481

482
void Util::requireExplicitBareRepository(QProcessEnvironment &env) {
557 ✔
483
  const QString key = QStringLiteral("safe.bareRepository");
557 ✔
484
  const QString value = QStringLiteral("explicit");
557 ✔
485
  const QString countText = env.value(QStringLiteral("GIT_CONFIG_COUNT"));
1,114 ✔
486
  bool ok = countText.isEmpty();
557 ✔
487
  int count = countText.isEmpty() ? 0 : countText.toInt(&ok);
557 ✔
488
  if (!ok || count < 0) {
557 ✔
489
    // git refuses to start with a malformed count, so the entries it was
490
    // meant to cover never applied: start the list afresh.
491
    count = 0;
492
  }
493
  // Keys and these values are case-insensitive to git; the last entry wins.
494
  QString last;
557 ✔
495
  for (int i = 0; i < count; ++i) {
913 ✔
496
    if (env.value(QStringLiteral("GIT_CONFIG_KEY_%1").arg(i))
712 ✔
497
            .compare(key, Qt::CaseInsensitive) == 0) {
356 ✔
498
      last = env.value(QStringLiteral("GIT_CONFIG_VALUE_%1").arg(i));
628 ✔
499
    }
500
  }
501
  // git reads GIT_CONFIG_PARAMETERS (`git -c`) after the numbered entries,
502
  // so when that names the key at all, explicit must be its last entry. Not
503
  // parsed: the string must end in this separate token, which a value
504
  // cannot fake (a quote inside one is written '\'', so it never follows a
505
  // blank); appending once too often does no harm.
506
  const QString parameters = env.value(QStringLiteral("GIT_CONFIG_PARAMETERS"));
1,114 ✔
507
  const QString explicitEntry =
508
      QStringLiteral("'safe.bareRepository=explicit'");
557 ✔
509
  if (parameters.contains(QLatin1String("barerepository"),
1,114 ✔
510
                          Qt::CaseInsensitive) &&
16 ✔
511
      parameters != explicitEntry &&
571 ✔
512
      !parameters.endsWith(QLatin1Char(' ') + explicitEntry)) {
571 ✔
513
    env.insert(QStringLiteral("GIT_CONFIG_PARAMETERS"),
12 ✔
514
               parameters + QLatin1Char(' ') + explicitEntry);
12 ✔
515
  }
516
  if (last.compare(value, Qt::CaseInsensitive) == 0) {
557 ✔
517
    return;
518
  }
519
  env.insert(QStringLiteral("GIT_CONFIG_KEY_%1").arg(count), key);
492 ✔
520
  env.insert(QStringLiteral("GIT_CONFIG_VALUE_%1").arg(count), value);
492 ✔
521
  env.insert(QStringLiteral("GIT_CONFIG_COUNT"), QString::number(count + 1));
492 ✔
522
}
523

524
auto Util::gitStoreVariables(const QString &store, const QString &git,
2,599 ✔
525
                             std::optional<uint> asUser)
526
    -> QList<std::pair<QString, QString>> {
527
  const QString ceiling = gitCeiling(store);
2,599 ✔
528
  if (ceiling.isEmpty()) {
2,599 ✔
529
    return {};
×
530
  }
531
  QList<std::pair<QString, QString>> vars{
532
      {QStringLiteral("GIT_CEILING_DIRECTORIES"), ceiling}};
7,797 ✔
533
#ifdef Q_OS_WIN
534
  const QChar separator = QLatin1Char(';');
535
#else
536
  const QChar separator = QLatin1Char(':');
537
#endif
538
  // git splits the ceiling list on the separator: "/home/a:b" would be
539
  // "/home/a" and "b", neither of them the parent, and git would climb.
540
  if (ceiling.contains(separator)) {
2,599 ✔
541
    QString root = QFileInfo(store).canonicalFilePath();
28 ✔
542
    if (root.isEmpty()) {
28 ✔
543
      root = QDir::cleanPath(QDir(store).absolutePath());
×
544
    }
545
    QString gitDir = QDir(root).filePath(QStringLiteral(".git"));
56 ✔
546
#ifdef Q_OS_UNIX
547
    // What discovery's ownership check would have looked at: the work tree,
548
    // the .git, and the directory a gitfile names. Not the user's: no
549
    // repository at all, under a path that cannot be created (its parent
550
    // is a device), rather than another user's hooks run as this one.
551
    const uint me = asUser.value_or(
552
        s_gitOwnerForTests.value_or(static_cast<uint>(::geteuid())));
28 ✔
553
    const auto ownedOrMissing = [me](const QString &path) {
33 ✔
554
      const QFileInfo info(path);
33 ✔
555
      return !info.exists() || info.ownerId() == me;
66 ✔
556
    };
33 ✔
557
    bool owned = ownedOrMissing(root) && ownedOrMissing(gitDir);
28 ✔
558
    if (owned && QFileInfo(gitDir).isFile()) {
28 ✔
559
      QFile gitFile(gitDir);
×
560
      if (gitFile.open(QIODevice::ReadOnly)) {
×
561
        const QString line =
562
            QString::fromUtf8(gitFile.readLine(4096)).trimmed();
×
563
        if (line.startsWith(QLatin1String("gitdir:"))) {
×
564
          const QString target = line.mid(7).trimmed();
×
565
          owned = ownedOrMissing(QDir(root).absoluteFilePath(target));
×
566
        }
567
      }
568
    }
×
569
    // Or trusted as git would trust it in place of ownership.
570
    if (!owned && !isSafeDirectory(root, git)) {
28 ✔
571
      gitDir = QStringLiteral("/dev/null/.git");
14 ✔
572
    }
573
#else
574
    // Git for Windows runs the same ownership check during discovery, on
575
    // SIDs, with its own rules for the Administrators group; this pin skips
576
    // it there and does not repeat it (a known gap, #2089).
577
    Q_UNUSED(git);
578
    Q_UNUSED(asUser);
579
#endif
580
    vars.append({QStringLiteral("GIT_DIR"), gitDir});
56 ✔
581
    vars.append({QStringLiteral("GIT_WORK_TREE"), root});
56 ✔
582
  }
583
  return vars;
584
}
2,599 ✔
585

586
auto Util::mkpathForStore(const QString &path) -> bool {
54 ✔
587
  const QString clean = QDir::cleanPath(QDir(path).absolutePath());
108 ✔
588
  if (QFileInfo(clean).isDir()) {
54 ✔
589
    return true;
590
  }
591
  const QString parent = QFileInfo(clean).absolutePath();
31 ✔
592
  if (parent != clean && !mkpathForStore(parent)) {
31 ✔
593
    return false;
594
  }
595
#ifdef Q_OS_UNIX
596
  // The store's umask, as git and gpg get it: a store shared with a group
597
  // (PASSWORD_STORE_UMASK=007) gets group folders, the default owner-only.
598
  const int umask = Executor::childUmask() >= 0 ? Executor::childUmask() : 077;
28 ✔
599
  QFile::Permissions permissions;
600
  const QFile::Permission bits[] = {
28 ✔
601
      QFile::ReadOwner, QFile::WriteOwner, QFile::ExeOwner,
602
      QFile::ReadGroup, QFile::WriteGroup, QFile::ExeGroup,
603
      QFile::ReadOther, QFile::WriteOther, QFile::ExeOther};
604
  for (int i = 0; i < 9; ++i) {
280 ✔
605
    if ((umask & (0400 >> i)) == 0) {
252 ✔
606
      permissions |= bits[i];
90 ✔
607
    }
608
  }
609
  // mkdir() still takes QtPass's own umask off (a session's 022 would drop
610
  // the group's write bit); set the mode exactly afterwards. That only ever
611
  // widens it to what was asked, never past.
612
  const bool made = QDir().mkdir(clean, permissions) &&
56 ✔
613
                    QFile::setPermissions(clean, permissions);
23 ✔
614
#else
615
  // Windows: permissions here would become an ACL of their own, replacing
616
  // the inherited one; the folder takes its parent's, as before.
617
  const bool made = QDir().mkdir(clean);
618
#endif
619
  return made || QFileInfo(clean).isDir();
28 ✔
620
}
621

622
auto Util::findBinaryInPath(const QString &binary) -> QString {
576 ✔
623
  if (binary.isEmpty()) {
576 ✔
624
    return {};
1 ✔
625
  }
626

627
  initialiseEnvironment();
575 ✔
628

629
  const QStringList dirs =
630
      _env.value(QStringLiteral("PATH"))
1,150 ✔
631
          .split(QDir::listSeparator(), Qt::SkipEmptyParts);
575 ✔
632
  QString ret;
575 ✔
633
  if (QDir::fromNativeSeparators(binary).contains(u'/')) {
575 ✔
634
    // An explicit path is not a PATH search: an absolute path is checked
635
    // as-is, a relative one is resolved against the PATH directories. The
636
    // directory-list overload refuses such names, so handle them here.
637
    if (QDir::isAbsolutePath(binary)) {
3 ✔
638
      ret = QStandardPaths::findExecutable(binary);
4 ✔
639
    } else if (!dirs.isEmpty()) {
1 ✔
640
      ret = QStandardPaths::findExecutable(binary, dirs);
2 ✔
641
    }
642
  } else {
643
    ret = findBinaryInPath(binary, dirs);
1,144 ✔
644
  }
645
#ifdef Q_OS_WIN
646
  if (ret.isEmpty()) {
647
    // Cache per-binary WSL lookup result — the wsl --version probe is a
648
    // blocking subprocess that can run several times per session for
649
    // missing binaries; once decided, the answer doesn't change at runtime.
650
    static QHash<QString, QString> wslBinaryCache;
651
    const bool hasWhitespace =
652
        std::any_of(binary.cbegin(), binary.cend(),
653
                    [](const QChar ch) { return ch.isSpace(); });
654
    if (!hasWhitespace) {
655
      auto cached = wslBinaryCache.constFind(binary);
656
      if (cached != wslBinaryCache.constEnd()) {
657
        ret = cached.value();
658
      } else {
659
        QString wslCommand = QStringLiteral("wsl ") + binary;
660
        qCDebug(lcQtPass)
661
            << "Util::findBinaryInPath(): falling back to WSL for binary"
662
            << binary;
663
        QString out, err;
664
        QString cachedResult;
665
        if (Executor::executeBlocking(wslCommand, {"--version"}, &out, &err) ==
666
                0 &&
667
            !out.isEmpty() && err.isEmpty()) {
668
          qCDebug(lcQtPass)
669
              << "Util::findBinaryInPath(): using WSL binary" << wslCommand;
670
          cachedResult = wslCommand;
671
        }
672
        wslBinaryCache.insert(binary, cachedResult);
673
        ret = cachedResult;
674
      }
675
    }
676
  }
677
#endif
678

679
  return ret;
680
}
681

682
// Bare names only: QStandardPaths::findExecutable() returns an absolute binary
683
// without consulting searchPaths, and a relative one with ".." could escape
684
// them.
685
auto Util::findBinaryInPath(const QString &binary,
586 ✔
686
                            const QStringList &searchPaths) -> QString {
687
  if (binary.isEmpty() || QDir::fromNativeSeparators(binary).contains(u'/')) {
1,171 ✔
688
    return {};
4 ✔
689
  }
690
  QStringList dirs;
582 ✔
691
  dirs.reserve(searchPaths.size());
582 ✔
692
  for (const QString &dir : searchPaths) {
9,070 ✔
693
    if (!dir.isEmpty()) {
8,488 ✔
694
      dirs.append(dir);
695
    }
696
  }
697
  if (dirs.isEmpty()) {
582 ✔
698
    // QStandardPaths::findExecutable() treats an empty list as "use PATH".
699
    return {};
4 ✔
700
  }
701
  return QStandardPaths::findExecutable(binary, dirs);
578 ✔
702
}
703

704
auto Util::configIsValid(const AppSettings &s) -> bool {
303 ✔
705
  const QString configFilePath = QDir(s.passStore).filePath(".gpg-id");
606 ✔
706
  if (!QFile(configFilePath).exists()) {
303 ✔
707
    return false;
708
  }
709

710
  const QString executable = s.usePass ? s.passExecutable : s.gpgExecutable;
218 ✔
711

712
  if (const auto wsl = Executor::parseWslCommand(executable)) {
218 ✔
713
    // Probe WSL once per session — availability doesn't change at runtime
714
    // and the executeBlocking call is a blocking subprocess.
715
    static const bool wslAvailable = [&wsl]() {
1 ✔
716
      QString out;
1 ✔
717
      QString err;
1 ✔
718
      return Executor::executeBlocking(wsl->launcher,
3 ✔
719
                                       {QStringLiteral("--version")}, &out,
1 ✔
720
                                       &err) == 0 &&
×
721
             !out.isEmpty() && err.isEmpty();
2 ✔
722
    }();
1 ✔
723
    if (wslAvailable) {
1 ✔
724
      return true;
725
    }
726
  }
727
  return QFile(executable).exists();
218 ✔
728
}
729

730
auto Util::endsWithGpg() -> const QRegularExpression & {
142,241 ✔
731
  static const QRegularExpression expr{R"(\.gpg$)"};
142,248 ✔
732
  return expr;
142,241 ✔
733
}
734

735
// Stops at whitespace, quotes and brackets so a URL on its own line keeps no
736
// line break. file:/// is excluded on purpose (local, not network); the test
737
// relies on that.
738
auto Util::protocolRegex() -> const QRegularExpression & {
161 ✔
739
  static const QRegularExpression regex{
740
      R"(((?:https?|ftp|ssh|sftp|ftps|webdav|webdavs)://[^"\s<>\)\]\[]+))"};
166 ✔
741
  return regex;
161 ✔
742
}
743

744
namespace {
745
/**
746
 * @brief The length of a URL's authority, found as QUrl finds it.
747
 *
748
 * QUrl takes the text before the first ':' that comes before any '/', '?'
749
 * or '#' as the scheme when it is one (a letter, then letters, digits,
750
 * '+', '-' or '.'); the rest starts there, or at the start otherwise. An
751
 * authority follows a "//" at that point and runs to the first '/', '?'
752
 * or '#'. So "//host" has one too, and a "://" later in the text does not
753
 * start it.
754
 * @param url The candidate URL.
755
 * @return The authority's length, or -1 when there is none.
756
 */
757
auto authorityLength(const QString &url) -> qsizetype {
124 ✔
758
  const auto endsPart = [](QChar c) {
759
    return c == QLatin1Char('/') || c == QLatin1Char('?') ||
760
           c == QLatin1Char('#');
761
  };
762
  const auto isAsciiLetter = [](QChar c) {
763
    return (c >= QLatin1Char('a') && c <= QLatin1Char('z')) ||
467 ✔
764
           (c >= QLatin1Char('A') && c <= QLatin1Char('Z'));
9 ✔
765
  };
766
  qsizetype colon = -1;
767
  for (qsizetype i = 0; i < url.size() && !endsPart(url.at(i)); ++i) {
857 ✔
768
    if (url.at(i) == QLatin1Char(':')) {
830 ✔
769
      colon = i;
770
      break;
771
    }
772
  }
773
  bool scheme = colon > 0 && isAsciiLetter(url.at(0));
124 ✔
774
  for (qsizetype i = 1; scheme && i < colon; ++i) {
494 ✔
775
    const QChar c = url.at(i);
776
    scheme =
777
        isAsciiLetter(c) || (c >= QLatin1Char('0') && c <= QLatin1Char('9')) ||
9 ✔
778
        c == QLatin1Char('+') || c == QLatin1Char('-') || c == QLatin1Char('.');
7 ✔
779
  }
780
  const qsizetype hier = scheme ? colon + 1 : 0;
124 ✔
781
  if (url.mid(hier, 2) != QLatin1String("//")) {
248 ✔
782
    return -1;
783
  }
784
  qsizetype end = hier + 2;
92 ✔
785
  while (end < url.size() && !endsPart(url.at(end))) {
201,621 ✔
786
    ++end;
201,529 ✔
787
  }
788
  return end - (hier + 2);
92 ✔
789
}
790
} // namespace
791

792
auto Util::isLaunchableWebUrl(const QString &value) -> bool {
128 ✔
793
  const QString trimmed = value.trimmed();
794
  if (trimmed.isEmpty()) {
128 ✔
795
    return false;
796
  }
797
  // Reject control characters first, before QUrl normalisation can hide a
798
  // CR/LF/NUL injection into the OS URL handler.
799
  for (const QChar &c : trimmed) {
264,770 ✔
800
    if (c == QLatin1Char('\r') || c == QLatin1Char('\n') ||
801
        c == QChar(QChar::Null)) {
802
      return false;
803
    }
804
  }
805
  // QUrl runs the host through Unicode normalisation, which takes time in
806
  // the square of a run of combining marks out of canonical order: one line
807
  // of an entry kept the window busy for minutes. A host has at most 253
808
  // characters and a port six more, so a longer authority is no web
809
  // address anyway.
810
  constexpr qsizetype kMaxAuthority = 259;
811
  if (authorityLength(trimmed) > kMaxAuthority) {
124 ✔
812
    return false;
813
  }
814
  const QUrl url(trimmed, QUrl::StrictMode);
118 ✔
815
  if (!url.isValid()) {
118 ✔
816
    return false;
817
  }
818
  const QString scheme = url.scheme().toLower();
103 ✔
819
  if (scheme != QLatin1String("http") && scheme != QLatin1String("https")) {
103 ✔
820
    return false;
36 ✔
821
  }
822
  if (url.host().isEmpty()) {
134 ✔
823
    return false;
824
  }
825
  // Embedded userinfo (user:pass@host) would leak into browser history.
826
  if (!url.userName().isEmpty() || !url.password().isEmpty()) {
127 ✔
827
    return false;
828
  }
829
  return true;
830
}
118 ✔
831

832
auto Util::displayable(const QString &text, bool lineBreaks) -> QString {
32,332 ✔
833
  QString shown = text;
834
  for (qsizetype i = 0; i < shown.size(); ++i) {
21,564,820 ✔
835
    const char16_t u = shown.at(i).unicode();
836
    // A carriage return before a line feed is a Windows line end (git or
837
    // gpg output quoted in a message), not a character of its own.
838
    const bool lineEnd =
839
        lineBreaks && (u == u'\n' || (u == u'\r' && i + 1 < shown.size() &&
21,532,488 ✔
840
                                      shown.at(i + 1) == u'\n'));
841
    if ((u < 0x20 && u != u'\t' && !lineEnd) || (u >= 0x7f && u <= 0x9f) ||
21,532,488 ✔
842
        u == 0x2028 || u == 0x2029 || (u >= 0x202a && u <= 0x202e) ||
21,532,432 ✔
843
        (u >= 0x2066 && u <= 0x2069)) {
21,532,420 ✔
844
      shown[i] = QChar(QChar::ReplacementCharacter);
70 ✔
845
    }
846
  }
847
  return shown;
32,332 ✔
848
}
849

850
auto Util::linkifyUrls(const QString &text, bool *linked) -> QString {
157 ✔
851
  if (linked != nullptr) {
157 ✔
852
    *linked = false;
61 ✔
853
  }
854
  QString html;
157 ✔
855
  html.reserve(text.size());
157 ✔
856
  qsizetype lastIndex = 0;
857
  QRegularExpressionMatchIterator it = protocolRegex().globalMatch(text);
157 ✔
858
  while (it.hasNext()) {
205 ✔
859
    const QRegularExpressionMatch match = it.next();
48 ✔
860
    const QString url = match.captured(0);
48 ✔
861
    // Only plain ASCII becomes a link: the link text is the URL as stored,
862
    // and a right-to-left letter, a bidi control or a look-alike host in it
863
    // makes it read as another address than the one it opens. Such a URL
864
    // stays plain text; the open button still takes it.
865
    const bool plain = std::all_of(url.cbegin(), url.cend(), [](QChar c) {
866
      return c.unicode() > 0x20 && c.unicode() < 0x7f;
1,139 ✔
867
    });
868
    if (!plain || !isLaunchableWebUrl(url)) {
48 ✔
869
      // Not a web URL (or it carries credentials): leave it in the escaped
870
      // plain-text run instead of making it clickable.
871
      continue;
872
    }
873
    const qsizetype start = match.capturedStart(0);
32 ✔
874
    html += text.mid(lastIndex, start - lastIndex).toHtmlEscaped();
32 ✔
875
    const QString escapedUrl = url.toHtmlEscaped();
32 ✔
876
    html += QStringLiteral("<a href=\"%1\">%1</a>").arg(escapedUrl);
64 ✔
877
    lastIndex = match.capturedEnd(0);
32 ✔
878
    if (linked != nullptr) {
32 ✔
879
      *linked = true;
24 ✔
880
    }
881
  }
48 ✔
882
  html += text.mid(lastIndex).toHtmlEscaped();
157 ✔
883
  // With a link in it, no bidi embedding, override or isolate control is
884
  // drawn: an override earlier in the entry (U+202E) drew the link text
885
  // reversed, so it read as another address. Shown as U+FFFD, so the user
886
  // sees that something was there; the copy button still copies the value.
887
  if (linked != nullptr ? *linked : html.contains(QLatin1String("<a href="))) {
253 ✔
888
    for (QChar &c : html) {
3,442 ✔
889
      const char16_t u = c.unicode();
3,412 ✔
890
      if ((u >= 0x202A && u <= 0x202E) || (u >= 0x2066 && u <= 0x2069)) {
3,412 ✔
891
        c = QChar(QChar::ReplacementCharacter);
1 ✔
892
      }
893
    }
894
  }
895
  return html;
157 ✔
896
}
157 ✔
897

898
auto Util::isOtherBlockBreak(QChar c) -> bool {
5,345,484 ✔
899
  const char16_t u = c.unicode();
5,345,484 ✔
900
  return u == u'\r' || u == 0x2029 || u == 0xFDD0 || u == 0xFDD1;
5,345,484 ✔
901
}
902

903
auto Util::withoutOtherBlockBreaks(QString text) -> QString {
227 ✔
904
  for (QChar &c : text) {
564,387 ✔
905
    if (isOtherBlockBreak(c)) {
564,160 ✔
906
      c = QLatin1Char(' ');
8,002 ✔
907
    }
908
  }
909
  return text;
227 ✔
910
}
911

912
auto Util::hasLongUnbrokenRun(QStringView text) -> bool {
538 ✔
913
  qsizetype run = 0;
914
  for (const QChar c : text) {
11,196,749 ✔
915
    // A no-break space (U+00A0, U+2007, U+202F) is white space to
916
    // isSpace(), but Qt does not wrap at it.
917
    const char16_t u = c.unicode();
918
    const bool breaks =
919
        c.isSpace() && u != 0x00A0 && u != 0x2007 && u != 0x202F;
11,196,224 ✔
920
    run = breaks ? 0 : run + 1;
11,126,875 ✔
921
    if (run > kMaxUnbrokenRun) {
11,196,224 ✔
922
      return true;
923
    }
924
  }
925
  return false;
926
}
927

928
auto Util::plainToolTip(const QString &text) -> QString {
18,853 ✔
929
  // Escaped, with its white space kept: two names that differ only in it
930
  // must not read the same; a long run is cut as everywhere it is kept.
931
  return QStringLiteral("<p style=\"white-space: pre-wrap;\">") +
18,853 ✔
932
         boundSpaceRuns(displayable(text, false)).toHtmlEscaped() +
37,706 ✔
933
         QStringLiteral("</p>");
37,706 ✔
934
}
935

936
auto Util::shownName(const QString &name, qsizetype max) -> QString {
360 ✔
937
  QString line = displayable(name, false);
360 ✔
938
  line.replace(QLatin1Char('\t'), QLatin1Char(' '));
360 ✔
939
  if (line.size() <= max) {
360 ✔
940
    return line;
348 ✔
941
  }
942
  // Too short for an ellipsis between two ends: the head alone.
943
  if (max < 3) {
12 ✔
944
    qsizetype keep = std::max<qsizetype>(max, 0);
945
    if (keep > 0 && line.at(keep - 1).isHighSurrogate()) {
5 ✔
946
      --keep;
947
    }
948
    return line.left(keep);
5 ✔
949
  }
950
  qsizetype head = max / 3;
7 ✔
951
  if (line.at(head - 1).isHighSurrogate()) {
7 ✔
952
    --head;
953
  }
954
  qsizetype tail = max - max / 3 - 1;
7 ✔
955
  if (line.at(line.size() - tail).isLowSurrogate()) {
7 ✔
956
    --tail;
×
957
  }
958
  return line.left(head) + QChar(0x2026) + line.right(tail);
14 ✔
959
}
960

961
// One pass, no regex: a pattern such as \s{1001,} retries from every
962
// character of a shorter run, which is quadratic on an entry made of them.
963
// A tab or a line feed ends a run in Qt's layout as well, so it ends one
964
// here; \v and U+0085 do not, so they count.
965
auto Util::boundSpaceRuns(const QString &text) -> QString {
19,084 ✔
966
  QString bounded;
19,084 ✔
967
  // Text before this index is in bounded already, or dropped.
968
  qsizetype from = 0;
969
  qsizetype run = 0;
970
  for (qsizetype i = 0; i < text.size(); ++i) {
20,772,379 ✔
971
    const QChar ch = text.at(i);
972
    if (!ch.isSpace() || ch == QLatin1Char('\t') || ch == QLatin1Char('\n')) {
20,753,295 ✔
973
      run = 0;
974
      continue;
20,599,249 ✔
975
    }
976
    if (++run <= kMaxSpaceRun) {
154,046 ✔
977
      continue;
18,509 ✔
978
    }
979
    if (run == kMaxSpaceRun + 1) {
135,537 ✔
980
      bounded += QStringView(text).sliced(from, i - from);
6 ✔
981
    }
982
    from = i + 1;
135,537 ✔
983
  }
984
  if (from == 0) {
19,084 ✔
985
    return text;
986
  }
987
  bounded += QStringView(text).sliced(from);
988
  return bounded;
989
}
990

991
auto Util::newLinesRegex() -> const QRegularExpression & {
819 ✔
992
  static const QRegularExpression regex{"[\r\n]"};
828 ✔
993
  return regex;
819 ✔
994
}
995

996
// No content heuristics: a line rejected here is erased the next time .gpg-id
997
// is rewritten. A leading `-` is refused because the recipients also go
998
// positionally to `gpg --list-keys`, where it would parse as an option.
999
auto Util::isValidKeyId(const QString &keyId) -> bool {
6,477 ✔
1000
  return !keyId.isEmpty() && !keyId.startsWith('-');
6,477 ✔
1001
}
1002

1003
namespace {
1004
/**
1005
 * @brief Whether the walk can see what is in @p dir: read permission to list
1006
 * it and, on Unix, search permission to look at what it holds (without it the
1007
 * names come, but no entry reads as a file or a folder), and no name Qt
1008
 * leaves out of the listing (Util::hasUnreadableName()).
1009
 * @param dir An existing directory.
1010
 * @return false when the walk would miss what is in it.
1011
 */
1012
auto canList(const QString &dir) -> bool {
241 ✔
1013
#ifdef Q_OS_WIN
1014
  // Qt answers from the attributes alone unless told to read the ACL.
1015
  QNtfsPermissionCheckGuard aclCheck;
1016
  return QFileInfo(dir).isReadable();
1017
#else
1018
  const QFileInfo info(dir);
241 ✔
1019
  return info.isReadable() && info.isExecutable() &&
474 ✔
1020
         !Util::hasUnreadableName(dir);
474 ✔
1021
#endif
1022
}
241 ✔
1023

1024
/**
1025
 * @brief Walk @p dir's real, visible directories in sorted pre-order and hand
1026
 * every entry to @p visit before any recursion; a directory is entered only
1027
 * when @p visit returns true for it. A directory that cannot be read goes to
1028
 * @p unlisted, when given: its listing would come back empty, as an empty
1029
 * folder's does, and what is in it would be left out without a sign.
1030
 */
1031
template <typename Visit>
1032
void walkStore(const QString &dir, Visit visit,
398 ✔
1033
               QStringList *unlisted = nullptr) {
1034
  // Absolute, so the results are whatever the caller's cwd; not canonical,
1035
  // so a linked root keeps the name it was configured under.
1036
  QStringList pending{QDir(QDir::cleanPath(dir)).absolutePath()};
1,194 ✔
1037
  while (!pending.isEmpty()) {
3,110 ✔
1038
    const QDir current(pending.takeLast());
1,361 ✔
1039
    if (unlisted != nullptr && current.exists() && !canList(current.path())) {
2,722 ✔
1040
      qCWarning(lcQtPass) << "Cannot list" << current.path();
20 ✔
1041
      *unlisted << current.path();
10 ✔
1042
      continue;
1043
    }
10 ✔
1044
    // Every entry once, links and hidden entries included, so the decision
1045
    // what to do with each is taken here, before any recursion. QDir::System
1046
    // keeps dangling links in the listing.
1047
    const QFileInfoList entries =
1,351 ✔
1048
        current.entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
1049
                                  QDir::System | QDir::NoDotAndDotDot,
1050
                              QDir::Name);
1051
    QStringList subdirs;
1,351 ✔
1052
    for (const QFileInfo &entry : entries) {
8,254 ✔
1053
      if (visit(entry)) {
6,903 ✔
1054
        subdirs << entry.filePath();
1,926 ✔
1055
      }
1056
    }
1057
    // Pushed last-to-first so the next one taken is the first by name.
1058
    for (auto it = subdirs.crbegin(); it != subdirs.crend(); ++it) {
2,314 ✔
1059
      pending << *it;
1060
    }
1061
  }
1062
}
796 ✔
1063

1064
/// A symlink or an NTFS junction: never entered, never listed.
1065
auto isLink(const QFileInfo &entry) -> bool {
157,364 ✔
1066
  return entry.isSymLink() || entry.isJunction();
157,364 ✔
1067
}
1068

1069
/// Hidden by attribute, or by the dot convention on every platform: Qt 6.11
1070
/// on macOS answers isHidden() from the UF_HIDDEN flag alone once an entry
1071
/// was lstat()ed (qfilesystemengine_unix.cpp marks the attribute known there
1072
/// without the dot check), and Windows does not consider .stversions hidden
1073
/// at all.
1074
auto isHiddenEntry(const QFileInfo &entry) -> bool {
5,696 ✔
1075
  return entry.isHidden() || entry.fileName().startsWith(QLatin1Char('.'));
11,370 ✔
1076
}
1077

1078
/// A real directory that is part of the store: .git, .stversions,
1079
/// .Trash-1000 are not, as with QDirIterator without QDir::Hidden.
1080
auto isStoreDirectory(const QFileInfo &entry) -> bool {
6,903 ✔
1081
  return !isLink(entry) && entry.isDir() && !isHiddenEntry(entry);
6,903 ✔
1082
}
1083
} // namespace
1084

1085
auto Util::regularFilesUnder(const QString &dir, const QStringList &nameFilters,
395 ✔
1086
                             QStringList *skipped, bool hiddenFiles,
1087
                             QStringList *unlisted) -> QStringList {
1088
  QStringList files;
395 ✔
1089
  walkStore(
395 ✔
1090
      dir,
1091
      [&](const QFileInfo &entry) {
6,827 ✔
1092
        if (isStoreDirectory(entry)) {
6,827 ✔
1093
          return true;
1094
        }
1095
        const bool named = QDir::match(nameFilters, entry.fileName());
5,885 ✔
1096
        if (isLink(entry) || (!entry.isDir() && !entry.isFile())) {
5,885 ✔
1097
          // A linked directory hides everything behind it; a linked file, or a
1098
          // FIFO, socket or device, is only of interest under a name the caller
1099
          // asked for.
1100
          if (skipped != nullptr && (entry.isDir() || named)) {
73 ✔
1101
            qCWarning(lcQtPass) << "Skipping" << entry.filePath()
108 ✔
1102
                                << ": not a regular file or directory";
54 ✔
1103
            *skipped << entry.filePath();
108 ✔
1104
          }
1105
          return false;
73 ✔
1106
        }
1107
        if (entry.isFile() && named && (hiddenFiles || !isHiddenEntry(entry))) {
5,812 ✔
1108
          files << entry.filePath();
9,898 ✔
1109
        }
1110
        return false;
1111
      },
1112
      unlisted);
1113
  return files;
395 ✔
1114
}
1115

1116
auto Util::directoriesUnder(const QString &dir) -> QStringList {
3 ✔
1117
  QStringList dirs;
3 ✔
1118
  walkStore(dir, [&](const QFileInfo &entry) {
3 ✔
1119
    if (!isStoreDirectory(entry)) {
76 ✔
1120
      return false;
1121
    }
1122
    dirs << entry.filePath();
21 ✔
1123
    return true;
21 ✔
1124
  });
1125
  return dirs;
3 ✔
1126
}
1127

1128
auto Util::hasUnreadableName(const QString &dir) -> bool {
412 ✔
1129
#ifdef Q_OS_WIN
1130
  Q_UNUSED(dir);
1131
  return false;
1132
#else
1133
  // The names as bytes, as readdir() gives them; Qt's own listing has
1134
  // already dropped the ones this is looking for.
1135
  DIR *listing = ::opendir(QFile::encodeName(dir).constData());
412 ✔
1136
  if (listing == nullptr) {
412 ✔
1137
    return false;
1138
  }
1139
  const auto close = qScopeGuard([listing] { ::closedir(listing); });
409 ✔
1140
  while (const dirent *entry = ::readdir(listing)) {
2,003 ✔
1141
    if (!QByteArrayView(entry->d_name).isValidUtf8()) {
1,600 ✔
1142
      return true;
1143
    }
1144
  }
1145
  return false;
1146
#endif
1147
}
1148

1149
auto Util::isLinkedFolder(const QString &path) -> bool {
144,534 ✔
1150
  return isLink(QFileInfo(QDir::cleanPath(path)));
289,068 ✔
1151
}
1152

1153
auto Util::isUnderLink(const QString &path, const QString &storeRoot,
140,499 ✔
1154
                       bool includeSelf) -> bool {
1155
  // "C:/Store" and "c:/store" are one directory on Windows; a path spelled
1156
  // the other way must not skip the walk (as in Pass::getGpgIdPath).
1157
#ifdef Q_OS_WIN
1158
  constexpr auto cs = Qt::CaseInsensitive;
1159
#else
1160
  constexpr auto cs = Qt::CaseSensitive;
1161
#endif
1162
  const QString root = QDir::cleanPath(storeRoot);
140,499 ✔
1163
  // A root of "/" or "C:/" already ends in the separator.
1164
  const QString prefix =
1165
      root.endsWith(QLatin1Char('/')) ? root : root + QLatin1Char('/');
140,499 ✔
1166
  const auto isRoot = [&](const QString &p) {
1167
    return p.compare(root, cs) == 0;
143,684 ✔
1168
  };
1169
  QString current = QDir::cleanPath(path);
140,499 ✔
1170
  if (!current.startsWith(prefix, cs)) {
140,499 ✔
1171
    // Not under the store as named: only the entry itself can be judged.
1172
    return includeSelf && !isRoot(current) && isLinkedFolder(current);
568 ✔
1173
  }
1174
  if (!includeSelf) {
140,215 ✔
1175
    current = QFileInfo(current).path();
278,426 ✔
1176
  }
1177
  for (; !isRoot(current) && current.startsWith(prefix, cs);
143,400 ✔
1178
       current = QFileInfo(current).path()) {
6,370 ✔
1179
    if (isLinkedFolder(current)) {
3,238 ✔
1180
      return true;
1181
    }
1182
  }
1183
  return false;
1184
}
1185

1186
#ifndef Q_OS_WIN
1187
namespace {
1188

1189
/// The filesystem cannot make hard links at all (FAT/exFAT refuse with
1190
/// EPERM, some FUSE filesystems with ENOTSUP or ENOSYS).
1191
auto hasNoHardLinks(int error) -> bool {
1192
  return error == EPERM || error == ENOTSUP || error == EOPNOTSUPP ||
2 ✔
1193
         error == ENOSYS;
1194
}
1195

1196
/// rename() that fails with EEXIST instead of replacing, where the platform
1197
/// has one; nothing when neither the platform nor the filesystem does.
1198
auto renameExclusive(const QByteArray &source, const QByteArray &target)
8 ✔
1199
    -> std::optional<bool> {
1200
#if defined(__GLIBC__) &&                                                      \
1201
    (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 28))
1202
  if (::renameat2(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(),
8 ✔
1203
                  RENAME_NOREPLACE) == 0) {
1204
    return true;
2 ✔
1205
  }
1206
  if (errno == EINVAL || errno == ENOSYS || hasNoHardLinks(errno)) {
6 ✔
1207
    return std::nullopt;
4 ✔
1208
  }
1209
  return false;
2 ✔
1210
#elif defined(Q_OS_MACOS)
1211
  if (::renamex_np(source.constData(), target.constData(), RENAME_EXCL) == 0) {
1212
    return true;
1213
  }
1214
  if (errno == EINVAL || errno == ENOTSUP) {
1215
    return std::nullopt;
1216
  }
1217
  return false;
1218
#else
1219
  Q_UNUSED(source);
1220
  Q_UNUSED(target);
1221
  return std::nullopt;
1222
#endif
1223
}
1224

1225
/**
1226
 * @brief Gives @p source the name @p target unless something already has it.
1227
 *
1228
 * A hard link is the one way every POSIX system can do that in one step:
1229
 * linkat() fails with EEXIST rather than replacing. Where the filesystem has
1230
 * no hard links, an exclusive rename does it; where that is missing too, the
1231
 * name is checked and then renamed, which leaves a short window for another
1232
 * writer to create it in between.
1233
 */
1234
auto placeWithoutReplacing(const QByteArray &source, const QByteArray &target)
127 ✔
1235
    -> bool {
1236
  // linkat() without AT_SYMLINK_FOLLOW follows nothing; link() would, on
1237
  // macOS and the BSDs, hard-link whatever a symlink planted under the
1238
  // source's name points at.
1239
  if (::linkat(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(), 0) ==
127 ✔
1240
      0) {
1241
    if (::unlink(source.constData()) == 0) {
111 ✔
1242
      return true;
1243
    }
1244
    // Both names now hold the file. Take the new one away again so the
1245
    // caller sees the state it started from, not a success with the source
1246
    // still there.
1247
    const int err = errno;
1 ✔
1248
    ::unlink(target.constData());
1 ✔
1249
    errno = err;
1 ✔
1250
    return false;
1 ✔
1251
  }
1252
  if (!hasNoHardLinks(errno)) {
16 ✔
1253
    return false;
1254
  }
1255
  if (const std::optional<bool> renamed = renameExclusive(source, target)) {
8 ✔
1256
    return *renamed;
4 ✔
1257
  }
1258
  struct stat st{};
4 ✔
1259
  if (::lstat(target.constData(), &st) == 0 || errno != ENOENT) {
4 ✔
1260
    errno = EEXIST;
2 ✔
1261
    return false;
2 ✔
1262
  }
1263
  return ::rename(source.constData(), target.constData()) == 0;
2 ✔
1264
}
1265

1266
} // namespace
1267
#endif
1268

1269
auto Util::replaceFile(const QString &from, const QString &to, bool replace)
319 ✔
1270
    -> bool {
1271
#ifdef Q_OS_WIN
1272
  const std::wstring source =
1273
      QDir::toNativeSeparators(QFileInfo(from).absoluteFilePath())
1274
          .toStdWString();
1275
  const std::wstring target =
1276
      QDir::toNativeSeparators(QFileInfo(to).absoluteFilePath()).toStdWString();
1277
  // WRITE_THROUGH: the new entry is on the device when this returns.
1278
  return MoveFileExW(source.c_str(), target.c_str(),
1279
                     (replace ? MOVEFILE_REPLACE_EXISTING : 0) |
1280
                         MOVEFILE_WRITE_THROUGH) != 0;
1281
#else
1282
  const QByteArray source = QFile::encodeName(from);
1283
  const QByteArray target = QFile::encodeName(to);
1284
  if (replace) {
319 ✔
1285
    if (::rename(source.constData(), target.constData()) != 0) {
192 ✔
1286
      return false;
1287
    }
1288
  } else {
1289
    if (!placeWithoutReplacing(source, target)) {
127 ✔
1290
      return false;
1291
    }
1292
  }
1293
  // Sync the directory entry so a crash does not lose the new name. Best
1294
  // effort: the bytes are already synced, and some network filesystems
1295
  // cannot sync a directory.
1296
  const int dir = ::open(QFile::encodeName(QFileInfo(to).path()).constData(),
606 ✔
1297
                         O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1298
  if (dir >= 0) {
303 ✔
1299
    int rc;
1300
    do {
1301
      rc = ::fsync(dir);
303 ✔
1302
    } while (rc != 0 && errno == EINTR);
303 ✔
1303
    ::close(dir);
303 ✔
1304
  }
1305
  return true;
1306
#endif
1307
}
1308

1309
auto Util::openRegularFile(const QString &path, QFile &file) -> bool {
635 ✔
1310
#ifdef Q_OS_WIN
1311
  // FILE_FLAG_OPEN_REPARSE_POINT opens a symbolic link or junction itself
1312
  // rather than its target, so the handle's attributes say what the name
1313
  // was at the moment of the open.
1314
  const std::wstring native =
1315
      QDir::toNativeSeparators(QFileInfo(path).absoluteFilePath())
1316
          .toStdWString();
1317
  HANDLE handle = CreateFileW(
1318
      native.c_str(), GENERIC_READ,
1319
      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
1320
      OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
1321
  if (handle == INVALID_HANDLE_VALUE) {
1322
    return false;
1323
  }
1324
  BY_HANDLE_FILE_INFORMATION info{};
1325
  if (!GetFileInformationByHandle(handle, &info) ||
1326
      (info.dwFileAttributes &
1327
       (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) != 0 ||
1328
      GetFileType(handle) != FILE_TYPE_DISK) {
1329
    CloseHandle(handle);
1330
    return false;
1331
  }
1332
  if ((info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
1333
    // A link, a junction or anything else that names another file is
1334
    // refused. Any other reparse point (the placeholder of a cloud
1335
    // provider such as OneDrive, whose content is not on disk yet) is
1336
    // opened once more through it, so its filter fetches the content, and
1337
    // only when that open reaches the very same file.
1338
    FILE_ATTRIBUTE_TAG_INFO tag{};
1339
    if (!GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &tag,
1340
                                      sizeof(tag)) ||
1341
        IsReparseTagNameSurrogate(tag.ReparseTag)) {
1342
      CloseHandle(handle);
1343
      return false;
1344
    }
1345
    HANDLE through =
1346
        CreateFileW(native.c_str(), GENERIC_READ,
1347
                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1348
                    nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
1349
    // The 128-bit file ID: the 64-bit index in BY_HANDLE_FILE_INFORMATION
1350
    // is not unique on ReFS.
1351
    FILE_ID_INFO firstId{};
1352
    FILE_ID_INFO throughId{};
1353
    BY_HANDLE_FILE_INFORMATION after{};
1354
    const bool same =
1355
        through != INVALID_HANDLE_VALUE &&
1356
        GetFileInformationByHandleEx(handle, FileIdInfo, &firstId,
1357
                                     sizeof(firstId)) &&
1358
        GetFileInformationByHandleEx(through, FileIdInfo, &throughId,
1359
                                     sizeof(throughId)) &&
1360
        firstId.VolumeSerialNumber == throughId.VolumeSerialNumber &&
1361
        std::memcmp(&firstId.FileId, &throughId.FileId,
1362
                    sizeof(firstId.FileId)) == 0 &&
1363
        GetFileInformationByHandle(through, &after) &&
1364
        (after.dwFileAttributes &
1365
         (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0 &&
1366
        GetFileType(through) == FILE_TYPE_DISK;
1367
    CloseHandle(handle);
1368
    if (!same) {
1369
      if (through != INVALID_HANDLE_VALUE) {
1370
        CloseHandle(through);
1371
      }
1372
      return false;
1373
    }
1374
    handle = through;
1375
  }
1376
  const int fd = _open_osfhandle(reinterpret_cast<intptr_t>(handle),
1377
                                 _O_RDONLY | _O_BINARY);
1378
  if (fd < 0) {
1379
    CloseHandle(handle);
1380
    return false;
1381
  }
1382
  if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
1383
    _close(fd);
1384
    return false;
1385
  }
1386
  return true;
1387
#else
1388
  // O_NOFOLLOW fails with ELOOP on a symbolic link; O_NONBLOCK keeps a FIFO
1389
  // from blocking the open until fstat() can refuse it.
1390
  const int fd = ::open(QFile::encodeName(path).constData(),
635 ✔
1391
                        O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
1392
  if (fd < 0) {
635 ✔
1393
    return false;
1394
  }
1395
  struct stat st{};
590 ✔
1396
  if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
590 ✔
1397
    ::close(fd);
7 ✔
1398
    return false;
7 ✔
1399
  }
1400
  // The descriptor, not the name, is what QFile opens here: the object
1401
  // fstat() judged is the object read. CodeQL's check-then-use pattern
1402
  // matcher sees an open after a check and cannot tell (its alert on this
1403
  // line is dismissed as a false positive; inline suppression comments are
1404
  // not read by the default setup).
1405
  if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
583 ✔
1406
    ::close(fd);
×
1407
    return false;
×
1408
  }
1409
  return true;
1410
#endif
1411
}
1412

1413
namespace {
1414
/**
1415
 * @brief Read an open regular file whole when it holds at most @p maxBytes.
1416
 * @param file Open on a regular file.
1417
 * @param maxBytes The most bytes accepted.
1418
 * @return The contents; nothing when larger or unreadable.
1419
 */
1420
auto readOpenFile(QFile &file, qint64 maxBytes) -> std::optional<QByteArray> {
1,225 ✔
1421
  // A regular file's size is reliable, also when sparse: refuse a large one
1422
  // before reading anything. One byte past the limit still guards a file
1423
  // that grows meanwhile.
1424
  if (file.size() > maxBytes) {
1,225 ✔
1425
    return std::nullopt;
8 ✔
1426
  }
1427
  QByteArray bytes = file.read(maxBytes + 1);
1,217 ✔
1428
  if (bytes.size() > maxBytes || file.error() != QFileDevice::NoError) {
1,217 ✔
1429
    return std::nullopt;
×
1430
  }
1431
  return bytes;
1432
}
1433
} // namespace
1434

1435
auto Util::readRegularFile(const QString &path, qint64 maxBytes)
80 ✔
1436
    -> std::optional<QByteArray> {
1437
  QFile file;
80 ✔
1438
  if (!openRegularFile(path, file)) {
80 ✔
1439
    return std::nullopt;
10 ✔
1440
  }
1441
  return readOpenFile(file, maxBytes);
70 ✔
1442
}
80 ✔
1443

1444
auto Util::readRegularFileInStore(const QString &store, const QString &path,
837 ✔
1445
                                  qint64 maxBytes)
1446
    -> std::optional<QByteArray> {
1447
  const auto under = [&path](const QString &root) {
841 ✔
1448
    const QString relative = QDir(root).relativeFilePath(QDir::cleanPath(path));
1,682 ✔
1449
    return !root.isEmpty() && !isAbsoluteFsPath(relative) &&
841 ✔
1450
           relative != QStringLiteral("..") &&
2,523 ✔
1451
           !relative.startsWith(QStringLiteral("../"));
2,523 ✔
1452
  };
837 ✔
1453
  const QString root = QDir::cleanPath(store);
837 ✔
1454
  if (under(root)) {
837 ✔
1455
    return readRegularFileUnder(root, path, maxBytes);
833 ✔
1456
  }
1457
  const QString canonical = QFileInfo(root).canonicalFilePath();
4 ✔
1458
  if (under(canonical)) {
4 ✔
1459
    return readRegularFileUnder(canonical, path, maxBytes);
2 ✔
1460
  }
1461
  return std::nullopt;
2 ✔
1462
}
1463

1464
auto Util::readRegularFileUnder(const QString &root, const QString &path,
1,276 ✔
1465
                                qint64 maxBytes) -> std::optional<QByteArray> {
1466
  const QString cleanRoot = QDir::cleanPath(root);
1,276 ✔
1467
  const QString relative =
1468
      QDir(cleanRoot).relativeFilePath(QDir::cleanPath(path));
2,552 ✔
1469
  const QStringList parts = relative.split(QLatin1Char('/'));
1,276 ✔
1470
  if (relative.isEmpty() || isAbsoluteFsPath(relative) ||
2,552 ✔
1471
      parts.contains(QStringLiteral("..")) ||
2,550 ✔
1472
      parts.contains(QStringLiteral(".")) || parts.contains(QString())) {
5,099 ✔
1473
    return std::nullopt;
3 ✔
1474
  }
1475
#ifdef Q_OS_WIN
1476
  // No openat() here: each folder from the root down is opened by name and
1477
  // held open, without FILE_SHARE_DELETE, until the file is read. A folder
1478
  // held that way cannot be renamed, removed or replaced by a junction
1479
  // meanwhile, so the file is opened through exactly the folders judged.
1480
  // The root itself is followed (a linked store is the user's setup).
1481
  std::vector<HANDLE> held;
1482
  const auto release = qScopeGuard([&held] {
1483
    for (HANDLE handle : held) {
1484
      CloseHandle(handle);
1485
    }
1486
  });
1487
  QString folder = cleanRoot;
1488
  for (qsizetype i = 0; i < parts.size(); ++i) {
1489
    const bool isRoot = i == 0;
1490
    if (!isRoot) {
1491
      folder += QLatin1Char('/') + parts.at(i - 1);
1492
    }
1493
    const std::wstring native = QDir::toNativeSeparators(folder).toStdWString();
1494
    // GENERIC_READ (listing the folder) is data access, so the share mode
1495
    // is enforced against a later open for DELETE; attribute access alone
1496
    // would not be.
1497
    HANDLE handle =
1498
        CreateFileW(native.c_str(), GENERIC_READ,
1499
                    FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
1500
                    FILE_FLAG_BACKUP_SEMANTICS |
1501
                        (isRoot ? 0 : FILE_FLAG_OPEN_REPARSE_POINT),
1502
                    nullptr);
1503
    if (handle == INVALID_HANDLE_VALUE) {
1504
      return std::nullopt;
1505
    }
1506
    held.push_back(handle);
1507
    // A reparse point that names another place (a symbolic link, a
1508
    // junction: what the walk's isLink() leaves out) is refused, as
1509
    // openRegularFile() refuses one as the file. A folder with another
1510
    // reparse tag, such as a cloud provider's placeholder, is listed by the
1511
    // walk and is read through here too.
1512
    FILE_ATTRIBUTE_TAG_INFO info{};
1513
    if (!GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &info,
1514
                                      sizeof(info)) ||
1515
        (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
1516
      return std::nullopt;
1517
    }
1518
    const bool link =
1519
        (info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 &&
1520
        IsReparseTagNameSurrogate(info.ReparseTag);
1521
    if (!isRoot && link) {
1522
      return std::nullopt;
1523
    }
1524
  }
1525
  // openRegularFile() refuses a link or junction as the file itself, and
1526
  // reads any other reparse point (a cloud placeholder) through.
1527
  return readRegularFile(path, maxBytes);
1528
#else
1529
  // The root by name, followed if it is a link (the user's setup); below it
1530
  // nothing is.
1531
  int dir = ::open(QFile::encodeName(cleanRoot).constData(),
1,273 ✔
1532
                   O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1533
  if (dir < 0) {
1,273 ✔
1534
    return std::nullopt;
×
1535
  }
1536
  for (qsizetype i = 0; i + 1 < parts.size(); ++i) {
1,476 ✔
1537
    const int next = ::openat(dir, QFile::encodeName(parts.at(i)).constData(),
212 ✔
1538
                              O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
1539
    ::close(dir);
212 ✔
1540
    if (next < 0) {
212 ✔
1541
      return std::nullopt;
9 ✔
1542
    }
1543
    dir = next;
1544
  }
1545
  // As openRegularFile(): no link, no FIFO left blocking the open.
1546
  const int fd = ::openat(dir, QFile::encodeName(parts.constLast()).constData(),
×
1547
                          O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
1548
  ::close(dir);
1,264 ✔
1549
  if (fd < 0) {
1,264 ✔
1550
    return std::nullopt;
107 ✔
1551
  }
1552
  struct stat st{};
1,157 ✔
1553
  if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
1,157 ✔
1554
    ::close(fd);
2 ✔
1555
    return std::nullopt;
2 ✔
1556
  }
1557
  // As in openRegularFile(): QFile takes the descriptor fstat() judged, not
1558
  // the name, so a name swapped between the check and the read cannot make
1559
  // it read another file (the file's contents can still change; the check
1560
  // is on what kind of file it is). CodeQL flags the open anyway; that alert
1561
  // is dismissed as a false positive.
1562
  QFile file;
1,155 ✔
1563
  if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
1,155 ✔
1564
    ::close(fd);
×
1565
    return std::nullopt;
×
1566
  }
1567
  return readOpenFile(file, maxBytes);
1,155 ✔
1568
#endif
1569
}
1,155 ✔
1570

1571
auto Util::syncToDisk(QFileDevice &file) -> bool {
302 ✔
1572
  if (!file.flush()) {
302 ✔
1573
    return false;
1574
  }
1575
#ifdef Q_OS_WIN
1576
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1577
  return handle != INVALID_HANDLE_VALUE && FlushFileBuffers(handle) != 0;
1578
#else
1579
  return ::fsync(file.handle()) == 0;
302 ✔
1580
#endif
1581
}
1582

1583
namespace {
1584

1585
/**
1586
 * @brief What tells one file object from another on its filesystem: device
1587
 * and inode on POSIX, volume serial and file index on Windows.
1588
 */
1589
struct FileIdentity {
1590
  quint64 volume = 0;
1591
  quint64 index = 0;
1592
  bool known = false;
1593
};
1594

1595
auto operator==(const FileIdentity &a, const FileIdentity &b) -> bool {
291 ✔
1596
  return a.known && b.known && a.volume == b.volume && a.index == b.index;
291 ✔
1597
}
1598

1599
/// The identity of the object @p file is open on, or an unknown one.
1600
auto identityOf(const QFileDevice &file) -> FileIdentity {
593 ✔
1601
#ifdef Q_OS_WIN
1602
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1603
  BY_HANDLE_FILE_INFORMATION info;
1604
  if (handle == INVALID_HANDLE_VALUE ||
1605
      GetFileInformationByHandle(handle, &info) == 0) {
1606
    return {};
1607
  }
1608
  // On FAT/exFAT the file ID is the directory entry's offset, which a rename
1609
  // can move. They have no hard links either (the swap this catches needs
1610
  // one), so the identity is left unknown there.
1611
  DWORD flags = 0;
1612
  if (GetVolumeInformationByHandleW(handle, nullptr, 0, nullptr, nullptr,
1613
                                    &flags, nullptr, 0) == 0 ||
1614
      (flags & FILE_SUPPORTS_HARD_LINKS) == 0) {
1615
    return {};
1616
  }
1617
  return {info.dwVolumeSerialNumber,
1618
          (static_cast<quint64>(info.nFileIndexHigh) << 32) |
1619
              info.nFileIndexLow,
1620
          true};
1621
#else
1622
  struct stat st{};
593 ✔
1623
  if (::fstat(file.handle(), &st) != 0) {
593 ✔
1624
    return {};
×
1625
  }
1626
  return {static_cast<quint64>(st.st_dev), static_cast<quint64>(st.st_ino),
593 ✔
1627
          true};
593 ✔
1628
#endif
1629
}
1630

1631
/// Put @p text in @p error when there is one; false, for `return fail(...)`.
1632
auto fail(QString *error, const QString &text) -> bool {
1633
  if (error != nullptr) {
22 ✔
1634
    *error = text;
22 ✔
1635
  }
1636
  return false;
1637
}
1638

1639
/// A filled, synced temporary next to its destination.
1640
struct Staged {
302 ✔
1641
  QString path;
1642
  FileIdentity identity;
1643
  /// POSIX: a descriptor kept open on the temporary until the identity
1644
  /// check, so the inode, and with it the number, stays the temporary's.
1645
  std::shared_ptr<void> pin;
1646
};
1647

1648
/**
1649
 * @brief Create the temporary next to @p path (opaque name, exclusive,
1650
 * owner-only), fill it through its handle and sync it. The QTemporaryFile
1651
 * goes out of scope before the caller renames: it keeps its handle open for
1652
 * as long as it lives, and Windows does not rename an open file.
1653
 */
1654
auto stageNextTo(const QString &path, const Util::Filler &fill, QString *why)
310 ✔
1655
    -> std::optional<Staged> {
1656
  Staged staged;
310 ✔
1657
  {
1658
    QTemporaryFile file(QFileInfo(path).path() +
620 ✔
1659
                        QStringLiteral("/.qtpass-XXXXXX.tmp"));
620 ✔
1660
    file.setAutoRemove(false);
310 ✔
1661
    if (!file.open()) {
310 ✔
1662
      *why = QCoreApplication::translate(
8 ✔
1663
                 "Util", "Cannot create a temporary file next to %1: %2")
1664
                 .arg(path, file.errorString());
16 ✔
1665
      return std::nullopt;
8 ✔
1666
    }
1667
    staged.path = file.fileName();
302 ✔
1668
    // Owner-only: a .gpg-id names the keys a store is encrypted to, an
1669
    // entry is an entry. QTemporaryFile creates 0600 already; say so for
1670
    // platforms where it may not.
1671
    file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
302 ✔
1672
    *why = fill(file);
604 ✔
1673
    if (why->isEmpty() && !Util::syncToDisk(file)) {
302 ✔
1674
      *why = QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1675
                 .arg(path, file.errorString());
×
1676
    }
1677
    staged.identity = identityOf(file);
302 ✔
1678
#ifndef Q_OS_WIN
1679
    // Closed and unlinked by a co-writer before the rename, the temporary's
1680
    // inode number would be free, and ext4 hands it to the next file made:
1681
    // the very file swapped in would then pass the check below. Windows
1682
    // cannot rename an open file, and NTFS does not reuse a file index so.
1683
    if (const int fd = ::dup(file.handle()); fd >= 0) {
302 ✔
1684
      staged.pin =
1685
          std::shared_ptr<void>(nullptr, [fd](void *) { ::close(fd); });
906 ✔
1686
    }
1687
#endif
1688
  }
310 ✔
1689
  if (!why->isEmpty()) {
302 ✔
1690
    QFile::remove(staged.path);
×
1691
    return std::nullopt;
×
1692
  }
1693
  return staged;
302 ✔
1694
}
310 ✔
1695

1696
/// Why replaceFile() could not put the temporary under @p path.
1697
auto placementError(const QString &path, bool replace) -> QString {
9 ✔
1698
  if (replace) {
9 ✔
1699
    return QCoreApplication::translate("Util", "Failed to replace %1.")
4 ✔
1700
        .arg(path);
2 ✔
1701
  }
1702
  const QFileInfo taken(path);
7 ✔
1703
  return taken.exists() || taken.isSymLink()
8 ✔
1704
             ? QCoreApplication::translate("Util", "%1 already exists.")
7 ✔
1705
                   .arg(path)
1706
             : QCoreApplication::translate("Util", "Failed to write %1.")
1 ✔
1707
                   .arg(path);
8 ✔
1708
}
7 ✔
1709

1710
/**
1711
 * @brief Whether what is under @p path is the file that was filled: not a
1712
 * link, and not another file (a hard link to something of the user's, say)
1713
 * swapped in under the temporary's name. Opened without following, compared
1714
 * by identity; only two known identities can prove a swap, otherwise every
1715
 * write on such a store would be reported as tampering.
1716
 */
1717
auto isTheFileWritten(const QString &path, const FileIdentity &written)
293 ✔
1718
    -> bool {
1719
  QFile placed;
293 ✔
1720
  if (!Util::openRegularFile(path, placed)) {
293 ✔
1721
    return false;
1722
  }
1723
  const FileIdentity there = identityOf(placed);
291 ✔
1724
  if (!written.known || !there.known) {
291 ✔
1725
    qCWarning(lcQtPass) << "Cannot tell whether" << path
×
1726
                        << "is the file that was written here";
×
1727
    return true;
×
1728
  }
1729
  return there == written;
291 ✔
1730
}
293 ✔
1731

1732
} // namespace
1733

1734
auto Util::stageFileReplacing(const QString &path, bool replace,
310 ✔
1735
                              const Filler &fill, QString *error) -> bool {
1736
  QString why;
310 ✔
1737
  const std::optional<Staged> staged = stageNextTo(path, fill, &why);
310 ✔
1738
  if (!staged) {
310 ✔
1739
    return fail(error, why);
1740
  }
1741
  if (s_beforePlacingForTests) {
302 ✔
1742
    s_beforePlacingForTests(staged->path);
1 ✔
1743
  }
1744
  if (!replaceFile(staged->path, path, replace)) {
302 ✔
1745
    QFile::remove(staged->path);
9 ✔
1746
    return fail(error, placementError(path, replace));
18 ✔
1747
  }
1748
  // A mismatch is reported and left: removing by name could take another
1749
  // writer's file.
1750
  if (!isTheFileWritten(path, staged->identity)) {
293 ✔
1751
    return fail(
1752
        error,
1753
        QCoreApplication::translate(
5 ✔
1754
            "Util", "%1 was swapped for another file while it was written.")
1755
            .arg(path));
10 ✔
1756
  }
1757
  return true;
1758
}
1759

1760
auto Util::writeFileReplacing(const QString &path, const QByteArray &bytes,
119 ✔
1761
                              bool replace, QString *error) -> bool {
1762
  return stageFileReplacing(
119 ✔
1763
      path, replace,
1764
      [&path, &bytes](QFileDevice &staged) -> QString {
236 ✔
1765
        if (staged.write(bytes) != bytes.size()) {
117 ✔
1766
          return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1767
              .arg(path, staged.errorString());
×
1768
        }
1769
        return {};
117 ✔
1770
      },
1771
      error);
119 ✔
1772
}
1773

1774
auto Util::copyFileReplacing(const QString &src, const QString &dst,
190 ✔
1775
                             bool replace, QString *error) -> bool {
1776
  QFile in;
190 ✔
1777
  if (!openRegularFile(src, in)) {
190 ✔
1778
    if (error)
4 ✔
1779
      *error = QCoreApplication::translate("Util", "Cannot read %1.").arg(src);
8 ✔
1780
    return false;
4 ✔
1781
  }
1782
  return stageFileReplacing(
186 ✔
1783
      dst, replace,
1784
      [&src, &dst, &in](QFileDevice &staged) -> QString {
552 ✔
1785
        char buf[64 * 1024];
1786
        for (;;) {
1787
          const qint64 n = in.read(buf, sizeof buf);
372 ✔
1788
          if (n < 0) {
372 ✔
1789
            return QCoreApplication::translate("Util", "Cannot read %1: %2")
×
1790
                .arg(src, in.errorString());
×
1791
          }
1792
          if (n == 0) {
372 ✔
1793
            return {};
180 ✔
1794
          }
1795
          if (staged.write(buf, n) != n) {
192 ✔
1796
            return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1797
                .arg(dst, staged.errorString());
×
1798
          }
1799
        }
1800
      },
1801
      error);
1802
}
190 ✔
1803

1804
namespace {
1805

1806
/// Remove one directory entry that is not a real directory: a link goes as
1807
/// the entry itself, never its target (a junction or a directory symlink on
1808
/// Windows is a directory entry and goes with rmdir); a read-only file gets
1809
/// write access and one more try, as QDir::removeRecursively() does.
1810
auto removeEntry(const QFileInfo &entry) -> bool {
14 ✔
1811
  const QString path = entry.filePath();
14 ✔
1812
  if (isLink(entry)) {
14 ✔
1813
    if (QFile::remove(path) || QDir().rmdir(path)) {
6 ✔
1814
      return true;
1815
    }
1816
    qCWarning(lcQtPass) << "Could not remove link" << path;
2 ✔
1817
    return false;
1 ✔
1818
  }
1819
  if (QFile::remove(path)) {
9 ✔
1820
    return true;
1821
  }
1822
  const QFile::Permissions perms = QFile::permissions(path);
2 ✔
1823
  if (!perms.testFlag(QFile::WriteUser) &&
1 ✔
1824
      QFile::setPermissions(path, perms | QFile::WriteUser) &&
3 ✔
1825
      QFile::remove(path)) {
1 ✔
1826
    return true;
1827
  }
1828
  qCWarning(lcQtPass) << "Could not remove" << path;
4 ✔
1829
  return false;
2 ✔
1830
}
1831

1832
} // namespace
1833

1834
auto Util::removeTree(const QString &dir) -> bool {
23 ✔
1835
  // A trailing separator makes lstat follow a link ("link/" is the target
1836
  // directory); the link itself is what this is about.
1837
  const QString path = QDir::cleanPath(dir);
23 ✔
1838
  const QFileInfo top(path);
23 ✔
1839
  if (isLink(top)) {
23 ✔
1840
    // rm -rf on a link removes the link.
1841
    return QFile::remove(path) || QDir().rmdir(path);
16 ✔
1842
  }
1843
  if (!top.isDir()) {
9 ✔
1844
    return false;
1845
  }
1846
  bool ok = true;
1847
  const QFileInfoList entries =
1848
      QDir(path).entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
16 ✔
1849
                                   QDir::System | QDir::NoDotAndDotDot,
1850
                               QDir::Name);
8 ✔
1851
  for (const QFileInfo &entry : entries) {
24 ✔
1852
    const bool removed = entry.isDir() && !isLink(entry)
22 ✔
1853
                             ? removeTree(entry.filePath())
18 ✔
1854
                             : removeEntry(entry);
14 ✔
1855
    ok = removed && ok;
16 ✔
1856
  }
1857
  return ok && QDir().rmdir(path);
13 ✔
1858
}
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