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

IJHack / QtPass / 44265697413

18 Nov 2026 08:17AM UTC coverage: 96.28% (-0.1%) from 96.396%
44265697413

push

github

web-flow
Git commits take only their own paths; tool output stays plain and short (#2260)

* Git commits take only their own paths; tool output stays plain and short

- createBackupCommit() stages and commits the store only (`-- .` with -C
  the store): in a repository above it, a modified tracked file outside
  was committed and auto-pushed. The conflict check keeps its
  repository-wide status. Move and copy commit their own paths, not
  whatever else was staged (ANT-2026-P6R5B5PK).
- The first-run wizard, Settings and the key export show their boxes
  with PlainMessageBox: ProfileInit's note ends in git's stderr, which can
  quote a pushed .gitattributes value as markup and a link
  (ANT-2026-V7X4M2B6).
- PlainMessageBox shows at most 40 lines and 4000 characters: a box
  laying out git's whole error output froze the GUI
  (ANT-2026-J1OLDGTJ).
- repositoryPassClimbsTo() reads HEAD and a .git file with
  openRegularFile(): a link to a FIFO or a device blocked the open on the
  GUI thread when Settings opened (ANT-2026-0KZE41ZD).

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

* Names on one line in confirmations; git's own metadata links count

From the #2260 review:
- The re-encrypt, link-removal and overwrite questions put the quoted
  names on one line: a folder name with line feeds pushed the warning out
  of the box, which now shows 40 lines at most, and Yes still ran.
- repositoryPassClimbsTo() opens HEAD and a .git file following links
  but only to a regular file, without blocking (O_NONBLOCK, then fstat):
  git takes HEAD -> refs/heads/main and a .git link to a gitfile, which
  openRegularFile()'s O_NOFOLLOW refused, so the Settings warning about
  the repository pass commits in went missing.

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

* Message boxes: the rest of a cut message under Show Details

From the #2260 review:... (continued)

79 of 93 new or added lines in 8 files covered. (84.95%)

6 existing lines in 1 file now uncovered.

9110 of 9462 relevant lines covered (96.28%)

1291.19 hits per line

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

93.98
/src/util.cpp
1
// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
/**
4
 * @file
5
 * @brief Implements Util; the staged, link-safe store writes
6
 * (stageFileReplacing() and its helpers) and the store walk (walkStore())
7
 * live here.
8
 */
9
#include "util.h"
10
#include "appsettings.h"
11
#include "executor.h"
12
#include <QCoreApplication>
13
#include <QDebug>
14
#include <QDir>
15
#include <QFile>
16
#include <QFileDevice>
17
#include <QFileInfo>
18
#include <QHash>
19
#include <QRegularExpression>
20
#include <QRegularExpressionMatchIterator>
21
#include <QScopeGuard>
22
#include <QStandardPaths>
23
#include <QTemporaryFile>
24
#include <QUrl>
25

26
#include <algorithm>
27
#include <memory>
28
#include <optional>
29

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

44
#include "qtpasslogging.h"
45

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

532
  initialiseEnvironment();
526 ✔
533

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

584
  return ret;
585
}
586

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

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

615
  const QString executable = s.usePass ? s.passExecutable : s.gpgExecutable;
197 ✔
616

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

635
auto Util::endsWithGpg() -> const QRegularExpression & {
15,850 ✔
636
  static const QRegularExpression expr{R"(\.gpg$)"};
15,857 ✔
637
  return expr;
15,850 ✔
638
}
639

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

649
auto Util::isLaunchableWebUrl(const QString &value) -> bool {
117 ✔
650
  const QString trimmed = value.trimmed();
651
  if (trimmed.isEmpty()) {
117 ✔
652
    return false;
653
  }
654
  // Reject control characters first, before QUrl normalisation can hide a
655
  // CR/LF/NUL injection into the OS URL handler.
656
  for (const QChar &c : trimmed) {
4,092 ✔
657
    if (c == QLatin1Char('\r') || c == QLatin1Char('\n') ||
658
        c == QChar(QChar::Null)) {
659
      return false;
660
    }
661
  }
662
  const QUrl url(trimmed, QUrl::StrictMode);
113 ✔
663
  if (!url.isValid()) {
113 ✔
664
    return false;
665
  }
666
  const QString scheme = url.scheme().toLower();
98 ✔
667
  if (scheme != QLatin1String("http") && scheme != QLatin1String("https")) {
98 ✔
668
    return false;
35 ✔
669
  }
670
  if (url.host().isEmpty()) {
126 ✔
671
    return false;
672
  }
673
  // Embedded userinfo (user:pass@host) would leak into browser history.
674
  if (!url.userName().isEmpty() || !url.password().isEmpty()) {
119 ✔
675
    return false;
676
  }
677
  return true;
678
}
113 ✔
679

