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

IJHack / QtPass / 46067891175

27 Nov 2026 09:04PM UTC coverage: 94.701%. Remained the same
46067891175

push

github

web-flow
util: explain the CodeQL false positive instead of a suppression tag (#2373)

Both QFile::open(fd) calls after an fstat() on the same descriptor carried
a // codeql[cpp/toctou-race-condition] tag, which the default CodeQL
setup does not read: the alert on the second one stayed open until it
was dismissed as a false positive. The tags are gone; each site now says
in plain words why there is no race (QFile takes the descriptor fstat()
judged, not the name, so a swapped name cannot make it read another
file; the contents can still change) and that the alert is dismissed.

Comments only.

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

2 of 2 new or added lines in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

10330 of 10908 relevant lines covered (94.7%)

25569.63 hits per line

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

94.31
/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() {
964 ✔
53
  if (!_envInitialised) {
964 ✔
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
}
964 ✔
78

79
auto Util::findPasswordStore() -> QString {
409 ✔
80
  QString path;
409 ✔
81
  initialiseEnvironment();
409 ✔
82
  if (_env.contains("PASSWORD_STORE_DIR")) {
818 ✔
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,218 ✔
89
#endif
90
  }
91
  return Util::normalizeFolderPath(QDir::cleanPath(path));
818 ✔
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::normalizeFolderPath(const QString &path) -> QString {
549 ✔
105
  QString normalizedPath = path;
106
  if (!normalizedPath.endsWith('/')) {
549 ✔
107
    normalizedPath += '/';
530 ✔
108
  }
109
  return normalizedPath;
549 ✔
110
}
111

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

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

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

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

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

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

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

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

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

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

431
void Util::requireExplicitBareRepository(QProcessEnvironment &env) {
512 ✔
432
  const QString key = QStringLiteral("safe.bareRepository");
512 ✔
433
  const QString value = QStringLiteral("explicit");
512 ✔
434
  const QString countText = env.value(QStringLiteral("GIT_CONFIG_COUNT"));
1,024 ✔
435
  bool ok = countText.isEmpty();
512 ✔
436
  int count = countText.isEmpty() ? 0 : countText.toInt(&ok);
512 ✔
437
  if (!ok || count < 0) {
512 ✔
438
    // git refuses to start with a malformed count, so the entries it was
439
    // meant to cover never applied: start the list afresh.
440
    count = 0;
441
  }
442
  // Keys and these values are case-insensitive to git; the last entry wins.
443
  QString last;
512 ✔
444
  for (int i = 0; i < count; ++i) {
840 ✔
445
    if (env.value(QStringLiteral("GIT_CONFIG_KEY_%1").arg(i))
656 ✔
446
            .compare(key, Qt::CaseInsensitive) == 0) {
328 ✔
447
      last = env.value(QStringLiteral("GIT_CONFIG_VALUE_%1").arg(i));
572 ✔
448
    }
449
  }
450
  // git reads GIT_CONFIG_PARAMETERS (`git -c`) after the numbered entries,
451
  // so when that names the key at all, explicit must be its last entry. Not
452
  // parsed: the string must end in this separate token, which a value
453
  // cannot fake (a quote inside one is written '\'', so it never follows a
454
  // blank); appending once too often does no harm.
455
  const QString parameters = env.value(QStringLiteral("GIT_CONFIG_PARAMETERS"));
1,024 ✔
456
  const QString explicitEntry =
457
      QStringLiteral("'safe.bareRepository=explicit'");
512 ✔
458
  if (parameters.contains(QLatin1String("barerepository"),
1,024 ✔
459
                          Qt::CaseInsensitive) &&
16 ✔
460
      parameters != explicitEntry &&
526 ✔
461
      !parameters.endsWith(QLatin1Char(' ') + explicitEntry)) {
526 ✔
462
    env.insert(QStringLiteral("GIT_CONFIG_PARAMETERS"),
12 ✔
463
               parameters + QLatin1Char(' ') + explicitEntry);
12 ✔
464
  }
465
  if (last.compare(value, Qt::CaseInsensitive) == 0) {
512 ✔
466
    return;
467
  }
468
  env.insert(QStringLiteral("GIT_CONFIG_KEY_%1").arg(count), key);
458 ✔
469
  env.insert(QStringLiteral("GIT_CONFIG_VALUE_%1").arg(count), value);
458 ✔
470
  env.insert(QStringLiteral("GIT_CONFIG_COUNT"), QString::number(count + 1));
458 ✔
471
}
472

473
auto Util::gitStoreVariables(const QString &store, const QString &git,
1,931 ✔
474
                             std::optional<uint> asUser)
475
    -> QList<std::pair<QString, QString>> {
476
  const QString ceiling = gitCeiling(store);
1,931 ✔
477
  if (ceiling.isEmpty()) {
1,931 ✔
478
    return {};
×
479
  }
480
  QList<std::pair<QString, QString>> vars{
481
      {QStringLiteral("GIT_CEILING_DIRECTORIES"), ceiling}};
5,793 ✔
482
#ifdef Q_OS_WIN
483
  const QChar separator = QLatin1Char(';');
484
#else
485
  const QChar separator = QLatin1Char(':');
486
#endif
487
  // git splits the ceiling list on the separator: "/home/a:b" would be
488
  // "/home/a" and "b", neither of them the parent, and git would climb.
489
  if (ceiling.contains(separator)) {
1,931 ✔
490
    QString root = QFileInfo(store).canonicalFilePath();
28 ✔
491
    if (root.isEmpty()) {
28 ✔
492
      root = QDir::cleanPath(QDir(store).absolutePath());
×
493
    }
494
    QString gitDir = QDir(root).filePath(QStringLiteral(".git"));
56 ✔
495
#ifdef Q_OS_UNIX
496
    // What discovery's ownership check would have looked at: the work tree,
497
    // the .git, and the directory a gitfile names. Not the user's: no
498
    // repository at all, under a path that cannot be created (its parent
499
    // is a device), rather than another user's hooks run as this one.
500
    const uint me = asUser.value_or(
501
        s_gitOwnerForTests.value_or(static_cast<uint>(::geteuid())));
28 ✔
502
    const auto ownedOrMissing = [me](const QString &path) {
33 ✔
503
      const QFileInfo info(path);
33 ✔
504
      return !info.exists() || info.ownerId() == me;
66 ✔
505
    };
33 ✔
506
    bool owned = ownedOrMissing(root) && ownedOrMissing(gitDir);
28 ✔
507
    if (owned && QFileInfo(gitDir).isFile()) {
28 ✔
508
      QFile gitFile(gitDir);
×
509
      if (gitFile.open(QIODevice::ReadOnly)) {
×
510
        const QString line =
511
            QString::fromUtf8(gitFile.readLine(4096)).trimmed();
×
512
        if (line.startsWith(QLatin1String("gitdir:"))) {
×
513
          const QString target = line.mid(7).trimmed();
×
514
          owned = ownedOrMissing(QDir(root).absoluteFilePath(target));
×
515
        }
516
      }
517
    }
×
518
    // Or trusted as git would trust it in place of ownership.
519
    if (!owned && !isSafeDirectory(root, git)) {
28 ✔
520
      gitDir = QStringLiteral("/dev/null/.git");
14 ✔
521
    }
522
#else
523
    // Git for Windows runs the same ownership check during discovery, on
524
    // SIDs, with its own rules for the Administrators group; this pin skips
525
    // it there and does not repeat it (a known gap, #2089).
526
    Q_UNUSED(git);
527
    Q_UNUSED(asUser);
528
#endif
529
    vars.append({QStringLiteral("GIT_DIR"), gitDir});
56 ✔
530
    vars.append({QStringLiteral("GIT_WORK_TREE"), root});
56 ✔
531
  }
532
  return vars;
533
}
1,931 ✔
534

535
auto Util::mkpathForStore(const QString &path) -> bool {
52 ✔
536
  const QString clean = QDir::cleanPath(QDir(path).absolutePath());
104 ✔
537
  if (QFileInfo(clean).isDir()) {
52 ✔
538
    return true;
539
  }
540
  const QString parent = QFileInfo(clean).absolutePath();
30 ✔
541
  if (parent != clean && !mkpathForStore(parent)) {
30 ✔
542
    return false;
543
  }
544
#ifdef Q_OS_UNIX
545
  // The store's umask, as git and gpg get it: a store shared with a group
546
  // (PASSWORD_STORE_UMASK=007) gets group folders, the default owner-only.
547
  const int umask = Executor::childUmask() >= 0 ? Executor::childUmask() : 077;
27 ✔
548
  QFile::Permissions permissions;
549
  const QFile::Permission bits[] = {
27 ✔
550
      QFile::ReadOwner, QFile::WriteOwner, QFile::ExeOwner,
551
      QFile::ReadGroup, QFile::WriteGroup, QFile::ExeGroup,
552
      QFile::ReadOther, QFile::WriteOther, QFile::ExeOther};
553
  for (int i = 0; i < 9; ++i) {
270 ✔
554
    if ((umask & (0400 >> i)) == 0) {
243 ✔
555
      permissions |= bits[i];
87 ✔
556
    }
557
  }
558
  // mkdir() still takes QtPass's own umask off (a session's 022 would drop
559
  // the group's write bit); set the mode exactly afterwards. That only ever
560
  // widens it to what was asked, never past.
561
  const bool made = QDir().mkdir(clean, permissions) &&
54 ✔
562
                    QFile::setPermissions(clean, permissions);
22 ✔
563
#else
564
  // Windows: permissions here would become an ACL of their own, replacing
565
  // the inherited one; the folder takes its parent's, as before.
566
  const bool made = QDir().mkdir(clean);
567
#endif
568
  return made || QFileInfo(clean).isDir();
27 ✔
569
}
570

571
auto Util::findBinaryInPath(const QString &binary) -> QString {
556 ✔
572
  if (binary.isEmpty()) {
556 ✔
573
    return {};
1 ✔
574
  }
575

576
  initialiseEnvironment();
555 ✔
577

578
  const QStringList dirs =
579
      _env.value(QStringLiteral("PATH"))
1,110 ✔
580
          .split(QDir::listSeparator(), Qt::SkipEmptyParts);
555 ✔
581
  QString ret;
555 ✔
582
  if (QDir::fromNativeSeparators(binary).contains(u'/')) {
555 ✔
583
    // An explicit path is not a PATH search: an absolute path is checked
584
    // as-is, a relative one is resolved against the PATH directories. The
585
    // directory-list overload refuses such names, so handle them here.
586
    if (QDir::isAbsolutePath(binary)) {
3 ✔
587
      ret = QStandardPaths::findExecutable(binary);
4 ✔
588
    } else if (!dirs.isEmpty()) {
1 ✔
589
      ret = QStandardPaths::findExecutable(binary, dirs);
2 ✔
590
    }
591
  } else {
592
    ret = findBinaryInPath(binary, dirs);
1,104 ✔
593
  }
594
#ifdef Q_OS_WIN
595
  if (ret.isEmpty()) {
596
    // Cache per-binary WSL lookup result — the wsl --version probe is a
597
    // blocking subprocess that can run several times per session for
598
    // missing binaries; once decided, the answer doesn't change at runtime.
599
    static QHash<QString, QString> wslBinaryCache;
600
    const bool hasWhitespace =
601
        std::any_of(binary.cbegin(), binary.cend(),
602
                    [](const QChar ch) { return ch.isSpace(); });
603
    if (!hasWhitespace) {
604
      auto cached = wslBinaryCache.constFind(binary);
605
      if (cached != wslBinaryCache.constEnd()) {
606
        ret = cached.value();
607
      } else {
608
        QString wslCommand = QStringLiteral("wsl ") + binary;
609
        qCDebug(lcQtPass)
610
            << "Util::findBinaryInPath(): falling back to WSL for binary"
611
            << binary;
612
        QString out, err;
613
        QString cachedResult;
614
        if (Executor::executeBlocking(wslCommand, {"--version"}, &out, &err) ==
615
                0 &&
616
            !out.isEmpty() && err.isEmpty()) {
617
          qCDebug(lcQtPass)
618
              << "Util::findBinaryInPath(): using WSL binary" << wslCommand;
619
          cachedResult = wslCommand;
620
        }
621
        wslBinaryCache.insert(binary, cachedResult);
622
        ret = cachedResult;
623
      }
624
    }
625
  }
626
#endif
627

628
  return ret;
629
}
630

631
// Bare names only: QStandardPaths::findExecutable() returns an absolute binary
632
// without consulting searchPaths, and a relative one with ".." could escape
633
// them.
634
auto Util::findBinaryInPath(const QString &binary,
566 ✔
635
                            const QStringList &searchPaths) -> QString {
636
  if (binary.isEmpty() || QDir::fromNativeSeparators(binary).contains(u'/')) {
1,131 ✔
637
    return {};
4 ✔
638
  }
639
  QStringList dirs;
562 ✔
640
  dirs.reserve(searchPaths.size());
562 ✔
641
  for (const QString &dir : searchPaths) {
8,868 ✔
642
    if (!dir.isEmpty()) {
8,306 ✔
643
      dirs.append(dir);
644
    }
645
  }
646
  if (dirs.isEmpty()) {
562 ✔
647
    // QStandardPaths::findExecutable() treats an empty list as "use PATH".
648
    return {};
4 ✔
649
  }
650
  return QStandardPaths::findExecutable(binary, dirs);
558 ✔
651
}
652

653
auto Util::configIsValid(const AppSettings &s) -> bool {
296 ✔
654
  const QString configFilePath = QDir(s.passStore).filePath(".gpg-id");
592 ✔
655
  if (!QFile(configFilePath).exists()) {
296 ✔
656
    return false;
657
  }
658

659
  const QString executable = s.usePass ? s.passExecutable : s.gpgExecutable;
213 ✔
660

661
  if (const auto wsl = Executor::parseWslCommand(executable)) {
213 ✔
662
    // Probe WSL once per session — availability doesn't change at runtime
663
    // and the executeBlocking call is a blocking subprocess.
664
    static const bool wslAvailable = [&wsl]() {
1 ✔
665
      QString out;
1 ✔
666
      QString err;
1 ✔
667
      return Executor::executeBlocking(wsl->launcher,
3 ✔
668
                                       {QStringLiteral("--version")}, &out,
1 ✔
669
                                       &err) == 0 &&
×
670
             !out.isEmpty() && err.isEmpty();
2 ✔
671
    }();
1 ✔
672
    if (wslAvailable) {
1 ✔
673
      return true;
674
    }
675
  }
676
  return QFile(executable).exists();
213 ✔
677
}
678

679
auto Util::endsWithGpg() -> const QRegularExpression & {
17,534 ✔
680
  static const QRegularExpression expr{R"(\.gpg$)"};
17,541 ✔
681
  return expr;
17,534 ✔
682
}
683

684
// Stops at whitespace, quotes and brackets so a URL on its own line keeps no
685
// line break. file:/// is excluded on purpose (local, not network); the test
686
// relies on that.
687
auto Util::protocolRegex() -> const QRegularExpression & {
158 ✔
688
  static const QRegularExpression regex{
689
      R"(((?:https?|ftp|ssh|sftp|ftps|webdav|webdavs)://[^"\s<>\)\]\[]+))"};
163 ✔
690
  return regex;
158 ✔
691
}
692

