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

IJHack / QtPass / 44963528650

21 Nov 2026 11:47PM UTC coverage: 94.71% (+0.02%) from 94.692%
44963528650

push

github

web-flow
Show store names on one bounded line (#2302)

* Show store names on one bounded line

Field names, entry and folder paths and template names come from the
store, and went whole into labels and a combo box whose size becomes the
window's minimum size. A co-writer's name of tens of thousands of
characters, or of thousands of line breaks, made the main window, the edit
dialog, the Add folder prompt and the users dialog hundreds of thousands
of pixels large and took gigabytes.

Util::shownName() gives such a name as shown: one line (controls as
U+FFFD, a tab as a space), at most 120 characters, cut in the middle and
never inside a surrogate pair. It is used for the display panel's and the
edit dialog's field names, template field labels, the entry name above
the panel, the Add folder prompt and, per run without a space, the users
dialog's warning, which also shows at most 12 lines. The whole name stays
where it is used: FieldLabel keeps it for renaming, and the template box
keeps names as item data and is no longer sized to its items.

FieldLabel now emits renamed() with a copy of the old name: a receiver
that accepts it calls setName(), and a later one read the new name as the
old.

Scan finding ANT-2026-MRD4LUFB.

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

* Store names: scroll the users warning, tooltips, short limits

The users warning cut each line to 12 and each word to 160 characters:
twelve line breaks in a folder name pushed the explanation out, and a
name of many short words kept its length. Show the whole text again, in a
scroll area of eight lines: a scroll area asks for a bounded size, so the
quoted names no longer size the dialog (566 x 14 246 px before).

The template box names each template whole in its item's tooltip, as the
folder picker does. shownName() with a limit below 3 returns the head
alone instead of reading before the start.

Co-Authored-By: Claude Opus 5.5 <no... (continued)

57 of 58 new or added lines in 6 files covered. (98.28%)

9615 of 10152 relevant lines covered (94.71%)

18580.07 hits per line

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

94.29
/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() {
910 ✔
51
  if (!_envInitialised) {
910 ✔
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
}
910 ✔
76

77
auto Util::findPasswordStore() -> QString {
381 ✔
78
  QString path;
381 ✔
79
  initialiseEnvironment();
381 ✔
80
  if (_env.contains("PASSWORD_STORE_DIR")) {
762 ✔
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,134 ✔
87
#endif
88
  }
89
  return Util::normalizeFolderPath(QDir::cleanPath(path));
762 ✔
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 {
515 ✔
103
  QString normalizedPath = path;
104
  if (!normalizedPath.endsWith('/')) {
515 ✔
105
    normalizedPath += '/';
496 ✔
106
  }
107
  return normalizedPath;
515 ✔
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,852 ✔
140
  if (store.isEmpty()) {
1,852 ✔
141
    return {};
×
142
  }
143
  QString path = QFileInfo(store).canonicalFilePath();
1,852 ✔
144
  if (path.isEmpty()) {
1,852 ✔
145
    path = QDir::cleanPath(QDir(store).absolutePath());
×
146
  }
147
  return QFileInfo(path).absolutePath();
1,852 ✔
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 ✔
171
    ::close(fd);
×
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,852 ✔
430
                             std::optional<uint> asUser)
431
    -> QList<std::pair<QString, QString>> {
432
  const QString ceiling = gitCeiling(store);
1,852 ✔
433
  if (ceiling.isEmpty()) {
1,852 ✔
434
    return {};
×
435
  }
436
  QList<std::pair<QString, QString>> vars{
437
      {QStringLiteral("GIT_CEILING_DIRECTORIES"), ceiling}};
5,556 ✔
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,852 ✔
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,852 ✔
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 {
530 ✔
528
  if (binary.isEmpty()) {
530 ✔
529
    return {};
1 ✔
530
  }
531

532
  initialiseEnvironment();
529 ✔
533

534
  const QStringList dirs =
535
      _env.value(QStringLiteral("PATH"))
1,058 ✔
536
          .split(QDir::listSeparator(), Qt::SkipEmptyParts);
529 ✔
537
  QString ret;
529 ✔
538
  if (QDir::fromNativeSeparators(binary).contains(u'/')) {
529 ✔
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,052 ✔
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,
540 ✔
591
                            const QStringList &searchPaths) -> QString {
592
  if (binary.isEmpty() || QDir::fromNativeSeparators(binary).contains(u'/')) {
1,079 ✔
593
    return {};
4 ✔
594
  }
595
  QStringList dirs;
536 ✔
596
  dirs.reserve(searchPaths.size());
536 ✔
597
  for (const QString &dir : searchPaths) {
8,420 ✔
598
    if (!dir.isEmpty()) {
7,884 ✔
599
      dirs.append(dir);
600
    }
601
  }
602
  if (dirs.isEmpty()) {
536 ✔
603
    // QStandardPaths::findExecutable() treats an empty list as "use PATH".
604
    return {};
4 ✔
605
  }
606
  return QStandardPaths::findExecutable(binary, dirs);
532 ✔
607
}
608

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

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

617
  if (const auto wsl = Executor::parseWslCommand(executable)) {
199 ✔
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();
199 ✔
633
}
634

635
auto Util::endsWithGpg() -> const QRegularExpression & {
16,234 ✔
636
  static const QRegularExpression expr{R"(\.gpg$)"};
16,241 ✔
637
  return expr;
16,234 ✔
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 & {
153 ✔
644
  static const QRegularExpression regex{
645
      R"(((?:https?|ftp|ssh|sftp|ftps|webdav|webdavs)://[^"\s<>\)\]\[]+))"};
158 ✔
646
  return regex;
153 ✔
647
}
648

649
namespace {
650
/**
651
 * @brief The length of a URL's authority, found as QUrl finds it.
652
 *
653
 * QUrl takes the text before the first ':' that comes before any '/', '?'
654
 * or '#' as the scheme when it is one (a letter, then letters, digits,
655
 * '+', '-' or '.'); the rest starts there, or at the start otherwise. An
656
 * authority follows a "//" at that point and runs to the first '/', '?'
657
 * or '#'. So "//host" has one too, and a "://" later in the text does not
658
 * start it.
659
 * @param url The candidate URL.
660
 * @return The authority's length, or -1 when there is none.
661
 */
662
auto authorityLength(const QString &url) -> qsizetype {
124 ✔
663
  const auto endsPart = [](QChar c) {
664
    return c == QLatin1Char('/') || c == QLatin1Char('?') ||
665
           c == QLatin1Char('#');
666
  };
667
  const auto isAsciiLetter = [](QChar c) {
668
    return (c >= QLatin1Char('a') && c <= QLatin1Char('z')) ||
467 ✔
669
           (c >= QLatin1Char('A') && c <= QLatin1Char('Z'));
9 ✔
670
  };
671
  qsizetype colon = -1;
672
  for (qsizetype i = 0; i < url.size() && !endsPart(url.at(i)); ++i) {
857 ✔
673
    if (url.at(i) == QLatin1Char(':')) {
830 ✔
674
      colon = i;
675
      break;
676
    }
677
  }
678
  bool scheme = colon > 0 && isAsciiLetter(url.at(0));
124 ✔
679
  for (qsizetype i = 1; scheme && i < colon; ++i) {
494 ✔
680
    const QChar c = url.at(i);
681
    scheme =
682
        isAsciiLetter(c) || (c >= QLatin1Char('0') && c <= QLatin1Char('9')) ||
9 ✔
683
        c == QLatin1Char('+') || c == QLatin1Char('-') || c == QLatin1Char('.');
7 ✔
684
  }
685
  const qsizetype hier = scheme ? colon + 1 : 0;
124 ✔
686
  if (url.mid(hier, 2) != QLatin1String("//")) {
248 ✔
687
    return -1;
688
  }
689
  qsizetype end = hier + 2;
92 ✔
690
  while (end < url.size() && !endsPart(url.at(end))) {
201,621 ✔
691
    ++end;
201,529 ✔
692
  }
693
  return end - (hier + 2);
92 ✔
694
}
695
} // namespace
696

697
auto Util::isLaunchableWebUrl(const QString &value) -> bool {
128 ✔
698
  const QString trimmed = value.trimmed();
699
  if (trimmed.isEmpty()) {
128 ✔
700
    return false;
701
  }
702
  // Reject control characters first, before QUrl normalisation can hide a
703
  // CR/LF/NUL injection into the OS URL handler.
704
  for (const QChar &c : trimmed) {
264,770 ✔
705
    if (c == QLatin1Char('\r') || c == QLatin1Char('\n') ||
706
        c == QChar(QChar::Null)) {
707
      return false;
708
    }
709
  }
710
  // QUrl runs the host through Unicode normalisation, which takes time in
711
  // the square of a run of combining marks out of canonical order: one line
712
  // of an entry kept the window busy for minutes. A host has at most 253
713
  // characters and a port six more, so a longer authority is no web
714
  // address anyway.
715
  constexpr qsizetype kMaxAuthority = 259;
716
  if (authorityLength(trimmed) > kMaxAuthority) {
124 ✔
717
    return false;
718
  }
719
  const QUrl url(trimmed, QUrl::StrictMode);
118 ✔
720
  if (!url.isValid()) {
118 ✔
721
    return false;
722
  }
723
  const QString scheme = url.scheme().toLower();
103 ✔
724
  if (scheme != QLatin1String("http") && scheme != QLatin1String("https")) {
103 ✔
725
    return false;
36 ✔
726
  }
727
  if (url.host().isEmpty()) {
134 ✔
728
    return false;
729
  }
730
  // Embedded userinfo (user:pass@host) would leak into browser history.
731
  if (!url.userName().isEmpty() || !url.password().isEmpty()) {
127 ✔
732
    return false;
733
  }
734
  return true;
735
}
118 ✔
736

737
auto Util::displayable(const QString &text, bool lineBreaks) -> QString {
31,695 ✔
738
  QString shown = text;
739
  for (qsizetype i = 0; i < shown.size(); ++i) {
21,538,309 ✔
740
    const char16_t u = shown.at(i).unicode();
741
    // A carriage return before a line feed is a Windows line end (git or
742
    // gpg output quoted in a message), not a character of its own.
743
    const bool lineEnd =
744
        lineBreaks && (u == u'\n' || (u == u'\r' && i + 1 < shown.size() &&
21,506,614 ✔
745
                                      shown.at(i + 1) == u'\n'));
746
    if ((u < 0x20 && u != u'\t' && !lineEnd) || (u >= 0x7f && u <= 0x9f) ||
21,506,614 ✔
747
        u == 0x2028 || u == 0x2029 || (u >= 0x202a && u <= 0x202e) ||
21,506,558 ✔
748
        (u >= 0x2066 && u <= 0x2069)) {
21,506,548 ✔
749
      shown[i] = QChar(QChar::ReplacementCharacter);
68 ✔
750
    }
751
  }
752
  return shown;
31,695 ✔
753
}
754

755
auto Util::linkifyUrls(const QString &text, bool *linked) -> QString {
149 ✔
756
  if (linked != nullptr) {
149 ✔
757
    *linked = false;
61 ✔
758
  }
759
  QString html;
149 ✔
760
  html.reserve(text.size());
149 ✔
761
  qsizetype lastIndex = 0;
762
  QRegularExpressionMatchIterator it = protocolRegex().globalMatch(text);
149 ✔
763
  while (it.hasNext()) {
197 ✔
764
    const QRegularExpressionMatch match = it.next();
48 ✔
765
    const QString url = match.captured(0);
48 ✔
766
    // Only plain ASCII becomes a link: the link text is the URL as stored,
767
    // and a right-to-left letter, a bidi control or a look-alike host in it
768
    // makes it read as another address than the one it opens. Such a URL
769
    // stays plain text; the open button still takes it.
770
    const bool plain = std::all_of(url.cbegin(), url.cend(), [](QChar c) {
771
      return c.unicode() > 0x20 && c.unicode() < 0x7f;
1,139 ✔
772
    });
773
    if (!plain || !isLaunchableWebUrl(url)) {
48 ✔
774
      // Not a web URL (or it carries credentials): leave it in the escaped
775
      // plain-text run instead of making it clickable.
776
      continue;
777
    }
778
    const qsizetype start = match.capturedStart(0);
32 ✔
779
    html += text.mid(lastIndex, start - lastIndex).toHtmlEscaped();
32 ✔
780
    const QString escapedUrl = url.toHtmlEscaped();
32 ✔
781
    html += QStringLiteral("<a href=\"%1\">%1</a>").arg(escapedUrl);
64 ✔
782
    lastIndex = match.capturedEnd(0);
32 ✔
783
    if (linked != nullptr) {
32 ✔
784
      *linked = true;
24 ✔
785
    }
786
  }
48 ✔
787
  html += text.mid(lastIndex).toHtmlEscaped();
149 ✔
788
  // With a link in it, no bidi embedding, override or isolate control is
789
  // drawn: an override earlier in the entry (U+202E) drew the link text
790
  // reversed, so it read as another address. Shown as U+FFFD, so the user
791
  // sees that something was there; the copy button still copies the value.
792
  if (linked != nullptr ? *linked : html.contains(QLatin1String("<a href="))) {
237 ✔
793
    for (QChar &c : html) {
3,442 ✔
794
      const char16_t u = c.unicode();
3,412 ✔
795
      if ((u >= 0x202A && u <= 0x202E) || (u >= 0x2066 && u <= 0x2069)) {
3,412 ✔
796
        c = QChar(QChar::ReplacementCharacter);
1 ✔
797
      }
798
    }
799
  }
800
  return html;
149 ✔
801
}
149 ✔
802

803
auto Util::isOtherBlockBreak(QChar c) -> bool {
1,000,770 ✔
804
  const char16_t u = c.unicode();
1,000,770 ✔
805
  return u == u'\r' || u == 0x2029 || u == 0xFDD0 || u == 0xFDD1;
1,000,770 ✔
806
}
807

808
auto Util::withoutOtherBlockBreaks(QString text) -> QString {
214 ✔
809
  for (QChar &c : text) {
494,100 ✔
810
    if (isOtherBlockBreak(c)) {
493,886 ✔
811
      c = QLatin1Char(' ');
8,002 ✔
812
    }
813
  }
814
  return text;
214 ✔
815
}
816

817
auto Util::hasLongUnbrokenRun(QStringView text) -> bool {
311 ✔
818
  qsizetype run = 0;
819
  for (const QChar c : text) {
248,222 ✔
820
    // A no-break space (U+00A0, U+2007, U+202F) is white space to
821
    // isSpace(), but Qt does not wrap at it.
822
    const char16_t u = c.unicode();
823
    const bool breaks =
824
        c.isSpace() && u != 0x00A0 && u != 0x2007 && u != 0x202F;
247,922 ✔
825
    run = breaks ? 0 : run + 1;
210,898 ✔
826
    if (run > kMaxUnbrokenRun) {
247,922 ✔
827
      return true;
828
    }
829
  }
830
  return false;
831
}
832

833
auto Util::plainToolTip(const QString &text) -> QString {
18,853 ✔
834
  // Escaped, with its white space kept: two names that differ only in it
835
  // must not read the same; a long run is cut as everywhere it is kept.
836
  return QStringLiteral("<p style=\"white-space: pre-wrap;\">") +
18,853 ✔
837
         boundSpaceRuns(displayable(text, false)).toHtmlEscaped() +
37,706 ✔
838
         QStringLiteral("</p>");
37,706 ✔
839
}
840

841
auto Util::shownName(const QString &name, qsizetype max) -> QString {
343 ✔
842
  QString line = displayable(name, false);
343 ✔
843
  line.replace(QLatin1Char('\t'), QLatin1Char(' '));
343 ✔
844
  if (line.size() <= max) {
343 ✔
845
    return line;
331 ✔
846
  }
847
  // Too short for an ellipsis between two ends: the head alone.
848
  if (max < 3) {
12 ✔
849
    qsizetype keep = std::max<qsizetype>(max, 0);
850
    if (keep > 0 && line.at(keep - 1).isHighSurrogate()) {
5 ✔
851
      --keep;
852
    }
853
    return line.left(keep);
5 ✔
854
  }
855
  qsizetype head = max / 3;
7 ✔
856
  if (line.at(head - 1).isHighSurrogate()) {
7 ✔
857
    --head;
858
  }
859
  qsizetype tail = max - max / 3 - 1;
7 ✔
860
  if (line.at(line.size() - tail).isLowSurrogate()) {
7 ✔
NEW
861
    --tail;
×
862
  }
863
  return line.left(head) + QChar(0x2026) + line.right(tail);
14 ✔
864
}
865

866
// One pass, no regex: a pattern such as \s{1001,} retries from every
867
// character of a shorter run, which is quadratic on an entry made of them.
868
// A tab or a line feed ends a run in Qt's layout as well, so it ends one
869
// here; \v and U+0085 do not, so they count.
870
auto Util::boundSpaceRuns(const QString &text) -> QString {
19,071 ✔
871
  QString bounded;
19,071 ✔
872
  // Text before this index is in bounded already, or dropped.
873
  qsizetype from = 0;
874
  qsizetype run = 0;
875
  for (qsizetype i = 0; i < text.size(); ++i) {
20,702,092 ✔
876
    const QChar ch = text.at(i);
877
    if (!ch.isSpace() || ch == QLatin1Char('\t') || ch == QLatin1Char('\n')) {
20,683,021 ✔
878
      run = 0;
879
      continue;
20,528,988 ✔
880
    }
881
    if (++run <= kMaxSpaceRun) {
154,033 ✔
882
      continue;
18,496 ✔
883
    }
884
    if (run == kMaxSpaceRun + 1) {
135,537 ✔
885
      bounded += QStringView(text).sliced(from, i - from);
6 ✔
886
    }
887
    from = i + 1;
135,537 ✔
888
  }
889
  if (from == 0) {
19,071 ✔
890
    return text;
891
  }
892
  bounded += QStringView(text).sliced(from);
893
  return bounded;
894
}
895

896
auto Util::newLinesRegex() -> const QRegularExpression & {
400 ✔
897
  static const QRegularExpression regex{"[\r\n]"};
409 ✔
898
  return regex;
400 ✔
899
}
900

901
// No content heuristics: a line rejected here is erased the next time .gpg-id
902
// is rewritten. A leading `-` is refused because the recipients also go
903
// positionally to `gpg --list-keys`, where it would parse as an option.
904
auto Util::isValidKeyId(const QString &keyId) -> bool {
6,293 ✔
905
  return !keyId.isEmpty() && !keyId.startsWith('-');
6,293 ✔
906
}
907

908
namespace {
909
/**
910
 * @brief Whether the walk can see what is in @p dir: read permission to list
911
 * it and, on Unix, search permission to look at what it holds (without it the
912
 * names come, but no entry reads as a file or a folder), and no name Qt
913
 * leaves out of the listing (Util::hasUnreadableName()).
914
 * @param dir An existing directory.
915
 * @return false when the walk would miss what is in it.
916
 */
917
auto canList(const QString &dir) -> bool {
206 ✔
918
#ifdef Q_OS_WIN
919
  // Qt answers from the attributes alone unless told to read the ACL.
920
  QNtfsPermissionCheckGuard aclCheck;
921
  return QFileInfo(dir).isReadable();
922
#else
923
  const QFileInfo info(dir);
206 ✔
924
  return info.isReadable() && info.isExecutable() &&
404 ✔
925
         !Util::hasUnreadableName(dir);
404 ✔
926
#endif
927
}
206 ✔
928

929
/**
930
 * @brief Walk @p dir's real, visible directories in sorted pre-order and hand
931
 * every entry to @p visit before any recursion; a directory is entered only
932
 * when @p visit returns true for it. A directory that cannot be read goes to
933
 * @p unlisted, when given: its listing would come back empty, as an empty
934
 * folder's does, and what is in it would be left out without a sign.
935
 */
936
template <typename Visit>
937
void walkStore(const QString &dir, Visit visit,
340 ✔
938
               QStringList *unlisted = nullptr) {
939
  // Absolute, so the results are whatever the caller's cwd; not canonical,
940
  // so a linked root keeps the name it was configured under.
941
  QStringList pending{QDir(QDir::cleanPath(dir)).absolutePath()};
1,020 ✔
942
  while (!pending.isEmpty()) {
2,928 ✔
943
    const QDir current(pending.takeLast());
1,299 ✔
944
    if (unlisted != nullptr && current.exists() && !canList(current.path())) {
2,598 ✔
945
      qCWarning(lcQtPass) << "Cannot list" << current.path();
20 ✔
946
      *unlisted << current.path();
10 ✔
947
      continue;
948
    }
10 ✔
949
    // Every entry once, links and hidden entries included, so the decision
950
    // what to do with each is taken here, before any recursion. QDir::System
951
    // keeps dangling links in the listing.
952
    const QFileInfoList entries =
1,289 ✔
953
        current.entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
954
                                  QDir::System | QDir::NoDotAndDotDot,
955
                              QDir::Name);
956
    QStringList subdirs;
1,289 ✔
957
    for (const QFileInfo &entry : entries) {
8,023 ✔
958
      if (visit(entry)) {
6,734 ✔
959
        subdirs << entry.filePath();
1,918 ✔
960
      }
961
    }
962
    // Pushed last-to-first so the next one taken is the first by name.
963
    for (auto it = subdirs.crbegin(); it != subdirs.crend(); ++it) {
2,248 ✔
964
      pending << *it;
965
    }
966
  }
967
}
680 ✔
968

969
/// A symlink or an NTFS junction: never entered, never listed.
970
auto isLink(const QFileInfo &entry) -> bool {
27,676 ✔
971
  return entry.isSymLink() || entry.isJunction();
27,676 ✔
972
}
973

974
/// Hidden by attribute, or by the dot convention on every platform: Qt 6.11
975
/// on macOS answers isHidden() from the UF_HIDDEN flag alone once an entry
976
/// was lstat()ed (qfilesystemengine_unix.cpp marks the attribute known there
977
/// without the dot check), and Windows does not consider .stversions hidden
978
/// at all.
979
auto isHiddenEntry(const QFileInfo &entry) -> bool {
5,679 ✔
980
  return entry.isHidden() || entry.fileName().startsWith(QLatin1Char('.'));
11,338 ✔
981
}
982

983
/// A real directory that is part of the store: .git, .stversions,
984
/// .Trash-1000 are not, as with QDirIterator without QDir::Hidden.
985
auto isStoreDirectory(const QFileInfo &entry) -> bool {
6,734 ✔
986
  return !isLink(entry) && entry.isDir() && !isHiddenEntry(entry);
6,734 ✔
987
}
988
} // namespace
989

990
auto Util::regularFilesUnder(const QString &dir, const QStringList &nameFilters,
337 ✔
991
                             QStringList *skipped, bool hiddenFiles,
992
                             QStringList *unlisted) -> QStringList {
993
  QStringList files;
337 ✔
994
  walkStore(
337 ✔
995
      dir,
996
      [&](const QFileInfo &entry) {
6,659 ✔
997
        if (isStoreDirectory(entry)) {
6,659 ✔
998
          return true;
999
        }
1000
        const bool named = QDir::match(nameFilters, entry.fileName());
5,721 ✔
1001
        if (isLink(entry) || (!entry.isDir() && !entry.isFile())) {
5,721 ✔
1002
          // A linked directory hides everything behind it; a linked file, or a
1003
          // FIFO, socket or device, is only of interest under a name the caller
1004
          // asked for.
1005
          if (skipped != nullptr && (entry.isDir() || named)) {
68 ✔
1006
            qCWarning(lcQtPass) << "Skipping" << entry.filePath()
104 ✔
1007
                                << ": not a regular file or directory";
52 ✔
1008
            *skipped << entry.filePath();
104 ✔
1009
          }
1010
          return false;
68 ✔
1011
        }
1012
        if (entry.isFile() && named && (hiddenFiles || !isHiddenEntry(entry))) {
5,653 ✔
1013
          files << entry.filePath();
9,798 ✔
1014
        }
1015
        return false;
1016
      },
1017
      unlisted);
1018
  return files;
337 ✔
1019
}
1020

1021
auto Util::directoriesUnder(const QString &dir) -> QStringList {
3 ✔
1022
  QStringList dirs;
3 ✔
1023
  walkStore(dir, [&](const QFileInfo &entry) {
3 ✔
1024
    if (!isStoreDirectory(entry)) {
75 ✔
1025
      return false;
1026
    }
1027
    dirs << entry.filePath();
21 ✔
1028
    return true;
21 ✔
1029
  });
1030
  return dirs;
3 ✔
1031
}
1032

1033
auto Util::hasUnreadableName(const QString &dir) -> bool {
273 ✔
1034
#ifdef Q_OS_WIN
1035
  Q_UNUSED(dir);
1036
  return false;
1037
#else
1038
  // The names as bytes, as readdir() gives them; Qt's own listing has
1039
  // already dropped the ones this is looking for.
1040
  DIR *listing = ::opendir(QFile::encodeName(dir).constData());
273 ✔
1041
  if (listing == nullptr) {
273 ✔
1042
    return false;
1043
  }
1044
  const auto close = qScopeGuard([listing] { ::closedir(listing); });
273 ✔
1045
  while (const dirent *entry = ::readdir(listing)) {
1,405 ✔
1046
    if (!QByteArrayView(entry->d_name).isValidUtf8()) {
1,138 ✔
1047
      return true;
1048
    }
1049
  }
1050
  return false;
1051
#endif
1052
}
1053

1054
auto Util::isLinkedFolder(const QString &path) -> bool {
15,178 ✔
1055
  return isLink(QFileInfo(QDir::cleanPath(path)));
30,356 ✔
1056
}
1057

1058
auto Util::isUnderLink(const QString &path, const QString &storeRoot,
12,172 ✔
1059
                       bool includeSelf) -> bool {
1060
  // "C:/Store" and "c:/store" are one directory on Windows; a path spelled
1061
  // the other way must not skip the walk (as in Pass::getGpgIdPath).
1062
#ifdef Q_OS_WIN
1063
  constexpr auto cs = Qt::CaseInsensitive;
1064
#else
1065
  constexpr auto cs = Qt::CaseSensitive;
1066
#endif
1067
  const QString root = QDir::cleanPath(storeRoot);
12,172 ✔
1068
  // A root of "/" or "C:/" already ends in the separator.
1069
  const QString prefix =
1070
      root.endsWith(QLatin1Char('/')) ? root : root + QLatin1Char('/');
12,172 ✔
1071
  const auto isRoot = [&](const QString &p) {
1072
    return p.compare(root, cs) == 0;
14,789 ✔
1073
  };
1074
  QString current = QDir::cleanPath(path);
12,172 ✔
1075
  if (!current.startsWith(prefix, cs)) {
12,172 ✔
1076
    // Not under the store as named: only the entry itself can be judged.
1077
    return includeSelf && !isRoot(current) && isLinkedFolder(current);
504 ✔
1078
  }
1079
  if (!includeSelf) {
11,920 ✔
1080
    current = QFileInfo(current).path();
21,932 ✔
1081
  }
1082
  for (; !isRoot(current) && current.startsWith(prefix, cs);
14,537 ✔
1083
       current = QFileInfo(current).path()) {
5,234 ✔
1084
    if (isLinkedFolder(current)) {
2,667 ✔
1085
      return true;
1086
    }
1087
  }
1088
  return false;
1089
}
1090

1091
#ifndef Q_OS_WIN
1092
namespace {
1093

1094
/// The filesystem cannot make hard links at all (FAT/exFAT refuse with
1095
/// EPERM, some FUSE filesystems with ENOTSUP or ENOSYS).
1096
auto hasNoHardLinks(int error) -> bool {
1097
  return error == EPERM || error == ENOTSUP || error == EOPNOTSUPP ||
2 ✔
1098
         error == ENOSYS;
1099
}
1100

1101
/// rename() that fails with EEXIST instead of replacing, where the platform
1102
/// has one; nothing when neither the platform nor the filesystem does.
1103
auto renameExclusive(const QByteArray &source, const QByteArray &target)
8 ✔
1104
    -> std::optional<bool> {
1105
#if defined(__GLIBC__) &&                                                      \
1106
    (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 28))
1107
  if (::renameat2(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(),
8 ✔
1108
                  RENAME_NOREPLACE) == 0) {
1109
    return true;
2 ✔
1110
  }
1111
  if (errno == EINVAL || errno == ENOSYS || hasNoHardLinks(errno)) {
6 ✔
1112
    return std::nullopt;
4 ✔
1113
  }
1114
  return false;
2 ✔
1115
#elif defined(Q_OS_MACOS)
1116
  if (::renamex_np(source.constData(), target.constData(), RENAME_EXCL) == 0) {
1117
    return true;
1118
  }
1119
  if (errno == EINVAL || errno == ENOTSUP) {
1120
    return std::nullopt;
1121
  }
1122
  return false;
1123
#else
1124
  Q_UNUSED(source);
1125
  Q_UNUSED(target);
1126
  return std::nullopt;
1127
#endif
1128
}
1129

1130
/**
1131
 * @brief Gives @p source the name @p target unless something already has it.
1132
 *
1133
 * A hard link is the one way every POSIX system can do that in one step:
1134
 * linkat() fails with EEXIST rather than replacing. Where the filesystem has
1135
 * no hard links, an exclusive rename does it; where that is missing too, the
1136
 * name is checked and then renamed, which leaves a short window for another
1137
 * writer to create it in between.
1138
 */
1139
auto placeWithoutReplacing(const QByteArray &source, const QByteArray &target)
110 ✔
1140
    -> bool {
1141
  // linkat() without AT_SYMLINK_FOLLOW follows nothing; link() would, on
1142
  // macOS and the BSDs, hard-link whatever a symlink planted under the
1143
  // source's name points at.
1144
  if (::linkat(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(), 0) ==
110 ✔
1145
      0) {
1146
    ::unlink(source.constData());
95 ✔
1147
    return true;
95 ✔
1148
  }
1149
  if (!hasNoHardLinks(errno)) {
15 ✔
1150
    return false;
1151
  }
1152
  if (const std::optional<bool> renamed = renameExclusive(source, target)) {
8 ✔
1153
    return *renamed;
4 ✔
1154
  }
1155
  struct stat st{};
4 ✔
1156
  if (::lstat(target.constData(), &st) == 0 || errno != ENOENT) {
4 ✔
1157
    errno = EEXIST;
2 ✔
1158
    return false;
2 ✔
1159
  }
1160
  return ::rename(source.constData(), target.constData()) == 0;
2 ✔
1161
}
1162

1163
} // namespace
1164
#endif
1165

1166
auto Util::replaceFile(const QString &from, const QString &to, bool replace)
285 ✔
1167
    -> bool {
1168
#ifdef Q_OS_WIN
1169
  const std::wstring source =
1170
      QDir::toNativeSeparators(QFileInfo(from).absoluteFilePath())
1171
          .toStdWString();
1172
  const std::wstring target =
1173
      QDir::toNativeSeparators(QFileInfo(to).absoluteFilePath()).toStdWString();
1174
  // WRITE_THROUGH: the new entry is on the device when this returns.
1175
  return MoveFileExW(source.c_str(), target.c_str(),
1176
                     (replace ? MOVEFILE_REPLACE_EXISTING : 0) |
1177
                         MOVEFILE_WRITE_THROUGH) != 0;
1178
#else
1179
  const QByteArray source = QFile::encodeName(from);
1180
  const QByteArray target = QFile::encodeName(to);
1181
  if (replace) {
285 ✔
1182
    if (::rename(source.constData(), target.constData()) != 0) {
175 ✔
1183
      return false;
1184
    }
1185
  } else {
1186
    if (!placeWithoutReplacing(source, target)) {
110 ✔
1187
      return false;
1188
    }
1189
  }
1190
  // Sync the directory entry so a crash does not lose the new name. Best
1191
  // effort: the bytes are already synced, and some network filesystems
1192
  // cannot sync a directory.
1193
  const int dir = ::open(QFile::encodeName(QFileInfo(to).path()).constData(),
542 ✔
1194
                         O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1195
  if (dir >= 0) {
271 ✔
1196
    int rc;
1197
    do {
1198
      rc = ::fsync(dir);
271 ✔
1199
    } while (rc != 0 && errno == EINTR);
271 ✔
1200
    ::close(dir);
271 ✔
1201
  }
1202
  return true;
1203
#endif
1204
}
1205

1206
auto Util::openRegularFile(const QString &path, QFile &file) -> bool {
1,085 ✔
1207
#ifdef Q_OS_WIN
1208
  // FILE_FLAG_OPEN_REPARSE_POINT opens a symbolic link or junction itself
1209
  // rather than its target, so the handle's attributes say what the name
1210
  // was at the moment of the open.
1211
  const std::wstring native =
1212
      QDir::toNativeSeparators(QFileInfo(path).absoluteFilePath())
1213
          .toStdWString();
1214
  HANDLE handle = CreateFileW(
1215
      native.c_str(), GENERIC_READ,
1216
      FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
1217
      OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
1218
  if (handle == INVALID_HANDLE_VALUE) {
1219
    return false;
1220
  }
1221
  BY_HANDLE_FILE_INFORMATION info{};
1222
  if (!GetFileInformationByHandle(handle, &info) ||
1223
      (info.dwFileAttributes &
1224
       (FILE_ATTRIBUTE_REPARSE_POINT | FILE_ATTRIBUTE_DIRECTORY |
1225
        FILE_ATTRIBUTE_DEVICE)) != 0 ||
1226
      GetFileType(handle) != FILE_TYPE_DISK) {
1227
    CloseHandle(handle);
1228
    return false;
1229
  }
1230
  const int fd = _open_osfhandle(reinterpret_cast<intptr_t>(handle),
1231
                                 _O_RDONLY | _O_BINARY);
1232
  if (fd < 0) {
1233
    CloseHandle(handle);
1234
    return false;
1235
  }
1236
  if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
1237
    _close(fd);
1238
    return false;
1239
  }
1240
  return true;
1241
#else
1242
  // O_NOFOLLOW fails with ELOOP on a symbolic link; O_NONBLOCK keeps a FIFO
1243
  // from blocking the open until fstat() can refuse it.
1244
  const int fd = ::open(QFile::encodeName(path).constData(),
1,085 ✔
1245
                        O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
1246
  if (fd < 0) {
1,085 ✔
1247
    return false;
1248
  }
1249
  struct stat st{};
1,028 ✔
1250
  if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
1,028 ✔
1251
    ::close(fd);
7 ✔
1252
    return false;
7 ✔
1253
  }
1254
  // The descriptor, not the name, is what QFile opens here: the object
1255
  // fstat() judged is the object read. CodeQL's check-then-use pattern
1256
  // matcher sees an open after a check and cannot tell.
1257
  if (!file.open(fd, QIODevice::ReadOnly, // codeql[cpp/toctou-race-condition]
1,021 ✔
1258
                 QFileDevice::AutoCloseHandle)) {
1259
    ::close(fd);
×
1260
    return false;
×
1261
  }
1262
  return true;
1263
#endif
1264
}
1265

1266
auto Util::readRegularFile(const QString &path, qint64 maxBytes)
446 ✔
1267
    -> std::optional<QByteArray> {
1268
  QFile file;
446 ✔
1269
  if (!openRegularFile(path, file)) {
446 ✔
1270
    return std::nullopt;
10 ✔
1271
  }
1272
  // A regular file's size is reliable, also when sparse: refuse a large one
1273
  // before reading anything. One byte past the limit still guards a file
1274
  // that grows meanwhile.
1275
  if (file.size() > maxBytes) {
436 ✔
1276
    return std::nullopt;
3 ✔
1277
  }
1278
  QByteArray bytes = file.read(maxBytes + 1);
433 ✔
1279
  if (bytes.size() > maxBytes || file.error() != QFileDevice::NoError) {
433 ✔
1280
    return std::nullopt;
×
1281
  }
1282
  return bytes;
1283
}
446 ✔
1284

1285
auto Util::syncToDisk(QFileDevice &file) -> bool {
271 ✔
1286
  if (!file.flush()) {
271 ✔
1287
    return false;
1288
  }
1289
#ifdef Q_OS_WIN
1290
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1291
  return handle != INVALID_HANDLE_VALUE && FlushFileBuffers(handle) != 0;
1292
#else
1293
  return ::fsync(file.handle()) == 0;
271 ✔
1294
#endif
1295
}
1296

1297
namespace {
1298

1299
/**
1300
 * @brief What tells one file object from another on its filesystem: device
1301
 * and inode on POSIX, volume serial and file index on Windows.
1302
 */
1303
struct FileIdentity {
1304
  quint64 volume = 0;
1305
  quint64 index = 0;
1306
  bool known = false;
1307
};
1308

1309
auto operator==(const FileIdentity &a, const FileIdentity &b) -> bool {
260 ✔
1310
  return a.known && b.known && a.volume == b.volume && a.index == b.index;
260 ✔
1311
}
1312

1313
/// The identity of the object @p file is open on, or an unknown one.
1314
auto identityOf(const QFileDevice &file) -> FileIdentity {
531 ✔
1315
#ifdef Q_OS_WIN
1316
  const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1317
  BY_HANDLE_FILE_INFORMATION info;
1318
  if (handle == INVALID_HANDLE_VALUE ||
1319
      GetFileInformationByHandle(handle, &info) == 0) {
1320
    return {};
1321
  }
1322
  // On FAT/exFAT the file ID is the directory entry's offset, which a rename
1323
  // can move. They have no hard links either (the swap this catches needs
1324
  // one), so the identity is left unknown there.
1325
  DWORD flags = 0;
1326
  if (GetVolumeInformationByHandleW(handle, nullptr, 0, nullptr, nullptr,
1327
                                    &flags, nullptr, 0) == 0 ||
1328
      (flags & FILE_SUPPORTS_HARD_LINKS) == 0) {
1329
    return {};
1330
  }
1331
  return {info.dwVolumeSerialNumber,
1332
          (static_cast<quint64>(info.nFileIndexHigh) << 32) |
1333
              info.nFileIndexLow,
1334
          true};
1335
#else
1336
  struct stat st{};
531 ✔
1337
  if (::fstat(file.handle(), &st) != 0) {
531 ✔
1338
    return {};
×
1339
  }
1340
  return {static_cast<quint64>(st.st_dev), static_cast<quint64>(st.st_ino),
531 ✔
1341
          true};
531 ✔
1342
#endif
1343
}
1344

1345
/// Put @p text in @p error when there is one; false, for `return fail(...)`.
1346
auto fail(QString *error, const QString &text) -> bool {
1347
  if (error != nullptr) {
22 ✔
1348
    *error = text;
22 ✔
1349
  }
1350
  return false;
1351
}
1352

1353
/// A filled, synced temporary next to its destination.
1354
struct Staged {
271 ✔
1355
  QString path;
1356
  FileIdentity identity;
1357
  /// POSIX: a descriptor kept open on the temporary until the identity
1358
  /// check, so the inode, and with it the number, stays the temporary's.
1359
  std::shared_ptr<void> pin;
1360
};
1361

1362
/**
1363
 * @brief Create the temporary next to @p path (opaque name, exclusive,
1364
 * owner-only), fill it through its handle and sync it. The QTemporaryFile
1365
 * goes out of scope before the caller renames: it keeps its handle open for
1366
 * as long as it lives, and Windows does not rename an open file.
1367
 */
1368
auto stageNextTo(const QString &path, const Util::Filler &fill, QString *why)
279 ✔
1369
    -> std::optional<Staged> {
1370
  Staged staged;
279 ✔
1371
  {
1372
    QTemporaryFile file(QFileInfo(path).path() +
558 ✔
1373
                        QStringLiteral("/.qtpass-XXXXXX.tmp"));
558 ✔
1374
    file.setAutoRemove(false);
279 ✔
1375
    if (!file.open()) {
279 ✔
1376
      *why = QCoreApplication::translate(
8 ✔
1377
                 "Util", "Cannot create a temporary file next to %1: %2")
1378
                 .arg(path, file.errorString());
16 ✔
1379
      return std::nullopt;
8 ✔
1380
    }
1381
    staged.path = file.fileName();
271 ✔
1382
    // Owner-only: a .gpg-id names the keys a store is encrypted to, an
1383
    // entry is an entry. QTemporaryFile creates 0600 already; say so for
1384
    // platforms where it may not.
1385
    file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
271 ✔
1386
    *why = fill(file);
542 ✔
1387
    if (why->isEmpty() && !Util::syncToDisk(file)) {
271 ✔
1388
      *why = QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1389
                 .arg(path, file.errorString());
×
1390
    }
1391
    staged.identity = identityOf(file);
271 ✔
1392
#ifndef Q_OS_WIN
1393
    // Closed and unlinked by a co-writer before the rename, the temporary's
1394
    // inode number would be free, and ext4 hands it to the next file made:
1395
    // the very file swapped in would then pass the check below. Windows
1396
    // cannot rename an open file, and NTFS does not reuse a file index so.
1397
    if (const int fd = ::dup(file.handle()); fd >= 0) {
271 ✔
1398
      staged.pin =
1399
          std::shared_ptr<void>(nullptr, [fd](void *) { ::close(fd); });
813 ✔
1400
    }
1401
#endif
1402
  }
279 ✔
1403
  if (!why->isEmpty()) {
271 ✔
1404
    QFile::remove(staged.path);
×
1405
    return std::nullopt;
×
1406
  }
1407
  return staged;
271 ✔
1408
}
279 ✔
1409

1410
/// Why replaceFile() could not put the temporary under @p path.
1411
auto placementError(const QString &path, bool replace) -> QString {
9 ✔
1412
  if (replace) {
9 ✔
1413
    return QCoreApplication::translate("Util", "Failed to replace %1.")
4 ✔
1414
        .arg(path);
2 ✔
1415
  }
1416
  const QFileInfo taken(path);
7 ✔
1417
  return taken.exists() || taken.isSymLink()
8 ✔
1418
             ? QCoreApplication::translate("Util", "%1 already exists.")
7 ✔
1419
                   .arg(path)
1420
             : QCoreApplication::translate("Util", "Failed to write %1.")
1 ✔
1421
                   .arg(path);
8 ✔
1422
}
7 ✔
1423

1424
/**
1425
 * @brief Whether what is under @p path is the file that was filled: not a
1426
 * link, and not another file (a hard link to something of the user's, say)
1427
 * swapped in under the temporary's name. Opened without following, compared
1428
 * by identity; only two known identities can prove a swap, otherwise every
1429
 * write on such a store would be reported as tampering.
1430
 */
1431
auto isTheFileWritten(const QString &path, const FileIdentity &written)
262 ✔
1432
    -> bool {
1433
  QFile placed;
262 ✔
1434
  if (!Util::openRegularFile(path, placed)) {
262 ✔
1435
    return false;
1436
  }
1437
  const FileIdentity there = identityOf(placed);
260 ✔
1438
  if (!written.known || !there.known) {
260 ✔
1439
    qCWarning(lcQtPass) << "Cannot tell whether" << path
×
1440
                        << "is the file that was written here";
×
1441
    return true;
×
1442
  }
1443
  return there == written;
260 ✔
1444
}
262 ✔
1445

1446
} // namespace
1447

1448
auto Util::stageFileReplacing(const QString &path, bool replace,
279 ✔
1449
                              const Filler &fill, QString *error) -> bool {
1450
  QString why;
279 ✔
1451
  const std::optional<Staged> staged = stageNextTo(path, fill, &why);
279 ✔
1452
  if (!staged) {
279 ✔
1453
    return fail(error, why);
1454
  }
1455
  if (s_beforePlacingForTests) {
271 ✔
1456
    s_beforePlacingForTests(staged->path);
1 ✔
1457
  }
1458
  if (!replaceFile(staged->path, path, replace)) {
271 ✔
1459
    QFile::remove(staged->path);
9 ✔
1460
    return fail(error, placementError(path, replace));
18 ✔
1461
  }
1462
  // A mismatch is reported and left: removing by name could take another
1463
  // writer's file.
1464
  if (!isTheFileWritten(path, staged->identity)) {
262 ✔
1465
    return fail(
1466
        error,
1467
        QCoreApplication::translate(
5 ✔
1468
            "Util", "%1 was swapped for another file while it was written.")
1469
            .arg(path));
10 ✔
1470
  }
1471
  return true;
1472
}
1473

1474
auto Util::writeFileReplacing(const QString &path, const QByteArray &bytes,
109 ✔
1475
                              bool replace, QString *error) -> bool {
1476
  return stageFileReplacing(
109 ✔
1477
      path, replace,
1478
      [&path, &bytes](QFileDevice &staged) -> QString {
216 ✔
1479
        if (staged.write(bytes) != bytes.size()) {
107 ✔
1480
          return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1481
              .arg(path, staged.errorString());
×
1482
        }
1483
        return {};
107 ✔
1484
      },
1485
      error);
109 ✔
1486
}
1487

1488
auto Util::copyFileReplacing(const QString &src, const QString &dst,
169 ✔
1489
                             bool replace, QString *error) -> bool {
1490
  QFile in;
169 ✔
1491
  if (!openRegularFile(src, in)) {
169 ✔
1492
    if (error)
4 ✔
1493
      *error = QCoreApplication::translate("Util", "Cannot read %1.").arg(src);
8 ✔
1494
    return false;
4 ✔
1495
  }
1496
  return stageFileReplacing(
165 ✔
1497
      dst, replace,
1498
      [&src, &dst, &in](QFileDevice &staged) -> QString {
489 ✔
1499
        char buf[64 * 1024];
1500
        for (;;) {
1501
          const qint64 n = in.read(buf, sizeof buf);
330 ✔
1502
          if (n < 0) {
330 ✔
1503
            return QCoreApplication::translate("Util", "Cannot read %1: %2")
×
1504
                .arg(src, in.errorString());
×
1505
          }
1506
          if (n == 0) {
330 ✔
1507
            return {};
159 ✔
1508
          }
1509
          if (staged.write(buf, n) != n) {
171 ✔
1510
            return QCoreApplication::translate("Util", "Cannot write %1: %2")
×
1511
                .arg(dst, staged.errorString());
×
1512
          }
1513
        }
1514
      },
1515
      error);
1516
}
169 ✔
1517

1518
namespace {
1519

1520
/// Remove one directory entry that is not a real directory: a link goes as
1521
/// the entry itself, never its target (a junction or a directory symlink on
1522
/// Windows is a directory entry and goes with rmdir); a read-only file gets
1523
/// write access and one more try, as QDir::removeRecursively() does.
1524
auto removeEntry(const QFileInfo &entry) -> bool {
14 ✔
1525
  const QString path = entry.filePath();
14 ✔
1526
  if (isLink(entry)) {
14 ✔
1527
    if (QFile::remove(path) || QDir().rmdir(path)) {
6 ✔
1528
      return true;
1529
    }
1530
    qCWarning(lcQtPass) << "Could not remove link" << path;
2 ✔
1531
    return false;
1 ✔
1532
  }
1533
  if (QFile::remove(path)) {
9 ✔
1534
    return true;
1535
  }
1536
  const QFile::Permissions perms = QFile::permissions(path);
2 ✔
1537
  if (!perms.testFlag(QFile::WriteUser) &&
1 ✔
1538
      QFile::setPermissions(path, perms | QFile::WriteUser) &&
3 ✔
1539
      QFile::remove(path)) {
1 ✔
1540
    return true;
1541
  }
1542
  qCWarning(lcQtPass) << "Could not remove" << path;
4 ✔
1543
  return false;
2 ✔
1544
}
1545

1546
} // namespace
1547

1548
auto Util::removeTree(const QString &dir) -> bool {
23 ✔
1549
  // A trailing separator makes lstat follow a link ("link/" is the target
1550
  // directory); the link itself is what this is about.
1551
  const QString path = QDir::cleanPath(dir);
23 ✔
1552
  const QFileInfo top(path);
23 ✔
1553
  if (isLink(top)) {
23 ✔
1554
    // rm -rf on a link removes the link.
1555
    return QFile::remove(path) || QDir().rmdir(path);
16 ✔
1556
  }
1557
  if (!top.isDir()) {
9 ✔
1558
    return false;
1559
  }
1560
  bool ok = true;
1561
  const QFileInfoList entries =
1562
      QDir(path).entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
16 ✔
1563
                                   QDir::System | QDir::NoDotAndDotDot,
1564
                               QDir::Name);
8 ✔
1565
  for (const QFileInfo &entry : entries) {
24 ✔
1566
    const bool removed = entry.isDir() && !isLink(entry)
22 ✔
1567
                             ? removeTree(entry.filePath())
18 ✔
1568
                             : removeEntry(entry);
14 ✔
1569
    ok = removed && ok;
16 ✔
1570
  }
1571
  return ok && QDir().rmdir(path);
13 ✔
1572
}
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