680
auto Util::displayable(const QString &text, bool lineBreaks) -> QString {
458 ✔
681
  QString shown = text;
682
  for (qsizetype i = 0; i < shown.size(); ++i) {
988,443 ✔
683
    const char16_t u = shown.at(i).unicode();
684
    // A carriage return before a line feed is a Windows line end (git or
685
    // gpg output quoted in a message), not a character of its own.
686
    const bool lineEnd =
687
        lineBreaks && (u == u'\n' || (u == u'\r' && i + 1 < shown.size() &&
987,985 ✔
688
                                      shown.at(i + 1) == u'\n'));
689
    if ((u < 0x20 && u != u'\t' && !lineEnd) || (u >= 0x7f && u <= 0x9f) ||
987,985 ✔
690
        u == 0x2028 || u == 0x2029 || (u >= 0x202a && u <= 0x202e) ||
987,931 ✔
691
        (u >= 0x2066 && u <= 0x2069)) {
987,923 ✔
692
      shown[i] = QChar(QChar::ReplacementCharacter);
64 ✔
693
    }
694
  }
695
  return shown;
458 ✔
696
}
697

698
auto Util::linkifyUrls(const QString &text, bool *linked) -> QString {
145 ✔
699
  if (linked != nullptr) {
145 ✔
700
    *linked = false;
60 ✔
701
  }
702
  QString html;
145 ✔
703
  html.reserve(text.size());
145 ✔
704
  qsizetype lastIndex = 0;
705
  QRegularExpressionMatchIterator it = protocolRegex().globalMatch(text);
145 ✔
706
  while (it.hasNext()) {
193 ✔
707
    const QRegularExpressionMatch match = it.next();
48 ✔
708
    const QString url = match.captured(0);
48 ✔
709
    // Only plain ASCII becomes a link: the link text is the URL as stored,
710
    // and a right-to-left letter, a bidi control or a look-alike host in it
711
    // makes it read as another address than the one it opens. Such a URL
712
    // stays plain text; the open button still takes it.
713
    const bool plain = std::all_of(url.cbegin(), url.cend(), [](QChar c) {
714
      return c.unicode() > 0x20 && c.unicode() < 0x7f;
1,139 ✔
715
    });
716
    if (!plain || !isLaunchableWebUrl(url)) {
48 ✔
717
      // Not a web URL (or it carries credentials): leave it in the escaped
718
      // plain-text run instead of making it clickable.
719
      continue;
720
    }
721
    const qsizetype start = match.capturedStart(0);
32 ✔
722
    html += text.mid(lastIndex, start - lastIndex).toHtmlEscaped();
32 ✔
723
    const QString escapedUrl = url.toHtmlEscaped();
32 ✔
724
    html += QStringLiteral("<a href=\"%1\">%1</a>").arg(escapedUrl);
64 ✔
725
    lastIndex = match.capturedEnd(0);
32 ✔
726
    if (linked != nullptr) {
32 ✔
727
      *linked = true;
24 ✔
728
    }
729
  }
48 ✔
730
  html += text.mid(lastIndex).toHtmlEscaped();
145 ✔
731
  // With a link in it, no bidi embedding, override or isolate control is
732
  // drawn: an override earlier in the entry (U+202E) drew the link text
733
  // reversed, so it read as another address. Shown as U+FFFD, so the user
734
  // sees that something was there; the copy button still copies the value.
735
  if (linked != nullptr ? *linked : html.contains(QLatin1String("<a href="))) {
230 ✔
736
    for (QChar &c : html) {
3,442 ✔
737
      const char16_t u = c.unicode();
3,412 ✔
738
      if ((u >= 0x202A && u <= 0x202E) || (u >= 0x2066 && u <= 0x2069)) {
3,412 ✔
739
        c = QChar(QChar::ReplacementCharacter);
1 ✔
740
      }
741
    }
742
  }
743
  return html;
145 ✔
744
}
145 ✔
745

746
// One pass, no regex: a pattern such as \s{1001,} retries from every
747
// character of a shorter run, which is quadratic on an entry made of them.
748
// A tab or a line feed ends a run in Qt's layout as well, so it ends one
749
// here; \v and U+0085 do not, so they count.
750
auto Util::boundSpaceRuns(const QString &text) -> QString {
210 ✔
751
  QString bounded;
210 ✔
752
  // Text before this index is in bounded already, or dropped.
753
  qsizetype from = 0;
754
  qsizetype run = 0;
755
  for (qsizetype i = 0; i < text.size(); ++i) {
154,087 ✔
756
    const QChar ch = text.at(i);
757
    if (!ch.isSpace() || ch == QLatin1Char('\t') || ch == QLatin1Char('\n')) {
153,877 ✔
758
      run = 0;
759
      continue;
6,850 ✔
760
    }
761
    if (++run <= kMaxSpaceRun) {
147,027 ✔
762
      continue;
11,490 ✔
763
    }
764
    if (run == kMaxSpaceRun + 1) {
135,537 ✔
765
      bounded += QStringView(text).sliced(from, i - from);
6 ✔
766
    }
767
    from = i + 1;
135,537 ✔
768
  }
769
  if (from == 0) {
210 ✔
770
    return text;
771
  }
772
  bounded += QStringView(text).sliced(from);
773
  return bounded;
774
}
775

776
auto Util::newLinesRegex() -> const QRegularExpression & {
326 ✔
777
  static const QRegularExpression regex{"[\r\n]"};
335 ✔
778
  return regex;
326 ✔
779
}
780

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