693
namespace {
694
/**
695
 * @brief The length of a URL's authority, found as QUrl finds it.
696
 *
697
 * QUrl takes the text before the first ':' that comes before any '/', '?'
698
 * or '#' as the scheme when it is one (a letter, then letters, digits,
699
 * '+', '-' or '.'); the rest starts there, or at the start otherwise. An
700
 * authority follows a "//" at that point and runs to the first '/', '?'
701
 * or '#'. So "//host" has one too, and a "://" later in the text does not
702
 * start it.
703
 * @param url The candidate URL.
704
 * @return The authority's length, or -1 when there is none.
705
 */
706
auto authorityLength(const QString &url) -> qsizetype {
124 ✔
707
  const auto endsPart = [](QChar c) {
708
    return c == QLatin1Char('/') || c == QLatin1Char('?') ||
709
           c == QLatin1Char('#');
710
  };
711
  const auto isAsciiLetter = [](QChar c) {
712
    return (c >= QLatin1Char('a') && c <= QLatin1Char('z')) ||
467 ✔
713
           (c >= QLatin1Char('A') && c <= QLatin1Char('Z'));
9 ✔
714
  };
715
  qsizetype colon = -1;
716
  for (qsizetype i = 0; i < url.size() && !endsPart(url.at(i)); ++i) {
857 ✔
717
    if (url.at(i) == QLatin1Char(':')) {
830 ✔
718
      colon = i;
719
      break;
720
    }
721
  }
722
  bool scheme = colon > 0 && isAsciiLetter(url.at(0));
124 ✔
723
  for (qsizetype i = 1; scheme && i < colon; ++i) {
494 ✔
724
    const QChar c = url.at(i);
725
    scheme =
726
        isAsciiLetter(c) || (c >= QLatin1Char('0') && c <= QLatin1Char('9')) ||
9 ✔
727
        c == QLatin1Char('+') || c == QLatin1Char('-') || c == QLatin1Char('.');
7 ✔
728
  }
729
  const qsizetype hier = scheme ? colon + 1 : 0;
124 ✔
730
  if (url.mid(hier, 2) != QLatin1String("//")) {
248 ✔
731
    return -1;
732
  }
733
  qsizetype end = hier + 2;
92 ✔
734
  while (end < url.size() && !endsPart(url.at(end))) {
201,621 ✔
735
    ++end;
201,529 ✔
736
  }
737
  return end - (hier + 2);
92 ✔
738
}
739
} // namespace
740

