QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
realpass.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
9#include "realpass.h"
10#include "executor.h"
11#include "gpgidsigner.h"
12#include "pathvalidator.h"
13#include "qtpasslogging.h"
14#include "util.h"
15#include <QSet>
16#include <optional>
17
18#include <QCoreApplication>
19#include <QCryptographicHash>
20#include <QDir>
21#include <QDirIterator>
22#include <QElapsedTimer>
23#include <QFile>
24#include <QFileInfo>
25#include <QMap>
26#include <QProcess>
27#include <QRegularExpression>
28#include <algorithm>
29#include <utility>
30
31#ifndef Q_OS_WIN
32#include <sys/stat.h>
33#endif
34
36using Enums::GIT_INIT;
37using Enums::GIT_PULL;
38using Enums::GIT_PUSH;
45
50
52
53void RealPass::GitInit() { executePass(GIT_INIT, {"git", "init"}); }
54
55void RealPass::GitPull_b(int timeoutMs) {
56 // In the store's environment, as every queued pass call: pass picks its
57 // store from PASSWORD_STORE_DIR alone, so without it the pull before an
58 // edit went to ~/.password-store instead of the configured store.
59 QProcess process;
60 process.setProcessEnvironment(storeEnvironment());
61 QString err;
62 QElapsedTimer timer;
63 timer.start();
64 const int result = Executor::executeBlocking(
65 process, m_settings.passExecutable, {"git", "pull"}, QString(), nullptr,
66 &err, nullptr, timeoutMs);
67 if (result != 0 && timer.elapsed() >= timeoutMs) {
68 emit statusMsg(pullTimedOut(timeoutMs), 5000);
69 } else if (result != 0) {
70 qCDebug(lcQtPass) << "Git pull failed with code:" << result;
71 // As the native backend does: the entry about to be edited is not up to
72 // date with the remote.
73 emit statusMsg(tr("Git pull failed: %1").arg(err.trimmed()), 5000);
74 }
75}
76
77void RealPass::GitPull() { executePass(GIT_PULL, {"git", "pull"}); }
78
80 // Queued behind an init, move or copy, the push would run before its
81 // outcome is known and send its commit even when the re-encryption then
82 // fails (the hold is set only then): it waits for them.
83 if (!m_reencryptScopes.isEmpty() || !m_reencryptPending.isEmpty()) {
86 return;
87 }
88 executePass(GIT_PUSH, {"git", "push"});
89}
90
92 if (!m_pushAfterReencrypt || !m_reencryptScopes.isEmpty() ||
93 !m_reencryptPending.isEmpty()) {
94 return;
95 }
96 const bool byHand = m_deferredPushByHand;
99 if (!byHand && autoPushHeld()) {
100 emit statusMsg(tr("Not pushing: an earlier re-encryption in this "
101 "store did not finish"),
102 5000);
103 return;
104 }
105 executePass(GIT_PUSH, {"git", "push"});
106}
107
108void RealPass::Show(QString file) {
109 // pass follows links as readily as gpg does.
110 if (refuseLinkedPath(file + ".gpg")) {
111 return;
112 }
113 queueShow(file);
114 // "--" ends the options so an entry named "--" or "-c" (which a co-writer can
115 // push) cannot be read as a pass option and decrypt a file outside the store
116 // or run a clip; it is always a path.
117 executePass(PASS_SHOW, {"show", "--", file}, "", true);
118}
119
121 GpgIdSigner signer{m_settings.gpgExecutable,
123 [this](const QString &app, const QStringList &args,
124 const QString &input, QString *out, QString *err) {
125 QProcess gpg;
126 gpg.setProcessEnvironment(exec.environment());
127 return Executor::executeBlocking(gpg, app, args, input,
128 out, err);
129 }};
130 signer.setStoreRoot(m_settings.passStore);
131 return signer;
132}
133
134auto RealPass::refuseList(const QString &file, const GpgIdSigner &signer,
135 QSet<QString> &verified, const QString &within,
136 const QString &except, SkippedWalks *walks) -> bool {
137 if (refuseSkippedGpgId(file, true, except, walks)) {
138 return true;
139 }
140 const QString gpgIdFile = Pass::getGpgIdPath(file, m_settings.passStore);
141 const QString absolute =
142 QDir::cleanPath(QFileInfo(gpgIdFile).absoluteFilePath());
143 if (verified.contains(gpgIdFile) ||
144 (!except.isEmpty() &&
145 absolute == QDir::cleanPath(QFileInfo(except).absoluteFilePath())) ||
146 (!within.isEmpty() && !absolute.startsWith(within))) {
147 return false;
148 }
149 QString why =
150 QCoreApplication::translate("ImitatePass", "Signature for %1 is invalid.")
151 .arg(gpgIdFile);
152 QByteArray contents;
153 if (!verifySignedList(signer, gpgIdFile, &contents, &why)) {
154 emit critical(QCoreApplication::translate("ImitatePass",
155 "Check .gpg-id file signature!"),
156 why);
157 return true;
158 }
159 verified.insert(gpgIdFile);
160 return false;
161}
162
163auto RealPass::refuseLinkedList(const QString &file, const QString &within,
164 const QString &except, LinkedWalks *walks)
165 -> bool {
166 const std::optional<QString> linked =
167 Pass::linkedGpgId(file, m_settings.passStore, walks);
168 if (!linked) {
169 return false;
170 }
171 const QString absolute =
172 QDir::cleanPath(QFileInfo(*linked).absoluteFilePath());
173 if ((!except.isEmpty() &&
174 absolute == QDir::cleanPath(QFileInfo(except).absoluteFilePath())) ||
175 (!within.isEmpty() && !absolute.startsWith(within))) {
176 return false;
177 }
178 emit critical(
179 tr("Recipient list is a link"),
180 tr("%1 is a link. pass would encrypt to the recipients in the file it "
181 "points to, while QtPass shows the list of a folder above it, so "
182 "nothing was encrypted. Replace the link with a copy of the list, or "
183 "remove it.")
184 .arg(QDir::toNativeSeparators(*linked)));
185 return true;
186}
187
188auto RealPass::refuseMisreadList(const QString &file, const QString &within,
189 const QString &except, QSet<QString> &checked)
190 -> bool {
191 const QString gpgIdFile = Pass::getGpgIdPath(file, m_settings.passStore);
192 const QString absolute =
193 QDir::cleanPath(QFileInfo(gpgIdFile).absoluteFilePath());
194 if (checked.contains(absolute) ||
195 (!except.isEmpty() &&
196 absolute == QDir::cleanPath(QFileInfo(except).absoluteFilePath())) ||
197 (!within.isEmpty() && !absolute.startsWith(within))) {
198 return false;
199 }
200 // A missing list is pass's to report. One that is there but not a
201 // regular file within the limit (too large, a FIFO, a device, unreadable)
202 // pass may still read in full, while the Users dialog shows none of it.
203 // A link was refused before this.
204 const std::optional<QByteArray> bytes = Util::readRegularFileInStore(
205 m_settings.passStore, gpgIdFile, Util::kMaxGpgIdBytes);
206 if (!bytes && QFileInfo::exists(gpgIdFile)) {
207 emit critical(tr("Recipient list cannot be read"),
208 //: %1 is the list's path, %2 a size such as "1 MiB".
209 tr("%1 is not a regular file of at most %2, so QtPass "
210 "cannot show who pass would encrypt to. Nothing was "
211 "encrypted. Check the recipients in Users for that "
212 "folder and press OK to write the list anew.")
213 .arg(QDir::toNativeSeparators(gpgIdFile),
214 QLocale().formattedDataSize(Util::kMaxGpgIdBytes)));
215 return true;
216 }
217 const QString misread =
218 bytes ? Pass::passReadsDifferently(*bytes) : QString();
219 if (misread.isEmpty()) {
220 checked.insert(absolute);
221 return false;
222 }
223 emit critical(tr("Recipient list reads differently"),
224 //: %1 is the list's path, %2 says what is wrong with it.
225 tr("pass reads %1 differently from the Users dialog (%2), so "
226 "it could encrypt to recipients the dialog does not show. "
227 "Nothing was encrypted. Check the recipients in Users for "
228 "that folder and press OK to write the list anew.")
229 .arg(QDir::toNativeSeparators(gpgIdFile), misread));
230 return true;
231}
232
233auto RealPass::refuseUnverifiedList(const QString &file) -> bool {
234 // pass verifies the signature itself, but knows nothing of the generation
235 // and folder lines: an older authentic list put back, or one signed for
236 // another folder, would get the secret (#2077). The same checks as the
237 // native backend, with gpg in the store's environment. pass reads the list
238 // again afterwards; a swap in between is a concurrent writer, out of
239 // scope (SECURITY.md). A linked list differs from what QtPass shows,
240 // signing key or not.
241 QSet<QString> readAlike;
242 if (refuseLinkedList(file) ||
243 refuseMisreadList(file, QString(), QString(), readAlike)) {
244 return true;
245 }
246 const GpgIdSigner signer = listSigner();
247 if (!signer.enabled()) {
248 return false;
249 }
250 QSet<QString> verified;
251 return refuseList(file, signer, verified);
252}
253
254namespace {
262auto passFoldersUnder(const QString &dir, QStringList &unreadable)
263 -> QStringList {
264 QStringList folders{QDir::cleanPath(dir)};
265 if (Util::hasUnreadableName(dir)) {
266 unreadable << QDir::cleanPath(dir);
267 return folders;
268 }
269 const QFileInfoList children = QDir(dir).entryInfoList(
270 QDir::Dirs | QDir::Hidden | QDir::System | QDir::NoDotAndDotDot);
271 for (const QFileInfo &child : children) {
272 if (child.isSymLink() || child.isJunction() ||
273 child.fileName() == QLatin1String(".git")) {
274 continue;
275 }
276 folders << passFoldersUnder(child.absoluteFilePath(), unreadable);
277 }
278 return folders;
279}
280
292auto firstSpecialEntry(const QStringList &folders) -> QString {
293 for (const QString &folder : folders) {
294 const QFileInfoList entries = QDir(folder).entryInfoList(
295 {QStringLiteral("*.gpg")}, QDir::Files | QDir::System | QDir::Hidden,
296 QDir::Name);
297 for (const QFileInfo &entry : entries) {
298 if (!entry.isSymLink() && !entry.isFile() && !entry.isDir()) {
299 return entry.filePath();
300 }
301 }
302 }
303 return {};
304}
305} // namespace
306
307auto RealPass::refuseSpecialEntry(const QString &entry) -> bool {
308 if (entry.isEmpty()) {
309 return false;
310 }
311 const QString title = tr("Not a password file");
312 //: %1 is a path in the password store.
313 const QString text =
314 tr("%1 is named like a password but is not a regular file (for "
315 "example a named pipe). pass would wait on it forever, so nothing "
316 "was changed. Remove it, then try again.")
317 .arg(QDir::toNativeSeparators(entry));
318 emit critical(title, text);
319 return true;
320}
321
322auto RealPass::refuseLineBreakName(const QString &path) -> bool {
323 const QString name = passName(path, false);
324 if (!name.contains(QLatin1Char('\n')) && !name.contains(QLatin1Char('\r'))) {
325 return false;
326 }
327 QString shown = name;
328 shown.replace(QLatin1Char('\n'), QStringLiteral("\\n"))
329 .replace(QLatin1Char('\r'), QStringLiteral("\\r"));
330 emit critical(tr("Name holds a line break"),
331 //: %1 is a name in the password store, each line break in it
332 //: shown as a backslash followed by n or r.
333 tr("\"%1\" holds a line break. pass would read the recipient "
334 "list of another folder for it, so nothing was changed. "
335 "Move or rename it first.")
336 .arg(shown));
337 return true;
338}
339
340auto RealPass::listLinesUnder(const QString &dir, const QString &except)
341 -> QStringList {
342 QStringList unreadable;
343 QStringList lines;
344 for (const QString &folder : passFoldersUnder(dir, unreadable)) {
345 const QString list = QDir(folder).filePath(QStringLiteral(".gpg-id"));
346 if (QDir::cleanPath(list) == QDir::cleanPath(except) ||
347 !QFileInfo(list).isFile()) {
348 continue;
349 }
350 // The folder's own list, read as such: a lookup through a made-up
351 // entry name would land in a folder by that name, if there is one.
352 if (const std::optional<QByteArray> bytes = Util::readRegularFileInStore(
353 m_settings.passStore, list, Util::kMaxGpgIdBytes)) {
354 lines << parseRecipients(*bytes, list);
355 }
356 }
357 return lines;
358}
359
361 const QString &entry, const QStringList &target, const QStringList &before,
362 QHash<QString, std::optional<QSet<QString>>> &probes) -> bool {
363 const auto probe = [this, &probes](const QStringList &lines) {
364 const QString key = lines.join(QLatin1Char('\n'));
365 const auto cached = probes.constFind(key);
366 if (cached != probes.constEnd()) {
367 return cached.value();
368 }
369 std::optional<QSet<QString>> keys;
370 if (const std::optional<QStringList> ids = encryptionReaches(lines);
371 ids && !ids->isEmpty()) {
372 keys = QSet<QString>();
373 for (const QString &id : *ids) {
374 keys->insert(id.toUpper());
375 }
376 }
377 probes.insert(key, keys);
378 return keys;
379 };
380 const std::optional<QSet<QString>> now = probe(target);
381 // A list the probe cannot read gives no answer: asked about.
382 if (!now) {
383 return true;
384 }
385 const QStringList ids = entryReaders(entry);
386 // Recipients gpg could not list (the listing failed for this path while
387 // pass may still decrypt it): no answer, so asked about.
388 if (ids.isEmpty()) {
389 return true;
390 }
391 QSet<QString> gaining = *now;
392 for (const QString &id : ids) {
393 gaining.remove(id);
394 }
395 if (target != before) {
396 if (const std::optional<QSet<QString>> old = probe(before)) {
397 QSet<QString> added = *now;
398 added.subtract(*old);
399 gaining.subtract(added);
400 }
401 }
402 return !gaining.isEmpty();
403}
404
405auto RealPass::entriesInitWouldWiden(const QString &dir,
406 const QList<UserInfo> &users)
407 -> QStringList {
408 const QString folder =
409 QDir::cleanPath(Util::joinPath(m_settings.passStore, dir));
410 const QString ownList =
411 QDir::cleanPath(QDir(folder).filePath(QStringLiteral(".gpg-id")));
412 const QStringList newLines = enabledKeyLines(users);
413 QHash<QString, std::optional<QSet<QString>>> probes;
414 QStringList widened;
415 QStringList unreadable;
416 for (const QString &sub : passFoldersUnder(folder, unreadable)) {
417 const QFileInfoList entries = QDir(sub).entryInfoList(
418 {QStringLiteral("*.gpg")}, QDir::Files | QDir::Hidden);
419 for (const QFileInfo &entry : entries) {
420 if (entry.isSymLink()) {
421 continue;
422 }
423 const QString path = entry.absoluteFilePath();
424 const QString list =
425 QDir::cleanPath(getGpgIdPath(path, m_settings.passStore));
426 const QStringList current = getRecipientList(path, m_settings.passStore);
427 // An entry under a list of its own below the folder keeps it; every
428 // other one gets the list written now.
429 const bool own =
430 list != ownList && list.startsWith(folder + QLatin1Char('/'));
431 const QStringList target = own ? current : newLines;
432 if (entryWouldGain(path, target, current, probes)) {
433 widened << path;
434 }
435 }
436 }
437 return widened;
438}
439
440auto RealPass::entriesMoveWouldWiden(const QString &src, const QString &dest)
441 -> QStringList {
442 // pass ends a mv or cp with reencrypt_path on where it landed: a folder
443 // moved or copied, renamed included, is re-encrypted itself, and when it
444 // lands in an existing folder, that whole folder is. What already lies in
445 // the destination, and what someone else pushed into the folder that
446 // moves, may be someone else's copy; the folder itself is the user's.
447 const PassMoveTarget target = passMoveTarget(src, dest);
448 QHash<QString, std::optional<QSet<QString>>> probes;
449 QStringList widened;
450 QStringList unreadable;
451 if (QFileInfo(target.newPath).isDir()) {
452 for (const QString &sub : passFoldersUnder(target.newPath, unreadable)) {
453 const QFileInfoList entries = QDir(sub).entryInfoList(
454 {QStringLiteral("*.gpg")}, QDir::Files | QDir::Hidden);
455 for (const QFileInfo &entry : entries) {
456 if (entry.isSymLink()) {
457 continue;
458 }
459 const QString path = entry.absoluteFilePath();
460 const QStringList list = getRecipientList(path, m_settings.passStore);
461 if (entryWouldGain(path, list, list, probes)) {
462 widened << path;
463 }
464 }
465 }
466 }
467 const QFileInfo srcInfo(src);
468 if (!srcInfo.isDir() || srcInfo.isSymLink()) {
469 return widened;
470 }
471 // Inside the folder that moves: an entry keeps a list that moves along
472 // with it (one inside the folder), and otherwise gets the list where the
473 // folder lands. Whom that adds gains every entry, as a move means.
474 const QString from = QDir::cleanPath(srcInfo.absoluteFilePath());
475 const QStringList landing =
476 getRecipientList(Util::joinPath(target.written, QStringLiteral("x.gpg")),
477 m_settings.passStore);
478 for (const QString &sub : passFoldersUnder(from, unreadable)) {
479 const QFileInfoList entries = QDir(sub).entryInfoList(
480 {QStringLiteral("*.gpg")}, QDir::Files | QDir::Hidden);
481 for (const QFileInfo &entry : entries) {
482 if (entry.isSymLink()) {
483 continue;
484 }
485 const QString path = entry.absoluteFilePath();
486 const QString list =
487 QDir::cleanPath(getGpgIdPath(path, m_settings.passStore));
488 const QStringList current = getRecipientList(path, m_settings.passStore);
489 const bool alongWith = list.startsWith(from + QLatin1Char('/'));
490 const QStringList targetList = alongWith ? current : landing;
491 if (entryWouldGain(path, targetList, current, probes)) {
492 widened << path;
493 }
494 }
495 }
496 return widened;
497}
498
499auto RealPass::refuseUnverifiedTree(const QString &dir, bool onlyListsWithin,
500 const QString &except) -> bool {
501 // Every folder pass's walk takes. A name Qt cannot read hides what is
502 // behind it, a linked list included, so the walk must be complete first,
503 // signing key or not.
504 QStringList unreadable;
505 const QStringList folders = passFoldersUnder(dir, unreadable);
506 if (!unreadable.isEmpty()) {
507 const QString title = tr("Cannot check the recipient lists");
508 //: %1 is a folder. "UTF-8" is the text encoding; keep it as is.
509 const QString text =
510 tr("%1 holds a file or folder whose name is not valid UTF-8. QtPass "
511 "cannot see what is behind that name, while pass would re-encrypt "
512 "it, so nothing was changed. Rename it, then try again.")
513 .arg(QDir::toNativeSeparators(unreadable.first()));
514 emit critical(title, text);
515 return true;
516 }
517 if (refuseSpecialEntry(firstSpecialEntry(folders))) {
518 return true;
519 }
520 // Absolute, as getGpgIdPath() hands lists back: a relative or other
521 // spelling would match nothing and check nothing.
522 const QString within =
523 onlyListsWithin ? QDir::cleanPath(QFileInfo(dir).absoluteFilePath()) +
524 QLatin1Char('/')
525 : QString();
526 // A linked list differs from what QtPass shows, signing key or not: in
527 // every folder of the walk, and above them unless only the lists within
528 // count (the folder that moves gets the destination's list, the folder
529 // pass init writes its own).
530 QSet<QString> readAlike;
531 // Each folder's linked-list answer once for the whole tree: climbed again
532 // from every folder, a deep chain cost depth squared stat calls.
533 LinkedWalks linkedWalks;
534 for (const QString &folder : folders) {
535 if (refuseLinkedList(folder + QLatin1Char('/'), within, except,
536 &linkedWalks) ||
537 refuseMisreadList(folder + QLatin1Char('/'), within, except,
538 readAlike)) {
539 return true;
540 }
541 }
542 const GpgIdSigner signer = listSigner();
543 if (!signer.enabled()) {
544 return false;
545 }
546 // One gpg call per list, before pass runs: a store with many lists makes
547 // that a noticeable pause, so say what it is.
548 emit statusMsg(tr("Checking the recipient lists under %1…")
549 .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))),
550 3000);
551 // pass mv and cp re-encrypt every entry of the folder they write to, each
552 // to its nearest list, walking as passFoldersUnder() does. For the folder
553 // that moves, the lists inside it go along: checked where they lie now
554 // (after the move their folder line names the old place until the
555 // recipients are saved there again), while a list above it is replaced
556 // by the destination's, which the caller checks. For entries already in
557 // the destination, their lists stay where they are: all of them count.
558 QSet<QString> verified;
559 // Each folder's skipped-list answer once for the whole tree: asked again
560 // from every folder, a deep chain cost depth squared record lookups.
561 SkippedWalks walks;
562 // Every folder's list counts, also where no entry uses it yet: cp -r
563 // merges an incoming folder into one of the same name, so the entries it
564 // brings get a list already there, and a list it brings replaces the one
565 // there for the entries already in it.
566 for (const QString &folder : folders) {
567 if (refuseList(folder, signer, verified, within, except, &walks)) {
568 return true;
569 }
570 }
571 return false;
572}
573
574auto RealPass::storeGit(const QStringList &args, QString *out) -> bool {
575 if (!m_settings.useGit) {
576 return false;
577 }
578 // `pass git` runs git in the store with PASSWORD_STORE_DIR set, as the
579 // store's other quick lookups do; its exit code is git's own.
580 QString err;
582 exec.environment(), m_settings.passExecutable,
583 QStringList{QStringLiteral("git")} + args, out, &err) == 0;
584}
585
586namespace {
593auto inRepository(const QString &repository, const QStringList &args)
594 -> QStringList {
595 if (repository.isEmpty()) {
596 return args;
597 }
598 return QStringList{QStringLiteral("-C"), repository} + args;
599}
600} // namespace
601
602auto RealPass::repositoryOf(const QString &path) -> QString {
603 if (!m_settings.useGit) {
604 return {};
605 }
606 const QString root = QDir::cleanPath(m_settings.passStore);
607 // From the nearest folder that exists, as pass looks for it.
608 QString folder = QDir::cleanPath(path);
609 while (!QFileInfo(folder).isDir() &&
610 folder.startsWith(root + QLatin1Char('/'))) {
611 folder = QFileInfo(folder).path();
612 }
613 const QString relative = QDir(root).relativeFilePath(folder);
614 if (relative == QLatin1String(".") || relative == QLatin1String("..") ||
615 relative.startsWith(QLatin1String("../"))) {
616 return {};
617 }
618 // The folder's place in its repository ("team/" in the store's own,
619 // "" at the top of the one it holds itself).
620 QString prefix;
621 storeGit({QStringLiteral("-C"), relative, QStringLiteral("rev-parse"),
622 QStringLiteral("--show-prefix")},
623 &prefix);
624 if (prefix.endsWith(QLatin1Char('\n'))) {
625 prefix.chop(1);
626 }
627 const QString withSlash = relative + QLatin1Char('/');
628 if (!withSlash.endsWith(prefix)) {
629 return {};
630 }
631 QString repository = withSlash.chopped(prefix.size());
632 if (repository.endsWith(QLatin1Char('/'))) {
633 repository.chop(1);
634 }
635 return repository;
636}
637
638auto RealPass::statusEntries(const QStringList &args, const QString &repository)
639 -> QStringList {
640 if (!m_settings.useGit) {
641 return {};
642 }
643 QString out;
644 // -z: names as they are, not quoted when they hold a non-ASCII letter.
645 // `pass git` exits 0 whatever git did: the output decides, and a git
646 // that cannot say (no repository) prints nothing to it.
647 storeGit(inRepository(repository, QStringList{QStringLiteral("status"),
648 QStringLiteral("--porcelain"),
649 QStringLiteral("-z")} +
650 args),
651 &out);
652 const QString place =
653 repository.isEmpty() ? QString() : repository + QLatin1Char('/');
654 QStringList entries;
655 const QStringList fields = out.split(QChar(0), Qt::SkipEmptyParts);
656 for (qsizetype i = 0; i < fields.size(); ++i) {
657 const QString &field = fields.at(i);
658 if (field.size() < 4 || field.at(2) != QLatin1Char(' ')) {
659 continue;
660 }
661 entries << field.left(3) + place + field.mid(3);
662 // A rename or copy, in the index or in the work tree (an intent-to-add
663 // file), is followed by its old name.
664 if (field.at(0) == QLatin1Char('R') || field.at(0) == QLatin1Char('C') ||
665 field.at(1) == QLatin1Char('R') || field.at(1) == QLatin1Char('C')) {
666 ++i;
667 }
668 }
669 return entries;
670}
671
672auto RealPass::unrecorded(const QStringList &paths, bool ignored)
673 -> QStringList {
674 if (paths.isEmpty()) {
675 return {};
676 }
677 const QDir store(QDir::cleanPath(m_settings.passStore));
678 // Each path in the repository pass commits it in: a folder may hold one
679 // of its own, which the store's status does not look into.
680 QMap<QString, QStringList> byRepository;
681 for (const QString &path : paths) {
682 const QString repository = repositoryOf(path);
683 const QDir top(repository.isEmpty() ? store.path()
684 : store.filePath(repository));
685 byRepository[repository] << top.relativeFilePath(QDir::cleanPath(path));
686 }
687 QStringList entries;
688 for (auto it = byRepository.cbegin(); it != byRepository.cend(); ++it) {
689 QStringList args{QStringLiteral("--untracked-files=all")};
690 if (ignored) {
691 args << QStringLiteral("--ignored");
692 }
693 args << QStringLiteral("--");
694 entries += statusEntries(args + it.value(), it.key());
695 }
696 return entries;
697}
698
699namespace {
709auto fileManagerFiles(const QStringList &lines, QStringList *paths)
710 -> QStringList {
711 QStringList found;
712 for (const QString &name :
713 {QStringLiteral(".DS_Store"), QStringLiteral("Thumbs.db"),
714 QStringLiteral("desktop.ini"), QStringLiteral(".directory")}) {
715 for (const QString &line : lines) {
716 if (line.startsWith(QLatin1String("?? ")) &&
717 QFileInfo(line.mid(3)).fileName() == name) {
718 if (!found.contains(name)) {
719 found << name;
720 }
721 *paths << line.mid(3);
722 }
723 }
724 }
725 return found;
726}
727
733auto isStoreFileName(const QString &name) -> bool {
734 return name.endsWith(QLatin1String(".gpg")) ||
735 name == QLatin1String(".gpg-id") ||
736 name == QLatin1String(".gpg-id.sig");
737}
738
740constexpr qsizetype kMaxNamedChanges = 10;
741
748auto namedChanges(const QStringList &lines) -> QString {
749 QString named = lines.mid(0, kMaxNamedChanges).join(QLatin1Char('\n'));
750 if (lines.size() > kMaxNamedChanges) {
751 named += QLatin1Char('\n') +
752 RealPass::tr("and %n more", nullptr,
753 static_cast<int>(lines.size() - kMaxNamedChanges));
754 }
755 return named;
756}
757
768auto exposedWhereLanded(const QStringList &moving, const QStringList &landed,
769 const QStringList &travelling,
770 const QStringList &ignoredThere) -> QStringList {
771 QStringList exposed;
772 for (qsizetype i = 0; i < landed.size(); ++i) {
773 if (!travelling.contains(moving.at(i)) &&
774 !ignoredThere.contains(landed.at(i))) {
775 exposed << moving.at(i) + QStringLiteral(" > ") + landed.at(i);
776 }
777 }
778 return exposed;
779}
780} // namespace
781
782auto RealPass::refuseUnrecordedChanges(const QStringList &paths,
783 const QStringList &committing) -> bool {
784 QStringList changes = unrecorded(paths, false);
785 QStringList repositories;
786 for (const QString &path : committing) {
787 const QString repository = repositoryOf(path);
788 if (!repositories.contains(repository)) {
789 repositories << repository;
790 }
791 }
792 // pass commits the whole index, not only what it staged: anything staged
793 // elsewhere goes along.
794 for (const QString &repository : std::as_const(repositories)) {
795 const QStringList tracked =
796 statusEntries({QStringLiteral("--untracked-files=no")}, repository);
797 for (const QString &entry : tracked) {
798 if (entry.at(0) != QLatin1Char(' ') && !changes.contains(entry)) {
799 changes << entry;
800 }
801 }
802 }
803 if (changes.isEmpty()) {
804 return false;
805 }
806 QString why =
807 tr("The folder holds changes Git has not recorded, and pass would "
808 "commit and push them along with this one:\n\n%1\n\nCommit, "
809 "remove or ignore them with Git first, then try again.")
810 .arg(namedChanges(changes));
811 // These come back in every folder the file manager opens: removing them
812 // does not last, ignoring them once does, in the .gitignore of the
813 // repository that reports them (a folder may hold one of its own).
814 QStringList writtenAt;
815 const QStringList written = fileManagerFiles(changes, &writtenAt);
816 if (!written.isEmpty()) {
817 const QDir store(QDir::cleanPath(m_settings.passStore));
818 // Each .gitignore with the names its repository reports, alone: a
819 // rule for a name that is not there could hide something else.
820 QStringList ignoreFiles;
821 QMap<QString, QStringList> namesFor;
822 for (const QString &path : std::as_const(writtenAt)) {
823 const QString repository = repositoryOf(store.filePath(path));
824 const QString file = repository.isEmpty()
825 ? QStringLiteral(".gitignore")
826 : repository + QStringLiteral("/.gitignore");
827 if (!ignoreFiles.contains(file)) {
828 ignoreFiles << file;
829 }
830 const QString name = QFileInfo(path).fileName();
831 if (!namesFor[file].contains(name)) {
832 namesFor[file] << name;
833 }
834 }
835 QStringList blocks;
836 for (const QString &file : std::as_const(ignoreFiles)) {
837 blocks << file + QStringLiteral(":\n") +
838 namesFor.value(file).join(QLatin1Char('\n'));
839 }
840 why += QStringLiteral("\n\n") +
841 tr("The system writes %1 by itself, in folders a file manager "
842 "opens (Finder on macOS, Explorer on Windows, Dolphin on "
843 "KDE). Git leaves such files alone in every folder once each "
844 ".gitignore in the store below holds its lines, committed:"
845 "\n\n%2")
846 .arg(written.join(QStringLiteral(", ")),
847 blocks.join(QStringLiteral("\n\n")));
848 }
849 // As the other refusals: the interface arms when an operation starts and
850 // is released by processErrorExit(); a refusal starts nothing.
852 emit critical(tr("Changes Git has not recorded"), why);
853 emit processErrorExit(1, why);
854 return true;
855}
856
857void RealPass::reportUnrecorded(const QStringList &paths) {
858 QStringList changes;
859 for (const QString &line : unrecorded(paths, true)) {
860 // What pass writes: entries and recipient lists. Other ignored files in
861 // a folder are the user's own business.
862 if (isStoreFileName(QFileInfo(line.mid(3)).fileName())) {
863 changes << line;
864 }
865 }
866 if (changes.isEmpty()) {
867 return;
868 }
869 emit critical(tr("Saved, not committed"),
870 tr("The change is in the store, but Git did not record it, "
871 "so it is not pushed, and a pull may overwrite it "
872 "(\"!!\" marks a file Git ignores):\n\n%1")
873 .arg(namedChanges(changes)));
874}
875
876auto RealPass::refuseLinkInCopiedFolder(const QString &src) -> bool {
877 QStringList folders{src};
878 QString found;
879 QString unreadable = Util::hasUnreadableName(src) ? src : QString();
880 // Folder by folder, so each can be asked about names Qt leaves out.
881 while (!folders.isEmpty() && found.isEmpty() && unreadable.isEmpty()) {
882 QDirIterator it(folders.takeFirst(), QDir::AllEntries | QDir::Hidden |
883 QDir::System |
884 QDir::NoDotAndDotDot);
885 while (it.hasNext()) {
886 const QString path = it.next();
887 if (Util::isLinkedFolder(path)) {
888 found = path;
889 break;
890 }
891 if (it.fileInfo().isDir()) {
892 if (Util::hasUnreadableName(path)) {
893 unreadable = path;
894 break;
895 }
896 folders << path;
897 }
898 }
899 }
900 if (found.isEmpty() && unreadable.isEmpty()) {
901 return false;
902 }
903 const QString why =
904 found.isEmpty()
905 ? tr("%1 holds a name QtPass cannot read, so it cannot tell "
906 "whether copying the folder would copy something from outside "
907 "the store. Nothing was copied.")
908 .arg(QDir::toNativeSeparators(QDir::cleanPath(unreadable)))
909 : tr("%1 is a symbolic link or junction. Copying the folder that "
910 "holds it would, on some systems, copy what it points to into "
911 "the store. Nothing was copied; remove the link first.")
912 .arg(QDir::toNativeSeparators(QDir::cleanPath(found)));
914 emit critical(tr("Not copied"), why);
915 emit processErrorExit(1, why);
916 return true;
917}
918
919auto RealPass::refuseIgnoredThatMoves(const QString &src, const QString &dest)
920 -> bool {
921 if (!m_settings.useGit || !QFileInfo(src).isDir()) {
922 return false;
923 }
924 const QDir store(QDir::cleanPath(m_settings.passStore));
925 // pass moves a folder into an existing one, as mv does.
926 const QString landing = QFileInfo(dest).isDir()
927 ? Util::joinPath(dest, QFileInfo(src).fileName())
928 : dest;
929 // Each side in its own repository: where the files lie now, and the one
930 // pass commits them in.
931 const QString fromRepository = repositoryOf(src);
932 const QString toRepository = repositoryOf(landing);
933 const QString from =
934 QDir(fromRepository.isEmpty() ? store.path()
935 : store.filePath(fromRepository))
936 .relativeFilePath(QDir::cleanPath(src));
937 const QString to =
938 QDir(toRepository.isEmpty() ? store.path() : store.filePath(toRepository))
939 .relativeFilePath(QDir::cleanPath(landing));
940 // ls-files names files relative to where git runs, where status names
941 // them from the repository's root; both are that repository here.
942 QString out;
943 storeGit(
944 inRepository(fromRepository,
945 {QStringLiteral("ls-files"), QStringLiteral("-z"),
946 QStringLiteral("--others"), QStringLiteral("--ignored"),
947 QStringLiteral("--exclude-standard"), QStringLiteral("--"),
948 from}),
949 &out);
950 QStringList moving;
951 QStringList landed;
952 for (const QString &file : out.split(QChar(0), Qt::SkipEmptyParts)) {
953 if (!file.startsWith(from + QLatin1Char('/')) ||
954 isStoreFileName(QFileInfo(file).fileName())) {
955 continue;
956 }
957 moving << file;
958 landed << to + file.mid(from.size());
959 }
960 if (landed.isEmpty()) {
961 return false;
962 }
963 // A rule in a .gitignore inside the folder goes with it, so what it
964 // ignores stays ignored where it lands, and decides there: deeper rules
965 // win. Into a folder that is already there, a rule waiting deeper in it
966 // could undo that, so only the lookup there counts.
967 const QStringList travelling =
968 QFileInfo::exists(landing)
969 ? QStringList()
970 : ignoredByRulesWithin(fromRepository, from, moving);
971 // A lookup that failed counts nothing as ignored: the move is refused.
972 QStringList ignoredThere;
973 if (!checkIgnore(toRepository, landed, false, &ignoredThere)) {
974 ignoredThere.clear();
975 }
976 const QStringList exposed =
977 exposedWhereLanded(moving, landed, travelling, ignoredThere);
978 if (exposed.isEmpty()) {
979 return false;
980 }
981 const QString why =
982 tr("Git ignores these files only where they are now, and pass would "
983 "commit and push them where they land:\n\n%1\n\nMove them out of "
984 "the folder, or have Git ignore them there too, then try again.")
985 .arg(namedChanges(exposed));
987 emit critical(tr("Ignored files would be committed"), why);
988 emit processErrorExit(1, why);
989 return true;
990}
991
992auto RealPass::ignoredByRulesWithin(const QString &repository,
993 const QString &from,
994 const QStringList &moving) -> QStringList {
995 QStringList travelling;
996 QStringList rules;
997 if (checkIgnore(repository, moving, true, &rules)) {
998 for (qsizetype i = 0; i + 3 < rules.size(); i += 4) {
999 if (rules.at(i).startsWith(from + QLatin1Char('/'))) {
1000 travelling << rules.at(i + 3);
1001 }
1002 }
1003 }
1004 return travelling;
1005}
1006
1007auto RealPass::checkIgnore(const QString &repository, const QStringList &paths,
1008 bool verbose, QStringList *fields) -> bool {
1009 // check-ignore takes -z only with --stdin. Without
1010 // GIT_LITERAL_PATHSPECS (below) a name starting with ':' reads as
1011 // pathspec magic: "./" keeps every name a name. Git answers with the
1012 // name as given.
1013 const QString here = QStringLiteral("./");
1014 QString input;
1015 for (const QString &path : paths) {
1016 input += here + path + QChar(0);
1017 }
1018 QStringList args{QStringLiteral("check-ignore"), QStringLiteral("--stdin"),
1019 QStringLiteral("-z")};
1020 if (verbose) {
1021 args << QStringLiteral("-v");
1022 }
1023 // check-ignore refuses every path under GIT_LITERAL_PATHSPECS, which
1024 // the store's environment sets; it takes its paths as names anyway.
1025 QProcessEnvironment environment = storeEnvironment();
1026 environment.remove(QStringLiteral("GIT_LITERAL_PATHSPECS"));
1027 QProcess lookup;
1028 lookup.setProcessEnvironment(environment);
1029 QString out;
1030 QString err;
1031 (void)Executor::executeBlocking(lookup, m_settings.passExecutable,
1032 QStringList{QStringLiteral("git")} +
1033 inRepository(repository, args),
1034 input, &out, &err);
1035 // pass git exits 0 whatever git did: a lookup that failed shows only on
1036 // stderr.
1037 if (!err.trimmed().isEmpty()) {
1038 return false;
1039 }
1040 *fields = out.split(QChar(0));
1041 if (!fields->isEmpty() && fields->constLast().isEmpty()) {
1042 fields->removeLast();
1043 }
1044 // The path is every field, or every fourth with -v.
1045 const qsizetype step = verbose ? 4 : 1;
1046 for (qsizetype i = step - 1; i < fields->size(); i += step) {
1047 if ((*fields)[i].startsWith(here)) {
1048 (*fields)[i].remove(0, here.size());
1049 }
1050 }
1051 return true;
1052}
1053
1054void RealPass::Insert(QString file, QString newValue, bool overwrite) {
1055 if (refuseLinkedPath(file + ".gpg")) {
1056 return;
1057 }
1058 const QString entry =
1059 QDir::cleanPath(Util::joinPath(m_settings.passStore, file) + ".gpg");
1060 if (refuseLineBreakName(entry)) {
1061 return;
1062 }
1063 if (refuseUnverifiedList(entry)) {
1064 return;
1065 }
1067 refuseUnrecordedChanges({}, {entry})) {
1068 return;
1069 }
1070 // A line two key blocks hold may encrypt to either; last, so the
1071 // refusals above run no gpg.
1073 return;
1074 }
1075 m_insertQueue.enqueue(entry);
1076 // Past every refusal: this insert is now queued and will report once.
1077 queueInsert(entry);
1078 QStringList args = {"insert", "-m"};
1079 if (overwrite) {
1080 args.append("-f");
1081 }
1082 // pass takes every name as one below the store root: an absolute one
1083 // would be saved under <store>/<the whole path>, for the root's list
1084 // rather than the one refuseUnverifiedList() checked.
1085 // A name that starts with a dash is still the entry, not an option.
1086 args.append(QStringLiteral("--"));
1087 args.append(passName(entry, true));
1088 executePass(PASS_INSERT, args, newValue);
1089}
1090
1091void RealPass::onDequeuing(int id, bool completes) {
1092 if (id == PASS_INIT || id == PASS_MOVE || id == PASS_COPY) {
1093 // Leaves the queue with its command: a dropped one's scope must not
1094 // pair with the next completion.
1095 const QString scope =
1096 m_reencryptScopes.isEmpty() ? QString() : m_reencryptScopes.dequeue();
1097 if (!completes) {
1098 return;
1099 }
1100 m_reencryptPending.enqueue(scope);
1101 // pass exits 0 when it could not re-encrypt an entry (reencrypt_path
1102 // drops the temporary and carries on), so its exit code says nothing.
1103 // gpg's status lines do, in every locale: on stderr (fd 1 is the
1104 // `gpg -d | gpg -e` pipe), for this one process (Pass resets the
1105 // environment before each start), the last --status-fd winning over a
1106 // user's own; pass's own `--status-fd=1` for verifying a signed
1107 // .gpg-id comes later on its command line and still wins. WSLENV
1108 // already forwards PASSWORD_STORE_GPG_OPTS.
1109 QProcessEnvironment environment = exec.environment();
1110 const QString key = QStringLiteral("PASSWORD_STORE_GPG_OPTS");
1111 environment.insert(
1112 key,
1113 (environment.value(key) + QStringLiteral(" --status-fd 2")).trimmed());
1114 exec.setEnvironment(environment);
1115 return;
1116 }
1117 if (id != PASS_INSERT || m_insertQueue.isEmpty()) {
1118 return;
1119 }
1120 const QString target = m_insertQueue.dequeue();
1121 if (completes) {
1122 m_insertPending.enqueue({target, entryFingerprint(target)});
1123 }
1124}
1125
1126auto RealPass::insertWritten(const QString &err) const -> bool {
1127 if (m_insertDone.target.isEmpty()) {
1128 return false;
1129 }
1130 // gpg broke off (a full disk, killed): pass says so, and what gpg left
1131 // at the entry's name, if anything, is no entry. The line is pass's own
1132 // (`die "Password encryption aborted."` after gpg in cmd_insert and
1133 // cmd_edit of password-store.sh), which pass does not translate.
1134 if (err.contains(QLatin1String("Password encryption aborted."))) {
1135 return false;
1136 }
1137 // pass writes the new ciphertext to the entry's name before it commits,
1138 // and an encryption never gives the same bytes twice (a fresh session
1139 // key), so an edited entry has changed as surely as a new one appeared.
1140 const QByteArray after = entryFingerprint(m_insertDone.target);
1141 return !after.isEmpty() && after != m_insertDone.before;
1142}
1143
1144auto RealPass::entryFingerprint(const QString &path) -> QByteArray {
1145 QFile file;
1146 if (!Util::openRegularFile(path, file)) {
1147 return {};
1148 }
1149 // The size and the head only: this runs on the GUI thread before every
1150 // insert, and a co-writer could pad an entry to gigabytes. An encryption
1151 // never gives the same head twice, as the session key encrypted to each
1152 // recipient comes first and is fresh every time.
1153 constexpr qint64 kHeadBytes = qint64{64} * 1024;
1154 const QByteArray head = file.read(kHeadBytes);
1155 if (head.isEmpty() && file.size() > 0) {
1156 return {};
1157 }
1158 QCryptographicHash hash(QCryptographicHash::Sha256);
1159 hash.addData(QByteArray::number(file.size()) + '\n');
1160 hash.addData(head);
1161 return hash.result();
1162}
1163
1164void RealPass::removeLinkedFolder(const QString &full) {
1165 if (!Util::removeTree(full)) {
1166 const QString why = tr("Could not remove the link %1.").arg(full);
1167 emit critical(tr("Delete failed"), why);
1168 emit processErrorExit(1, why);
1169 return;
1170 }
1171 if (m_settings.useGit) {
1172 // `pass git` exits 0 whatever git did, so ask by output whether git
1173 // knew the link (these quick lookups block; the commit is queued).
1174 const QString rel = QDir(m_settings.passStore).relativeFilePath(full);
1175 // With the store's environment (PASSWORD_STORE_DIR), as executePass.
1176 QString known;
1177 QString err;
1178 // The link is gone from disk either way. A failed lookup or rm leaves
1179 // git tracking it: say so rather than report a clean removal.
1180 bool recorded = Executor::executeBlocking(
1182 {"git", "ls-files", "--", rel}, &known, &err) == 0;
1183 if (recorded && !known.trimmed().isEmpty()) {
1184 recorded =
1187 {"git", "rm", "-q", "--cached", "--", rel}, &known, &err) == 0;
1188 if (recorded) {
1189 // `pass git commit` is git's commit as it is: pass adds -S only
1190 // to the commits it makes itself, so ask as its git_commit() does.
1191 QString signs;
1192 const bool sign =
1195 {"git", "config", "--bool", "--get", "pass.signcommits"},
1196 &signs, nullptr) == 0 &&
1197 signs.trimmed() == QLatin1String("true");
1198 QStringList commit{"git", "commit", "-q"};
1199 if (sign) {
1200 commit << "-S";
1201 }
1202 // Queued, as every other commit, so a signer or hook that waits
1203 // (a pinentry, an agent) does not freeze the window; finished()
1204 // judges it by what is left staged, since `pass git` exits 0
1205 // whatever git did.
1206 m_linkCommits.enqueue(
1209 commit + QStringList{"-m",
1210 "Remove for " + rel + " using QtPass.",
1211 "--", rel});
1212 return;
1213 }
1214 }
1215 if (!recorded) {
1216 const QString why =
1217 tr("The link %1 was removed, but git could not record it: %2")
1218 .arg(rel, err.trimmed());
1219 emit critical(tr("Delete incomplete"), why);
1220 emit processErrorExit(1, why);
1221 }
1222 }
1223 // Nothing ran for pass to finish: the removal is done here, and the
1224 // store changed.
1225 emit finishedRemove(QString(), QString());
1226}
1227
1228void RealPass::Remove(QString file, bool isDir) {
1229 // Nothing behind a link is the store's to delete.
1230 if (refuseLinkedPath(isDir ? file : file + ".gpg", LinkScope::ParentsOnly)) {
1231 return;
1232 }
1234 return;
1235 }
1236 // pass rm turns a folder into "<folder>/" and rm -rf then follows a link
1237 // and empties its target, so a linked folder is unlinked here and pass's
1238 // git is only asked to forget it. pass rm -f on a linked .gpg unlinks.
1239 const QString full = QDir::cleanPath(m_settings.passStore + file);
1240 if (isDir && Util::isLinkedFolder(full)) {
1241 removeLinkedFolder(full);
1242 return;
1243 }
1244 executePass(PASS_REMOVE, {"rm", (isDir ? "-rf" : "-f"), "--", file});
1245}
1246
1247void RealPass::finished(int id, int exitCode, const QString &out,
1248 const QString &err) {
1249 if (static_cast<PROCESS>(id) == GIT_COMMIT && !m_linkCommits.isEmpty()) {
1250 // Whatever the exit code (pass itself failing, or 0 whatever git
1251 // did), what is left staged decides.
1252 finishLinkCommit(m_linkCommits.dequeue(), out, err);
1253 return;
1254 }
1255 if (static_cast<PROCESS>(id) == PASS_INSERT) {
1256 // This completion's own insert, not whichever left the queue last.
1257 m_insertDone =
1258 m_insertPending.isEmpty() ? InsertRecord{} : m_insertPending.dequeue();
1259 }
1260 const auto pid = static_cast<PROCESS>(id);
1261 if (pid == PASS_INIT || pid == PASS_MOVE || pid == PASS_COPY) {
1262 finishRecipientRun(pid, exitCode, out, err);
1263 return;
1264 }
1265 if (pid == PASS_INSERT && exitCode == 0 && !m_insertDone.target.isEmpty()) {
1267 }
1268 Pass::finished(id, exitCode, out, err);
1269}
1270
1273void RealPass::finishRecipientRun(PROCESS pid, int exitCode, const QString &out,
1274 const QString &err) {
1275 // Without a recorded scope (not queued through Init/Move/Copy), the
1276 // whole store: held as a whole, released by nothing short of it.
1277 const QString scope =
1278 m_reencryptPending.isEmpty() ? QString() : m_reencryptPending.dequeue();
1279 // Counted by the Executor over the whole of stderr: err itself is
1280 // capped. Outside an emission of its own (a test driving finished())
1281 // there is no count, and err is all there is.
1282 const QHash<QString, qint64> status = exec.lastStatusCounts();
1283 if (exitCode == 0 && (status.isEmpty() ? reencryptFailed(out, err)
1284 : reencryptFailed(out, status))) {
1285 holdAutoPush(scope);
1287 reportReencryptFailure(pid, out, err);
1288 return;
1289 }
1290 // A run that failed may have stopped after its commit (pass init commits
1291 // the new .gpg-id before re-encrypting; signing it may fail, the process
1292 // may be killed): held as well, until a clean init covers it. A move or
1293 // copy that failed before re-encrypting anything (the destination
1294 // exists, a mistyped name) changed no recipients: not held.
1295 if (exitCode != 0 &&
1296 (pid == PASS_INIT || out.contains(QLatin1String(": reencrypting to ")))) {
1297 holdAutoPush(scope);
1298 }
1299 // pass init re-encrypts everything under its folder: a clean run
1300 // releases the holds there. A move or copy covers only its entries.
1301 if (pid == PASS_INIT && exitCode == 0 && !scope.isEmpty()) {
1302 releaseAutoPush(scope);
1303 }
1304 if (exitCode == 0 && !scope.isEmpty()) {
1305 reportUnrecorded({scope});
1306 }
1308 // The status lines are for this check, not for the output panel.
1309 Pass::finished(pid, exitCode, out, withoutStatusLines(err));
1310}
1311
1312auto RealPass::reencryptFailed(const QString &out, const QString &err) -> bool {
1313 Executor::CappedOutput counter;
1314 counter.append(err.toUtf8());
1315 counter.take();
1316 return reencryptFailed(out, counter.statusCounts());
1317}
1318
1319auto RealPass::reencryptFailed(const QString &out,
1320 const QHash<QString, qint64> &status) -> bool {
1321 // pass's own line for each entry it re-encrypts ("name: reencrypting to
1322 // KEY..."), which it does not translate; one per line, counted once
1323 // even when the entry's own name holds the words.
1324 const QStringList outLines = out.split(QLatin1Char('\n'));
1325 const auto attempts = std::count_if(
1326 outLines.cbegin(), outLines.cend(), [](const QString &line) {
1327 return line.contains(QLatin1String(": reencrypting to "));
1328 });
1329 // A recipient gpg cannot encrypt to, or a decrypt that failed (no
1330 // secret key, pinentry cancelled, no smartcard): that entry was left as
1331 // it was. KEYEXPIRED and NO_SECKEY alone are not failures.
1332 for (const QLatin1String failure :
1333 {QLatin1String("INV_RECP"), QLatin1String("FAILURE"),
1334 QLatin1String("DECRYPTION_FAILED")}) {
1335 if (status.value(failure) > 0) {
1336 return true;
1337 }
1338 }
1339 // Without any status line the option did not reach gpg (a pass that does
1340 // not pass PASSWORD_STORE_GPG_OPTS on): nothing to judge by.
1341 return !status.isEmpty() &&
1342 status.value(QStringLiteral("END_ENCRYPTION")) < attempts;
1343}
1344
1345void RealPass::reportReencryptFailure(PROCESS pid, const QString &out,
1346 const QString &err) {
1347 QStringList failures;
1348 for (QString line : err.split(QLatin1Char('\n'))) {
1349 line.remove(QLatin1Char('\r'));
1350 // Encrypt-side only: gpgErrorMessage() reads any FAILURE as a key that
1351 // cannot encrypt, wrong advice for a decrypt that failed (no secret
1352 // key, pinentry cancelled), whose reason gpg's own text gives.
1353 if (line.startsWith(QLatin1String("[GNUPG:] INV_RECP ")) ||
1354 line.startsWith(QLatin1String("[GNUPG:] FAILURE encrypt"))) {
1355 failures << line;
1356 }
1357 }
1358 const QString human = withoutStatusLines(err).trimmed();
1359 const QString reason = gpgErrorMessage(failures.join(QLatin1Char('\n')));
1360 QString body =
1361 tr("The recipients were changed, but some entries could not be "
1362 "re-encrypted for them: those are still encrypted to the previous "
1363 "recipients, who can still read them. With Git the change is "
1364 "committed locally and not pushed: QtPass does not push this store "
1365 "automatically until a re-encryption succeeds, and a push by hand "
1366 "sends it.");
1367 for (const QString &part : {reason, human}) {
1368 if (!part.isEmpty()) {
1369 body += QStringLiteral("\n\n") + part;
1370 }
1371 }
1372 // pass's "reencrypting to" lines and gpg's own text, for the output panel.
1373 emit finishedAnyWithPid(out, human, pid);
1374 emit critical(
1375 QCoreApplication::translate("ImitatePass", "Re-encryption failed"), body);
1376 // Not finishedInit/Move/Copy: that would push the store as it now is.
1377 emit processErrorExit(1, body);
1378}
1379
1380void RealPass::finishLinkCommit(const LinkCommit &commit, const QString &out,
1381 const QString &err) {
1382 // In the store the commit ran in, which a profile switch meanwhile does
1383 // not change.
1384 const QString &rel = commit.rel;
1385 QString staged;
1386 const bool committed =
1388 commit.environment, commit.passExecutable,
1389 {"git", "diff", "--cached", "--name-only", "--", rel}, &staged,
1390 nullptr) == 0 &&
1391 staged.trimmed().isEmpty();
1392 if (committed) {
1393 // As Pass::finished() would: git's output (a hook's warning, say) for
1394 // the output panel, then the removal.
1395 emit finishedAnyWithPid(out, err, GIT_COMMIT);
1396 emit finishedRemove(out, err);
1397 return;
1398 }
1399 const QString why = tr("The link %1 was removed and git no longer tracks "
1400 "it, but the commit failed: %2")
1401 .arg(rel, err.trimmed());
1402 emit critical(tr("Delete incomplete"), why);
1403 emit processErrorExit(1, why);
1404 emit finishedRemove(QString(), QString());
1405}
1406
1407void RealPass::Init(QString path, const QList<UserInfo> &users) {
1408 // A relative path names a folder in the store, as --path does for pass:
1409 // resolved once, so the checks below look where pass writes, not in the
1410 // working directory.
1411 const QString folder =
1412 QDir::cleanPath(Util::joinPath(m_settings.passStore, path));
1413 // pass init writes .gpg-id with a shell redirection and gpg writes the
1414 // signature with --output; both follow a link planted under those names.
1415 // --path is store-relative, or pass creates passStore/passStore/dir: the
1416 // store check hands it over as it judged it, so a store root reached
1417 // through a link and a folder spelled through its target agree (a lexical
1418 // relativeFilePath() made that ../../target/dir, which pass refuses).
1419 QString dirWithoutPassdir;
1420 const auto refusePlaced = [this](const QString &placed) {
1423 };
1424 if (refusePlaced(folder) ||
1425 refusePlaced(folder + QStringLiteral("/.gpg-id")) ||
1426 refusePlaced(folder + QStringLiteral("/.gpg-id.sig")) ||
1427 refuseFolderOutsideStore(folder, &dirWithoutPassdir)) {
1428 return;
1429 }
1430 // pass init writes this folder's list and then re-encrypts everything
1431 // under it to each entry's nearest list, a deeper folder's own included:
1432 // those are checked as for a move. This folder's list is the one being
1433 // written, so it is neither verified nor missed. Walked in the store's
1434 // own spelling: a folder spelled through the target of a linked store
1435 // root is not under the store as named, and the lookup of each nearest
1436 // list would stop at once and miss the deeper ones.
1437 const QString inStore =
1438 QDir::cleanPath(Util::joinPath(m_settings.passStore, dirWithoutPassdir));
1439 if (refuseUnverifiedTree(inStore, true,
1440 QDir(inStore).filePath(QStringLiteral(".gpg-id")))) {
1441 return;
1442 }
1444 refuseUnrecordedChanges({inStore}, {inStore})) {
1445 return;
1446 }
1447 // pass writes the list once `pass init` runs: under initIfUnchanged() it
1448 // must start now, with nothing queued before it, and the list is compared
1449 // as late as that allows.
1451 return;
1452 }
1453 QStringList args = {"init", "--path=" + dirWithoutPassdir};
1454 for (const UserInfo &user : users) {
1455 if (user.enabled) {
1456 args.append(user.key_id);
1457 }
1458 }
1459 // A line two key blocks hold may encrypt to either: the new list and every
1460 // list below that pass re-encrypts to, after the refusals above, so those
1461 // still run no gpg.
1463 enabledKeyLines(users) +
1464 listLinesUnder(inStore,
1465 QDir(inStore).filePath(QStringLiteral(".gpg-id"))))) {
1466 return;
1467 }
1468 m_reencryptScopes.enqueue(inStore);
1469 executePass(PASS_INIT, args);
1470}
1471
1472void RealPass::Move(const QString src, const QString dest, const bool force) {
1473 passMoveOrCopy(PASS_MOVE, QStringLiteral("mv"), src, dest, force);
1474}
1475
1476void RealPass::Copy(const QString src, const QString dest, const bool force) {
1477 passMoveOrCopy(PASS_COPY, QStringLiteral("cp"), src, dest, force);
1478}
1479
1480auto RealPass::passName(const QString &path, bool stripGpg) const -> QString {
1481 QString name =
1482 QDir(QDir::cleanPath(m_settings.passStore))
1483 .relativeFilePath(QDir::cleanPath(QDir(path).absolutePath()));
1484 if (stripGpg) {
1485 name.replace(Util::endsWithGpg(), "");
1486 }
1487 return name;
1488}
1489
1490namespace {
1498auto sameObject(const QString &a, const QString &b) -> bool {
1499#ifdef Q_OS_WIN
1500 const QString canonical = QFileInfo(a).canonicalFilePath();
1501 return !canonical.isEmpty() &&
1502 canonical.compare(QFileInfo(b).canonicalFilePath(),
1503 Qt::CaseInsensitive) == 0;
1504#else
1505 struct stat first{};
1506 struct stat second{};
1507 return ::stat(QFile::encodeName(a).constData(), &first) == 0 &&
1508 ::stat(QFile::encodeName(b).constData(), &second) == 0 &&
1509 first.st_dev == second.st_dev && first.st_ino == second.st_ino;
1510#endif
1511}
1512} // namespace
1513
1514auto RealPass::passMoveTarget(const QString &src, const QString &dest) const
1515 -> PassMoveTarget {
1516 const QFileInfo srcInfo(src);
1517 const QFileInfo destInfo(dest);
1518 PassMoveTarget target;
1519 // A folder's name ends in a slash: without it pass takes an entry of the
1520 // same name beside the folder. pass appends .gpg to an entry itself.
1521 target.passSrc =
1522 srcInfo.isDir()
1523 ? passName(src, false) + QLatin1Char('/')
1524 : passName(src, srcInfo.isFile() &&
1525 srcInfo.suffix() == QLatin1String("gpg"));
1526 // An entry named with .gpg would come out as "name.gpg.gpg"; the
1527 // destination usually does not exist yet.
1528 target.passDest = passName(
1529 dest, !destInfo.isDir() && destInfo.suffix() == QLatin1String("gpg"));
1530 target.newPath = QDir::cleanPath(
1531 Util::joinPath(QDir::cleanPath(m_settings.passStore), target.passDest));
1532 // `[[ -d $old_path || -d $new_path ]] || new_path="${new_path}.gpg"`;
1533 // -d follows a link, as isDir() does.
1534 if (!srcInfo.isDir() && !QFileInfo(target.newPath).isDir()) {
1535 target.newPath += QLatin1String(".gpg");
1536 }
1537 target.written = QFileInfo(target.newPath).isDir()
1538 ? Util::joinPath(target.newPath, srcInfo.fileName())
1539 : target.newPath;
1540 return target;
1541}
1542
1543void RealPass::passMoveOrCopy(PROCESS id, const QString &subcommand,
1544 const QString &src, const QString &dest,
1545 const bool force) {
1546 if (refuseLinkedPath(src)) {
1547 return;
1548 }
1549 // Everything below judges where pass puts the source, not dest as spelled
1550 // here: pass appends .gpg, or moves into a folder (or a link to one) of
1551 // the destination's name. Its folders count too: mv into a linked folder
1552 // moves out of the store, and cp writes through a link at the name.
1553 const PassMoveTarget target = passMoveTarget(src, dest);
1554 if (refuseLinkedPath(target.written)) {
1555 return;
1556 }
1557
1558 // pass re-encrypts a moved or copied entry at its new place, and gpg
1559 // never returns from a FIFO named like one.
1560 const QFileInfo srcFileInfo(src);
1561 if (refuseSpecialEntry(srcFileInfo.exists() && !srcFileInfo.isFile() &&
1562 !srcFileInfo.isDir()
1563 ? src
1564 : QString())) {
1565 return;
1566 }
1567
1568 if (stopsAtOccupiedTarget(id, src, srcFileInfo, dest, target.written,
1569 force) ||
1570 refuseMoveOrCopyRisks(id, src, srcFileInfo, target)) {
1571 return;
1572 }
1573
1574 QStringList args;
1575 args << subcommand;
1576 if (force) {
1577 args << "-f";
1578 }
1579 // A source or destination that begins with "-" is a path, not an option.
1580 args << "--";
1581 args << target.passSrc;
1582 args << target.passDest;
1583 m_reencryptScopes.enqueue(target.newPath);
1584 executePass(id, args);
1585}
1586
1587auto RealPass::stopsAtOccupiedTarget(PROCESS id, const QString &src,
1588 const QFileInfo &srcFileInfo,
1589 const QString &dest,
1590 const QString &occupied, bool force)
1591 -> bool {
1592 // pass always forces when called from QtPass, so refuse file-onto-file:
1593 // the user declined to overwrite it.
1594 if (!force && srcFileInfo.isFile() && QFileInfo(dest).isFile()) {
1595 return true;
1596 }
1597 // Nor anything else already where pass writes: the entry of that name in
1598 // a folder an entry is dropped on or renamed into, or a folder of the
1599 // moved folder's name inside the one it goes into, which cp -r merges
1600 // into, writing through a link inside it. Force is consent for the entry
1601 // named as dest only.
1602 if (!QFileInfo::exists(occupied)) {
1603 return false;
1604 }
1605 if (sameObject(occupied, src)) {
1606 // The source itself. Renamed to its own name or dropped on its own
1607 // folder: nothing to do. Respelled in case only on a case-insensitive
1608 // file system: pass renames it.
1609 return occupied == QDir::cleanPath(QDir(src).absolutePath());
1610 }
1611 if (force && srcFileInfo.isFile() &&
1612 occupied == QDir::cleanPath(QDir(dest).absolutePath())) {
1613 return false;
1614 }
1615 const QString why =
1616 tr("%1 already exists, and pass would replace it. Nothing was "
1617 "changed; rename one of them first.")
1618 .arg(QDir::toNativeSeparators(occupied));
1620 emit critical(id == PASS_MOVE ? tr("Not moved") : tr("Not copied"), why);
1621 emit processErrorExit(1, why);
1622 return true;
1623}
1624
1625auto RealPass::refuseMoveOrCopyRisks(PROCESS id, const QString &src,
1626 const QFileInfo &srcFileInfo,
1627 const PassMoveTarget &target) -> bool {
1628 // pass re-encrypts what it moves or copies to the destination's list, a
1629 // folder's entries also to the lists that go along with it, and, when it
1630 // writes into an existing folder, everything already in that folder too
1631 // (reencrypt_path on the whole destination).
1632 const bool intoFolder = QFileInfo(target.newPath).isDir();
1633 if (refuseUnverifiedList(target.written) ||
1634 (srcFileInfo.isDir() && refuseUnverifiedTree(src, true)) ||
1635 (intoFolder && refuseUnverifiedTree(target.newPath, false))) {
1636 return true;
1637 }
1638 // cp -r follows a link inside the folder on BSD and macOS.
1639 if (id == PASS_COPY && srcFileInfo.isDir() && refuseLinkInCopiedFolder(src)) {
1640 return true;
1641 }
1642 // pass stages what it moved or copied with `git add` on the new path,
1643 // and a folder brings whatever lies in it along. It commits there, and a
1644 // move commits the removal where the original was as well.
1645 const QStringList committing = id == PASS_MOVE
1646 ? QStringList{src, target.newPath}
1647 : QStringList{target.newPath};
1649 refuseUnrecordedChanges({src, target.newPath}, committing) ||
1650 refuseIgnoredThatMoves(src, target.newPath)) {
1651 return true;
1652 }
1653 // A line two key blocks hold may encrypt to either: every list pass
1654 // re-encrypts to here, last, so the refusals above run no gpg.
1656 linesPassEncryptsTo(src, target, srcFileInfo.isDir(), intoFolder));
1657}
1658
1659auto RealPass::linesPassEncryptsTo(const QString &src,
1660 const PassMoveTarget &target, bool srcIsDir,
1661 bool intoFolder) -> QStringList {
1662 QStringList lines = getRecipientList(target.written, m_settings.passStore);
1663 if (srcIsDir) {
1664 lines << listLinesUnder(src, QString());
1665 }
1666 if (intoFolder) {
1667 lines << listLinesUnder(target.newPath, QString());
1668 }
1669 return lines;
1670}
1671
1672// Not `pass grep` (find -L follows links out of the store): the native
1673// search walks real files only (Util::regularFilesUnder), so it needs gpg.
1674void RealPass::Grep(QString pattern, bool caseInsensitive) {
1675 if (m_settings.gpgExecutable.isEmpty()) {
1676 emit statusMsg(tr("Search needs the GPG executable to be configured."),
1677 5000);
1678 emit finishedGrep({});
1679 return;
1680 }
1681 m_grep.search(pattern, caseInsensitive, m_settings.gpgExecutable,
1683}
1684
1685void RealPass::executePass(PROCESS id, const QStringList &args, QString input,
1686 bool readStdout, bool readStderr) {
1687 executeWrapper(id, m_settings.passExecutable, args, std::move(input),
1688 readStdout, readStderr);
1689}
A stream of bytes held as its first and last kMaxStderrBytes / 2 bytes, with its gpg status records c...
Definition executor.h:193
void append(const QByteArray &chunk)
Add what the process wrote next.
Definition executor.cpp:89
auto take() -> QByteArray
Everything kept, and start over.
Definition executor.cpp:131
auto statusCounts() const -> QHash< QString, qint64 >
How many complete lines of each gpg status keyword came by since the last take(), the left-out ones i...
Definition executor.h:217
void dequeuing(int id, bool completes)
Emitted, synchronously, when the queue's head leaves it: just before it is started,...
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
auto environment() const -> QProcessEnvironment
Return the environment passed to child processes.
Definition executor.cpp:735
auto lastStatusCounts() const -> QHash< QString, qint64 >
The gpg status records on the stderr of the command whose finished() or error() is being emitted,...
Definition executor.h:645
void setEnvironment(const QProcessEnvironment &env)
Set the environment passed to all child processes.
Definition executor.cpp:731
The detached signature on a store's .gpg-id: whether the configured signing key is usable,...
Definition gpgidsigner.h:29
void setStoreRoot(const QString &root)
The store the lists and signatures this signer reads belong to.
Definition gpgidsigner.h:76
auto enabled() const -> bool
Whether any signing key is configured at all.
static auto keysFromSetting(const QString &passSigningKey) -> QStringList
Split the settings value into keys, upper-cased the way gpg prints fingerprints.
void finished(const QList< QPair< QString, QStringList > > &results)
The newest search is over.
void search(const QString &pattern, bool caseInsensitive, const QString &gpgExe, const QString &storeDir, const QProcessEnvironment &env)
Start a search; finished() follows asynchronously, also for an empty or invalid pattern (with no resu...
void cancel()
Ask running searches to stop without waiting for them: the walk ends at the next file and a gpg that ...
auto storeEnvironment() const -> QProcessEnvironment
The environment QtPass runs the store's processes in.
Definition pass.h:124
void startingExecuteWrapper()
Emitted each time a queued process is about to start, and by the refusals that go on to emit processE...
void finishedAnyWithPid(const QString &out, const QString &err, Enums::PROCESS pid)
A process of any kind finished successfully and its output cannot contain a secret.
AppSettings m_settings
Application settings snapshot injected at init() time.
Definition pass.h:145
static auto passReadsDifferently(const QByteArray &contents) -> QString
Why pass would read a .gpg-id differently from parseRecipients(), if it would.
Definition pass.cpp:1869
static auto getGpgIdPath(const QString &for_file, const QString &passStore) -> QString
Get .gpg-id file path for a password file.
Definition pass.cpp:1511
virtual auto encryptionReaches(const QStringList &recipients) -> std::optional< QStringList >
The keys a gpg encryption to recipients reaches: a throwaway encryption outside the store,...
Definition pass.cpp:707
auto refusePendingPull() -> bool
Refuse a store change while a Git pull is still queued or running.
Definition pass.cpp:1427
void releaseAutoPush(const QString &folder)
Release the holds a clean re-encryption of folder covers: those for folder itself and everything unde...
Definition pass.cpp:1312
Enums::PROCESS PROCESS
Alias for Enums::PROCESS used throughout this class.
Definition pass.h:154
void queueInsert(const QString &entry=QString())
Count one insert that has started queueing but not yet reported.
Definition pass.h:853
void queueShow(const QString &file)
Remember what a Show() asked for, so its completion can say so.
Definition pass.h:841
void statusMsg(const QString &msg, int timeout)
Progress or a non-fatal problem worth a line in the status bar ("Creating backup commit",...
@ PlacedByCaller
Through the target of a linked store root, by a caller that places such a folder itself (Init()): not...
Definition pass.h:879
auto pushIsAutomatic() const -> bool
Whether the GitPush() running now is an automatic one.
Definition pass.cpp:1306
void holdAutoPush(const QString &scope)
Hold automatic pushes of the store that holds scope (autoPushHeld()): its re-encryption did not finis...
Definition pass.cpp:1308
void executeWrapper(PROCESS id, const QString &app, const QStringList &args, bool readStdout=true, bool readStderr=true)
Execute external wrapper command.
Definition pass.cpp:126
auto refuseLinkedPath(const QString &path, LinkScope scope=LinkScope::EntryAndParents, PathSpelling spelling=PathSpelling::Configured) -> bool
Refuse an operation on something that is, or lies behind, a symbolic link or NTFS junction inside the...
Definition pass.cpp:1321
void finishedGrep(const QList< QPair< QString, QStringList > > &results)
The newest Grep() is over; an empty list means no entry matched.
QHash< QString, SkippedWalk > SkippedWalks
SkippedWalk per absolute folder, for one check of many folders.
Definition pass.h:165
static auto enabledKeyLines(const QList< UserInfo > &users) -> QStringList
The enabled users' key IDs, as Init() writes them to .gpg-id.
Definition pass.cpp:580
static auto linkedGpgId(const QString &forFile, const QString &passStore, LinkedWalks *walks=nullptr) -> std::optional< QString >
The link or junction under the name .gpg-id that getGpgIdPath() skips on its way up from forFile,...
Definition pass.cpp:1659
auto refuseBusyForExpectedList() -> bool
Refuse an Init() under initIfUnchanged() while the executor has work queued or running,...
Definition pass.cpp:1475
Executor exec
Internal command executor for queuing and running subprocesses.
Definition pass.h:149
void processErrorExit(int exitCode, const QString &err)
An operation ended in failure: its process exited non-zero, could not be started or crashed,...
auto verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile, QByteArray *contents, QString *why) const -> bool
Whether gpgIdFile is a signed list QtPass accepts: its signature verifies (GpgIdSigner::verifyFile())...
Definition pass.cpp:1555
auto refuseChangedList() -> bool
Refuse an Init() under initIfUnchanged() when the folder's list no longer reads as the caller read it...
Definition pass.cpp:1452
auto entryReaders(const QString &path) -> QStringList
The long key IDs an entry is encrypted to, as gpg lists them without anyone's secret key (ENC_TO).
Definition pass.cpp:664
static auto withoutStatusLines(const QString &err) -> QString
gpg's stderr without its machine-readable [GNUPG:] lines (and without carriage returns),...
Definition pass.cpp:926
auto autoPushHeld() const -> bool
Whether automatic pushes of the current store are held because its last re-encryption did not finish ...
Definition pass.cpp:1291
static auto pullTimedOut(int timeoutMs) -> QString
The status-bar text for a blocking pull stopped at its deadline.
Definition pass.cpp:1940
QHash< QString, std::optional< QString > > LinkedWalks
Definition pass.h:168
virtual void finished(int id, int exitCode, const QString &out, const QString &err)
Handle process completion.
Definition pass.cpp:860
void critical(const QString &title, const QString &message)
Something went wrong that the user has to be told about in a dialog, such as a refused path or a fail...
auto refuseSkippedGpgId(const QString &file, bool signing, const QString &except=QString(), SkippedWalks *walks=nullptr) -> bool
With signing on, refuse to encrypt file when the lookup passed over its folder's own list (skippedGpg...
Definition pass.cpp:1518
auto refuseKeyLinesHeldTwice(const QStringList &lines) -> bool
Refuse, with critical(), a recipient list with a line that more than one key block holds (keyLinesHel...
Definition pass.cpp:568
static auto getRecipientList(const QString &for_file, const QString &passStore) -> QStringList
Get list of recipients for a password file.
Definition pass.cpp:1833
@ ParentsOnly
Only the folders above it: a removal unlinks a link and touches nothing behind it.
Definition pass.h:865
@ EntryAndParents
The entry itself and every folder above it in the store.
Definition pass.h:860
void finishedRemove(const QString &out, const QString &err)
A Remove() succeeded; the entry or folder is gone from the store.
auto refuseUnfinishedGitOperation() -> bool
Refuse to change the store while git is mid-rebase, -merge, -cherry-pick or -revert.
Definition pass.cpp:1489
static auto parseRecipients(const QByteArray &contents, const QString &sourceName) -> QStringList
Parse the contents of a .gpg-id: one recipient per line, # starts a comment, unusable lines are logge...
Definition pass.cpp:1848
auto refuseFolderOutsideStore(const QString &folder, QString *relative=nullptr) -> bool
Refuse recipients for a folder outside the store, as pass refuses a path with .. in it.
Definition pass.cpp:1347
NativeGrep m_grep
Definition realpass.h:38
void finishLinkCommit(const LinkCommit &commit, const QString &out, const QString &err)
Judge a queued linked-folder removal commit by what is left staged in the store it ran in: pass git e...
void reportReencryptFailure(Enums::PROCESS pid, const QString &out, const QString &err)
Report a pass init, mv or cp that exited 0 having left entries encrypted to the previous recipients: ...
QQueue< QString > m_reencryptPending
Definition realpass.h:528
void Remove(QString file, bool isDir) override
Remove an entry or folder with pass rm.
void Init(QString path, const QList< UserInfo > &users) override
Initialize password store.
auto refuseUnrecordedChanges(const QStringList &paths, const QStringList &committing) -> bool
Refuse a pass init, mv, cp or insert when paths hold changes git has not recorded,...
Definition realpass.cpp:782
void Copy(const QString src, const QString dest, const bool force) override
Copy password file or directory.
auto entryWouldGain(const QString &entry, const QStringList &target, const QStringList &before, QHash< QString, std::optional< QSet< QString > > > &probes) -> bool
Whether pass re-encrypting entry to target would hand it to someone who cannot read it now,...
Definition realpass.cpp:360
auto unrecorded(const QStringList &paths, bool ignored) -> QStringList
What git has not recorded at paths: git status --porcelain lines, through pass git....
Definition realpass.cpp:672
auto storeGit(const QStringList &args, QString *out) -> bool override
Run a git command in the store through pass git, blocking.
Definition realpass.cpp:574
bool m_pushAfterReencrypt
Definition realpass.h:531
QQueue< InsertRecord > m_insertPending
Definition realpass.h:519
auto checkIgnore(const QString &repository, const QStringList &paths, bool verbose, QStringList *fields) -> bool
git check-ignore --stdin -z on paths through pass git.
auto refuseSpecialEntry(const QString &entry) -> bool
Refuse, and tell the user, when entry is set: an entry named like a password that is no regular file,...
Definition realpass.cpp:307
auto refuseIgnoredThatMoves(const QString &src, const QString &dest) -> bool
Refuse a pass mv or cp of the folder src when a file in it that Git ignores would not be ignored wher...
Definition realpass.cpp:919
auto passMoveTarget(const QString &src, const QString &dest) const -> PassMoveTarget
Name src and dest for pass mv/pass cp, and work out where pass 1.7.4 then puts the source.
auto stopsAtOccupiedTarget(PROCESS id, const QString &src, const QFileInfo &srcFileInfo, const QString &dest, const QString &occupied, bool force) -> bool
Whether a move or copy stops at what already lies where pass writes: a file dest the user declined to...
auto ignoredByRulesWithin(const QString &repository, const QString &from, const QStringList &moving) -> QStringList
Those of moving that a .gitignore inside the folder from ignores, by git check-ignore -v: the rule mo...
Definition realpass.cpp:992
auto entriesInitWouldWiden(const QString &dir, const QList< UserInfo > &users) -> QStringList override
Entries a pass init of dir with users would hand to someone who cannot read them now (an entry copied...
Definition realpass.cpp:405
auto entriesMoveWouldWiden(const QString &src, const QString &dest) -> QStringList override
Entries already in the place a pass mv or pass cp of src to dest re-encrypts (the whole destination f...
Definition realpass.cpp:440
auto refuseMoveOrCopyRisks(PROCESS id, const QString &src, const QFileInfo &srcFileInfo, const PassMoveTarget &target) -> bool
Whether a move or copy is refused for what pass would do along the way: re-encrypt to an unverified l...
void Insert(QString file, QString newValue, bool overwrite) override
Insert new password.
static auto reencryptFailed(const QString &out, const QString &err) -> bool
Whether a pass init, mv or cp that exited 0 left entries as they were: pass carries on past an entry ...
~RealPass() override
Destructor; lets the search workers wind down.
Definition realpass.cpp:51
void Show(QString file) override
Show decrypted password.
Definition realpass.cpp:108
InsertRecord m_insertDone
The insert whose completion is being handled.
Definition realpass.h:521
void reportUnrecorded(const QStringList &paths)
After a pass insert, init, mv or cp that exited 0, say so when git did not record the entries it wrot...
Definition realpass.cpp:857
RealPass()
Construct a RealPass instance.
Definition realpass.cpp:46
void onDequeuing(int id, bool completes)
The executor is about to run (or drop) its next item: for an insert, take its entry from m_insertQueu...
auto refuseLinkInCopiedFolder(const QString &src) -> bool
Refuse a pass cp of the folder src when anything in it is a symbolic link or NTFS junction,...
Definition realpass.cpp:876
auto refuseLinkedList(const QString &file, const QString &within=QString(), const QString &except=QString(), LinkedWalks *walks=nullptr) -> bool
Refuse to have pass encrypt file when the walk to its list meets a .gpg-id that is a link or junction...
Definition realpass.cpp:163
void passMoveOrCopy(PROCESS id, const QString &subcommand, const QString &src, const QString &dest, bool force)
Shared implementation of Move and Copy via pass mv/pass cp.
auto passName(const QString &path, bool stripGpg) const -> QString
path as pass names it: relative to the store, without the .gpg pass appends itself.
auto refuseUnverifiedList(const QString &file) -> bool
Refuse to have pass encrypt file when the list it would use is a link (refuseLinkedList()),...
Definition realpass.cpp:233
auto refuseList(const QString &file, const GpgIdSigner &signer, QSet< QString > &verified, const QString &within=QString(), const QString &except=QString(), SkippedWalks *walks=nullptr) -> bool
The checks of refuseUnverifiedList() for file's nearest list, once per list.
Definition realpass.cpp:134
auto repositoryOf(const QString &path) -> QString
The Git repository pass commits path in: the store's own, or one a folder in it holds (pass looks for...
Definition realpass.cpp:602
void sendDeferredPush()
Once the last queued init, move or copy has completed, make the push asked for meanwhile (GitPush())....
Definition realpass.cpp:91
static auto entryFingerprint(const QString &path) -> QByteArray
A SHA-256 of the size and first 64 KiB of the regular file path (opened without following a link or b...
void GitInit() override
Initialize Git repository in password store.
Definition realpass.cpp:53
QQueue< QString > m_reencryptScopes
Definition realpass.h:524
auto statusEntries(const QStringList &args, const QString &repository=QString()) -> QStringList
git status --porcelain -z through pass git, read: one "XY name" per entry, a rename's old name droppe...
Definition realpass.cpp:638
void GitPull() override
Pull changes from remote.
Definition realpass.cpp:77
auto listLinesUnder(const QString &dir, const QString &except) -> QStringList
The lines of every folder's own .gpg-id that pass's walk of dir meets, for keyLinesHeldTwice(): pass ...
Definition realpass.cpp:340
bool m_deferredPushByHand
One of those pushes was asked for by hand: it goes despite a hold.
Definition realpass.h:533
QQueue< LinkCommit > m_linkCommits
Definition realpass.h:50
void removeLinkedFolder(const QString &full)
Remove a linked folder for Remove(): unlink it here, so that pass rm -rf cannot follow it,...
void Move(const QString src, const QString dest, const bool force) override
Move password file or directory.
auto linesPassEncryptsTo(const QString &src, const PassMoveTarget &target, bool srcIsDir, bool intoFolder) -> QStringList
The recipient lines pass re-encrypts to when it moves or copies src as target says: the destination's...
void finished(int id, int exitCode, const QString &out, const QString &err) override
Finish a process; a linked-folder removal commit (GIT_COMMIT, which RealPass uses for nothing else) i...
void GitPull_b(int timeoutMs) override
Run pass git pull and wait for it, at most timeoutMs.
Definition realpass.cpp:55
void finishRecipientRun(Enums::PROCESS pid, int exitCode, const QString &out, const QString &err)
Finish a pass init, mv or cp: hold the automatic push for a run that left entries to the previous rec...
auto refuseLineBreakName(const QString &path) -> bool
Refuse, and tell the user, when the store-relative name of path holds a line feed or carriage return.
Definition realpass.cpp:322
void executePass(PROCESS id, const QStringList &args, QString input=QString(), bool readStdout=true, bool readStderr=true)
Execute pass command with arguments.
void GitPush() override
Push changes to remote.
Definition realpass.cpp:79
auto insertWritten(const QString &err) const -> bool override
Whether the failed pass insert wrote its entry before its git step failed. pass does not say,...
auto refuseMisreadList(const QString &file, const QString &within, const QString &except, QSet< QString > &checked) -> bool
Refuse to have pass encrypt file when its nearest .gpg-id holds lines pass reads differently from the...
Definition realpass.cpp:188
void Grep(QString pattern, bool caseInsensitive) override
Search all password content by GPG-decrypting each real .gpg file, as ImitatePass does.
auto refuseUnverifiedTree(const QString &dir, bool onlyListsWithin, const QString &except=QString()) -> bool
For a folder pass is about to re-encrypt in a move or copy: refuse when an entry pass's walk takes (h...
Definition realpass.cpp:499
auto listSigner() -> GpgIdSigner
The verifier for signed lists, gpg in the store's environment.
Definition realpass.cpp:120
QQueue< QString > m_insertQueue
The entries of the queued inserts, oldest first.
Definition realpass.h:515
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 hasUnreadableName(const QString &dir) -> bool
Whether dir holds an entry whose name is not valid UTF-8.
Definition util.cpp:1192
static constexpr qint64 kMaxGpgIdBytes
Most bytes of a .gpg-id QtPass reads.
Definition util.h:561
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 joinPath(const QString &dir, const QString &name) -> QString
name in dir, as the file system means it.
Definition util.cpp:110
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 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
Executor, the FIFO queue every gpg, git and pass child process of QtPass goes through,...
GpgIdSigner, which signs a store's .gpg-id and verifies an existing .gpg-id.sig against the configure...
@ PASS_INIT
Definition enums.h:53
@ PASS_INSERT
Definition enums.h:51
@ GIT_INIT
Definition enums.h:44
@ PASS_COPY
Definition enums.h:56
@ PASS_MOVE
Definition enums.h:55
@ PASS_REMOVE
Definition enums.h:52
@ GIT_COMMIT
Definition enums.h:46
@ PASS_SHOW
Definition enums.h:50
@ GIT_PULL
Definition enums.h:48
@ GIT_PUSH
Definition enums.h:49
@ PASS_INIT
Definition enums.h:53
@ PASS_INSERT
Definition enums.h:51
@ GIT_INIT
Definition enums.h:44
@ PASS_COPY
Definition enums.h:56
@ PASS_MOVE
Definition enums.h:55
@ PASS_REMOVE
Definition enums.h:52
@ GIT_COMMIT
Definition enums.h:46
@ PASS_SHOW
Definition enums.h:50
@ GIT_PULL
Definition enums.h:48
@ GIT_PUSH
Definition enums.h:49
auto gpgErrorMessage(const QString &err) -> QString
Maps GPG stderr (which may include –status-fd 2 tokens) to a translated user-friendly encryption erro...
Definition pass.cpp:808
PathValidator: is a path inside the password store, and how is it spelled relative to the store root.
The "qtpass" logging category.
RealPass, the backend that hands every store operation to the pass command-line tool.
QString gpgExecutable
Path to the gpg/gpg2 executable.
Definition appsettings.h:66
QString passStore
Password-store root path.
Definition appsettings.h:60
QString passExecutable
Path to the pass executable.
Definition appsettings.h:64
bool useGit
Enable git integration.
QString target
The entry's file.
Definition realpass.h:511
What pass mv/pass cp is handed and what it then does with it.
Definition realpass.h:124
QString passSrc
The source name handed to pass.
Definition realpass.h:125
Stores GPG key info including validity, creation date, and more.
Definition userinfo.h:20
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...