788
namespace {
789
/**
790
 * @brief Whether the walk can see what is in @p dir: read permission to list
791
 * it and, on Unix, search permission to look at what it holds (without it the
792
 * names come, but no entry reads as a file or a folder), and no name Qt
793
 * leaves out of the listing (Util::hasUnreadableName()).
794
 * @param dir An existing directory.
795
 * @return false when the walk would miss what is in it.
796
 */
797
auto canList(const QString &dir) -> bool {
183 ✔
798
#ifdef Q_OS_WIN
799
  // Qt answers from the attributes alone unless told to read the ACL.
800
  QNtfsPermissionCheckGuard aclCheck;
801
  return QFileInfo(dir).isReadable();
802
#else
803
  const QFileInfo info(dir);
183 ✔
804
  return info.isReadable() && info.isExecutable() &&
358 ✔
805
         !Util::hasUnreadableName(dir);
358 ✔
806
#endif
807
}
183 ✔
808

809
/**
810
 * @brief Walk @p dir's real, visible directories in sorted pre-order and hand
811
 * every entry to @p visit before any recursion; a directory is entered only
812
 * when @p visit returns true for it. A directory that cannot be read goes to
813
 * @p unlisted, when given: its listing would come back empty, as an empty
814
 * folder's does, and what is in it would be left out without a sign.
815
 */
816
template <typename Visit>
817
void walkStore(const QString &dir, Visit visit,
299 ✔
818
               QStringList *unlisted = nullptr) {
819
  // Absolute, so the results are whatever the caller's cwd; not canonical,
820
  // so a linked root keeps the name it was configured under.
821
  QStringList pending{QDir(QDir::cleanPath(dir)).absolutePath()};
897 ✔
822
  while (!pending.isEmpty()) {
1,169 ✔
823
    const QDir current(pending.takeLast());
440 ✔
824
    if (unlisted != nullptr && current.exists() && !canList(current.path())) {
880 ✔
825
      qCWarning(lcQtPass) << "Cannot list" << current.path();
20 ✔
826
      *unlisted << current.path();
10 ✔
827
      continue;
828
    }
10 ✔
829
    // Every entry once, links and hidden entries included, so the decision
830
    // what to do with each is taken here, before any recursion. QDir::System
831
    // keeps dangling links in the listing.
832
    const QFileInfoList entries =
430 ✔
833
        current.entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
834
                                  QDir::System | QDir::NoDotAndDotDot,
835
                              QDir::Name);
836
    QStringList subdirs;
430 ✔
837
    for (const QFileInfo &entry : entries) {
2,223 ✔
838
      if (visit(entry)) {
1,793 ✔
839
        subdirs << entry.filePath();
282 ✔
840
      }
841
    }
842
    // Pushed last-to-first so the next one taken is the first by name.
843
    for (auto it = subdirs.crbegin(); it != subdirs.crend(); ++it) {
571 ✔
844
      pending << *it;
845
    }
846
  }
847
}
598 ✔
848

849
/// A symlink or an NTFS junction: never entered, never listed.
850
auto isLink(const QFileInfo &entry) -> bool {
16,643 ✔
851
  return entry.isSymLink() || entry.isJunction();
16,643 ✔
852
}
853

854
/// Hidden by attribute, or by the dot convention on every platform: Qt 6.11
855
/// on macOS answers isHidden() from the UF_HIDDEN flag alone once an entry
856
/// was lstat()ed (qfilesystemengine_unix.cpp marks the attribute known there
857
/// without the dot check), and Windows does not consider .stversions hidden
858
/// at all.
859
auto isHiddenEntry(const QFileInfo &entry) -> bool {
967 ✔
860
  return entry.isHidden() || entry.fileName().startsWith(QLatin1Char('.'));
1,917 ✔
861
}
862

863
/// A real directory that is part of the store: .git, .stversions,
864
/// .Trash-1000 are not, as with QDirIterator without QDir::Hidden.
865
auto isStoreDirectory(const QFileInfo &entry) -> bool {
1,793 ✔
866
  return !isLink(entry) && entry.isDir() && !isHiddenEntry(entry);
1,793 ✔
867
}
868
} // namespace
869

870
auto Util::regularFilesUnder(const QString &dir, const QStringList &nameFilters,
296 ✔
871
                             QStringList *skipped, bool hiddenFiles,
872
                             QStringList *unlisted) -> QStringList {
873
  QStringList files;
296 ✔
874
  walkStore(
296 ✔
875
      dir,
876
      [&](const QFileInfo &entry) {
1,718 ✔
877
        if (isStoreDirectory(entry)) {
1,718 ✔
878
          return true;
879
        }
880
        const bool named = QDir::match(nameFilters, entry.fileName());
1,598 ✔
881
        if (isLink(entry) || (!entry.isDir() && !entry.isFile())) {
1,598 ✔
882
          // A linked directory hides everything behind it; a linked file, or a
883
          // FIFO, socket or device, is only of interest under a name the caller
884
          // asked for.
885
          if (skipped != nullptr && (entry.isDir() || named)) {
25 ✔
886
            qCWarning(lcQtPass) << "Skipping" << entry.filePath()
24 ✔
887
                                << ": not a regular file or directory";
12 ✔
888
            *skipped << entry.filePath();
24 ✔
889
          }
890
          return false;
25 ✔
891
        }
892
        if (entry.isFile() && named && (hiddenFiles || !isHiddenEntry(entry))) {
1,573 ✔
893
          files << entry.filePath();
1,728 ✔
894
        }
895
        return false;
896
      },
897
      unlisted);
898
  return files;
296 ✔
899
}
900