741
auto Util::isLaunchableWebUrl(const QString &value) -> bool {
128 ✔
742
  const QString trimmed = value.trimmed();
743
  if (trimmed.isEmpty()) {
128 ✔
744
    return false;
745
  }
746
  // Reject control characters first, before QUrl normalisation can hide a
747
  // CR/LF/NUL injection into the OS URL handler.
748
  for (const QChar &c : trimmed) {
264,770 ✔
749
    if (c == QLatin1Char('\r') || c == QLatin1Char('\n') ||
750
        c == QChar(QChar::Null)) {
751
      return false;
752
    }
753
  }
754
  // QUrl runs the host through Unicode normalisation, which takes time in
755
  // the square of a run of combining marks out of canonical order: one line
756
  // of an entry kept the window busy for minutes. A host has at most 253
757
  // characters and a port six more, so a longer authority is no web
758
  // address anyway.
759
  constexpr qsizetype kMaxAuthority = 259;
760
  if (authorityLength(trimmed) > kMaxAuthority) {
124 ✔
761
    return false;
762
  }
763
  const QUrl url(trimmed, QUrl::StrictMode);
118 ✔
764
  if (!url.isValid()) {
118 ✔
765
    return false;
766
  }
767
  const QString scheme = url.scheme().toLower();
103 ✔
768
  if (scheme != QLatin1String("http") && scheme != QLatin1String("https")) {
103 ✔
769
    return false;
36 ✔
770
  }
771
  if (url.host().isEmpty()) {
134 ✔
772
    return false;
773
  }
774
  // Embedded userinfo (user:pass@host) would leak into browser history.
775
  if (!url.userName().isEmpty() || !url.password().isEmpty()) {
127 ✔
776
    return false;
777
  }
778
  return true;
779
}
118 ✔
780

781
auto Util::displayable(const QString &text, bool lineBreaks) -> QString {
31,821 ✔
782
  QString shown = text;
783
  for (qsizetype i = 0; i < shown.size(); ++i) {
21,542,702 ✔
784
    const char16_t u = shown.at(i).unicode();
785
    // A carriage return before a line feed is a Windows line end (git or
786
    // gpg output quoted in a message), not a character of its own.
787
    const bool lineEnd =
788
        lineBreaks && (u == u'\n' || (u == u'\r' && i + 1 < shown.size() &&
21,510,881 ✔
789
                                      shown.at(i + 1) == u'\n'));
790
    if ((u < 0x20 && u != u'\t' && !lineEnd) || (u >= 0x7f && u <= 0x9f) ||
21,510,881 ✔
791
        u == 0x2028 || u == 0x2029 || (u >= 0x202a && u <= 0x202e) ||
21,510,825 ✔
792
        (u >= 0x2066 && u <= 0x2069)) {
21,510,813 ✔
793
      shown[i] = QChar(QChar::ReplacementCharacter);
70 ✔
794
    }
795
  }
796
  return shown;
31,821 ✔
797
}
798

799
auto Util::linkifyUrls(const QString &text, bool *linked) -> QString {
154 ✔
800
  if (linked != nullptr) {
154 ✔
801
    *linked = false;
61 ✔
802
  }
803
  QString html;
154 ✔
804
  html.reserve(text.size());
154 ✔
805
  qsizetype lastIndex = 0;
806
  QRegularExpressionMatchIterator it = protocolRegex().globalMatch(text);
154 ✔
807
  while (it.hasNext()) {
202 ✔
808
    const QRegularExpressionMatch match = it.next();
48 ✔
809
    const QString url = match.captured(0);
48 ✔
810
    // Only plain ASCII becomes a link: the link text is the URL as stored,
811
    // and a right-to-left letter, a bidi control or a look-alike host in it
812
    // makes it read as another address than the one it opens. Such a URL
813
    // stays plain text; the open button still takes it.
814
    const bool plain = std::all_of(url.cbegin(), url.cend(), [](QChar c) {
815
      return c.unicode() > 0x20 && c.unicode() < 0x7f;
1,139 ✔
816
    });
817
    if (!plain || !isLaunchableWebUrl(url)) {
48 ✔
818
      // Not a web URL (or it carries credentials): leave it in the escaped
819
      // plain-text run instead of making it clickable.
820
      continue;
821
    }
822
    const qsizetype start = match.capturedStart(0);
32 ✔
823
    html += text.mid(lastIndex, start - lastIndex).toHtmlEscaped();
32 ✔
824
    const QString escapedUrl = url.toHtmlEscaped();
32 ✔
825
    html += QStringLiteral("<a href=\"%1\">%1</a>").arg(escapedUrl);
64 ✔
826
    lastIndex = match.capturedEnd(0);
32 ✔
827
    if (linked != nullptr) {
32 ✔
828
      *linked = true;
24 ✔
829
    }
830
  }
48 ✔
831
  html += text.mid(lastIndex).toHtmlEscaped();
154 ✔
832
  // With a link in it, no bidi embedding, override or isolate control is
833
  // drawn: an override earlier in the entry (U+202E) drew the link text
834
  // reversed, so it read as another address. Shown as U+FFFD, so the user
835
  // sees that something was there; the copy button still copies the value.
836
  if (linked != nullptr ? *linked : html.contains(QLatin1String("<a href="))) {
247 ✔
837
    for (QChar &c : html) {
3,442 ✔
838
      const char16_t u = c.unicode();
3,412 ✔
839
      if ((u >= 0x202A && u <= 0x202E) || (u >= 0x2066 && u <= 0x2069)) {
3,412 ✔
840
        c = QChar(QChar::ReplacementCharacter);
1 ✔
841
      }
842
    }
843
  }
844
  return html;
154 ✔
845
}
154 ✔
846

847
auto Util::isOtherBlockBreak(QChar c) -> bool {
5,345,354 ✔
848
  const char16_t u = c.unicode();
5,345,354 ✔
849
  return u == u'\r' || u == 0x2029 || u == 0xFDD0 || u == 0xFDD1;
5,345,354 ✔
850
}
851

852
auto Util::withoutOtherBlockBreaks(QString text) -> QString {
224 ✔
853
  for (QChar &c : text) {
564,261 ✔
854
    if (isOtherBlockBreak(c)) {
564,037 ✔
855
      c = QLatin1Char(' ');
8,002 ✔
856
    }
857
  }
858
  return text;
224 ✔
859
}
860

861
auto Util::hasLongUnbrokenRun(QStringView text) -> bool {
534 ✔
862
  qsizetype run = 0;
863
  for (const QChar c : text) {
11,196,690 ✔
864
    // A no-break space (U+00A0, U+2007, U+202F) is white space to
865
    // isSpace(), but Qt does not wrap at it.
866
    const char16_t u = c.unicode();
867
    const bool breaks =
868
        c.isSpace() && u != 0x00A0 && u != 0x2007 && u != 0x202F;
11,196,169 ✔
869
    run = breaks ? 0 : run + 1;
11,126,813 ✔
870
    if (run > kMaxUnbrokenRun) {
11,196,169 ✔
871
      return true;
872
    }
873
  }
874
  return false;
875
}
876

877
auto Util::plainToolTip(const QString &text) -> QString {
18,853 ✔
878
  // Escaped, with its white space kept: two names that differ only in it
879
  // must not read the same; a long run is cut as everywhere it is kept.
880
  return QStringLiteral("<p style=\"white-space: pre-wrap;\">") +
18,853 ✔
881
         boundSpaceRuns(displayable(text, false)).toHtmlEscaped() +
37,706 ✔
882
         QStringLiteral("</p>");
37,706 ✔
883
}
884

