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

IJHack / QtPass / 44218871118

18 Nov 2026 01:50AM UTC coverage: 96.356% (-0.04%) from 96.396%
44218871118

Pull #2260

github

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

74 of 86 new or added lines in 8 files covered. (86.05%)

26 existing lines in 1 file now uncovered.

9097 of 9441 relevant lines covered (96.36%)

831.08 hits per line

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

94.3
/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 {
33 ✔
163
  const int fd = ::open(QFile::encodeName(path).constData(),
33 ✔
164
                        O_RDONLY | O_NONBLOCK | O_CLOEXEC);
165
  if (fd < 0) {
33 ✔
166
    return false;
167
  }
168
  struct stat info{};
33 ✔
169
  if (::fstat(fd, &info) != 0 || !S_ISREG(info.st_mode) ||
65 ✔
170
      !file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
64 ✔
171
    ::close(fd);
1 ✔
172
    return false;
1 ✔
173
  }
174
  return true;
175
}
176
} // namespace
177
#endif
178

179
auto Util::repositoryPassClimbsTo(const QString &store) -> QString {
43 ✔
180
#ifdef Q_OS_WIN
181
  Q_UNUSED(store);
182
  return {};
183
#else
184
  if (!store.contains(QLatin1Char(':'))) {
43 ✔
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;
66 ✔
197
  while (path.size() > 1 && path.endsWith(u'/')) {
36 ✔
198
    path.chop(1);
3 ✔
199
  }
200
  QString rest;
33 ✔
201
  while (!QFileInfo::exists(path)) {
43 ✔
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();
33 ✔
211
  QString start = real.isEmpty() ? QDir::cleanPath(path) : real;
33 ✔
212
  if (!rest.isEmpty()) {
33 ✔
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;
33 ✔
221
  bool afterEmpty = false;
222
  for (const QString &piece :
223
       (store + QStringLiteral("/..")).split(QLatin1Char(':'))) {
135 ✔
224
    if (piece.isEmpty()) {
69 ✔
225
      afterEmpty = true;
226
      continue;
34 ✔
227
    }
228
    if (!piece.startsWith(u'/')) {
67 ✔
229
      continue;
32 ✔
230
    }
231
    const QString entry =
232
        afterEmpty ? piece : QFileInfo(piece).canonicalFilePath();
36 ✔
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'/';
35 ✔
236
    if (!entry.isEmpty() && start.startsWith(under) &&
35 ✔
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) {
94 ✔
245
    const QDir dir(candidate);
94 ✔
246
    if (!QFileInfo(dir.filePath(QStringLiteral("objects"))).isDir() ||
214 ✔
247
        !QFileInfo(dir.filePath(QStringLiteral("refs"))).isDir()) {
172 ✔
248
      return false;
249
    }
250
    // Only a regular file, link or not (git takes HEAD -> refs/heads/main):
251
    // a HEAD that is a link to a device or a FIFO (a pushed commit can carry
252
    // a link) blocked the open and the read on the GUI thread when Settings
253
    // opened.
254
    QFile head;
26 ✔
255
    if (!openFollowedRegularFile(dir.filePath(QStringLiteral("HEAD")), head)) {
52 ✔
256
      return false;
257
    }
258
    static const QRegularExpression valid(
259
        QStringLiteral("^(?:ref: refs/|[0-9a-f]{40}\\s*$|[0-9a-f]{64}\\s*$)"));
29 ✔
260
    return valid.match(QString::fromUtf8(head.read(256))).hasMatch();
75 ✔
261
  };
94 ✔
262
  // At each folder, as git: a .git folder that is a repository, or a .git
263
  // file naming one ("gitdir: ..."), is the repository. Any other .git file
264
  // stops git with an error, and pass then commits nothing; a .git folder
265
  // that is no repository is passed by.
266
  enum class Found { Nothing, Repository, Refused };
267
  const auto repositoryAt = [&isGitDirectory](const QString &dir) {
92 ✔
268
    const QString dotGit = QDir(dir).filePath(QStringLiteral(".git"));
184 ✔
269
    const QFileInfo info(dotGit);
92 ✔
270
    if (info.isDir()) {
92 ✔
271
      return isGitDirectory(dotGit) ? Found::Repository : Found::Nothing;
23 ✔
272
    }
273
    if (!info.exists()) {
69 ✔
274
      return Found::Nothing;
275
    }
276
    // The same for a .git file (or a link to one): a FIFO there blocked in
277
    // open().
278
    QFile file;
7 ✔
279
    if (!openFollowedRegularFile(dotGit, file)) {
7 ✔
280
      return Found::Refused;
281
    }
282
    const QString line = QString::fromUtf8(file.readLine(4096)).trimmed();
7 ✔
283
    if (!line.startsWith(QLatin1String("gitdir: "))) {
7 ✔
284
      return Found::Refused;
285
    }
286
    const QString target = line.mid(8);
5 ✔
287
    return isGitDirectory(target.startsWith(u'/') ? target
10 ✔
288
                                                  : QDir(dir).filePath(target))
8 ✔
289
               ? Found::Repository
5 ✔
290
               : Found::Refused;
291
  };
125 ✔
292
  // The store's own repository comes first; only without one does git look
293
  // further up, and never into the ceiling. By name from here: the real
294
  // path holds no link or "..".
295
  for (QString dir = start;;) {
296
    switch (repositoryAt(dir)) {
92 ✔
297
    case Found::Repository:
298
      return dir == start ? QString() : dir;
53 ✔
299
    case Found::Refused:
3 ✔
300
      return {};
3 ✔
301
    case Found::Nothing:
302
      break;
303
    }
304
    // A bare repository: git stops there, and pass, finding no work tree,
305
    // commits nothing.
306
    if (isGitDirectory(dir)) {
66 ✔
307
      return {};
1 ✔
308
    }
309
    const QString up = QFileInfo(dir).absolutePath();
65 ✔
310
    if (up == dir || up == ceiling) {
65 ✔
311
      return {};
6 ✔
312
    }
313
    dir = up;
59 ✔
314
  }
315
#endif
316
}
317

318
namespace {
319
/// setGitOwnerForTests(): who owns "the user's own" store, when set.
320
std::optional<uint> s_gitOwnerForTests;
321
} // namespace
322

323
void Util::setGitOwnerForTests(std::optional<uint> user) {
4 ✔
324
  s_gitOwnerForTests = user;
4 ✔
325
}
4 ✔
326

327
/// setBeforePlacingForTests(): called between staging and the rename.
328
std::function<void(const QString &)> s_beforePlacingForTests;
329

330
void Util::setBeforePlacingForTests(std::function<void(const QString &)> hook) {
3 ✔
331
  s_beforePlacingForTests = std::move(hook);
3 ✔
332
}
3 ✔
333

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

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

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

520
auto Util::findBinaryInPath(const QString &binary) -> QString {
527 ✔
521
  if (binary.isEmpty()) {
527 ✔
522
    return {};
1 ✔
523
  }
524

525
  initialiseEnvironment();
526 ✔
526

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

577
  return ret;
578
}
579

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

602
auto Util::configIsValid(const AppSettings &s) -> bool {
279 ✔
603
  const QString configFilePath = QDir(s.passStore).filePath(".gpg-id");
558 ✔
604
  if (!QFile(configFilePath).exists()) {
279 ✔
605
    return false;
606
  }
607

608
  const QString executable = s.usePass ? s.passExecutable : s.gpgExecutable;
197 ✔
609

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

628
auto Util::endsWithGpg() -> const QRegularExpression & {
16,131 ✔
629
  static const QRegularExpression expr{R"(\.gpg$)"};
16,138 ✔
630
  return expr;
16,131 ✔
631
}
632

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

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

673
auto Util::displayable(const QString &text, bool lineBreaks) -> QString {
444 ✔
674
  QString shown = text;
675
  for (qsizetype i = 0; i < shown.size(); ++i) {
123,015 ✔
676
    const char16_t u = shown.at(i).unicode();
677
    // A carriage return before a line feed is a Windows line end (git or
678
    // gpg output quoted in a message), not a character of its own.
679
    const bool lineEnd =
680
        lineBreaks && (u == u'\n' || (u == u'\r' && i + 1 < shown.size() &&
122,571 ✔
681
                                      shown.at(i + 1) == u'\n'));
682
    if ((u < 0x20 && u != u'\t' && !lineEnd) || (u >= 0x7f && u <= 0x9f) ||
122,571 ✔
683
        u == 0x2028 || u == 0x2029 || (u >= 0x202a && u <= 0x202e) ||
122,517 ✔
684
        (u >= 0x2066 && u <= 0x2069)) {
122,509 ✔
685
      shown[i] = QChar(QChar::ReplacementCharacter);
64 ✔
686
    }
687
  }
688
  return shown;
444 ✔
689
}
690

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

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

769
auto Util::newLinesRegex() -> const QRegularExpression & {
326 ✔
770
  static const QRegularExpression regex{"[\r\n]"};
335 ✔
771
  return regex;
326 ✔
772
}
773

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

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

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

842
/// A symlink or an NTFS junction: never entered, never listed.
843
auto isLink(const QFileInfo &entry) -> bool {
17,003 ✔
844
  return entry.isSymLink() || entry.isJunction();
17,003 ✔
845
}
846

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

856
/// A real directory that is part of the store: .git, .stversions,
857
/// .Trash-1000 are not, as with QDirIterator without QDir::Hidden.
858
auto isStoreDirectory(const QFileInfo &entry) -> bool {
1,793 ✔
859
  return !isLink(entry) && entry.isDir() && !isHiddenEntry(entry);
1,793 ✔
860
}
861
} // namespace
862

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

894
auto Util::directoriesUnder(const QString &dir) -> QStringList {
3 ✔
895
  QStringList dirs;
3 ✔
896
  walkStore(dir, [&](const QFileInfo &entry) {
3 ✔
897
    if (!isStoreDirectory(entry)) {
75 ✔
898
      return false;
899
    }
900
    dirs << entry.filePath();
21 ✔
901
    return true;
21 ✔
902
  });
903
  return dirs;
3 ✔
904
}
905

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

927
auto Util::isLinkedFolder(const QString &path) -> bool {
13,569 ✔
928
  return isLink(QFileInfo(QDir::cleanPath(path)));
27,138 ✔
929
}
930

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

964
#ifndef Q_OS_WIN
965
namespace {
966

967
/// The filesystem cannot make hard links at all (FAT/exFAT refuse with
968
/// EPERM, some FUSE filesystems with ENOTSUP or ENOSYS).
969
auto hasNoHardLinks(int error) -> bool {
970
  return error == EPERM || error == ENOTSUP || error == EOPNOTSUPP ||
2 ✔
971
         error == ENOSYS;
972
}
973

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

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

1036
} // namespace
1037
#endif
1038

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

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

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

1158
auto Util::syncToDisk(QFileDevice &file) -> bool {
231 ✔
1159
  if (!file.flush()) {
231 ✔
1160
    return false;
1161
  }
1162
#ifdef Q_OS_WIN
1163
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1164
  return handle != INVALID_HANDLE_VALUE && FlushFileBuffers(handle) != 0;
1165
#else
1166
  return ::fsync(file.handle()) == 0;
231 ✔
1167
#endif
1168
}
1169

1170
namespace {
1171

1172
/**
1173
 * @brief What tells one file object from another on its filesystem: device
1174
 * and inode on POSIX, volume serial and file index on Windows.
1175
 */
1176
struct FileIdentity {
1177
  quint64 volume = 0;
1178
  quint64 index = 0;
1179
  bool known = false;
1180
};
1181

1182
auto operator==(const FileIdentity &a, const FileIdentity &b) -> bool {
220 ✔
1183
  return a.known && b.known && a.volume == b.volume && a.index == b.index;
220 ✔
1184
}
1185

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

1218
/// Put @p text in @p error when there is one; false, for `return fail(...)`.
1219
auto fail(QString *error, const QString &text) -> bool {
1220
  if (error != nullptr) {
22 ✔
1221
    *error = text;
22 ✔
1222
  }
1223
  return false;
1224
}
1225

1226
/// A filled, synced temporary next to its destination.
1227
struct Staged {
231 ✔
1228
  QString path;
1229
  FileIdentity identity;
1230
  /// POSIX: a descriptor kept open on the temporary until the identity
1231
  /// check, so the inode, and with it the number, stays the temporary's.
1232
  std::shared_ptr<void> pin;
1233
};
1234

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

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

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

1319
} // namespace
1320

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

1347
auto Util::writeFileReplacing(const QString &path, const QByteArray &bytes,
106 ✔
1348
                              bool replace, QString *error) -> bool {
1349
  return stageFileReplacing(
106 ✔
1350
      path, replace,
1351
      [&path, &bytes](QFileDevice &staged) -> QString {
210 ✔
1352
        if (staged.write(bytes) != bytes.size()) {
104 ✔
UNCOV
1353
          return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
UNCOV
1354
              .arg(path, staged.errorString());
×
1355
        }
1356
        return {};
104 ✔
1357
      },
1358
      error);
106 ✔
1359
}
1360

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

1391
namespace {
1392

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

1419
} // namespace
1420

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