901
auto Util::directoriesUnder(const QString &dir) -> QStringList {
3 ✔
902
  QStringList dirs;
3 ✔
903
  walkStore(dir, [&](const QFileInfo &entry) {
3 ✔
904
    if (!isStoreDirectory(entry)) {
75 ✔
905
      return false;
906
    }
907
    dirs << entry.filePath();
21 ✔
908
    return true;
21 ✔
909
  });
910
  return dirs;
3 ✔
911
}
912

913
auto Util::hasUnreadableName(const QString &dir) -> bool {
202 ✔
914
#ifdef Q_OS_WIN
915
  Q_UNUSED(dir);
916
  return false;
917
#else
918
  // The names as bytes, as readdir() gives them; Qt's own listing has
919
  // already dropped the ones this is looking for.
920
  DIR *listing = ::opendir(QFile::encodeName(dir).constData());
202 ✔
921
  if (listing == nullptr) {
202 ✔
922
    return false;
923
  }
924
  const auto close = qScopeGuard([listing] { ::closedir(listing); });
202 ✔
925
  while (const dirent *entry = ::readdir(listing)) {
1,117 ✔
926
    if (!QByteArrayView(entry->d_name).isValidUtf8()) {
920 ✔
927
      return true;
928
    }
929
  }
930
  return false;
931
#endif
932
}
933

934
auto Util::isLinkedFolder(const QString &path) -> bool {
13,209 ✔
935
  return isLink(QFileInfo(QDir::cleanPath(path)));
26,418 ✔
936
}
937

938
auto Util::isUnderLink(const QString &path, const QString &storeRoot,
11,406 ✔
939
                       bool includeSelf) -> bool {
940
  // "C:/Store" and "c:/store" are one directory on Windows; a path spelled
941
  // the other way must not skip the walk (as in Pass::getGpgIdPath).
942
#ifdef Q_OS_WIN
943
  constexpr auto cs = Qt::CaseInsensitive;
944
#else
945
  constexpr auto cs = Qt::CaseSensitive;
946
#endif
947
  const QString root = QDir::cleanPath(storeRoot);
11,406 ✔
948
  // A root of "/" or "C:/" already ends in the separator.
949
  const QString prefix =
950
      root.endsWith(QLatin1Char('/')) ? root : root + QLatin1Char('/');
11,406 ✔
951
  const auto isRoot = [&](const QString &p) {
952
    return p.compare(root, cs) == 0;
12,486 ✔
953
  };
954
  QString current = QDir::cleanPath(path);
11,406 ✔
955
  if (!current.startsWith(prefix, cs)) {
11,406 ✔
956
    // Not under the store as named: only the entry itself can be judged.
957
    return includeSelf && !isRoot(current) && isLinkedFolder(current);
470 ✔
958
  }
959
  if (!includeSelf) {
11,171 ✔
960
    current = QFileInfo(current).path();
21,192 ✔
961
  }
962
  for (; !isRoot(current) && current.startsWith(prefix, cs);
12,251 ✔
963
       current = QFileInfo(current).path()) {
2,160 ✔
964
    if (isLinkedFolder(current)) {
1,126 ✔
965
      return true;
966
    }
967
  }
968
  return false;
969
}
970

971
#ifndef Q_OS_WIN
972
namespace {
973

974
/// The filesystem cannot make hard links at all (FAT/exFAT refuse with
975
/// EPERM, some FUSE filesystems with ENOTSUP or ENOSYS).
976
auto hasNoHardLinks(int error) -> bool {
977
  return error == EPERM || error == ENOTSUP || error == EOPNOTSUPP ||
2 ✔
978
         error == ENOSYS;
979
}
980

981
/// rename() that fails with EEXIST instead of replacing, where the platform
982
/// has one; nothing when neither the platform nor the filesystem does.
983
auto renameExclusive(const QByteArray &source, const QByteArray &target)
8 ✔
984
    -> std::optional<bool> {
985
#if defined(__GLIBC__) &&                                                      \
986
    (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 28))
987
  if (::renameat2(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(),
8 ✔
988
                  RENAME_NOREPLACE) == 0) {
989
    return true;
2 ✔
990
  }
991
  if (errno == EINVAL || errno == ENOSYS || hasNoHardLinks(errno)) {
6 ✔
992
    return std::nullopt;
4 ✔
993
  }
994
  return false;
2 ✔
995
#elif defined(Q_OS_MACOS)
996
  if (::renamex_np(source.constData(), target.constData(), RENAME_EXCL) == 0) {
997
    return true;
998
  }
999
  if (errno == EINVAL || errno == ENOTSUP) {
1000
    return std::nullopt;
1001
  }
1002
  return false;
1003
#else
1004
  Q_UNUSED(source);
1005
  Q_UNUSED(target);
1006
  return std::nullopt;
1007
#endif
1008
}
1009