885
auto Util::shownName(const QString &name, qsizetype max) -> QString {
360 ✔
886
  QString line = displayable(name, false);
360 ✔
887
  line.replace(QLatin1Char('\t'), QLatin1Char(' '));
360 ✔
888
  if (line.size() <= max) {
360 ✔
889
    return line;
348 ✔
890
  }
891
  // Too short for an ellipsis between two ends: the head alone.
892
  if (max < 3) {
12 ✔
893
    qsizetype keep = std::max<qsizetype>(max, 0);
894
    if (keep > 0 && line.at(keep - 1).isHighSurrogate()) {
5 ✔
895
      --keep;
896
    }
897
    return line.left(keep);
5 ✔
898
  }
899
  qsizetype head = max / 3;
7 ✔
900
  if (line.at(head - 1).isHighSurrogate()) {
7 ✔
901
    --head;
902
  }
903
  qsizetype tail = max - max / 3 - 1;
7 ✔
904
  if (line.at(line.size() - tail).isLowSurrogate()) {
7 ✔
905
    --tail;
×
906
  }
907
  return line.left(head) + QChar(0x2026) + line.right(tail);
14 ✔
908
}
909

910
// One pass, no regex: a pattern such as \s{1001,} retries from every
911
// character of a shorter run, which is quadratic on an entry made of them.
912
// A tab or a line feed ends a run in Qt's layout as well, so it ends one
913
// here; \v and U+0085 do not, so they count.
914
auto Util::boundSpaceRuns(const QString &text) -> QString {
19,081 ✔
915
  QString bounded;
19,081 ✔
916
  // Text before this index is in bounded already, or dropped.
917
  qsizetype from = 0;
918
  qsizetype run = 0;
919
  for (qsizetype i = 0; i < text.size(); ++i) {
20,772,253 ✔
920
    const QChar ch = text.at(i);
921
    if (!ch.isSpace() || ch == QLatin1Char('\t') || ch == QLatin1Char('\n')) {
20,753,172 ✔
922
      run = 0;
923
      continue;
20,599,127 ✔
924
    }
925
    if (++run <= kMaxSpaceRun) {
154,045 ✔
926
      continue;
18,508 ✔
927
    }
928
    if (run == kMaxSpaceRun + 1) {
135,537 ✔
929
      bounded += QStringView(text).sliced(from, i - from);
6 ✔
930
    }
931
    from = i + 1;
135,537 ✔
932
  }
933
  if (from == 0) {
19,081 ✔
934
    return text;
935
  }
936
  bounded += QStringView(text).sliced(from);
937
  return bounded;
938
}
939

940
auto Util::newLinesRegex() -> const QRegularExpression & {
338 ✔
941
  static const QRegularExpression regex{"[\r\n]"};
346 ✔
942
  return regex;
338 ✔
943
}
944

945
// No content heuristics: a line rejected here is erased the next time .gpg-id
946
// is rewritten. A leading `-` is refused because the recipients also go
947
// positionally to `gpg --list-keys`, where it would parse as an option.
948
auto Util::isValidKeyId(const QString &keyId) -> bool {
6,343 ✔
949
  return !keyId.isEmpty() && !keyId.startsWith('-');
6,343 ✔
950
}
951

952
namespace {
953
/**
954
 * @brief Whether the walk can see what is in @p dir: read permission to list
955
 * it and, on Unix, search permission to look at what it holds (without it the
956
 * names come, but no entry reads as a file or a folder), and no name Qt
957
 * leaves out of the listing (Util::hasUnreadableName()).
958
 * @param dir An existing directory.
959
 * @return false when the walk would miss what is in it.
960
 */
961
auto canList(const QString &dir) -> bool {
214 ✔
962
#ifdef Q_OS_WIN
963
  // Qt answers from the attributes alone unless told to read the ACL.
964
  QNtfsPermissionCheckGuard aclCheck;
965
  return QFileInfo(dir).isReadable();
966
#else
967
  const QFileInfo info(dir);
214 ✔
968
  return info.isReadable() && info.isExecutable() &&
420 ✔
969
         !Util::hasUnreadableName(dir);
420 ✔
970
#endif
971
}
214 ✔
972

973
/**
974
 * @brief Walk @p dir's real, visible directories in sorted pre-order and hand
975
 * every entry to @p visit before any recursion; a directory is entered only
976
 * when @p visit returns true for it. A directory that cannot be read goes to
977
 * @p unlisted, when given: its listing would come back empty, as an empty
978
 * folder's does, and what is in it would be left out without a sign.
979
 */
980
template <typename Visit>
981
void walkStore(const QString &dir, Visit visit,
352 ✔
982
               QStringList *unlisted = nullptr) {
983
  // Absolute, so the results are whatever the caller's cwd; not canonical,
984
  // so a linked root keeps the name it was configured under.
985
  QStringList pending{QDir(QDir::cleanPath(dir)).absolutePath()};
1,056 ✔
986
  while (!pending.isEmpty()) {
2,968 ✔
987
    const QDir current(pending.takeLast());
1,313 ✔
988
    if (unlisted != nullptr && current.exists() && !canList(current.path())) {
2,626 ✔
989
      qCWarning(lcQtPass) << "Cannot list" << current.path();
20 ✔
990
      *unlisted << current.path();
10 ✔
991
      continue;
992
    }
10 ✔
993
    // Every entry once, links and hidden entries included, so the decision
994
    // what to do with each is taken here, before any recursion. QDir::System
995
    // keeps dangling links in the listing.
996
    const QFileInfoList entries =
1,303 ✔
997
        current.entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
998
                                  QDir::System | QDir::NoDotAndDotDot,
999
                              QDir::Name);
1000
    QStringList subdirs;
1,303 ✔
1001
    for (const QFileInfo &entry : entries) {
8,082 ✔
1002
      if (visit(entry)) {
6,779 ✔
1003
        subdirs << entry.filePath();
1,922 ✔
1004
      }
1005
    }
1006
    // Pushed last-to-first so the next one taken is the first by name.
1007
    for (auto it = subdirs.crbegin(); it != subdirs.crend(); ++it) {
2,264 ✔
1008
      pending << *it;
1009
    }
1010
  }
1011
}
704 ✔
1012

1013
/// A symlink or an NTFS junction: never entered, never listed.
1014
auto isLink(const QFileInfo &entry) -> bool {
28,641 ✔
1015
  return entry.isSymLink() || entry.isJunction();
28,641 ✔
1016
}
1017

1018
/// Hidden by attribute, or by the dot convention on every platform: Qt 6.11
1019
/// on macOS answers isHidden() from the UF_HIDDEN flag alone once an entry
1020
/// was lstat()ed (qfilesystemengine_unix.cpp marks the attribute known there
1021
/// without the dot check), and Windows does not consider .stversions hidden
1022
/// at all.
1023
auto isHiddenEntry(const QFileInfo &entry) -> bool {
5,692 ✔
1024
  return entry.isHidden() || entry.fileName().startsWith(QLatin1Char('.'));
11,364 ✔
1025
}
1026

1027
/// A real directory that is part of the store: .git, .stversions,
1028
/// .Trash-1000 are not, as with QDirIterator without QDir::Hidden.
1029
auto isStoreDirectory(const QFileInfo &entry) -> bool {
6,779 ✔
1030
  return !isLink(entry) && entry.isDir() && !isHiddenEntry(entry);
6,779 ✔
1031
}
1032
} // namespace
1033

1034
auto Util::regularFilesUnder(const QString &dir, const QStringList &nameFilters,
349 ✔
1035
                             QStringList *skipped, bool hiddenFiles,
1036
                             QStringList *unlisted) -> QStringList {
1037
  QStringList files;
349 ✔
1038
  walkStore(
349 ✔
1039
      dir,
1040
      [&](const QFileInfo &entry) {
6,703 ✔
1041
        if (isStoreDirectory(entry)) {
6,703 ✔
1042
          return true;
1043
        }
1044
        const bool named = QDir::match(nameFilters, entry.fileName());
5,763 ✔
1045
        if (isLink(entry) || (!entry.isDir() && !entry.isFile())) {
5,763 ✔
1046
          // A linked directory hides everything behind it; a linked file, or a
1047
          // FIFO, socket or device, is only of interest under a name the caller
1048
          // asked for.
1049
          if (skipped != nullptr && (entry.isDir() || named)) {
73 ✔
1050
            qCWarning(lcQtPass) << "Skipping" << entry.filePath()
108 ✔
1051
                                << ": not a regular file or directory";
54 ✔
1052
            *skipped << entry.filePath();
108 ✔
1053
          }
1054
          return false;
73 ✔
1055
        }
1056
        if (entry.isFile() && named && (hiddenFiles || !isHiddenEntry(entry))) {
5,690 ✔
1057
          files << entry.filePath();
9,842 ✔
1058
        }
1059
        return false;
1060
      },
1061
      unlisted);
1062
  return files;
349 ✔
1063
}
1064

