QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
util.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
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 <array>
28#include <cstring>
29#include <memory>
30#include <optional>
31#include <utility>
32#include <vector>
33
34#ifdef Q_OS_WIN
35#include <fcntl.h>
36#include <io.h>
37#include <windows.h>
38#else
39#include <cerrno>
40#include <cstdio>
41#include <dirent.h>
42#include <fcntl.h>
43#include <sys/stat.h>
44#include <sys/time.h>
45#include <unistd.h>
46#endif
47
48#include "qtpasslogging.h"
49
50QProcessEnvironment Util::_env;
51bool Util::_envInitialised = false;
52
53// macOS and Windows: append the usual GPG install directories to PATH.
55 if (!_envInitialised) {
56 _env = QProcessEnvironment::systemEnvironment();
57#ifdef __APPLE__
58 QString path = _env.value("PATH");
59 if (!path.contains("/usr/local/MacGPG2/bin") &&
60 QDir("/usr/local/MacGPG2/bin").exists())
61 path += ":/usr/local/MacGPG2/bin";
62 if (!path.contains("/usr/local/bin"))
63 path += ":/usr/local/bin";
64 _env.insert("PATH", path);
65#endif
66#ifdef Q_OS_WIN
67 QString path = _env.value("PATH");
68 if (!path.contains("C:\\Program Files\\WinGPG\\x86") &&
69 QDir("C:\\Program Files\\WinGPG\\x86").exists())
70 path += ";C:\\Program Files\\WinGPG\\x86";
71 if (!path.contains("C:\\Program Files\\GnuPG\\bin") &&
72 QDir("C:\\Program Files\\GnuPG\\bin").exists())
73 path += ";C:\\Program Files\\GnuPG\\bin";
74 _env.insert("PATH", path);
75#endif
76 qCDebug(lcQtPass) << _env.value("PATH");
77 _envInitialised = true;
78 }
79}
80
81auto Util::findPasswordStore() -> QString {
82 QString path;
84 if (_env.contains("PASSWORD_STORE_DIR")) {
85 path = Util::expandTilde(_env.value("PASSWORD_STORE_DIR"));
86 } else {
87#ifdef Q_OS_WIN
88 path = QDir(QDir::homePath()).filePath("password-store");
89#else
90 path = QDir(QDir::homePath()).filePath(".password-store");
91#endif
92 }
93 return Util::normalizeFolderPath(QDir::cleanPath(path));
94}
95
96auto Util::expandTilde(const QString &path) -> QString {
97 if (path == QLatin1String("~")) {
98 return QDir::homePath();
99 }
100 if (path.startsWith(QLatin1String("~/"))) {
101 return QDir::homePath() + path.mid(1);
102 }
103 return path;
104}
105
106auto Util::isAbsoluteFsPath(const QString &path) -> bool {
107 return QDir::isAbsolutePath(path) && !path.startsWith(QLatin1Char(':'));
108}
109
110auto Util::joinPath(const QString &dir, const QString &name) -> QString {
111 if (name.startsWith(QLatin1Char(':'))) {
112 return dir.endsWith(QLatin1Char('/')) ? dir + name
113 : dir + QLatin1Char('/') + name;
114 }
115 return QDir(dir).filePath(name);
116}
117
118auto Util::normalizeFolderPath(const QString &path) -> QString {
119 QString normalizedPath = path;
120 if (!normalizedPath.endsWith('/')) {
121 normalizedPath += '/';
122 }
123 return normalizedPath;
124}
125
127 // pass unsets these before it runs git: a GIT_DIR inherited from the
128 // environment (QtPass started from a git hook, or an IDE terminal) would
129 // send every commit and push to that repository instead of the store.
130 for (const char *variable :
131 {"GIT_DIR", "GIT_WORK_TREE", "GIT_NAMESPACE", "GIT_INDEX_FILE",
132 "GIT_INDEX_VERSION", "GIT_OBJECT_DIRECTORY", "GIT_COMMON_DIR",
133 // QtPass sets GIT_LITERAL_PATHSPECS for its git; git refuses a
134 // pathspec when one of these is set as well.
135 "GIT_GLOB_PATHSPECS", "GIT_NOGLOB_PATHSPECS", "GIT_ICASE_PATHSPECS"}) {
136 qunsetenv(variable);
137 }
139 passUmask(qEnvironmentVariable("PASSWORD_STORE_UMASK")));
140}
141
142auto Util::passUmask(const QString &value) -> int {
143 // Taken as it is, as bash's umask builtin (which pass hands it to) takes
144 // it: " 022" is no umask there either. pass then keeps the session's;
145 // QtPass falls back to 077.
146 // anchoredPattern(), not ^...$: $ also matches before a final newline.
147 static const QRegularExpression octal(
148 QRegularExpression::anchoredPattern(QStringLiteral("[0-7]{1,4}")));
149 if (!octal.match(value).hasMatch()) {
150 return 077;
151 }
152 return value.toInt(nullptr, 8);
153}
154
155auto Util::gitCeiling(const QString &store) -> QString {
156 if (store.isEmpty()) {
157 return {};
158 }
159 QString path = QFileInfo(store).canonicalFilePath();
160 if (path.isEmpty()) {
161 path = QDir::cleanPath(QDir(store).absolutePath());
162 }
163 return QFileInfo(path).absolutePath();
164}
165
166#ifndef Q_OS_WIN
167namespace {
178auto openFollowedRegularFile(const QString &path, QFile &file) -> bool {
179 const int fd = ::open(QFile::encodeName(path).constData(),
180 O_RDONLY | O_NONBLOCK | O_CLOEXEC);
181 if (fd < 0) {
182 return false;
183 }
184 struct stat info{};
185 if (::fstat(fd, &info) != 0 || !S_ISREG(info.st_mode) ||
186 !file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
187 ::close(fd);
188 return false;
189 }
190 return true;
191}
192
199auto gitWalkStart(const QString &store) -> QString {
200 // git walks up from the real folder, so the real path is the one to walk,
201 // and for a store that does not exist yet the one it will have: its
202 // nearest existing folder resolved, the rest appended. By the raw string:
203 // QDir and QFileInfo clean a path by name, and "link/.." is the parent
204 // of the link's target, not the folder the link is in. On macOS the
205 // temporary folder is under /var, a link to /private/var.
206 // Absolute as git means it, a leading "/" (Qt would take ":name" for a
207 // resource path).
208 QString path =
209 store.startsWith(u'/') ? store : QDir::currentPath() + u'/' + store;
210 while (path.size() > 1 && path.endsWith(u'/')) {
211 path.chop(1);
212 }
213 QString rest;
214 while (!QFileInfo::exists(path)) {
215 const qsizetype slash = path.lastIndexOf(u'/');
216 if (slash < 0) {
217 return {};
218 }
219 const QString name = path.mid(slash + 1);
220 rest = rest.isEmpty() ? name : name + u'/' + rest;
221 path = slash == 0 ? QStringLiteral("/") : path.left(slash);
222 }
223 const QString real = QFileInfo(path).canonicalFilePath();
224 const QString start = real.isEmpty() ? QDir::cleanPath(path) : real;
225 return rest.isEmpty() ? start : QDir::cleanPath(start + u'/' + rest);
226}
227
235auto passCeilingFor(const QString &store, const QString &start) -> QString {
236 // The pieces of pass's ceiling as git takes them (setup.c,
237 // canonicalize_ceiling_entry): relative ones are dropped, the rest
238 // resolved, one that cannot be resolved is dropped; after an empty piece
239 // ("::") they are kept exactly as written. A piece can still be a real
240 // ceiling: "/repo/:vault/.." holds "/repo/".
241 QString ceiling;
242 bool afterEmpty = false;
243 const QStringList pieces =
244 (store + QStringLiteral("/..")).split(QLatin1Char(':'));
245 for (const QString &piece : pieces) {
246 if (piece.isEmpty()) {
247 afterEmpty = true;
248 continue;
249 }
250 if (!piece.startsWith(u'/')) {
251 continue;
252 }
253 const QString entry =
254 afterEmpty ? piece : QFileInfo(piece).canonicalFilePath();
255 // git stops below the longest entry the store lies under
256 // (longest_ancestor_length: "/" is above everything).
257 const QString under = entry == u'/' ? entry : entry + u'/';
258 if (!entry.isEmpty() && start.startsWith(under) &&
259 entry.size() > ceiling.size()) {
260 ceiling = entry;
261 }
262 }
263 return ceiling;
264}
265
273auto isGitDirectory(const QString &candidate) -> bool {
274 const QDir dir(candidate);
275 if (!QFileInfo(dir.filePath(QStringLiteral("objects"))).isDir() ||
276 !QFileInfo(dir.filePath(QStringLiteral("refs"))).isDir()) {
277 return false;
278 }
279 // As git (setup.c, validate_headref()): a HEAD that is a link counts
280 // when the link text starts with "refs/", without reading what it
281 // names, and not otherwise. Anything else is read only when it is a
282 // regular file, without waiting: a HEAD that is a FIFO (a pushed commit
283 // can carry a link to one, or to a device) blocked the open and the
284 // read on the GUI thread when Settings opened.
285 const QString headPath = dir.filePath(QStringLiteral("HEAD"));
286 if (const QFileInfo headInfo(headPath); headInfo.isSymLink()) {
287 // The link text as stored (Qt 6.6), not the path it resolves to.
288 return headInfo.readSymLink().startsWith(QLatin1String("refs/"));
289 }
290 QFile head;
291 if (!openFollowedRegularFile(headPath, head)) {
292 return false;
293 }
294 static const QRegularExpression valid(
295 QStringLiteral("^(?:ref: refs/|[0-9a-f]{40}\\s*$|[0-9a-f]{64}\\s*$)"));
296 return valid.match(QString::fromUtf8(head.read(256))).hasMatch();
297}
298
300enum class Found {
301 Nothing,
302 Repository,
303 Refused
304};
305
314auto repositoryAt(const QString &dir) -> Found {
315 const QString dotGit = QDir(dir).filePath(QStringLiteral(".git"));
316 const QFileInfo info(dotGit);
317 if (info.isDir()) {
318 return isGitDirectory(dotGit) ? Found::Repository : Found::Nothing;
319 }
320 if (!info.exists()) {
321 return Found::Nothing;
322 }
323 // The same for a .git file (or a link to one): a FIFO there blocked in
324 // open().
325 QFile file;
326 if (!openFollowedRegularFile(dotGit, file)) {
327 return Found::Refused;
328 }
329 const QString line = QString::fromUtf8(file.readLine(4096)).trimmed();
330 if (!line.startsWith(QLatin1String("gitdir: "))) {
331 return Found::Refused;
332 }
333 const QString target = line.mid(8);
334 return isGitDirectory(target.startsWith(u'/') ? target
335 : QDir(dir).filePath(target))
336 ? Found::Repository
337 : Found::Refused;
338}
339} // namespace
340#endif
341
342auto Util::repositoryPassClimbsTo(const QString &store) -> QString {
343#ifdef Q_OS_WIN
344 Q_UNUSED(store);
345 return {};
346#else
347 if (!store.contains(QLatin1Char(':'))) {
348 return {};
349 }
350 const QString start = gitWalkStart(store);
351 if (start.isEmpty()) {
352 return {};
353 }
354 const QString ceiling = passCeilingFor(store, start);
355 // The store's own repository comes first; only without one does git look
356 // further up, and never into the ceiling. By name from here: the real
357 // path holds no link or "..".
358 for (QString dir = start;;) {
359 switch (repositoryAt(dir)) {
360 case Found::Repository:
361 return dir == start ? QString() : std::move(dir);
362 case Found::Refused:
363 return {};
364 case Found::Nothing:
365 break;
366 }
367 // A bare repository: git stops there, and pass, finding no work tree,
368 // commits nothing.
369 if (isGitDirectory(dir)) {
370 return {};
371 }
372 const QString up = QFileInfo(dir).absolutePath();
373 if (up == dir || up == ceiling) {
374 return {};
375 }
376 dir = up;
377 }
378#endif
379}
380
381namespace {
383std::optional<uint> s_gitOwnerForTests;
384} // namespace
385
386void Util::setGitOwnerForTests(std::optional<uint> user) {
387 s_gitOwnerForTests = user;
388}
389
391std::function<void(const QString &)> s_beforePlacingForTests;
392
393void Util::setBeforePlacingForTests(std::function<void(const QString &)> hook) {
394 s_beforePlacingForTests = std::move(hook);
395}
396
397#ifdef Q_OS_UNIX
398namespace {
405auto safeDirectoryEntries(const QString &git) -> std::optional<QString> {
406 // Outside any repository, as git reads its protected config: no
407 // repository's own config, and no includeIf "gitdir:" or "onbranch:"
408 // that matches (a GIT_DIR, even one that cannot exist, would be matched
409 // against them, and one that cannot exist makes git config fail). From
410 // "/", which a user cannot make a repository; a local scope is dropped
411 // by the caller in any case.
412 QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
413 env.remove(QStringLiteral("GIT_DIR"));
414 env.remove(QStringLiteral("GIT_WORK_TREE"));
415 env.remove(QStringLiteral("GIT_COMMON_DIR"));
416 // git config alone reads GIT_CONFIG in place of the system and global
417 // configuration (and reports it as "command"); the ownership check never
418 // reads it.
419 env.remove(QStringLiteral("GIT_CONFIG"));
420 QProcess process;
421 process.setProcessEnvironment(env);
422 process.setWorkingDirectory(QStringLiteral("/"));
423 // Bounded: Git calls wait for this, and a git that never answers trusts
424 // nothing.
425 constexpr int kQueryTimeoutMs = 5000;
426 QString out;
428 process, git.isEmpty() ? QStringLiteral("git") : git,
429 {QStringLiteral("config"), QStringLiteral("--show-scope"),
430 QStringLiteral("--type=path"), QStringLiteral("--get-all"),
431 QStringLiteral("safe.directory")},
432 QString(), &out, nullptr, nullptr, kQueryTimeoutMs) != 0) {
433 return std::nullopt;
434 }
435 return out;
436}
437
445auto safeDirectoryNames(const QString &value, const QString &root) -> bool {
446 if (!QDir::isAbsolutePath(value)) {
447 return false;
448 }
449 if (value.endsWith(QLatin1String("/*"))) {
450 const QString base = value.chopped(2);
451 QString prefix = QFileInfo(base.isEmpty() ? QStringLiteral("/") : base)
452 .canonicalFilePath();
453 if (prefix.isEmpty()) {
454 return false;
455 }
456 if (!prefix.endsWith(QLatin1Char('/'))) {
457 prefix += QLatin1Char('/');
458 }
459 return root.startsWith(prefix);
460 }
461 const QString named = QFileInfo(value).canonicalFilePath();
462 return !named.isEmpty() && named == root;
463}
464
481auto isSafeDirectory(const QString &root, const QString &git) -> bool {
482 const std::optional<QString> out = safeDirectoryEntries(git);
483 if (!out) {
484 return false;
485 }
486 bool safe = false;
487 const QStringList lines = out->split(QLatin1Char('\n'));
488 for (const QString &line : lines) {
489 const qsizetype tab = line.indexOf(QLatin1Char('\t'));
490 if (tab < 0) {
491 continue;
492 }
493 const QString scope = line.left(tab);
494 if (scope != QLatin1String("system") && scope != QLatin1String("global") &&
495 scope != QLatin1String("command")) {
496 continue;
497 }
498 const QString value = line.mid(tab + 1);
499 if (value.isEmpty()) {
500 safe = false;
501 } else {
502 safe = safe || value == QLatin1String("*") ||
503 safeDirectoryNames(value, root);
504 }
505 }
506 return safe;
507}
508} // namespace
509#endif
510
511void Util::requireExplicitBareRepository(QProcessEnvironment &env) {
512 const QString key = QStringLiteral("safe.bareRepository");
513 const QString value = QStringLiteral("explicit");
514 const QString countText = env.value(QStringLiteral("GIT_CONFIG_COUNT"));
515 bool ok = countText.isEmpty();
516 int count = countText.isEmpty() ? 0 : countText.toInt(&ok);
517 if (!ok || count < 0) {
518 // git refuses to start with a malformed count, so the entries it was
519 // meant to cover never applied: start the list afresh.
520 count = 0;
521 }
522 // Keys and these values are case-insensitive to git; the last entry wins.
523 QString last;
524 for (int i = 0; i < count; ++i) {
525 if (env.value(QStringLiteral("GIT_CONFIG_KEY_%1").arg(i))
526 .compare(key, Qt::CaseInsensitive) == 0) {
527 last = env.value(QStringLiteral("GIT_CONFIG_VALUE_%1").arg(i));
528 }
529 }
530 // git reads GIT_CONFIG_PARAMETERS (`git -c`) after the numbered entries,
531 // so when that names the key at all, explicit must be its last entry. Not
532 // parsed: the string must end in this separate token, which a value
533 // cannot fake (a quote inside one is written '\'', so it never follows a
534 // blank); appending once too often does no harm.
535 const QString parameters = env.value(QStringLiteral("GIT_CONFIG_PARAMETERS"));
536 const QString explicitEntry =
537 QStringLiteral("'safe.bareRepository=explicit'");
538 if (parameters.contains(QLatin1String("barerepository"),
539 Qt::CaseInsensitive) &&
540 parameters != explicitEntry &&
541 !parameters.endsWith(QLatin1Char(' ') + explicitEntry)) {
542 env.insert(QStringLiteral("GIT_CONFIG_PARAMETERS"),
543 parameters + QLatin1Char(' ') + explicitEntry);
544 }
545 if (last.compare(value, Qt::CaseInsensitive) == 0) {
546 return;
547 }
548 env.insert(QStringLiteral("GIT_CONFIG_KEY_%1").arg(count), key);
549 env.insert(QStringLiteral("GIT_CONFIG_VALUE_%1").arg(count), value);
550 env.insert(QStringLiteral("GIT_CONFIG_COUNT"), QString::number(count + 1));
551}
552
553auto Util::gitStoreVariables(const QString &store, const QString &git,
554 std::optional<uint> asUser)
555 -> QList<std::pair<QString, QString>> {
556 const QString ceiling = gitCeiling(store);
557 if (ceiling.isEmpty()) {
558 return {};
559 }
560 QList<std::pair<QString, QString>> vars{
561 {QStringLiteral("GIT_CEILING_DIRECTORIES"), ceiling}};
562#ifdef Q_OS_WIN
563 const QChar separator = QLatin1Char(';');
564#else
565 const QChar separator = QLatin1Char(':');
566#endif
567 // git splits the ceiling list on the separator: "/home/a:b" would be
568 // "/home/a" and "b", neither of them the parent, and git would climb.
569 if (ceiling.contains(separator)) {
570 QString root = QFileInfo(store).canonicalFilePath();
571 if (root.isEmpty()) {
572 root = QDir::cleanPath(QDir(store).absolutePath());
573 }
574 QString gitDir = QDir(root).filePath(QStringLiteral(".git"));
575#ifdef Q_OS_UNIX
576 // What discovery's ownership check would have looked at: the work tree,
577 // the .git, and the directory a gitfile names. Not the user's: no
578 // repository at all, under a path that cannot be created (its parent
579 // is a device), rather than another user's hooks run as this one.
580 const uint me = asUser.value_or(
581 s_gitOwnerForTests.value_or(static_cast<uint>(::geteuid())));
582 const auto ownedOrMissing = [me](const QString &path) {
583 const QFileInfo info(path);
584 return !info.exists() || info.ownerId() == me;
585 };
586 bool owned = ownedOrMissing(root) && ownedOrMissing(gitDir);
587 if (owned && QFileInfo(gitDir).isFile()) {
588 QFile gitFile(gitDir);
589 if (gitFile.open(QIODevice::ReadOnly)) {
590 const QString line =
591 QString::fromUtf8(gitFile.readLine(4096)).trimmed();
592 if (line.startsWith(QLatin1String("gitdir:"))) {
593 const QString target = line.mid(7).trimmed();
594 owned = ownedOrMissing(QDir(root).absoluteFilePath(target));
595 }
596 }
597 }
598 // Or trusted as git would trust it in place of ownership.
599 if (!owned && !isSafeDirectory(root, git)) {
600 gitDir = QStringLiteral("/dev/null/.git");
601 }
602#else
603 // Git for Windows runs the same ownership check during discovery, on
604 // SIDs, with its own rules for the Administrators group; this pin skips
605 // it there and does not repeat it (a known gap, #2089).
606 Q_UNUSED(git);
607 Q_UNUSED(asUser);
608#endif
609 vars.append({QStringLiteral("GIT_DIR"), gitDir});
610 vars.append({QStringLiteral("GIT_WORK_TREE"), root});
611 }
612 return vars;
613}
614
615auto Util::mkpathForStore(const QString &path) -> bool {
616 const QString clean = QDir::cleanPath(QDir(path).absolutePath());
617 if (QFileInfo(clean).isDir()) {
618 return true;
619 }
620 const QString parent = QFileInfo(clean).absolutePath();
621 if (parent != clean && !mkpathForStore(parent)) {
622 return false;
623 }
624#ifdef Q_OS_UNIX
625 // The store's umask, as git and gpg get it: a store shared with a group
626 // (PASSWORD_STORE_UMASK=007) gets group folders, the default owner-only.
627 const int umask = Executor::childUmask() >= 0 ? Executor::childUmask() : 077;
628 QFile::Permissions permissions;
629 const std::array<QFile::Permission, 9> bits = {
630 QFile::ReadOwner, QFile::WriteOwner, QFile::ExeOwner,
631 QFile::ReadGroup, QFile::WriteGroup, QFile::ExeGroup,
632 QFile::ReadOther, QFile::WriteOther, QFile::ExeOther};
633 for (int i = 0; i < 9; ++i) {
634 if ((umask & (0400 >> i)) == 0) {
635 permissions |= bits[i];
636 }
637 }
638 // mkdir() still takes QtPass's own umask off (a session's 022 would drop
639 // the group's write bit); set the mode exactly afterwards. That only ever
640 // widens it to what was asked, never past.
641 const bool made = QDir().mkdir(clean, permissions) &&
642 QFile::setPermissions(clean, permissions);
643#else
644 // Windows: permissions here would become an ACL of their own, replacing
645 // the inherited one; the folder takes its parent's, as before.
646 const bool made = QDir().mkdir(clean);
647#endif
648 return made || QFileInfo(clean).isDir();
649}
650
651auto Util::findBinaryInPath(const QString &binary) -> QString {
652 if (binary.isEmpty()) {
653 return {};
654 }
655
657
658 const QStringList dirs =
659 _env.value(QStringLiteral("PATH"))
660 .split(QDir::listSeparator(), Qt::SkipEmptyParts);
661 QString ret;
662 if (QDir::fromNativeSeparators(binary).contains(u'/')) {
663 // An explicit path is not a PATH search: an absolute path is checked
664 // as-is, a relative one is resolved against the PATH directories. The
665 // directory-list overload refuses such names, so handle them here.
666 if (QDir::isAbsolutePath(binary)) {
667 ret = QStandardPaths::findExecutable(binary);
668 } else if (!dirs.isEmpty()) {
669 ret = QStandardPaths::findExecutable(binary, dirs);
670 }
671 } else {
672 ret = findBinaryInPath(binary, dirs);
673 }
674#ifdef Q_OS_WIN
675 if (ret.isEmpty()) {
676 // Cache per-binary WSL lookup result — the wsl --version probe is a
677 // blocking subprocess that can run several times per session for
678 // missing binaries; once decided, the answer doesn't change at runtime.
679 static QHash<QString, QString> wslBinaryCache;
680 const bool hasWhitespace =
681 std::any_of(binary.cbegin(), binary.cend(),
682 [](const QChar ch) { return ch.isSpace(); });
683 if (!hasWhitespace) {
684 auto cached = wslBinaryCache.constFind(binary);
685 if (cached != wslBinaryCache.constEnd()) {
686 ret = cached.value();
687 } else {
688 QString wslCommand = QStringLiteral("wsl ") + binary;
689 qCDebug(lcQtPass)
690 << "Util::findBinaryInPath(): falling back to WSL for binary"
691 << binary;
692 QString out, err;
693 QString cachedResult;
694 if (Executor::executeBlocking(wslCommand, {"--version"}, &out, &err) ==
695 0 &&
696 !out.isEmpty() && err.isEmpty()) {
697 qCDebug(lcQtPass)
698 << "Util::findBinaryInPath(): using WSL binary" << wslCommand;
699 cachedResult = wslCommand;
700 }
701 wslBinaryCache.insert(binary, cachedResult);
702 ret = cachedResult;
703 }
704 }
705 }
706#endif
707
708 return ret;
709}
710
711// Bare names only: QStandardPaths::findExecutable() returns an absolute binary
712// without consulting searchPaths, and a relative one with ".." could escape
713// them.
714auto Util::findBinaryInPath(const QString &binary,
715 const QStringList &searchPaths) -> QString {
716 if (binary.isEmpty() || QDir::fromNativeSeparators(binary).contains(u'/')) {
717 return {};
718 }
719 QStringList dirs;
720 dirs.reserve(searchPaths.size());
721 for (const QString &dir : searchPaths) {
722 if (!dir.isEmpty()) {
723 dirs.append(dir);
724 }
725 }
726 if (dirs.isEmpty()) {
727 // QStandardPaths::findExecutable() treats an empty list as "use PATH".
728 return {};
729 }
730 return QStandardPaths::findExecutable(binary, dirs);
731}
732
733auto Util::configIsValid(const AppSettings &s) -> bool {
734 const QString configFilePath = QDir(s.passStore).filePath(".gpg-id");
735 if (!QFile(configFilePath).exists()) {
736 return false;
737 }
738
739 const QString executable = s.usePass ? s.passExecutable : s.gpgExecutable;
740
741 if (const auto wsl = Executor::parseWslCommand(executable)) {
742 // Probe WSL once per session — availability doesn't change at runtime
743 // and the executeBlocking call is a blocking subprocess.
744 static const bool wslAvailable = [&wsl]() {
745 QString out;
746 QString err;
747 return Executor::executeBlocking(wsl->launcher,
748 {QStringLiteral("--version")}, &out,
749 &err) == 0 &&
750 !out.isEmpty() && err.isEmpty();
751 }();
752 if (wslAvailable) {
753 return true;
754 }
755 }
756 return QFile(executable).exists();
757}
758
759auto Util::endsWithGpg() -> const QRegularExpression & {
760 static const QRegularExpression expr{R"(\.gpg$)"};
761 return expr;
762}
763
764// Stops at whitespace, quotes and brackets so a URL on its own line keeps no
765// line break. file:/// is excluded on purpose (local, not network); the test
766// relies on that.
767auto Util::protocolRegex() -> const QRegularExpression & {
768 static const QRegularExpression regex{
769 R"(((?:https?|ftp|ssh|sftp|ftps|webdav|webdavs)://[^"\s<>\)\‍]\‍[]+))"};
770 return regex;
771}
772
773namespace {
779auto endsUrlPart(QChar c) -> bool {
780 return c == QLatin1Char('/') || c == QLatin1Char('?') ||
781 c == QLatin1Char('#');
782}
783
789auto isAsciiLetter(QChar c) -> bool {
790 return (c >= QLatin1Char('a') && c <= QLatin1Char('z')) ||
791 (c >= QLatin1Char('A') && c <= QLatin1Char('Z'));
792}
793
800auto afterScheme(const QString &url) -> qsizetype {
801 qsizetype colon = -1;
802 for (qsizetype i = 0; i < url.size() && !endsUrlPart(url.at(i)); ++i) {
803 if (url.at(i) == QLatin1Char(':')) {
804 colon = i;
805 break;
806 }
807 }
808 bool scheme = colon > 0 && isAsciiLetter(url.at(0));
809 for (qsizetype i = 1; scheme && i < colon; ++i) {
810 const QChar c = url.at(i);
811 scheme =
812 isAsciiLetter(c) || (c >= QLatin1Char('0') && c <= QLatin1Char('9')) ||
813 c == QLatin1Char('+') || c == QLatin1Char('-') || c == QLatin1Char('.');
814 }
815 return scheme ? colon + 1 : 0;
816}
817
830auto authorityLength(const QString &url) -> qsizetype {
831 const qsizetype hier = afterScheme(url);
832 if (url.mid(hier, 2) != QLatin1String("//")) {
833 return -1;
834 }
835 qsizetype end = hier + 2;
836 while (end < url.size() && !endsUrlPart(url.at(end))) {
837 ++end;
838 }
839 return end - (hier + 2);
840}
841} // namespace
842
843auto Util::isLaunchableWebUrl(const QString &value) -> bool {
844 const QString trimmed = value.trimmed();
845 if (trimmed.isEmpty()) {
846 return false;
847 }
848 // Reject control characters first, before QUrl normalisation can hide a
849 // CR/LF/NUL injection into the OS URL handler.
850 for (const QChar &c : trimmed) {
851 if (c == QLatin1Char('\r') || c == QLatin1Char('\n') ||
852 c == QChar(QChar::Null)) {
853 return false;
854 }
855 }
856 // QUrl runs the host through Unicode normalisation, which takes time in
857 // the square of a run of combining marks out of canonical order: one line
858 // of an entry kept the window busy for minutes. A host has at most 253
859 // characters and a port six more, so a longer authority is no web
860 // address anyway.
861 constexpr qsizetype kMaxAuthority = 259;
862 if (authorityLength(trimmed) > kMaxAuthority) {
863 return false;
864 }
865 const QUrl url(trimmed, QUrl::StrictMode);
866 if (!url.isValid()) {
867 return false;
868 }
869 const QString scheme = url.scheme().toLower();
870 if (scheme != QLatin1String("http") && scheme != QLatin1String("https")) {
871 return false;
872 }
873 if (url.host().isEmpty()) {
874 return false;
875 }
876 // Embedded userinfo (user:pass@host) would leak into browser history.
877 if (!url.userName().isEmpty() || !url.password().isEmpty()) {
878 return false;
879 }
880 return true;
881}
882
883namespace {
891auto isDeceptiveChar(char16_t u) -> bool {
892 return (u < 0x20 && u != u'\t') || (u >= 0x7f && u <= 0x9f) || u == 0x2028 ||
893 u == 0x2029 || (u >= 0x202a && u <= 0x202e) ||
894 (u >= 0x2066 && u <= 0x2069);
895}
896} // namespace
897
898auto Util::displayable(const QString &text, bool lineBreaks) -> QString {
899 QString shown = text;
900 for (qsizetype i = 0; i < shown.size(); ++i) {
901 const char16_t u = shown.at(i).unicode();
902 // A carriage return before a line feed is a Windows line end (git or
903 // gpg output quoted in a message), not a character of its own.
904 const bool lineEnd =
905 lineBreaks && (u == u'\n' || (u == u'\r' && i + 1 < shown.size() &&
906 shown.at(i + 1) == u'\n'));
907 if (!lineEnd && isDeceptiveChar(u)) {
908 shown[i] = QChar(QChar::ReplacementCharacter);
909 }
910 }
911 return shown;
912}
913
914auto Util::linkifyUrls(const QString &text, bool *linked) -> QString {
915 if (linked != nullptr) {
916 *linked = false;
917 }
918 QString html;
919 html.reserve(text.size());
920 qsizetype lastIndex = 0;
921 QRegularExpressionMatchIterator it = protocolRegex().globalMatch(text);
922 while (it.hasNext()) {
923 const QRegularExpressionMatch match = it.next();
924 const QString url = match.captured(0);
925 // Only plain ASCII becomes a link: the link text is the URL as stored,
926 // and a right-to-left letter, a bidi control or a look-alike host in it
927 // makes it read as another address than the one it opens. Such a URL
928 // stays plain text; the open button still takes it.
929 const bool plain = std::all_of(url.cbegin(), url.cend(), [](QChar c) {
930 return c.unicode() > 0x20 && c.unicode() < 0x7f;
931 });
932 if (!plain || !isLaunchableWebUrl(url)) {
933 // Not a web URL (or it carries credentials): leave it in the escaped
934 // plain-text run instead of making it clickable.
935 continue;
936 }
937 const qsizetype start = match.capturedStart(0);
938 html += text.mid(lastIndex, start - lastIndex).toHtmlEscaped();
939 const QString escapedUrl = url.toHtmlEscaped();
940 html += QStringLiteral("<a href=\"%1\">%1</a>").arg(escapedUrl);
941 lastIndex = match.capturedEnd(0);
942 if (linked != nullptr) {
943 *linked = true;
944 }
945 }
946 html += text.mid(lastIndex).toHtmlEscaped();
947 // With a link in it, no bidi embedding, override or isolate control is
948 // drawn: an override earlier in the entry (U+202E) drew the link text
949 // reversed, so it read as another address. Shown as U+FFFD, so the user
950 // sees that something was there; the copy button still copies the value.
951 if (linked != nullptr ? *linked : html.contains(QLatin1String("<a href="))) {
952 for (QChar &c : html) {
953 const char16_t u = c.unicode();
954 if ((u >= 0x202A && u <= 0x202E) || (u >= 0x2066 && u <= 0x2069)) {
955 c = QChar(QChar::ReplacementCharacter);
956 }
957 }
958 }
959 return html;
960}
961
962auto Util::isOtherBlockBreak(QChar c) -> bool {
963 const char16_t u = c.unicode();
964 return u == u'\r' || u == 0x2029 || u == 0xFDD0 || u == 0xFDD1;
965}
966
967auto Util::withoutOtherBlockBreaks(QString text) -> QString {
968 for (QChar &c : text) {
969 if (isOtherBlockBreak(c)) {
970 c = QLatin1Char(' ');
971 }
972 }
973 return text;
974}
975
976auto Util::hasLongUnbrokenRun(QStringView text) -> bool {
977 qsizetype run = 0;
978 for (const QChar c : text) {
979 // A no-break space (U+00A0, U+2007, U+202F) is white space to
980 // isSpace(), but Qt does not wrap at it.
981 const char16_t u = c.unicode();
982 const bool breaks =
983 c.isSpace() && u != 0x00A0 && u != 0x2007 && u != 0x202F;
984 run = breaks ? 0 : run + 1;
985 if (run > kMaxUnbrokenRun) {
986 return true;
987 }
988 }
989 return false;
990}
991
992auto Util::plainToolTip(const QString &text) -> QString {
993 // Escaped, with its white space kept: two names that differ only in it
994 // must not read the same; a long run is cut as everywhere it is kept.
995 return QStringLiteral("<p style=\"white-space: pre-wrap;\">") +
996 boundSpaceRuns(displayable(text, false)).toHtmlEscaped() +
997 QStringLiteral("</p>");
998}
999
1000auto Util::shownName(const QString &name, qsizetype max) -> QString {
1001 QString line = displayable(name, false);
1002 line.replace(QLatin1Char('\t'), QLatin1Char(' '));
1003 if (line.size() <= max) {
1004 return line;
1005 }
1006 // Too short for an ellipsis between two ends: the head alone.
1007 if (max < 3) {
1008 qsizetype keep = std::max<qsizetype>(max, 0);
1009 if (keep > 0 && line.at(keep - 1).isHighSurrogate()) {
1010 --keep;
1011 }
1012 return line.left(keep);
1013 }
1014 qsizetype head = max / 3;
1015 if (line.at(head - 1).isHighSurrogate()) {
1016 --head;
1017 }
1018 qsizetype tail = max - max / 3 - 1;
1019 if (line.at(line.size() - tail).isLowSurrogate()) {
1020 --tail;
1021 }
1022 return line.left(head) + QChar(0x2026) + line.right(tail);
1023}
1024
1025// One pass, no regex: a pattern such as \s{1001,} retries from every
1026// character of a shorter run, which is quadratic on an entry made of them.
1027// A tab or a line feed ends a run in Qt's layout as well, so it ends one
1028// here; \v and U+0085 do not, so they count.
1029auto Util::boundSpaceRuns(const QString &text) -> QString {
1030 QString bounded;
1031 // Text before this index is in bounded already, or dropped.
1032 qsizetype from = 0;
1033 qsizetype run = 0;
1034 for (qsizetype i = 0; i < text.size(); ++i) {
1035 const QChar ch = text.at(i);
1036 if (!ch.isSpace() || ch == QLatin1Char('\t') || ch == QLatin1Char('\n')) {
1037 run = 0;
1038 continue;
1039 }
1040 if (++run <= kMaxSpaceRun) {
1041 continue;
1042 }
1043 if (run == kMaxSpaceRun + 1) {
1044 bounded += QStringView(text).sliced(from, i - from);
1045 }
1046 from = i + 1;
1047 }
1048 if (from == 0) {
1049 return text;
1050 }
1051 bounded += QStringView(text).sliced(from);
1052 return bounded;
1053}
1054
1055auto Util::newLinesRegex() -> const QRegularExpression & {
1056 static const QRegularExpression regex{"[\r\n]"};
1057 return regex;
1058}
1059
1060// No content heuristics: a line rejected here is erased the next time .gpg-id
1061// is rewritten. A leading `-` is refused because the recipients also go
1062// positionally to `gpg --list-keys`, where it would parse as an option.
1063auto Util::isValidKeyId(const QString &keyId) -> bool {
1064 return !keyId.isEmpty() && !keyId.startsWith('-');
1065}
1066
1067namespace {
1076auto canList(const QString &dir) -> bool {
1077#ifdef Q_OS_WIN
1078 // Qt answers from the attributes alone unless told to read the ACL.
1079 QNtfsPermissionCheckGuard aclCheck;
1080 return QFileInfo(dir).isReadable();
1081#else
1082 const QFileInfo info(dir);
1083 return info.isReadable() && info.isExecutable() &&
1085#endif
1086}
1087
1095template <typename Visit>
1096void walkStore(const QString &dir, Visit visit,
1097 QStringList *unlisted = nullptr) {
1098 // Absolute, so the results are whatever the caller's cwd; not canonical,
1099 // so a linked root keeps the name it was configured under.
1100 QStringList pending{QDir(QDir::cleanPath(dir)).absolutePath()};
1101 while (!pending.isEmpty()) {
1102 const QDir current(pending.takeLast());
1103 if (unlisted != nullptr && current.exists() && !canList(current.path())) {
1104 qCWarning(lcQtPass) << "Cannot list" << current.path();
1105 *unlisted << current.path();
1106 continue;
1107 }
1108 // Every entry once, links and hidden entries included, so the decision
1109 // what to do with each is taken here, before any recursion. QDir::System
1110 // keeps dangling links in the listing.
1111 const QFileInfoList entries =
1112 current.entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
1113 QDir::System | QDir::NoDotAndDotDot,
1114 QDir::Name);
1115 QStringList subdirs;
1116 for (const QFileInfo &entry : entries) {
1117 if (visit(entry)) {
1118 subdirs << entry.filePath();
1119 }
1120 }
1121 // Pushed last-to-first so the next one taken is the first by name.
1122 for (auto it = subdirs.crbegin(); it != subdirs.crend(); ++it) {
1123 pending << *it;
1124 }
1125 }
1126}
1127
1129auto isLink(const QFileInfo &entry) -> bool {
1130 return entry.isSymLink() || entry.isJunction();
1131}
1132
1138auto isHiddenEntry(const QFileInfo &entry) -> bool {
1139 return entry.isHidden() || entry.fileName().startsWith(QLatin1Char('.'));
1140}
1141
1144auto isStoreDirectory(const QFileInfo &entry) -> bool {
1145 return !isLink(entry) && entry.isDir() && !isHiddenEntry(entry);
1146}
1147} // namespace
1148
1149auto Util::regularFilesUnder(const QString &dir, const QStringList &nameFilters,
1150 QStringList *skipped, bool hiddenFiles,
1151 QStringList *unlisted) -> QStringList {
1152 QStringList files;
1153 walkStore(
1154 dir,
1155 [&](const QFileInfo &entry) {
1156 if (isStoreDirectory(entry)) {
1157 return true;
1158 }
1159 const bool named = QDir::match(nameFilters, entry.fileName());
1160 if (isLink(entry) || (!entry.isDir() && !entry.isFile())) {
1161 // A linked directory hides everything behind it; a linked file, or a
1162 // FIFO, socket or device, is only of interest under a name the caller
1163 // asked for.
1164 if (skipped != nullptr && (entry.isDir() || named)) {
1165 qCWarning(lcQtPass) << "Skipping" << entry.filePath()
1166 << ": not a regular file or directory";
1167 *skipped << entry.filePath();
1168 }
1169 return false;
1170 }
1171 if (entry.isFile() && named && (hiddenFiles || !isHiddenEntry(entry))) {
1172 files << entry.filePath();
1173 }
1174 return false;
1175 },
1176 unlisted);
1177 return files;
1178}
1179
1180auto Util::directoriesUnder(const QString &dir) -> QStringList {
1181 QStringList dirs;
1182 walkStore(dir, [&](const QFileInfo &entry) {
1183 if (!isStoreDirectory(entry)) {
1184 return false;
1185 }
1186 dirs << entry.filePath();
1187 return true;
1188 });
1189 return dirs;
1190}
1191
1192auto Util::hasUnreadableName(const QString &dir) -> bool {
1193#ifdef Q_OS_WIN
1194 Q_UNUSED(dir);
1195 return false;
1196#else
1197 // The names as bytes, as readdir() gives them; Qt's own listing has
1198 // already dropped the ones this is looking for.
1199 DIR *listing = ::opendir(QFile::encodeName(dir).constData());
1200 if (listing == nullptr) {
1201 return false;
1202 }
1203 const auto close = qScopeGuard([listing] { ::closedir(listing); });
1204 while (const dirent *entry = ::readdir(listing)) {
1205 if (!QByteArrayView(entry->d_name).isValidUtf8()) {
1206 return true;
1207 }
1208 }
1209 return false;
1210#endif
1211}
1212
1213auto Util::isLinkedFolder(const QString &path) -> bool {
1214 return isLink(QFileInfo(QDir::cleanPath(path)));
1215}
1216
1217auto Util::isUnderLink(const QString &path, const QString &storeRoot,
1218 bool includeSelf) -> bool {
1219 // "C:/Store" and "c:/store" are one directory on Windows; a path spelled
1220 // the other way must not skip the walk (as in Pass::getGpgIdPath).
1221#ifdef Q_OS_WIN
1222 constexpr auto cs = Qt::CaseInsensitive;
1223#else
1224 constexpr auto cs = Qt::CaseSensitive;
1225#endif
1226 const QString root = QDir::cleanPath(storeRoot);
1227 // A root of "/" or "C:/" already ends in the separator.
1228 const QString prefix =
1229 root.endsWith(QLatin1Char('/')) ? root : root + QLatin1Char('/');
1230 const auto isRoot = [&](const QString &p) {
1231 return p.compare(root, cs) == 0;
1232 };
1233 QString current = QDir::cleanPath(path);
1234 if (!current.startsWith(prefix, cs)) {
1235 // Not under the store as named: only the entry itself can be judged.
1236 return includeSelf && !isRoot(current) && isLinkedFolder(current);
1237 }
1238 if (!includeSelf) {
1239 current = QFileInfo(current).path();
1240 }
1241 for (; !isRoot(current) && current.startsWith(prefix, cs);
1242 current = QFileInfo(current).path()) {
1243 if (isLinkedFolder(current)) {
1244 return true;
1245 }
1246 }
1247 return false;
1248}
1249
1250#ifndef Q_OS_WIN
1251namespace {
1252
1255auto hasNoHardLinks(int error) -> bool {
1256 return error == EPERM || error == ENOTSUP || error == EOPNOTSUPP ||
1257 error == ENOSYS;
1258}
1259
1262auto renameExclusive(const QByteArray &source, const QByteArray &target)
1263 -> std::optional<bool> {
1264#if defined(__GLIBC__) && \
1265 (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 28))
1266 if (::renameat2(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(),
1267 RENAME_NOREPLACE) == 0) {
1268 return true;
1269 }
1270 if (errno == EINVAL || errno == ENOSYS || hasNoHardLinks(errno)) {
1271 return std::nullopt;
1272 }
1273 return false;
1274#elif defined(Q_OS_MACOS)
1275 if (::renamex_np(source.constData(), target.constData(), RENAME_EXCL) == 0) {
1276 return true;
1277 }
1278 if (errno == EINVAL || errno == ENOTSUP) {
1279 return std::nullopt;
1280 }
1281 return false;
1282#else
1283 Q_UNUSED(source);
1284 Q_UNUSED(target);
1285 return std::nullopt;
1286#endif
1287}
1288
1298auto placeWithoutReplacing(const QByteArray &source, const QByteArray &target)
1299 -> bool {
1300 // linkat() without AT_SYMLINK_FOLLOW follows nothing; link() would, on
1301 // macOS and the BSDs, hard-link whatever a symlink planted under the
1302 // source's name points at.
1303 if (::linkat(AT_FDCWD, source.constData(), AT_FDCWD, target.constData(), 0) ==
1304 0) {
1305 if (::unlink(source.constData()) == 0) {
1306 return true;
1307 }
1308 // Both names now hold the file. Take the new one away again so the
1309 // caller sees the state it started from, not a success with the source
1310 // still there.
1311 const int err = errno;
1312 ::unlink(target.constData());
1313 errno = err;
1314 return false;
1315 }
1316 if (!hasNoHardLinks(errno)) {
1317 return false;
1318 }
1319 if (const std::optional<bool> renamed = renameExclusive(source, target)) {
1320 return *renamed;
1321 }
1322 struct stat st{};
1323 if (::lstat(target.constData(), &st) == 0 || errno != ENOENT) {
1324 errno = EEXIST;
1325 return false;
1326 }
1327 return ::rename(source.constData(), target.constData()) == 0;
1328}
1329
1330} // namespace
1331#endif
1332
1333auto Util::replaceFile(const QString &from, const QString &to, bool replace)
1334 -> bool {
1335#ifdef Q_OS_WIN
1336 const std::wstring source =
1337 QDir::toNativeSeparators(QFileInfo(from).absoluteFilePath())
1338 .toStdWString();
1339 const std::wstring target =
1340 QDir::toNativeSeparators(QFileInfo(to).absoluteFilePath()).toStdWString();
1341 // WRITE_THROUGH: the new entry is on the device when this returns.
1342 return MoveFileExW(source.c_str(), target.c_str(),
1343 (replace ? MOVEFILE_REPLACE_EXISTING : 0) |
1344 MOVEFILE_WRITE_THROUGH) != 0;
1345#else
1346 const QByteArray source = QFile::encodeName(from);
1347 const QByteArray target = QFile::encodeName(to);
1348 if (replace) {
1349 if (::rename(source.constData(), target.constData()) != 0) {
1350 return false;
1351 }
1352 } else {
1353 if (!placeWithoutReplacing(source, target)) {
1354 return false;
1355 }
1356 }
1357 // Sync the directory entry so a crash does not lose the new name. Best
1358 // effort: the bytes are already synced, and some network filesystems
1359 // cannot sync a directory.
1360 const int dir = ::open(QFile::encodeName(QFileInfo(to).path()).constData(),
1361 O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1362 if (dir >= 0) {
1363 int rc;
1364 do {
1365 rc = ::fsync(dir);
1366 } while (rc != 0 && errno == EINTR);
1367 ::close(dir);
1368 }
1369 return true;
1370#endif
1371}
1372
1373namespace {
1374#ifdef Q_OS_WIN
1381auto diskFileAttributes(HANDLE handle) -> std::optional<DWORD> {
1382 BY_HANDLE_FILE_INFORMATION info{};
1383 if (!GetFileInformationByHandle(handle, &info) ||
1384 (info.dwFileAttributes &
1385 (FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_DEVICE)) != 0 ||
1386 GetFileType(handle) != FILE_TYPE_DISK) {
1387 return std::nullopt;
1388 }
1389 return info.dwFileAttributes;
1390}
1391
1405auto openThroughReparsePoint(HANDLE handle, const std::wstring &native)
1406 -> HANDLE {
1407 FILE_ATTRIBUTE_TAG_INFO tag{};
1408 if (!GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &tag,
1409 sizeof(tag)) ||
1410 IsReparseTagNameSurrogate(tag.ReparseTag)) {
1411 return INVALID_HANDLE_VALUE;
1412 }
1413 HANDLE through =
1414 CreateFileW(native.c_str(), GENERIC_READ,
1415 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,
1416 nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
1417 if (through == INVALID_HANDLE_VALUE) {
1418 return INVALID_HANDLE_VALUE;
1419 }
1420 // The 128-bit file ID: the 64-bit index in BY_HANDLE_FILE_INFORMATION
1421 // is not unique on ReFS.
1422 FILE_ID_INFO firstId{};
1423 FILE_ID_INFO throughId{};
1424 const bool same =
1425 GetFileInformationByHandleEx(handle, FileIdInfo, &firstId,
1426 sizeof(firstId)) &&
1427 GetFileInformationByHandleEx(through, FileIdInfo, &throughId,
1428 sizeof(throughId)) &&
1429 firstId.VolumeSerialNumber == throughId.VolumeSerialNumber &&
1430 std::memcmp(&firstId.FileId, &throughId.FileId, sizeof(firstId.FileId)) ==
1431 0 &&
1432 diskFileAttributes(through).has_value();
1433 if (!same) {
1434 CloseHandle(through);
1435 return INVALID_HANDLE_VALUE;
1436 }
1437 return through;
1438}
1439
1446auto openRegularFileNative(const QString &path, QFile &file) -> bool {
1447 // FILE_FLAG_OPEN_REPARSE_POINT opens a symbolic link or junction itself
1448 // rather than its target, so the handle's attributes say what the name
1449 // was at the moment of the open.
1450 const std::wstring native =
1451 QDir::toNativeSeparators(QFileInfo(path).absoluteFilePath())
1452 .toStdWString();
1453 HANDLE handle = CreateFileW(
1454 native.c_str(), GENERIC_READ,
1455 FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, nullptr,
1456 OPEN_EXISTING, FILE_FLAG_OPEN_REPARSE_POINT, nullptr);
1457 if (handle == INVALID_HANDLE_VALUE) {
1458 return false;
1459 }
1460 const std::optional<DWORD> attributes = diskFileAttributes(handle);
1461 if (!attributes) {
1462 CloseHandle(handle);
1463 return false;
1464 }
1465 if ((*attributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0) {
1466 const HANDLE through = openThroughReparsePoint(handle, native);
1467 CloseHandle(handle);
1468 if (through == INVALID_HANDLE_VALUE) {
1469 return false;
1470 }
1471 handle = through;
1472 }
1473 const int fd = _open_osfhandle(reinterpret_cast<intptr_t>(handle),
1474 _O_RDONLY | _O_BINARY);
1475 if (fd < 0) {
1476 CloseHandle(handle);
1477 return false;
1478 }
1479 if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
1480 _close(fd);
1481 return false;
1482 }
1483 return true;
1484}
1485#else
1493auto adoptRegularFd(int fd, QFile &file) -> bool {
1494 struct stat st{};
1495 if (::fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) {
1496 ::close(fd);
1497 return false;
1498 }
1499 // The descriptor, not the name, is what QFile opens here: the object
1500 // fstat() judged is the object read, so a name swapped between the check
1501 // and the read cannot make it read another file (the file's contents can
1502 // still change; the check is on what kind of file it is). CodeQL's
1503 // check-then-use pattern matcher sees an open after a check and cannot
1504 // tell (its alert on this line is dismissed as a false positive; inline
1505 // suppression comments are not read by the default setup).
1506 if (!file.open(fd, QIODevice::ReadOnly, QFileDevice::AutoCloseHandle)) {
1507 ::close(fd);
1508 return false;
1509 }
1510 return true;
1511}
1512
1519auto openRegularFileNative(const QString &path, QFile &file) -> bool {
1520 // O_NOFOLLOW fails with ELOOP on a symbolic link; O_NONBLOCK keeps a FIFO
1521 // from blocking the open until fstat() can refuse it.
1522 const int fd = ::open(QFile::encodeName(path).constData(),
1523 O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
1524 return fd >= 0 && adoptRegularFd(fd, file);
1525}
1526#endif
1527} // namespace
1528
1529auto Util::openRegularFile(const QString &path, QFile &file) -> bool {
1530 return openRegularFileNative(path, file);
1531}
1532
1533namespace {
1540auto readOpenFile(QFile &file, qint64 maxBytes) -> std::optional<QByteArray> {
1541 // A regular file's size is reliable, also when sparse: refuse a large one
1542 // before reading anything. One byte past the limit still guards a file
1543 // that grows meanwhile.
1544 if (file.size() > maxBytes) {
1545 return std::nullopt;
1546 }
1547 QByteArray bytes = file.read(maxBytes + 1);
1548 if (bytes.size() > maxBytes || file.error() != QFileDevice::NoError) {
1549 return std::nullopt;
1550 }
1551 return bytes;
1552}
1553} // namespace
1554
1555auto Util::readRegularFile(const QString &path, qint64 maxBytes)
1556 -> std::optional<QByteArray> {
1557 QFile file;
1558 if (!openRegularFile(path, file)) {
1559 return std::nullopt;
1560 }
1561 return readOpenFile(file, maxBytes);
1562}
1563
1564auto Util::readRegularFileInStore(const QString &store, const QString &path,
1565 qint64 maxBytes)
1566 -> std::optional<QByteArray> {
1567 const auto under = [&path](const QString &root) {
1568 const QString relative = QDir(root).relativeFilePath(QDir::cleanPath(path));
1569 return !root.isEmpty() && !isAbsoluteFsPath(relative) &&
1570 relative != QStringLiteral("..") &&
1571 !relative.startsWith(QStringLiteral("../"));
1572 };
1573 const QString root = QDir::cleanPath(store);
1574 if (under(root)) {
1575 return readRegularFileUnder(root, path, maxBytes);
1576 }
1577 const QString canonical = QFileInfo(root).canonicalFilePath();
1578 if (under(canonical)) {
1579 return readRegularFileUnder(canonical, path, maxBytes);
1580 }
1581 return std::nullopt;
1582}
1583
1584namespace {
1585#ifdef Q_OS_WIN
1599auto holdFolder(const QString &folder, bool isRoot) -> HANDLE {
1600 const std::wstring native = QDir::toNativeSeparators(folder).toStdWString();
1601 // GENERIC_READ (listing the folder) is data access, so the share mode
1602 // is enforced against a later open for DELETE; attribute access alone
1603 // would not be.
1604 HANDLE handle = CreateFileW(
1605 native.c_str(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
1606 OPEN_EXISTING,
1607 FILE_FLAG_BACKUP_SEMANTICS | (isRoot ? 0 : FILE_FLAG_OPEN_REPARSE_POINT),
1608 nullptr);
1609 if (handle == INVALID_HANDLE_VALUE) {
1610 return INVALID_HANDLE_VALUE;
1611 }
1612 FILE_ATTRIBUTE_TAG_INFO info{};
1613 if (!GetFileInformationByHandleEx(handle, FileAttributeTagInfo, &info,
1614 sizeof(info)) ||
1615 (info.FileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) {
1616 CloseHandle(handle);
1617 return INVALID_HANDLE_VALUE;
1618 }
1619 const bool link = (info.FileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0 &&
1620 IsReparseTagNameSurrogate(info.ReparseTag);
1621 if (!isRoot && link) {
1622 CloseHandle(handle);
1623 return INVALID_HANDLE_VALUE;
1624 }
1625 return handle;
1626}
1627
1636auto readUnderNative(const QString &cleanRoot, const QStringList &parts,
1637 const QString &path, qint64 maxBytes)
1638 -> std::optional<QByteArray> {
1639 // No openat() here: each folder from the root down is opened by name and
1640 // held open, without FILE_SHARE_DELETE, until the file is read. A folder
1641 // held that way cannot be renamed, removed or replaced by a junction
1642 // meanwhile, so the file is opened through exactly the folders judged.
1643 // The root itself is followed (a linked store is the user's setup).
1644 std::vector<HANDLE> held;
1645 const auto release = qScopeGuard([&held] {
1646 for (HANDLE handle : held) {
1647 CloseHandle(handle);
1648 }
1649 });
1650 QString folder = cleanRoot;
1651 for (qsizetype i = 0; i < parts.size(); ++i) {
1652 const bool isRoot = i == 0;
1653 if (!isRoot) {
1654 folder += QLatin1Char('/') + parts.at(i - 1);
1655 }
1656 const HANDLE handle = holdFolder(folder, isRoot);
1657 if (handle == INVALID_HANDLE_VALUE) {
1658 return std::nullopt;
1659 }
1660 held.push_back(handle);
1661 }
1662 // openRegularFile() refuses a link or junction as the file itself, and
1663 // reads any other reparse point (a cloud placeholder) through.
1664 return Util::readRegularFile(path, maxBytes);
1665}
1666#else
1675auto readUnderNative(const QString &cleanRoot, const QStringList &parts,
1676 const QString &path, qint64 maxBytes)
1677 -> std::optional<QByteArray> {
1678 Q_UNUSED(path)
1679 // The root by name, followed if it is a link (the user's setup); below it
1680 // nothing is.
1681 int dir = ::open(QFile::encodeName(cleanRoot).constData(),
1682 O_RDONLY | O_DIRECTORY | O_CLOEXEC);
1683 if (dir < 0) {
1684 return std::nullopt;
1685 }
1686 for (qsizetype i = 0; i + 1 < parts.size(); ++i) {
1687 const int next = ::openat(dir, QFile::encodeName(parts.at(i)).constData(),
1688 O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC);
1689 ::close(dir);
1690 if (next < 0) {
1691 return std::nullopt;
1692 }
1693 dir = next;
1694 }
1695 // As openRegularFile(): no link, no FIFO left blocking the open.
1696 const int fd = ::openat(dir, QFile::encodeName(parts.constLast()).constData(),
1697 O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC);
1698 ::close(dir);
1699 QFile file;
1700 if (fd < 0 || !adoptRegularFd(fd, file)) {
1701 return std::nullopt;
1702 }
1703 return readOpenFile(file, maxBytes);
1704}
1705#endif
1706} // namespace
1707
1708auto Util::readRegularFileUnder(const QString &root, const QString &path,
1709 qint64 maxBytes) -> std::optional<QByteArray> {
1710 const QString cleanRoot = QDir::cleanPath(root);
1711 const QString relative =
1712 QDir(cleanRoot).relativeFilePath(QDir::cleanPath(path));
1713 const QStringList parts = relative.split(QLatin1Char('/'));
1714 if (relative.isEmpty() || isAbsoluteFsPath(relative) ||
1715 parts.contains(QStringLiteral("..")) ||
1716 parts.contains(QStringLiteral(".")) || parts.contains(QString())) {
1717 return std::nullopt;
1718 }
1719 return readUnderNative(cleanRoot, parts, path, maxBytes);
1720}
1721
1722auto Util::syncToDisk(QFileDevice &file) -> bool {
1723 if (!file.flush()) {
1724 return false;
1725 }
1726#ifdef Q_OS_WIN
1727 const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1728 return handle != INVALID_HANDLE_VALUE && FlushFileBuffers(handle) != 0;
1729#else
1730 return ::fsync(file.handle()) == 0;
1731#endif
1732}
1733
1734namespace {
1735
1740struct FileIdentity {
1741 quint64 volume = 0;
1742 quint64 index = 0;
1743 bool known = false;
1744};
1745
1746auto operator==(const FileIdentity &a, const FileIdentity &b) -> bool {
1747 return a.known && b.known && a.volume == b.volume && a.index == b.index;
1748}
1749
1751auto identityOf(const QFileDevice &file) -> FileIdentity {
1752#ifdef Q_OS_WIN
1753 const HANDLE handle = reinterpret_cast<HANDLE>(_get_osfhandle(file.handle()));
1754 BY_HANDLE_FILE_INFORMATION info;
1755 if (handle == INVALID_HANDLE_VALUE ||
1756 GetFileInformationByHandle(handle, &info) == 0) {
1757 return {};
1758 }
1759 // On FAT/exFAT the file ID is the directory entry's offset, which a rename
1760 // can move. They have no hard links either (the swap this catches needs
1761 // one), so the identity is left unknown there.
1762 DWORD flags = 0;
1763 if (GetVolumeInformationByHandleW(handle, nullptr, 0, nullptr, nullptr,
1764 &flags, nullptr, 0) == 0 ||
1765 (flags & FILE_SUPPORTS_HARD_LINKS) == 0) {
1766 return {};
1767 }
1768 return {info.dwVolumeSerialNumber,
1769 (static_cast<quint64>(info.nFileIndexHigh) << 32) |
1770 info.nFileIndexLow,
1771 true};
1772#else
1773 struct stat st{};
1774 if (::fstat(file.handle(), &st) != 0) {
1775 return {};
1776 }
1777 return {static_cast<quint64>(st.st_dev), static_cast<quint64>(st.st_ino),
1778 true};
1779#endif
1780}
1781
1783auto fail(QString *error, const QString &text) -> bool {
1784 if (error != nullptr) {
1785 *error = text;
1786 }
1787 return false;
1788}
1789
1791struct Staged {
1792 QString path;
1793 FileIdentity identity;
1796 std::shared_ptr<void> pin;
1797};
1798
1805auto stageNextTo(const QString &path, const Util::Filler &fill, QString *why)
1806 -> std::optional<Staged> {
1807 Staged staged;
1808 {
1809 QTemporaryFile file(QFileInfo(path).path() +
1810 QStringLiteral("/.qtpass-XXXXXX.tmp"));
1811 file.setAutoRemove(false);
1812 if (!file.open()) {
1813 *why = QCoreApplication::translate(
1814 "Util", "Cannot create a temporary file next to %1: %2")
1815 .arg(path, file.errorString());
1816 return std::nullopt;
1817 }
1818 staged.path = file.fileName();
1819 // Owner-only: a .gpg-id names the keys a store is encrypted to, an
1820 // entry is an entry. QTemporaryFile creates 0600 already; say so for
1821 // platforms where it may not.
1822 file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
1823 *why = fill(file);
1824 if (why->isEmpty() && !Util::syncToDisk(file)) {
1825 *why = QCoreApplication::translate("Util", "Cannot write %1: %2")
1826 .arg(path, file.errorString());
1827 }
1828 staged.identity = identityOf(file);
1829#ifndef Q_OS_WIN
1830 // Closed and unlinked by a co-writer before the rename, the temporary's
1831 // inode number would be free, and ext4 hands it to the next file made:
1832 // the very file swapped in would then pass the check below. Windows
1833 // cannot rename an open file, and NTFS does not reuse a file index so.
1834 if (const int fd = ::dup(file.handle()); fd >= 0) {
1835 staged.pin =
1836 std::shared_ptr<void>(nullptr, [fd](void *) { ::close(fd); });
1837 }
1838#endif
1839 }
1840 if (!why->isEmpty()) {
1841 QFile::remove(staged.path);
1842 return std::nullopt;
1843 }
1844 return staged;
1845}
1846
1848auto placementError(const QString &path, bool replace) -> QString {
1849 if (replace) {
1850 return QCoreApplication::translate("Util", "Failed to replace %1.")
1851 .arg(path);
1852 }
1853 const QFileInfo taken(path);
1854 return taken.exists() || taken.isSymLink()
1855 ? QCoreApplication::translate("Util", "%1 already exists.")
1856 .arg(path)
1857 : QCoreApplication::translate("Util", "Failed to write %1.")
1858 .arg(path);
1859}
1860
1868auto isTheFileWritten(const QString &path, const FileIdentity &written)
1869 -> bool {
1870 QFile placed;
1871 if (!Util::openRegularFile(path, placed)) {
1872 return false;
1873 }
1874 const FileIdentity there = identityOf(placed);
1875 if (!written.known || !there.known) {
1876 qCWarning(lcQtPass) << "Cannot tell whether" << path
1877 << "is the file that was written here";
1878 return true;
1879 }
1880 return there == written;
1881}
1882
1883} // namespace
1884
1885auto Util::stageFileReplacing(const QString &path, bool replace,
1886 const Filler &fill, QString *error) -> bool {
1887 QString why;
1888 const std::optional<Staged> staged = stageNextTo(path, fill, &why);
1889 if (!staged) {
1890 return fail(error, why);
1891 }
1893 s_beforePlacingForTests(staged->path);
1894 }
1895 if (!replaceFile(staged->path, path, replace)) {
1896 QFile::remove(staged->path);
1897 return fail(error, placementError(path, replace));
1898 }
1899 // A mismatch is reported and left: removing by name could take another
1900 // writer's file.
1901 if (!isTheFileWritten(path, staged->identity)) {
1902 return fail(
1903 error,
1904 QCoreApplication::translate(
1905 "Util", "%1 was swapped for another file while it was written.")
1906 .arg(path));
1907 }
1908 return true;
1909}
1910
1911auto Util::writeFileReplacing(const QString &path, const QByteArray &bytes,
1912 bool replace, QString *error) -> bool {
1913 return stageFileReplacing(
1914 path, replace,
1915 [&path, &bytes](QFileDevice &staged) -> QString {
1916 if (staged.write(bytes) != bytes.size()) {
1917 return QCoreApplication::translate("Util", "Cannot write %1: %2")
1918 .arg(path, staged.errorString());
1919 }
1920 return {};
1921 },
1922 error);
1923}
1924
1925auto Util::copyFileReplacing(const QString &src, const QString &dst,
1926 bool replace, QString *error) -> bool {
1927 QFile in;
1928 if (!openRegularFile(src, in)) {
1929 if (error)
1930 *error = QCoreApplication::translate("Util", "Cannot read %1.").arg(src);
1931 return false;
1932 }
1933 return stageFileReplacing(
1934 dst, replace,
1935 [&src, &dst, &in](QFileDevice &staged) -> QString {
1936 std::array<char, std::size_t{64} * 1024> buf;
1937 for (;;) {
1938 const qint64 n = in.read(buf.data(), buf.size());
1939 if (n < 0) {
1940 return QCoreApplication::translate("Util", "Cannot read %1: %2")
1941 .arg(src, in.errorString());
1942 }
1943 if (n == 0) {
1944 return {};
1945 }
1946 if (staged.write(buf.data(), n) != n) {
1947 return QCoreApplication::translate("Util", "Cannot write %1: %2")
1948 .arg(dst, staged.errorString());
1949 }
1950 }
1951 },
1952 error);
1953}
1954
1955namespace {
1956
1961auto removeEntry(const QFileInfo &entry) -> bool {
1962 const QString path = entry.filePath();
1963 if (isLink(entry)) {
1964 if (QFile::remove(path) || QDir().rmdir(path)) {
1965 return true;
1966 }
1967 qCWarning(lcQtPass) << "Could not remove link" << path;
1968 return false;
1969 }
1970 if (QFile::remove(path)) {
1971 return true;
1972 }
1973 const QFile::Permissions perms = QFile::permissions(path);
1974 if (!perms.testFlag(QFile::WriteUser) &&
1975 QFile::setPermissions(path, perms | QFile::WriteUser) &&
1976 QFile::remove(path)) {
1977 return true;
1978 }
1979 qCWarning(lcQtPass) << "Could not remove" << path;
1980 return false;
1981}
1982
1983} // namespace
1984
1985auto Util::removeTree(const QString &dir) -> bool {
1986 // A trailing separator makes lstat follow a link ("link/" is the target
1987 // directory); the link itself is what this is about.
1988 const QString path = QDir::cleanPath(dir);
1989 const QFileInfo top(path);
1990 if (isLink(top)) {
1991 // rm -rf on a link removes the link.
1992 return QFile::remove(path) || QDir().rmdir(path);
1993 }
1994 if (!top.isDir()) {
1995 return false;
1996 }
1997 bool ok = true;
1998 const QFileInfoList entries =
1999 QDir(path).entryInfoList(QDir::Dirs | QDir::Files | QDir::Hidden |
2000 QDir::System | QDir::NoDotAndDotDot,
2001 QDir::Name);
2002 for (const QFileInfo &entry : entries) {
2003 const bool removed = entry.isDir() && !isLink(entry)
2004 ? removeTree(entry.filePath())
2005 : removeEntry(entry);
2006 ok = removed && ok;
2007 }
2008 return ok && QDir().rmdir(path);
2009}
AppSettings, the value object holding every flat QtPass setting.
static auto childUmask() -> int
The umask setChildUmask() set.
Definition executor.cpp:225
static auto executeBlocking(const QString &app, const QStringList &args, const QString &input=QString(), QString *process_out=nullptr, QString *process_err=nullptr) -> int
Run a command synchronously and return its exit code.
Definition executor.cpp:700
static void setChildUmask(int mask)
The umask every child QtPass starts gets, as pass sets its own.
Definition executor.cpp:223
static auto parseWslCommand(const QString &app) -> std::optional< WslCommand >
Parse a configured executable as a WSL command.
Definition executor.cpp:272
static auto passUmask(const QString &value) -> int
The umask pass would use for value of PASSWORD_STORE_UMASK.
Definition util.cpp:142
static auto protocolRegex() -> const QRegularExpression &
Returns a regex to match URL protocols.
Definition util.cpp:767
static auto repositoryPassClimbsTo(const QString &store) -> QString
The repository above store that pass itself would commit to, if any.
Definition util.cpp:342
static auto removeTree(const QString &dir) -> bool
Remove dir and everything in it, the way rm -rf does: a symbolic link or NTFS junction,...
Definition util.cpp:1985
static auto endsWithGpg() -> const QRegularExpression &
Returns a regex to match .gpg file extensions.
Definition util.cpp:759
static auto hasLongUnbrokenRun(QStringView text) -> bool
Whether text holds more than kMaxUnbrokenRun characters in a row without white space Qt wraps at (a n...
Definition util.cpp:976
static auto isAbsoluteFsPath(const QString &path) -> bool
Whether path is absolute to the file system: as QDir::isAbsolutePath(), except that a name starting w...
Definition util.cpp:106
static auto isUnderLink(const QString &path, const QString &storeRoot, bool includeSelf=true) -> bool
Whether the way from storeRoot down to path passes through a symbolic link or NTFS junction: path its...
Definition util.cpp:1217
static auto withoutOtherBlockBreaks(QString text) -> QString
text with every block break other than a line feed (isOtherBlockBreak()) shown as a space,...
Definition util.cpp:967
static auto hasUnreadableName(const QString &dir) -> bool
Whether dir holds an entry whose name is not valid UTF-8.
Definition util.cpp:1192
static void setGitOwnerForTests(std::optional< uint > user)
For tests: the user gitStoreVariables() compares owners with when no asUser is given,...
Definition util.cpp:386
static auto findPasswordStore() -> QString
Locate the password store directory.
Definition util.cpp:81
static auto configIsValid(const AppSettings &s) -> bool
Verify that the required configuration is complete.
Definition util.cpp:733
static auto boundSpaceRuns(const QString &text) -> QString
text with every run of white space other than tabs and line feeds cut to kMaxSpaceRun characters,...
Definition util.cpp:1029
static auto writeFileReplacing(const QString &path, const QByteArray &bytes, bool replace, QString *error=nullptr) -> bool
Write bytes as the file path through stageFileReplacing().
Definition util.cpp:1911
static auto regularFilesUnder(const QString &dir, const QStringList &nameFilters, QStringList *skipped=nullptr, bool hiddenFiles=false, QStringList *unlisted=nullptr) -> QStringList
Regular files under dir whose name matches one of nameFilters, found by walking only real directories...
Definition util.cpp:1149
static QProcessEnvironment _env
Definition util.h:697
static void requireExplicitBareRepository(QProcessEnvironment &env)
Make git in env refuse a folder that is merely laid out as a bare repository (safe....
Definition util.cpp:511
static void setBeforePlacingForTests(std::function< void(const QString &)> hook)
For tests: called by stageFileReplacing() with the temporary's path after it is filled and before it ...
Definition util.cpp:393
static auto isLaunchableWebUrl(const QString &value) -> bool
Check whether a value is a safe, launchable web URL.
Definition util.cpp:843
static constexpr qsizetype kMaxUnbrokenRun
Longest run without white space hasLongUnbrokenRun() allows.
Definition util.h:354
static auto readRegularFile(const QString &path, qint64 maxBytes) -> std::optional< QByteArray >
Read path whole, as the regular file it is (openRegularFile()), when it holds at most maxBytes.
Definition util.cpp:1555
static auto gitStoreVariables(const QString &store, const QString &git={}, std::optional< uint > asUser=std::nullopt) -> QList< std::pair< QString, QString > >
The variables that keep git in store's own repository, never one above it: GIT_CEILING_DIRECTORIES (g...
Definition util.cpp:553
static auto syncToDisk(QFileDevice &file) -> bool
Flush file's bytes to the device (fsync, FlushFileBuffers) before it is renamed into place,...
Definition util.cpp:1722
static auto mkpathForStore(const QString &path) -> bool
Create path and any missing parents as pass would.
Definition util.cpp:615
static auto expandTilde(const QString &path) -> QString
Expand a leading current-user tilde in a path.
Definition util.cpp:96
static auto displayable(const QString &text, bool lineBreaks=true) -> QString
text with the characters that change how the text around them reads replaced by U+FFFD,...
Definition util.cpp:898
static auto isLinkedFolder(const QString &path) -> bool
Whether path names a symbolic link or NTFS junction, with or without a trailing separator (which woul...
Definition util.cpp:1213
static auto replaceFile(const QString &from, const QString &to, bool replace) -> bool
Give the file at from the name to, atomically and without following anything: the operating system's ...
Definition util.cpp:1333
static void applyPassProcessDefaults()
Set up the process the way pass sets up its own, before anything runs git or gpg or writes into the s...
Definition util.cpp:126
static auto readRegularFileUnder(const QString &root, const QString &path, qint64 maxBytes) -> std::optional< QByteArray >
readRegularFile() for a file under root, with no link followed anywhere on the way down from it.
Definition util.cpp:1708
static auto joinPath(const QString &dir, const QString &name) -> QString
name in dir, as the file system means it.
Definition util.cpp:110
static auto isValidKeyId(const QString &keyId) -> bool
Check whether a .gpg-id token may be passed to gpg as a key selector. Accepts any non-empty token tha...
Definition util.cpp:1063
static auto copyFileReplacing(const QString &src, const QString &dst, bool replace, QString *error=nullptr) -> bool
Copy the regular file src to the name dst through stageFileReplacing(): src is read through a handle ...
Definition util.cpp:1925
static auto isOtherBlockBreak(QChar c) -> bool
Whether Qt's text document starts a new block at c, besides at a line feed: a carriage return,...
Definition util.cpp:962
static auto plainToolTip(const QString &text) -> QString
text as a tooltip that shows it as written.
Definition util.cpp:992
std::function< QString(QFileDevice &)> Filler
Fills the temporary of stageFileReplacing() through its open handle; returns why it could not (transl...
Definition util.h:620
static auto newLinesRegex() -> const QRegularExpression &
Returns a regex to match newline characters.
Definition util.cpp:1055
static auto openRegularFile(const QString &path, QFile &file) -> bool
Open path for reading as the regular file it is, not as what a link under that name points to: the ob...
Definition util.cpp:1529
static auto normalizeFolderPath(const QString &path) -> QString
Ensure a folder path always ends with '/'.
Definition util.cpp:118
static constexpr qsizetype kMaxSpaceRun
Longest run of white space boundSpaceRuns() leaves.
Definition util.h:306
static auto shownName(const QString &name, qsizetype max=kMaxShownName) -> QString
A name or path from the store, as a label or list shows it: one line, at most max characters.
Definition util.cpp:1000
static auto readRegularFileInStore(const QString &store, const QString &path, qint64 maxBytes) -> std::optional< QByteArray >
readRegularFileUnder() for a file of the store at store, spelled under the store as configured or und...
Definition util.cpp:1564
static auto linkifyUrls(const QString &text, bool *linked=nullptr) -> QString
Turn plain text into HTML with clickable links for safe web URLs.
Definition util.cpp:914
static auto stageFileReplacing(const QString &path, bool replace, const Filler &fill, QString *error=nullptr) -> bool
The staged write every file QtPass puts into a store goes through: a temporary created next to path (...
Definition util.cpp:1885
static void initialiseEnvironment()
Fill _env once: the process environment with the usual GPG install directories appended to PATH (MacG...
Definition util.cpp:54
static auto directoriesUnder(const QString &dir) -> QStringList
Every real, visible directory under dir, walked by the same rules as regularFilesUnder(): links,...
Definition util.cpp:1180
static bool _envInitialised
Whether initialiseEnvironment() has run.
Definition util.h:699
static auto findBinaryInPath(const QString &binary) -> QString
Locate an executable by searching the process PATH and (on Windows) falling back to WSL.
Definition util.cpp:651
static auto gitCeiling(const QString &store) -> QString
GIT_CEILING_DIRECTORIES for a store, as pass sets it.
Definition util.cpp:155
Executor, the FIFO queue every gpg, git and pass child process of QtPass goes through,...
bool operator==(const NamedValue &a, const NamedValue &b)
Two fields are equal when name and value match; originalLine is formatting, not content,...
Definition filecontent.h:49
The "qtpass" logging category.
Plain value-object holding all flat QtPass configuration.
Definition appsettings.h:36
std::function< void(const QString &)> s_beforePlacingForTests
setBeforePlacingForTests(): called between staging and the rename.
Definition util.cpp:391
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...