1010
/**
1011
 * @brief Gives @p source the name @p target unless something already has it.
1012
 *
1013
 * A hard link is the one way every POSIX system can do that in one step:
1014
 * linkat() fails with EEXIST rather than replacing. Where the filesystem has
1015
 * no hard links, an exclusive rename does it; where that is missing too, the
1016
 * name is checked and then renamed, which leaves a short window for another
1017
 * writer to create it in between.
1018
 */
1019
auto placeWithoutReplacing(const QByteArray &source, const QByteArray &target)
88 ✔
1020
    -> bool {
1021
  // linkat() without AT_SYMLINK_FOLLOW follows nothing; link() would, on
1022
  // macOS and the BSDs, hard-link whatever a symlink planted under the
1023
  // source's name points at.
1024
  if (::linkat(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(), 0) ==
88 ✔
1025
      0) {
1026
    ::unlink(source.constData());
73 ✔
1027
    return true;
73 ✔
1028
  }
1029
  if (!hasNoHardLinks(errno)) {
15 ✔
1030
    return false;
1031
  }
1032
  if (const std::optional<bool> renamed = renameExclusive(source, target)) {
8 ✔
1033
    return *renamed;
4 ✔
1034
  }
1035
  struct stat st{};
4 ✔
1036
  if (::lstat(target.constData(), &st) == 0 || errno != ENOENT) {
4 ✔
1037
    errno = EEXIST;
2 ✔
1038
    return false;
2 ✔
1039
  }
1040
  return ::rename(source.constData(), target.constData()) == 0;
2 ✔
1041
}
1042

1043
} // namespace
1044
#endif
1045