1065
auto Util::directoriesUnder(const QString &dir) -> QStringList {
3 ✔
1066
  QStringList dirs;
3 ✔
1067
  walkStore(dir, [&](const QFileInfo &entry) {
3 ✔
1068
    if (!isStoreDirectory(entry)) {
76 ✔
1069
      return false;
1070
    }
1071
    dirs << entry.filePath();
21 ✔
1072
    return true;
21 ✔
1073
  });
1074
  return dirs;
3 ✔
1075
}
1076

1077
auto Util::hasUnreadableName(const QString &dir) -> bool {
313 ✔
1078
#ifdef Q_OS_WIN
1079
  Q_UNUSED(dir);
1080
  return false;
1081
#else
1082
  // The names as bytes, as readdir() gives them; Qt's own listing has
1083
  // already dropped the ones this is looking for.
1084
  DIR *listing = ::opendir(QFile::encodeName(dir).constData());
313 ✔
1085
  if (listing == nullptr) {
313 ✔
1086
    return false;
1087
  }
1088
  const auto close = qScopeGuard([listing] { ::closedir(listing); });
310 ✔
1089
  while (const dirent *entry = ::readdir(listing)) {
1,566 ✔
1090
    if (!QByteArrayView(entry->d_name).isValidUtf8()) {
1,262 ✔
1091
      return true;
1092
    }
1093
  }
1094
  return false;
1095
#endif
1096
}
1097

1098
auto Util::isLinkedFolder(const QString &path) -> bool {
16,058 ✔
1099
  return isLink(QFileInfo(QDir::cleanPath(path)));
32,116 ✔
1100
}
1101

1102
auto Util::isUnderLink(const QString &path, const QString &storeRoot,
12,929 ✔
1103
                       bool includeSelf) -> bool {
1104
  // "C:/Store" and "c:/store" are one directory on Windows; a path spelled
1105
  // the other way must not skip the walk (as in Pass::getGpgIdPath).
1106
#ifdef Q_OS_WIN
1107
  constexpr auto cs = Qt::CaseInsensitive;
1108
#else
1109
  constexpr auto cs = Qt::CaseSensitive;
1110
#endif
1111
  const QString root = QDir::cleanPath(storeRoot);
12,929 ✔
1112
  // A root of "/" or "C:/" already ends in the separator.
1113
  const QString prefix =
1114
      root.endsWith(QLatin1Char('/')) ? root : root + QLatin1Char('/');
12,929 ✔
1115
  const auto isRoot = [&](const QString &p) {
1116
    return p.compare(root, cs) == 0;
15,553 ✔
1117
  };
1118
  QString current = QDir::cleanPath(path);
12,929 ✔
1119
  if (!current.startsWith(prefix, cs)) {
12,929 ✔
1120
    // Not under the store as named: only the entry itself can be judged.
1121
    return includeSelf && !isRoot(current) && isLinkedFolder(current);
532 ✔
1122
  }
1123
  if (!includeSelf) {
12,663 ✔
1124
    current = QFileInfo(current).path();
23,476 ✔
1125
  }
1126
  for (; !isRoot(current) && current.startsWith(prefix, cs);
15,287 ✔
1127
       current = QFileInfo(current).path()) {
5,248 ✔
1128
    if (isLinkedFolder(current)) {
2,676 ✔
1129
      return true;
1130
    }
1131
  }
1132
  return false;
1133
}
1134

1135
#ifndef Q_OS_WIN
1136
namespace {
1137

1138
/// The filesystem cannot make hard links at all (FAT/exFAT refuse with
1139
/// EPERM, some FUSE filesystems with ENOTSUP or ENOSYS).
1140
auto hasNoHardLinks(int error) -> bool {
1141
  return error == EPERM || error == ENOTSUP || error == EOPNOTSUPP ||
2 ✔
1142
         error == ENOSYS;
1143
}
1144

1145
/// rename() that fails with EEXIST instead of replacing, where the platform
1146
/// has one; nothing when neither the platform nor the filesystem does.
1147
auto renameExclusive(const QByteArray &source, const QByteArray &target)
8 ✔
1148
    -> std::optional<bool> {
1149
#if defined(__GLIBC__) &&                                                      \
1150
    (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 28))
1151
  if (::renameat2(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(),
8 ✔
1152
                  RENAME_NOREPLACE) == 0) {
1153
    return true;
2 ✔
1154
  }
1155
  if (errno == EINVAL || errno == ENOSYS || hasNoHardLinks(errno)) {
6 ✔
1156
    return std::nullopt;
4 ✔
1157
  }
1158
  return false;
2 ✔
1159
#elif defined(Q_OS_MACOS)
1160
  if (::renamex_np(source.constData(), target.constData(), RENAME_EXCL) == 0) {
1161
    return true;
1162
  }
1163
  if (errno == EINVAL || errno == ENOTSUP) {
1164
    return std::nullopt;
1165
  }
1166
  return false;
1167
#else
1168
  Q_UNUSED(source);
1169
  Q_UNUSED(target);
1170
  return std::nullopt;
1171
#endif
1172
}
1173

1174
/**
1175
 * @brief Gives @p source the name @p target unless something already has it.
1176
 *
1177
 * A hard link is the one way every POSIX system can do that in one step:
1178
 * linkat() fails with EEXIST rather than replacing. Where the filesystem has
1179
 * no hard links, an exclusive rename does it; where that is missing too, the
1180
 * name is checked and then renamed, which leaves a short window for another
1181
 * writer to create it in between.
1182
 */
1183
auto placeWithoutReplacing(const QByteArray &source, const QByteArray &target)
116 ✔
1184
    -> bool {
1185
  // linkat() without AT_SYMLINK_FOLLOW follows nothing; link() would, on
1186
  // macOS and the BSDs, hard-link whatever a symlink planted under the
1187
  // source's name points at.
1188
  if (::linkat(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(), 0) ==
116 ✔
1189
      0) {
1190
    if (::unlink(source.constData()) == 0) {
100 ✔
1191
      return true;
1192
    }
1193
    // Both names now hold the file. Take the new one away again so the
1194
    // caller sees the state it started from, not a success with the source
1195
    // still there.
1196
    const int err = errno;
1 ✔
1197
    ::unlink(target.constData());
1 ✔
1198
    errno = err;
1 ✔
1199
    return false;
1 ✔
1200
  }
1201
  if (!hasNoHardLinks(errno)) {
16 ✔
1202
    return false;
1203
  }
1204
  if (const std::optional<bool> renamed = renameExclusive(source, target)) {
8 ✔
1205
    return *renamed;
4 ✔
1206
  }
1207
  struct stat st{};
4 ✔
1208
  if (::lstat(target.constData(), &st) == 0 || errno != ENOENT) {
4 ✔
1209
    errno = EEXIST;
2 ✔
1210
    return false;
2 ✔
1211
  }
1212
  return ::rename(source.constData(), target.constData()) == 0;
2 ✔
1213
}
1214

1215
} // namespace
1216
#endif
1217

1218
auto Util::replaceFile(const QString &from, const QString &to, bool replace)
294 ✔
1219
    -> bool {
1220
#ifdef Q_OS_WIN
1221
  const std::wstring source =
1222
      QDir::toNativeSeparators(QFileInfo(from).absoluteFilePath())
1223
          .toStdWString();
1224
  const std::wstring target =
1225
      QDir::toNativeSeparators(QFileInfo(to).absoluteFilePath()).toStdWString();
1226
  // WRITE_THROUGH: the new entry is on the device when this returns.
1227
  return MoveFileExW(source.c_str(), target.c_str(),
1228
                     (replace ? MOVEFILE_REPLACE_EXISTING : 0) |
1229
                         MOVEFILE_WRITE_THROUGH) != 0;
1230
#else
1231
  const QByteArray source = QFile::encodeName(from);
1232
  const QByteArray target = QFile::encodeName(to);
1233
  if (replace) {
294 ✔
1234
    if (::rename(source.constData(), target.constData()) != 0) {
178 ✔
1235
      return false;
1236
    }
1237
  } else {
1238
    if (!placeWithoutReplacing(source, target)) {
116 ✔
1239
      return false;
1240
    }
1241
  }
1242
  // Sync the directory entry so a crash does not lose the new name. Best
1243
  // effort: the bytes are already synced, and some network filesystems
1244
  // cannot sync a directory.
1245
  const int dir = ::open(QFile::encodeName(QFileInfo(to).path()).constData(),
556 ✔
1246
                         O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1247
  if (dir >= 0) {
278 ✔
1248
    int rc;
1249
    do {
1250
      rc = ::fsync(dir);
278 ✔
1251
    } while (rc != 0 && errno == EINTR);
278 ✔
1252
    ::close(dir);
278 ✔
1253
  }
1254
  return true;
1255
#endif
1256
}
1257

1258
auto Util::openRegularFile(const QString &path, QFile &file) -> bool {
587 ✔
1259
#ifdef Q_OS_WIN
1260
  // FILE_FLAG_OPEN_REPARSE_POINT opens a symbolic link or junction itself
1261
  // rather than its target, so the handle's attributes say what the name
1262
  // was at the moment of the open.
1263
  const std::wstring native =
1264
      QDir::toNativeSeparators(QFileInfo(path).absoluteFilePath())
1265
          .toStdWString();
1266
  HANDLE handle = CreateFileW(
1267
      native.c_str(), GENERIC_READ,
1268
      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
1269
      OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
1270
  if (handle == INVALID_HANDLE_VALUE) {
1271
    return false;
1272
  }
1273
  BY_HANDLE_FILE_INFORMATION info{};
1274
  if (!GetFileInformationByHandle(handle, &info) ||
1275
      (info.dwFileAttributes &
1276
       (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) != 0 ||
1277
      GetFileType(handle) != FILE_TYPE_DISK) {
1278
    CloseHandle(handle);
1279
    return false;
1280
  }
1281
  if ((info.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
1282
    // A link, a junction or anything else that names another file is
1283
    // refused. Any other reparse point (the placeholder of a cloud
1284
    // provider such as OneDrive, whose content is not on disk yet) is
1285
    // opened once more through it, so its filter fetches the content, and
1286
    // only when that open reaches the very same file.
1287
    FILE_ATTRIBUTE_TAG_INFO tag{};
1288
    if (!GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &tag,
1289
                                      sizeof(tag)) ||
1290
        IsReparseTagNameSurrogate(tag.ReparseTag)) {
1291
      CloseHandle(handle);
1292
      return false;
1293
    }
1294
    HANDLE through =
1295
        CreateFileW(native.c_str(), GENERIC_READ,
1296
                    FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1297
                    nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
1298
    // The 128-bit file ID: the 64-bit index in BY_HANDLE_FILE_INFORMATION
1299
    // is not unique on ReFS.
1300
    FILE_ID_INFO firstId{};
1301
    FILE_ID_INFO throughId{};
1302
    BY_HANDLE_FILE_INFORMATION after{};
1303
    const bool same =
1304
        through != INVALID_HANDLE_VALUE &&
1305
        GetFileInformationByHandleEx(handle, FileIdInfo, &firstId,
1306
                                     sizeof(firstId)) &&
1307
        GetFileInformationByHandleEx(through, FileIdInfo, &throughId,
1308
                                     sizeof(throughId)) &&
1309
        firstId.VolumeSerialNumber == throughId.VolumeSerialNumber &&
1310
        std::memcmp(&firstId.FileId, &throughId.FileId,
1311
                    sizeof(firstId.FileId)) == 0 &&
1312
        GetFileInformationByHandle(through, &after) &&
1313
        (after.dwFileAttributes &
1314
         (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) == 0 &&
1315
        GetFileType(through) == FILE_TYPE_DISK;
1316
    CloseHandle(handle);
1317
    if (!same) {
1318
      if (through != INVALID_HANDLE_VALUE) {
1319
        CloseHandle(through);
1320
      }
1321
      return false;
1322
    }
1323
    handle = through;
1324
  }
1325
  const int fd = _open_osfhandle(reinterpret_cast<intptr_t>(handle),
1326
                                 _O_RDONLY | _O_BINARY);
1327
  if (fd < 0) {
1328
    CloseHandle(handle);
1329
    return false;
1330
  }
1331
  if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
1332
    _close(fd);
1333
    return false;
1334
  }
1335
  return true;
1336
#else
1337
  // O_NOFOLLOW fails with ELOOP on a symbolic link; O_NONBLOCK keeps a FIFO
1338
  // from blocking the open until fstat() can refuse it.
1339
  const int fd = ::open(QFile::encodeName(path).constData(),
587 ✔
1340
                        O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
1341
  if (fd < 0) {
587 ✔
1342
    return false;
1343
  }
1344
  struct stat st{};
542 ✔
1345
  if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
542 ✔
1346
    ::close(fd);
7 ✔
1347
    return false;
7 ✔
1348
  }
1349
  // The descriptor, not the name, is what QFile opens here: the object
1350
  // fstat() judged is the object read. CodeQL's check-then-use pattern
1351
  // matcher sees an open after a check and cannot tell (its alert on this
1352
  // line is dismissed as a false positive; inline suppression comments are
1353
  // not read by the default setup).
1354
  if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
535 ✔
1355
    ::close(fd);
×
1356
    return false;
×
1357
  }
1358
  return true;
1359
#endif
1360
}
1361

1362
namespace {
1363
/**
1364
 * @brief Read an open regular file whole when it holds at most @p maxBytes.
1365
 * @param file Open on a regular file.
1366
 * @param maxBytes The most bytes accepted.
1367
 * @return The contents; nothing when larger or unreadable.
1368
 */
1369
auto readOpenFile(QFile &file, qint64 maxBytes) -> std::optional<QByteArray> {
1,056 ✔
1370
  // A regular file's size is reliable, also when sparse: refuse a large one
1371
  // before reading anything. One byte past the limit still guards a file
1372
  // that grows meanwhile.
1373
  if (file.size() > maxBytes) {
1,056 ✔
1374
    return std::nullopt;
7 ✔
1375
  }
1376
  QByteArray bytes = file.read(maxBytes + 1);
1,049 ✔
1377
  if (bytes.size() > maxBytes || file.error() != QFileDevice::NoError) {
1,049 ✔
1378
    return std::nullopt;
×
1379
  }
1380
  return bytes;
1381
}
1382
} // namespace
1383

1384
auto Util::readRegularFile(const QString &path, qint64 maxBytes)
73 ✔
1385
    -> std::optional<QByteArray> {
1386
  QFile file;
73 ✔
1387
  if (!openRegularFile(path, file)) {
73 ✔
1388
    return std::nullopt;
10 ✔
1389
  }
1390
  return readOpenFile(file, maxBytes);
63 ✔
1391
}
73 ✔
1392

1393
auto Util::readRegularFileInStore(const QString &store, const QString &path,
629 ✔
1394
                                  qint64 maxBytes)
1395
    -> std::optional<QByteArray> {
1396
  const auto under = [&path](const QString &root) {
633 ✔
1397
    const QString relative = QDir(root).relativeFilePath(QDir::cleanPath(path));
1,266 ✔
1398
    return !root.isEmpty() && !QDir::isAbsolutePath(relative) &&
633 ✔
1399
           relative != QStringLiteral("..") &&
1,899 ✔
1400
           !relative.startsWith(QStringLiteral("../"));
1,899 ✔
1401
  };
629 ✔
1402
  const QString root = QDir::cleanPath(store);
629 ✔
1403
  if (under(root)) {
629 ✔
1404
    return readRegularFileUnder(root, path, maxBytes);
625 ✔
1405
  }
1406
  const QString canonical = QFileInfo(root).canonicalFilePath();
4 ✔
1407
  if (under(canonical)) {
4 ✔
1408
    return readRegularFileUnder(canonical, path, maxBytes);
2 ✔
1409
  }
1410
  return std::nullopt;
2 ✔
1411
}
1412

1413
auto Util::readRegularFileUnder(const QString &root, const QString &path,
1,068 ✔
1414
                                qint64 maxBytes) -> std::optional<QByteArray> {
1415
  const QString cleanRoot = QDir::cleanPath(root);
1,068 ✔
1416
  const QString relative =
1417
      QDir(cleanRoot).relativeFilePath(QDir::cleanPath(path));
2,136 ✔
1418
  const QStringList parts = relative.split(QLatin1Char('/'));
1,068 ✔
1419
  if (relative.isEmpty() || QDir::isAbsolutePath(relative) ||
2,136 ✔
1420
      parts.contains(QStringLiteral("..")) ||
2,134 ✔
1421
      parts.contains(QStringLiteral(".")) || parts.contains(QString())) {
4,267 ✔
1422
    return std::nullopt;
3 ✔
1423
  }
1424
#ifdef Q_OS_WIN
1425
  // No openat() here: each folder from the root down is opened by name and
1426
  // held open, without FILE_SHARE_DELETE, until the file is read. A folder
1427
  // held that way cannot be renamed, removed or replaced by a junction
1428
  // meanwhile, so the file is opened through exactly the folders judged.
1429
  // The root itself is followed (a linked store is the user's setup).
1430
  std::vector<HANDLE> held;
1431
  const auto release = qScopeGuard([&held] {
1432
    for (HANDLE handle : held) {
1433
      CloseHandle(handle);
1434
    }
1435
  });
1436
  QString folder = cleanRoot;
1437
  for (qsizetype i = 0; i < parts.size(); ++i) {
1438
    const bool isRoot = i == 0;
1439
    if (!isRoot) {
1440
      folder += QLatin1Char('/') + parts.at(i - 1);
1441
    }
1442
    const std::wstring native = QDir::toNativeSeparators(folder).toStdWString();
1443
    // GENERIC_READ (listing the folder) is data access, so the share mode
1444
    // is enforced against a later open for DELETE; attribute access alone
1445
    // would not be.
1446
    HANDLE handle =
1447
        CreateFileW(native.c_str(), GENERIC_READ,
1448
                    FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING,
1449
                    FILE_FLAG_BACKUP_SEMANTICS |
1450
                        (isRoot ? 0 : FILE_FLAG_OPEN_REPARSE_POINT),
1451
                    nullptr);
1452
    if (handle == INVALID_HANDLE_VALUE) {
1453
      return std::nullopt;
1454
    }
1455
    held.push_back(handle);
1456
    // A reparse point that names another place (a symbolic link, a
1457
    // junction: what the walk's isLink() leaves out) is refused, as
1458
    // openRegularFile() refuses one as the file. A folder with another
1459
    // reparse tag, such as a cloud provider's placeholder, is listed by the
1460
    // walk and is read through here too.
1461
    FILE_ATTRIBUTE_TAG_INFO info{};
1462
    if (!GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &info,
1463
                                      sizeof(info)) ||
1464
        (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
1465
      return std::nullopt;
1466
    }
1467
    const bool link =
1468
        (info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 &&
1469
        IsReparseTagNameSurrogate(info.ReparseTag);
1470
    if (!isRoot && link) {
1471
      return std::nullopt;
1472
    }
1473
  }
1474
  // openRegularFile() refuses a link or junction as the file itself, and
1475
  // reads any other reparse point (a cloud placeholder) through.
1476
  return readRegularFile(path, maxBytes);
1477
#else
1478
  // The root by name, followed if it is a link (the user's setup); below it
1479
  // nothing is.
1480
  int dir = ::open(QFile::encodeName(cleanRoot).constData(),
1,065 ✔
1481
                   O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1482
  if (dir < 0) {
1,065 ✔
1483
    return std::nullopt;
×
1484
  }
1485
  for (qsizetype i = 0; i + 1 < parts.size(); ++i) {
1,201 ✔
1486
    const int next = ::openat(dir, QFile::encodeName(parts.at(i)).constData(),
145 ✔
1487
                              O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
1488
    ::close(dir);
145 ✔
1489
    if (next < 0) {
145 ✔
1490
      return std::nullopt;
9 ✔
1491
    }
1492
    dir = next;
1493
  }
1494
  // As openRegularFile(): no link, no FIFO left blocking the open.
1495
  const int fd = ::openat(dir, QFile::encodeName(parts.constLast()).constData(),
×
1496
                          O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
1497
  ::close(dir);
1,056 ✔
1498
  if (fd < 0) {
1,056 ✔
1499
    return std::nullopt;
61 ✔
1500
  }
1501
  struct stat st{};
995 ✔
1502
  if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
995 ✔
1503
    ::close(fd);
2 ✔
1504
    return std::nullopt;
2 ✔
1505
  }
1506
  // As in openRegularFile(): QFile takes the descriptor fstat() judged, not
1507
  // the name, so a name swapped between the check and the read cannot make
1508
  // it read another file (the file's contents can still change; the check
1509
  // is on what kind of file it is). CodeQL flags the open anyway; that alert
1510
  // is dismissed as a false positive.
1511
  QFile file;
993 ✔
1512
  if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
993 ✔
UNCOV
1513
    ::close(fd);
×
1514
    return std::nullopt;
×
1515
  }
1516
  return readOpenFile(file, maxBytes);
993 ✔
1517
#endif
1518
}
993 ✔
1519

1520
auto Util::syncToDisk(QFileDevice &file) -> bool {
277 ✔
1521
  if (!file.flush()) {
277 ✔
1522
    return false;
1523
  }
1524
#ifdef Q_OS_WIN
1525
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1526
  return handle != INVALID_HANDLE_VALUE && FlushFileBuffers(handle) != 0;
1527
#else
1528
  return ::fsync(file.handle()) == 0;
277 ✔
1529
#endif
1530
}
1531

1532
namespace {
1533

1534
/**
1535
 * @brief What tells one file object from another on its filesystem: device
1536
 * and inode on POSIX, volume serial and file index on Windows.
1537
 */
1538
struct FileIdentity {
1539
  quint64 volume = 0;
1540
  quint64 index = 0;
1541
  bool known = false;
1542
};
1543

1544
auto operator==(const FileIdentity &a, const FileIdentity &b) -> bool {
266 ✔
1545
  return a.known && b.known && a.volume == b.volume && a.index == b.index;
266 ✔
1546
}
1547

1548
/// The identity of the object @p file is open on, or an unknown one.
1549
auto identityOf(const QFileDevice &file) -> FileIdentity {
543 ✔
1550
#ifdef Q_OS_WIN
1551
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1552
  BY_HANDLE_FILE_INFORMATION info;
1553
  if (handle == INVALID_HANDLE_VALUE ||
1554
      GetFileInformationByHandle(handle, &info) == 0) {
1555
    return {};
1556
  }
1557
  // On FAT/exFAT the file ID is the directory entry's offset, which a rename
1558
  // can move. They have no hard links either (the swap this catches needs
1559
  // one), so the identity is left unknown there.
1560
  DWORD flags = 0;
1561
  if (GetVolumeInformationByHandleW(handle, nullptr, 0, nullptr, nullptr,
1562
                                    &flags, nullptr, 0) == 0 ||
1563
      (flags & FILE_SUPPORTS_HARD_LINKS) == 0) {
1564
    return {};
1565
  }
1566
  return {info.dwVolumeSerialNumber,
1567
          (static_cast<quint64>(info.nFileIndexHigh) << 32) |
1568
              info.nFileIndexLow,
1569
          true};
1570
#else
1571
  struct stat st{};
543 ✔
1572
  if (::fstat(file.handle(), &st) != 0) {
543 ✔
1573
    return {};
×
1574
  }
1575
  return {static_cast<quint64>(st.st_dev), static_cast<quint64>(st.st_ino),
543 ✔
1576
          true};
543 ✔
1577
#endif
1578
}
1579

1580
/// Put @p text in @p error when there is one; false, for `return fail(...)`.
1581
auto fail(QString *error, const QString &text) -> bool {
1582
  if (error != nullptr) {
22 ✔
1583
    *error = text;
22 ✔
1584
  }
1585
  return false;
1586
}
1587

1588
/// A filled, synced temporary next to its destination.
1589
struct Staged {
277 ✔
1590
  QString path;
1591
  FileIdentity identity;
1592
  /// POSIX: a descriptor kept open on the temporary until the identity
1593
  /// check, so the inode, and with it the number, stays the temporary's.
1594
  std::shared_ptr<void> pin;
1595
};
1596

1597
/**
1598
 * @brief Create the temporary next to @p path (opaque name, exclusive,
1599
 * owner-only), fill it through its handle and sync it. The QTemporaryFile
1600
 * goes out of scope before the caller renames: it keeps its handle open for
1601
 * as long as it lives, and Windows does not rename an open file.
1602
 */
1603
auto stageNextTo(const QString &path, const Util::Filler &fill, QString *why)
285 ✔
1604
    -> std::optional<Staged> {
1605
  Staged staged;
285 ✔
1606
  {
1607
    QTemporaryFile file(QFileInfo(path).path() +
570 ✔
1608
                        QStringLiteral("/.qtpass-XXXXXX.tmp"));
570 ✔
1609
    file.setAutoRemove(false);
285 ✔
1610
    if (!file.open()) {
285 ✔
1611
      *why = QCoreApplication::translate(
8 ✔
1612
                 "Util", "Cannot create a temporary file next to %1: %2")
1613
                 .arg(path, file.errorString());
16 ✔
1614
      return std::nullopt;
8 ✔
1615
    }
1616
    staged.path = file.fileName();
277 ✔
1617
    // Owner-only: a .gpg-id names the keys a store is encrypted to, an
1618
    // entry is an entry. QTemporaryFile creates 0600 already; say so for
1619
    // platforms where it may not.
1620
    file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
277 ✔
1621
    *why = fill(file);
554 ✔
1622
    if (why->isEmpty() && !Util::syncToDisk(file)) {
277 ✔
1623
      *why = QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1624
                 .arg(path, file.errorString());
×
1625
    }
1626
    staged.identity = identityOf(file);
277 ✔
1627
#ifndef Q_OS_WIN
1628
    // Closed and unlinked by a co-writer before the rename, the temporary's
1629
    // inode number would be free, and ext4 hands it to the next file made:
1630
    // the very file swapped in would then pass the check below. Windows
1631
    // cannot rename an open file, and NTFS does not reuse a file index so.
1632
    if (const int fd = ::dup(file.handle()); fd >= 0) {
277 ✔
1633
      staged.pin =
1634
          std::shared_ptr<void>(nullptr, [fd](void *) { ::close(fd); });
831 ✔
1635
    }
1636
#endif
1637
  }
285 ✔
1638
  if (!why->isEmpty()) {
277 ✔
1639
    QFile::remove(staged.path);
×
1640
    return std::nullopt;
×
1641
  }
1642
  return staged;
277 ✔
1643
}
285 ✔
1644

1645
/// Why replaceFile() could not put the temporary under @p path.
1646
auto placementError(const QString &path, bool replace) -> QString {
9 ✔
1647
  if (replace) {
9 ✔
1648
    return QCoreApplication::translate("Util", "Failed to replace %1.")
4 ✔
1649
        .arg(path);
2 ✔
1650
  }
1651
  const QFileInfo taken(path);
7 ✔
1652
  return taken.exists() || taken.isSymLink()
8 ✔
1653
             ? QCoreApplication::translate("Util", "%1 already exists.")
7 ✔
1654
                   .arg(path)
1655
             : QCoreApplication::translate("Util", "Failed to write %1.")
1 ✔
1656
                   .arg(path);
8 ✔
1657
}
7 ✔
1658

1659
/**
1660
 * @brief Whether what is under @p path is the file that was filled: not a
1661
 * link, and not another file (a hard link to something of the user's, say)
1662
 * swapped in under the temporary's name. Opened without following, compared
1663
 * by identity; only two known identities can prove a swap, otherwise every
1664
 * write on such a store would be reported as tampering.
1665
 */
1666
auto isTheFileWritten(const QString &path, const FileIdentity &written)
268 ✔
1667
    -> bool {
1668
  QFile placed;
268 ✔
1669
  if (!Util::openRegularFile(path, placed)) {
268 ✔
1670
    return false;
1671
  }
1672
  const FileIdentity there = identityOf(placed);
266 ✔
1673
  if (!written.known || !there.known) {
266 ✔
1674
    qCWarning(lcQtPass) << "Cannot tell whether" << path
×
1675
                        << "is the file that was written here";
×
1676
    return true;
×
1677
  }
1678
  return there == written;
266 ✔
1679
}
268 ✔
1680

1681
} // namespace
1682

1683
auto Util::stageFileReplacing(const QString &path, bool replace,
285 ✔
1684
                              const Filler &fill, QString *error) -> bool {
1685
  QString why;
285 ✔
1686
  const std::optional<Staged> staged = stageNextTo(path, fill, &why);
285 ✔
1687
  if (!staged) {
285 ✔
1688
    return fail(error, why);
1689
  }
1690
  if (s_beforePlacingForTests) {
277 ✔
1691
    s_beforePlacingForTests(staged->path);
1 ✔
1692
  }
1693
  if (!replaceFile(staged->path, path, replace)) {
277 ✔
1694
    QFile::remove(staged->path);
9 ✔
1695
    return fail(error, placementError(path, replace));
18 ✔
1696
  }
1697
  // A mismatch is reported and left: removing by name could take another
1698
  // writer's file.
1699
  if (!isTheFileWritten(path, staged->identity)) {
268 ✔
1700
    return fail(
1701
        error,
1702
        QCoreApplication::translate(
5 ✔
1703
            "Util", "%1 was swapped for another file while it was written.")
1704
            .arg(path));
10 ✔
1705
  }
1706
  return true;
1707
}
1708

1709
auto Util::writeFileReplacing(const QString &path, const QByteArray &bytes,
110 ✔
1710
                              bool replace, QString *error) -> bool {
1711
  return stageFileReplacing(
110 ✔
1712
      path, replace,
1713
      [&path, &bytes](QFileDevice &staged) -> QString {
218 ✔
1714
        if (staged.write(bytes) != bytes.size()) {
108 ✔
1715
          return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1716
              .arg(path, staged.errorString());
×
1717
        }
1718
        return {};
108 ✔
1719
      },
1720
      error);
110 ✔
1721
}
1722

1723
auto Util::copyFileReplacing(const QString &src, const QString &dst,
174 ✔
1724
                             bool replace, QString *error) -> bool {
1725
  QFile in;
174 ✔
1726
  if (!openRegularFile(src, in)) {
174 ✔
1727
    if (error)
4 ✔
1728
      *error = QCoreApplication::translate("Util", "Cannot read %1.").arg(src);
8 ✔
1729
    return false;
4 ✔
1730
  }
1731
  return stageFileReplacing(
170 ✔
1732
      dst, replace,
1733
      [&src, &dst, &in](QFileDevice &staged) -> QString {
504 ✔
1734
        char buf[64 * 1024];
1735
        for (;;) {
1736
          const qint64 n = in.read(buf, sizeof buf);
340 ✔
1737
          if (n < 0) {
340 ✔
1738
            return QCoreApplication::translate("Util", "Cannot read %1: %2")
×
1739
                .arg(src, in.errorString());
×
1740
          }
1741
          if (n == 0) {
340 ✔
1742
            return {};
164 ✔
1743
          }
1744
          if (staged.write(buf, n) != n) {
176 ✔
1745
            return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1746
                .arg(dst, staged.errorString());
×
1747
          }
1748
        }
1749
      },
1750
      error);
1751
}
174 ✔
1752

1753
namespace {
1754

1755
/// Remove one directory entry that is not a real directory: a link goes as
1756
/// the entry itself, never its target (a junction or a directory symlink on
1757
/// Windows is a directory entry and goes with rmdir); a read-only file gets
1758
/// write access and one more try, as QDir::removeRecursively() does.
1759
auto removeEntry(const QFileInfo &entry) -> bool {
14 ✔
1760
  const QString path = entry.filePath();
14 ✔
1761
  if (isLink(entry)) {
14 ✔
1762
    if (QFile::remove(path) || QDir().rmdir(path)) {
6 ✔
1763
      return true;
1764
    }
1765
    qCWarning(lcQtPass) << "Could not remove link" << path;
2 ✔
1766
    return false;
1 ✔
1767
  }
1768
  if (QFile::remove(path)) {
9 ✔
1769
    return true;
1770
  }
1771
  const QFile::Permissions perms = QFile::permissions(path);
2 ✔
1772
  if (!perms.testFlag(QFile::WriteUser) &&
1 ✔
1773
      QFile::setPermissions(path, perms | QFile::WriteUser) &&
3 ✔
1774
      QFile::remove(path)) {
1 ✔
1775
    return true;
1776
  }
1777
  qCWarning(lcQtPass) << "Could not remove" << path;
4 ✔
1778
  return false;
2 ✔
1779
}
1780

1781
} // namespace
1782

1783
auto Util::removeTree(const QString &dir) -> bool {
23 ✔
1784
  // A trailing separator makes lstat follow a link ("link/" is the target
1785
  // directory); the link itself is what this is about.
1786
  const QString path = QDir::cleanPath(dir);
23 ✔
1787
  const QFileInfo top(path);
23 ✔
1788
  if (isLink(top)) {
23 ✔
1789
    // rm -rf on a link removes the link.
1790
    return QFile::remove(path) || QDir().rmdir(path);
16 ✔
1791
  }
1792
  if (!top.isDir()) {
9 ✔
1793
    return false;
1794
  }
1795
  bool ok = true;
1796
  const QFileInfoList entries =
1797
      QDir(path).entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
16 ✔
1798
                                   QDir::System | QDir::NoDotAndDotDot,
1799
                               QDir::Name);
8 ✔
1800
  for (const QFileInfo &entry : entries) {
24 ✔
1801
    const bool removed = entry.isDir() && !isLink(entry)
22 ✔
1802
                             ? removeTree(entry.filePath())
18 ✔
1803
                             : removeEntry(entry);
14 ✔
1804
    ok = removed && ok;
16 ✔
1805
  }
1806
  return ok && QDir().rmdir(path);
13 ✔
1807
}
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