1046
auto Util::replaceFile(const QString &from, const QString &to, bool replace)
245 ✔
1047
    -> bool {
1048
#ifdef Q_OS_WIN
1049
  const std::wstring source =
1050
      QDir::toNativeSeparators(QFileInfo(from).absoluteFilePath())
1051
          .toStdWString();
1052
  const std::wstring target =
1053
      QDir::toNativeSeparators(QFileInfo(to).absoluteFilePath()).toStdWString();
1054
  // WRITE_THROUGH: the new entry is on the device when this returns.
1055
  return MoveFileExW(source.c_str(), target.c_str(),
1056
                     (replace ? MOVEFILE_REPLACE_EXISTING : 0) |
1057
                         MOVEFILE_WRITE_THROUGH) != 0;
1058
#else
1059
  const QByteArray source = QFile::encodeName(from);
1060
  const QByteArray target = QFile::encodeName(to);
1061
  if (replace) {
245 ✔
1062
    if (::rename(source.constData(), target.constData()) != 0) {
157 ✔
1063
      return false;
1064
    }
1065
  } else {
1066
    if (!placeWithoutReplacing(source, target)) {
88 ✔
1067
      return false;
1068
    }
1069
  }
1070
  // Sync the directory entry so a crash does not lose the new name. Best
1071
  // effort: the bytes are already synced, and some network filesystems
1072
  // cannot sync a directory.
1073
  const int dir = ::open(QFile::encodeName(QFileInfo(to).path()).constData(),
462 ✔
1074
                         O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1075
  if (dir >= 0) {
231 ✔
1076
    int rc;
1077
    do {
1078
      rc = ::fsync(dir);
231 ✔
1079
    } while (rc != 0 && errno == EINTR);
231 ✔
1080
    ::close(dir);
231 ✔
1081
  }
1082
  return true;
1083
#endif
1084
}
1085

1086
auto Util::openRegularFile(const QString &path, QFile &file) -> bool {
834 ✔
1087
#ifdef Q_OS_WIN
1088
  // FILE_FLAG_OPEN_REPARSE_POINT opens a symbolic link or junction itself
1089
  // rather than its target, so the handle's attributes say what the name
1090
  // was at the moment of the open.
1091
  const std::wstring native =
1092
      QDir::toNativeSeparators(QFileInfo(path).absoluteFilePath())
1093
          .toStdWString();
1094
  HANDLE handle = CreateFileW(
1095
      native.c_str(), GENERIC_READ,
1096
      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
1097
      OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
1098
  if (handle == INVALID_HANDLE_VALUE) {
1099
    return false;
1100
  }
1101
  BY_HANDLE_FILE_INFORMATION info{};
1102
  if (!GetFileInformationByHandle(handle, &info) ||
1103
      (info.dwFileAttributes &
1104
       (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY |
1105
        FILE_ATTRIBUTE_DEVICE)) != 0 ||
1106
      GetFileType(handle) != FILE_TYPE_DISK) {
1107
    CloseHandle(handle);
1108
    return false;
1109
  }
1110
  const int fd = _open_osfhandle(reinterpret_cast<intptr_t>(handle),
1111
                                 _O_RDONLY | _O_BINARY);
1112
  if (fd < 0) {
1113
    CloseHandle(handle);
1114
    return false;
1115
  }
1116
  if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
1117
    _close(fd);
1118
    return false;
1119
  }
1120
  return true;
1121
#else
1122
  // O_NOFOLLOW fails with ELOOP on a symbolic link; O_NONBLOCK keeps a FIFO
1123
  // from blocking the open until fstat() can refuse it.
1124
  const int fd = ::open(QFile::encodeName(path).constData(),
834 ✔
1125
                        O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
1126
  if (fd < 0) {
834 ✔
1127
    return false;
1128
  }
1129
  struct stat st{};
781 ✔
1130
  if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
781 ✔
1131
    ::close(fd);
7 ✔
1132
    return false;
7 ✔
1133
  }
1134
  // The descriptor, not the name, is what QFile opens here: the object
1135
  // fstat() judged is the object read. CodeQL's check-then-use pattern
1136
  // matcher sees an open after a check and cannot tell.
1137
  if (!file.open(fd, QIODevice::ReadOnly, // codeql[cpp/toctou-race-condition]
774 ✔
1138
                 QFileDevice::AutoCloseHandle)) {
1139
    ::close(fd);
×
1140
    return false;
×
1141
  }
1142
  return true;
1143
#endif
1144
}
1145

1146
auto Util::readRegularFile(const QString &path, qint64 maxBytes)
284 ✔
1147
    -> std::optional<QByteArray> {
1148
  QFile file;
284 ✔
1149
  if (!openRegularFile(path, file)) {
284 ✔
1150
    return std::nullopt;
10 ✔
1151
  }
1152
  // A regular file's size is reliable, also when sparse: refuse a large one
1153
  // before reading anything. One byte past the limit still guards a file
1154
  // that grows meanwhile.
1155
  if (file.size() > maxBytes) {
274 ✔
1156
    return std::nullopt;
3 ✔
1157
  }
1158
  QByteArray bytes = file.read(maxBytes + 1);
271 ✔
1159
  if (bytes.size() > maxBytes || file.error() != QFileDevice::NoError) {
271 ✔
1160
    return std::nullopt;
×
1161
  }
1162
  return bytes;
1163
}
284 ✔
1164

1165
auto Util::syncToDisk(QFileDevice &file) -> bool {
231 ✔
1166
  if (!file.flush()) {
231 ✔
1167
    return false;
1168
  }
1169
#ifdef Q_OS_WIN
1170
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1171
  return handle != INVALID_HANDLE_VALUE && FlushFileBuffers(handle) != 0;
1172
#else
1173
  return ::fsync(file.handle()) == 0;
231 ✔
1174
#endif
1175
}
1176

1177
namespace {
1178

1179
/**
1180
 * @brief What tells one file object from another on its filesystem: device
1181
 * and inode on POSIX, volume serial and file index on Windows.
1182
 */
1183
struct FileIdentity {
1184
  quint64 volume = 0;
1185
  quint64 index = 0;
1186
  bool known = false;
1187
};
1188

1189
auto operator==(const FileIdentity &a, const FileIdentity &b) -> bool {
220 ✔
1190
  return a.known && b.known && a.volume == b.volume && a.index == b.index;
220 ✔
1191
}
1192

1193
/// The identity of the object @p file is open on, or an unknown one.
1194
auto identityOf(const QFileDevice &file) -> FileIdentity {
451 ✔
1195
#ifdef Q_OS_WIN
1196
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1197
  BY_HANDLE_FILE_INFORMATION info;
1198
  if (handle == INVALID_HANDLE_VALUE ||
1199
      GetFileInformationByHandle(handle, &info) == 0) {
1200
    return {};
1201
  }
1202
  // On FAT/exFAT the file ID is the directory entry's offset, which a rename
1203
  // can move. They have no hard links either (the swap this catches needs
1204
  // one), so the identity is left unknown there.
1205
  DWORD flags = 0;
1206
  if (GetVolumeInformationByHandleW(handle, nullptr, 0, nullptr, nullptr,
1207
                                    &flags, nullptr, 0) == 0 ||
1208
      (flags & FILE_SUPPORTS_HARD_LINKS) == 0) {
1209
    return {};
1210
  }
1211
  return {info.dwVolumeSerialNumber,
1212
          (static_cast<quint64>(info.nFileIndexHigh) << 32) |
1213
              info.nFileIndexLow,
1214
          true};
1215
#else
1216
  struct stat st{};
451 ✔
1217
  if (::fstat(file.handle(), &st) != 0) {
451 ✔
1218
    return {};
×
1219
  }
1220
  return {static_cast<quint64>(st.st_dev), static_cast<quint64>(st.st_ino),
451 ✔
1221
          true};
451 ✔
1222
#endif
1223
}
1224

1225
/// Put @p text in @p error when there is one; false, for `return fail(...)`.
1226
auto fail(QString *error, const QString &text) -> bool {
1227
  if (error != nullptr) {
22 ✔
1228
    *error = text;
22 ✔
1229
  }
1230
  return false;
1231
}
1232

1233
/// A filled, synced temporary next to its destination.
1234
struct Staged {
231 ✔
1235
  QString path;
1236
  FileIdentity identity;
1237
  /// POSIX: a descriptor kept open on the temporary until the identity
1238
  /// check, so the inode, and with it the number, stays the temporary's.
1239
  std::shared_ptr<void> pin;
1240
};
1241

1242
/**
1243
 * @brief Create the temporary next to @p path (opaque name, exclusive,
1244
 * owner-only), fill it through its handle and sync it. The QTemporaryFile
1245
 * goes out of scope before the caller renames: it keeps its handle open for
1246
 * as long as it lives, and Windows does not rename an open file.
1247
 */
1248
auto stageNextTo(const QString &path, const Util::Filler &fill, QString *why)
239 ✔
1249
    -> std::optional<Staged> {
1250
  Staged staged;
239 ✔
1251
  {
1252
    QTemporaryFile file(QFileInfo(path).path() +
478 ✔
1253
                        QStringLiteral("/.qtpass-XXXXXX.tmp"));
478 ✔
1254
    file.setAutoRemove(false);
239 ✔
1255
    if (!file.open()) {
239 ✔
1256
      *why = QCoreApplication::translate(
8 ✔
1257
                 "Util", "Cannot create a temporary file next to %1: %2")
1258
                 .arg(path, file.errorString());
16 ✔
1259
      return std::nullopt;
8 ✔
1260
    }
1261
    staged.path = file.fileName();
231 ✔
1262
    // Owner-only: a .gpg-id names the keys a store is encrypted to, an
1263
    // entry is an entry. QTemporaryFile creates 0600 already; say so for
1264
    // platforms where it may not.
1265
    file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
231 ✔
1266
    *why = fill(file);
462 ✔
1267
    if (why->isEmpty() && !Util::syncToDisk(file)) {
231 ✔
1268
      *why = QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1269
                 .arg(path, file.errorString());
×
1270
    }
1271
    staged.identity = identityOf(file);
231 ✔
1272
#ifndef Q_OS_WIN
1273
    // Closed and unlinked by a co-writer before the rename, the temporary's
1274
    // inode number would be free, and ext4 hands it to the next file made:
1275
    // the very file swapped in would then pass the check below. Windows
1276
    // cannot rename an open file, and NTFS does not reuse a file index so.
1277
    if (const int fd = ::dup(file.handle()); fd >= 0) {
231 ✔
1278
      staged.pin =
1279
          std::shared_ptr<void>(nullptr, [fd](void *) { ::close(fd); });
693 ✔
1280
    }
1281
#endif
1282
  }
239 ✔
1283
  if (!why->isEmpty()) {
231 ✔
1284
    QFile::remove(staged.path);
×
1285
    return std::nullopt;
×
1286
  }
1287
  return staged;
231 ✔
1288
}
239 ✔
1289

1290
/// Why replaceFile() could not put the temporary under @p path.
1291
auto placementError(const QString &path, bool replace) -> QString {
9 ✔
1292
  if (replace) {
9 ✔
1293
    return QCoreApplication::translate("Util", "Failed to replace %1.")
4 ✔
1294
        .arg(path);
2 ✔
1295
  }
1296
  const QFileInfo taken(path);
7 ✔
1297
  return taken.exists() || taken.isSymLink()
8 ✔
1298
             ? QCoreApplication::translate("Util", "%1 already exists.")
7 ✔
1299
                   .arg(path)
1300
             : QCoreApplication::translate("Util", "Failed to write %1.")
1 ✔
1301
                   .arg(path);
8 ✔
1302
}
7 ✔
1303

1304
/**
1305
 * @brief Whether what is under @p path is the file that was filled: not a
1306
 * link, and not another file (a hard link to something of the user's, say)
1307
 * swapped in under the temporary's name. Opened without following, compared
1308
 * by identity; only two known identities can prove a swap, otherwise every
1309
 * write on such a store would be reported as tampering.
1310
 */
1311
auto isTheFileWritten(const QString &path, const FileIdentity &written)
222 ✔
1312
    -> bool {
1313
  QFile placed;
222 ✔
1314
  if (!Util::openRegularFile(path, placed)) {
222 ✔
1315
    return false;
1316
  }
1317
  const FileIdentity there = identityOf(placed);
220 ✔
1318
  if (!written.known || !there.known) {
220 ✔
1319
    qCWarning(lcQtPass) << "Cannot tell whether" << path
×
1320
                        << "is the file that was written here";
×
1321
    return true;
×
1322
  }
1323
  return there == written;
220 ✔
1324
}
222 ✔
1325

1326
} // namespace
1327

1328
auto Util::stageFileReplacing(const QString &path, bool replace,
239 ✔
1329
                              const Filler &fill, QString *error) -> bool {
1330
  QString why;
239 ✔
1331
  const std::optional<Staged> staged = stageNextTo(path, fill, &why);
239 ✔
1332
  if (!staged) {
239 ✔
1333
    return fail(error, why);
1334
  }
1335
  if (s_beforePlacingForTests) {
231 ✔
1336
    s_beforePlacingForTests(staged->path);
1 ✔
1337
  }
1338
  if (!replaceFile(staged->path, path, replace)) {
231 ✔
1339
    QFile::remove(staged->path);
9 ✔
1340
    return fail(error, placementError(path, replace));
18 ✔
1341
  }
1342
  // A mismatch is reported and left: removing by name could take another
1343
  // writer's file.
1344
  if (!isTheFileWritten(path, staged->identity)) {
222 ✔
1345
    return fail(
1346
        error,
1347
        QCoreApplication::translate(
5 ✔
1348
            "Util", "%1 was swapped for another file while it was written.")
1349
            .arg(path));
10 ✔
1350
  }
1351
  return true;
1352
}
1353

1354
auto Util::writeFileReplacing(const QString &path, const QByteArray &bytes,
106 ✔
1355
                              bool replace, QString *error) -> bool {
1356
  return stageFileReplacing(
106 ✔
1357
      path, replace,
1358
      [&path, &bytes](QFileDevice &staged) -> QString {
210 ✔
1359
        if (staged.write(bytes) != bytes.size()) {
104 ✔
1360
          return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1361
              .arg(path, staged.errorString());
×
1362
        }
1363
        return {};
104 ✔
1364
      },
1365
      error);
106 ✔
1366
}
1367

1368
auto Util::copyFileReplacing(const QString &src, const QString &dst,
132 ✔
1369
                             bool replace, QString *error) -> bool {
1370
  QFile in;
132 ✔
1371
  if (!openRegularFile(src, in)) {
132 ✔
1372
    if (error)
4 ✔
1373
      *error = QCoreApplication::translate("Util", "Cannot read %1.").arg(src);
8 ✔
1374
    return false;
4 ✔
1375
  }
1376
  return stageFileReplacing(
128 ✔
1377
      dst, replace,
1378
      [&src, &dst, &in](QFileDevice &staged) -> QString {
378 ✔
1379
        char buf[64 * 1024];
1380
        for (;;) {
1381
          const qint64 n = in.read(buf, sizeof buf);
256 ✔
1382
          if (n < 0) {
256 ✔
1383
            return QCoreApplication::translate("Util", "Cannot read %1: %2")
×
1384
                .arg(src, in.errorString());
×
1385
          }
1386
          if (n == 0) {
256 ✔
1387
            return {};
122 ✔
1388
          }
1389
          if (staged.write(buf, n) != n) {
134 ✔
1390
            return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1391
                .arg(dst, staged.errorString());
×
1392
          }
1393
        }
1394
      },
1395
      error);
1396
}
132 ✔
1397

1398
namespace {
1399

1400
/// Remove one directory entry that is not a real directory: a link goes as
1401
/// the entry itself, never its target (a junction or a directory symlink on
1402
/// Windows is a directory entry and goes with rmdir); a read-only file gets
1403
/// write access and one more try, as QDir::removeRecursively() does.
1404
auto removeEntry(const QFileInfo &entry) -> bool {
14 ✔
1405
  const QString path = entry.filePath();
14 ✔
1406
  if (isLink(entry)) {
14 ✔
1407
    if (QFile::remove(path) || QDir().rmdir(path)) {
6 ✔
1408
      return true;
1409
    }
1410
    qCWarning(lcQtPass) << "Could not remove link" << path;
2 ✔
1411
    return false;
1 ✔
1412
  }
1413
  if (QFile::remove(path)) {
9 ✔
1414
    return true;
1415
  }
1416
  const QFile::Permissions perms = QFile::permissions(path);
2 ✔
1417
  if (!perms.testFlag(QFile::WriteUser) &&
1 ✔
1418
      QFile::setPermissions(path, perms | QFile::WriteUser) &&
3 ✔
1419
      QFile::remove(path)) {
1 ✔
1420
    return true;
1421
  }
1422
  qCWarning(lcQtPass) << "Could not remove" << path;
4 ✔
1423
  return false;
2 ✔
1424
}
1425

1426
} // namespace
1427

1428
auto Util::removeTree(const QString &dir) -> bool {
23 ✔
1429
  // A trailing separator makes lstat follow a link ("link/" is the target
1430
  // directory); the link itself is what this is about.
1431
  const QString path = QDir::cleanPath(dir);
23 ✔
1432
  const QFileInfo top(path);
23 ✔
1433
  if (isLink(top)) {
23 ✔
1434
    // rm -rf on a link removes the link.
1435
    return QFile::remove(path) || QDir().rmdir(path);
16 ✔
1436
  }
1437
  if (!top.isDir()) {
9 ✔
1438
    return false;
1439
  }
1440
  bool ok = true;
1441
  const QFileInfoList entries =
1442
      QDir(path).entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
16 ✔
1443
                                   QDir::System | QDir::NoDotAndDotDot,
1444
                               QDir::Name);
8 ✔
1445
  for (const QFileInfo &entry : entries) {
24 ✔
1446
    const bool removed = entry.isDir() && !isLink(entry)
22 ✔
1447
                             ? removeTree(entry.filePath())
18 ✔
1448
                             : removeEntry(entry);
14 ✔
1449
    ok = removed && ok;
16 ✔
1450
  }
1451
  return ok && QDir().rmdir(path);
13 ✔
1452
}
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