18#include <QCoreApplication>
19#include <QCryptographicHash>
21#include <QDirIterator>
22#include <QElapsedTimer>
27#include <QRegularExpression>
66 &err,
nullptr, timeoutMs);
67 if (result != 0 && timer.elapsed() >= timeoutMs) {
69 }
else if (result != 0) {
70 qCDebug(lcQtPass) <<
"Git pull failed with code:" << result;
73 emit
statusMsg(tr(
"Git pull failed: %1").arg(err.trimmed()), 5000);
100 emit
statusMsg(tr(
"Not pushing: an earlier re-encryption in this "
101 "store did not finish"),
123 [
this](
const QString &app,
const QStringList &args,
124 const QString &input, QString *out, QString *err) {
126 gpg.setProcessEnvironment(
exec.environment());
135 QSet<QString> &verified,
const QString &within,
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))) {
150 QCoreApplication::translate(
"ImitatePass",
"Signature for %1 is invalid.")
154 emit
critical(QCoreApplication::translate(
"ImitatePass",
155 "Check .gpg-id file signature!"),
159 verified.insert(gpgIdFile);
166 const std::optional<QString> linked =
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))) {
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 "
184 .arg(QDir::toNativeSeparators(*linked)));
189 const QString &except, QSet<QString> &checked)
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))) {
206 if (!bytes && QFileInfo::exists(gpgIdFile)) {
207 emit
critical(tr(
"Recipient list cannot be read"),
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),
217 const QString misread =
219 if (misread.isEmpty()) {
220 checked.insert(absolute);
223 emit
critical(tr(
"Recipient list reads differently"),
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));
241 QSet<QString> readAlike;
250 QSet<QString> verified;
262auto passFoldersUnder(
const QString &dir, QStringList &unreadable)
264 QStringList folders{QDir::cleanPath(dir)};
266 unreadable << QDir::cleanPath(dir);
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")) {
276 folders << passFoldersUnder(child.absoluteFilePath(), unreadable);
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,
297 for (
const QFileInfo &entry : entries) {
298 if (!entry.isSymLink() && !entry.isFile() && !entry.isDir()) {
299 return entry.filePath();
308 if (entry.isEmpty()) {
311 const QString title = tr(
"Not a password file");
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));
323 const QString name =
passName(path,
false);
324 if (!name.contains(QLatin1Char(
'\n')) && !name.contains(QLatin1Char(
'\r'))) {
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"),
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.")
342 QStringList unreadable;
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()) {
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();
369 std::optional<QSet<QString>> keys;
371 ids && !ids->isEmpty()) {
372 keys = QSet<QString>();
373 for (
const QString &
id : *ids) {
374 keys->insert(
id.toUpper());
377 probes.insert(key, keys);
380 const std::optional<QSet<QString>> now = probe(target);
391 QSet<QString> gaining = *now;
392 for (
const QString &
id : ids) {
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);
402 return !gaining.isEmpty();
406 const QList<UserInfo> &users)
408 const QString folder =
410 const QString ownList =
411 QDir::cleanPath(QDir(folder).filePath(QStringLiteral(
".gpg-id")));
413 QHash<QString, std::optional<QSet<QString>>> probes;
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()) {
423 const QString path = entry.absoluteFilePath();
430 list != ownList && list.startsWith(folder + QLatin1Char(
'/'));
431 const QStringList target = own ? current : newLines;
448 QHash<QString, std::optional<QSet<QString>>> probes;
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()) {
459 const QString path = entry.absoluteFilePath();
467 const QFileInfo srcInfo(src);
468 if (!srcInfo.isDir() || srcInfo.isSymLink()) {
474 const QString from = QDir::cleanPath(srcInfo.absoluteFilePath());
475 const QStringList landing =
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()) {
485 const QString path = entry.absoluteFilePath();
489 const bool alongWith = list.startsWith(from + QLatin1Char(
'/'));
490 const QStringList targetList = alongWith ? current : landing;
500 const QString &except) ->
bool {
504 QStringList unreadable;
505 const QStringList folders = passFoldersUnder(dir, unreadable);
506 if (!unreadable.isEmpty()) {
507 const QString title = tr(
"Cannot check the recipient lists");
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()));
522 const QString within =
523 onlyListsWithin ? QDir::cleanPath(QFileInfo(dir).absoluteFilePath()) +
530 QSet<QString> readAlike;
534 for (
const QString &folder : folders) {
548 emit
statusMsg(tr(
"Checking the recipient lists under %1…")
549 .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))),
558 QSet<QString> verified;
566 for (
const QString &folder : folders) {
567 if (
refuseList(folder, signer, verified, within, except, &walks)) {
583 QStringList{QStringLiteral(
"git")} + args, out, &err) == 0;
593auto inRepository(
const QString &repository,
const QStringList &args)
595 if (repository.isEmpty()) {
598 return QStringList{QStringLiteral(
"-C"), repository} + args;
606 const QString root = QDir::cleanPath(
m_settings.passStore);
608 QString folder = QDir::cleanPath(path);
609 while (!QFileInfo(folder).isDir() &&
610 folder.startsWith(root + QLatin1Char(
'/'))) {
611 folder = QFileInfo(folder).path();
613 const QString relative = QDir(root).relativeFilePath(folder);
614 if (relative == QLatin1String(
".") || relative == QLatin1String(
"..") ||
615 relative.startsWith(QLatin1String(
"../"))) {
621 storeGit({QStringLiteral(
"-C"), relative, QStringLiteral(
"rev-parse"),
622 QStringLiteral(
"--show-prefix")},
624 if (prefix.endsWith(QLatin1Char(
'\n'))) {
627 const QString withSlash = relative + QLatin1Char(
'/');
628 if (!withSlash.endsWith(prefix)) {
631 QString repository = withSlash.chopped(prefix.size());
632 if (repository.endsWith(QLatin1Char(
'/'))) {
647 storeGit(inRepository(repository, QStringList{QStringLiteral(
"status"),
648 QStringLiteral(
"--porcelain"),
649 QStringLiteral(
"-z")} +
652 const QString place =
653 repository.isEmpty() ? QString() : repository + QLatin1Char(
'/');
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(
' ')) {
661 entries << field.left(3) + place + field.mid(3);
664 if (field.at(0) == QLatin1Char(
'R') || field.at(0) == QLatin1Char(
'C') ||
665 field.at(1) == QLatin1Char(
'R') || field.at(1) == QLatin1Char(
'C')) {
674 if (paths.isEmpty()) {
677 const QDir store(QDir::cleanPath(
m_settings.passStore));
680 QMap<QString, QStringList> byRepository;
681 for (
const QString &path : paths) {
683 const QDir top(repository.isEmpty() ? store.path()
684 : store.filePath(repository));
685 byRepository[repository] << top.relativeFilePath(QDir::cleanPath(path));
688 for (
auto it = byRepository.cbegin(); it != byRepository.cend(); ++it) {
689 QStringList args{QStringLiteral(
"--untracked-files=all")};
691 args << QStringLiteral(
"--ignored");
693 args << QStringLiteral(
"--");
709auto fileManagerFiles(
const QStringList &lines, QStringList *paths)
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)) {
721 *paths << line.mid(3);
733auto isStoreFileName(
const QString &name) ->
bool {
734 return name.endsWith(QLatin1String(
".gpg")) ||
735 name == QLatin1String(
".gpg-id") ||
736 name == QLatin1String(
".gpg-id.sig");
740constexpr qsizetype kMaxNamedChanges = 10;
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));
768auto exposedWhereLanded(
const QStringList &moving,
const QStringList &landed,
769 const QStringList &travelling,
770 const QStringList &ignoredThere) -> QStringList {
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);
783 const QStringList &committing) ->
bool {
784 QStringList changes =
unrecorded(paths,
false);
785 QStringList repositories;
786 for (
const QString &path : committing) {
788 if (!repositories.contains(repository)) {
789 repositories << repository;
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)) {
803 if (changes.isEmpty()) {
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));
814 QStringList writtenAt;
815 const QStringList written = fileManagerFiles(changes, &writtenAt);
816 if (!written.isEmpty()) {
817 const QDir store(QDir::cleanPath(
m_settings.passStore));
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)) {
830 const QString name = QFileInfo(path).fileName();
831 if (!namesFor[file].contains(name)) {
832 namesFor[file] << name;
836 for (
const QString &file : std::as_const(ignoreFiles)) {
837 blocks << file + QStringLiteral(
":\n") +
838 namesFor.value(file).join(QLatin1Char(
'\n'));
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:"
846 .arg(written.join(QStringLiteral(
", ")),
847 blocks.join(QStringLiteral(
"\n\n")));
852 emit
critical(tr(
"Changes Git has not recorded"), why);
859 for (
const QString &line :
unrecorded(paths,
true)) {
862 if (isStoreFileName(QFileInfo(line.mid(3)).fileName())) {
866 if (changes.isEmpty()) {
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)));
877 QStringList folders{src};
881 while (!folders.isEmpty() && found.isEmpty() && unreadable.isEmpty()) {
882 QDirIterator it(folders.takeFirst(), QDir::AllEntries | QDir::Hidden |
884 QDir::NoDotAndDotDot);
885 while (it.hasNext()) {
886 const QString path = it.next();
891 if (it.fileInfo().isDir()) {
900 if (found.isEmpty() && unreadable.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);
921 if (!
m_settings.useGit || !QFileInfo(src).isDir()) {
924 const QDir store(QDir::cleanPath(
m_settings.passStore));
926 const QString landing = QFileInfo(dest).isDir()
934 QDir(fromRepository.isEmpty() ? store.path()
935 : store.filePath(fromRepository))
936 .relativeFilePath(QDir::cleanPath(src));
938 QDir(toRepository.isEmpty() ? store.path() : store.filePath(toRepository))
939 .relativeFilePath(QDir::cleanPath(landing));
944 inRepository(fromRepository,
945 {QStringLiteral(
"ls-files"), QStringLiteral(
"-z"),
946 QStringLiteral(
"--others"), QStringLiteral(
"--ignored"),
947 QStringLiteral(
"--exclude-standard"), QStringLiteral(
"--"),
952 for (
const QString &file : out.split(QChar(0), Qt::SkipEmptyParts)) {
953 if (!file.startsWith(from + QLatin1Char(
'/')) ||
954 isStoreFileName(QFileInfo(file).fileName())) {
958 landed << to + file.mid(from.size());
960 if (landed.isEmpty()) {
967 const QStringList travelling =
968 QFileInfo::exists(landing)
972 QStringList ignoredThere;
973 if (!
checkIgnore(toRepository, landed,
false, &ignoredThere)) {
974 ignoredThere.clear();
976 const QStringList exposed =
977 exposedWhereLanded(moving, landed, travelling, ignoredThere);
978 if (exposed.isEmpty()) {
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);
994 const QStringList &moving) -> QStringList {
995 QStringList travelling;
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);
1008 bool verbose, QStringList *fields) ->
bool {
1013 const QString here = QStringLiteral(
"./");
1015 for (
const QString &path : paths) {
1016 input += here + path + QChar(0);
1018 QStringList args{QStringLiteral(
"check-ignore"), QStringLiteral(
"--stdin"),
1019 QStringLiteral(
"-z")};
1021 args << QStringLiteral(
"-v");
1026 environment.remove(QStringLiteral(
"GIT_LITERAL_PATHSPECS"));
1028 lookup.setProcessEnvironment(environment);
1032 QStringList{QStringLiteral(
"git")} +
1033 inRepository(repository, args),
1037 if (!err.trimmed().isEmpty()) {
1040 *fields = out.split(QChar(0));
1041 if (!fields->isEmpty() && fields->constLast().isEmpty()) {
1042 fields->removeLast();
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());
1058 const QString entry =
1078 QStringList args = {
"insert",
"-m"};
1086 args.append(QStringLiteral(
"--"));
1087 args.append(
passName(entry,
true));
1095 const QString scope =
1110 const QString key = QStringLiteral(
"PASSWORD_STORE_GPG_OPTS");
1113 (environment.value(key) + QStringLiteral(
" --status-fd 2")).trimmed());
1134 if (err.contains(QLatin1String(
"Password encryption aborted."))) {
1141 return !after.isEmpty() && after !=
m_insertDone.before;
1153 constexpr qint64 kHeadBytes = qint64{64} * 1024;
1154 const QByteArray head = file.read(kHeadBytes);
1155 if (head.isEmpty() && file.size() > 0) {
1158 QCryptographicHash hash(QCryptographicHash::Sha256);
1159 hash.addData(QByteArray::number(file.size()) +
'\n');
1161 return hash.result();
1166 const QString why = tr(
"Could not remove the link %1.").arg(full);
1167 emit
critical(tr(
"Delete failed"), why);
1182 {
"git",
"ls-files",
"--", rel}, &known, &err) == 0;
1183 if (recorded && !known.trimmed().isEmpty()) {
1187 {
"git",
"rm",
"-q",
"--cached",
"--", rel}, &known, &err) == 0;
1195 {
"git",
"config",
"--bool",
"--get",
"pass.signcommits"},
1196 &signs,
nullptr) == 0 &&
1197 signs.trimmed() == QLatin1String(
"true");
1198 QStringList commit{
"git",
"commit",
"-q"};
1209 commit + QStringList{
"-m",
1210 "Remove for " + rel +
" using QtPass.",
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);
1248 const QString &err) {
1260 const auto pid =
static_cast<PROCESS>(id);
1274 const QString &err) {
1277 const QString scope =
1295 if (exitCode != 0 &&
1296 (pid ==
PASS_INIT || out.contains(QLatin1String(
": reencrypting to ")))) {
1301 if (pid ==
PASS_INIT && exitCode == 0 && !scope.isEmpty()) {
1304 if (exitCode == 0 && !scope.isEmpty()) {
1314 counter.
append(err.toUtf8());
1320 const QHash<QString, qint64> &status) ->
bool {
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 "));
1332 for (
const QLatin1String failure :
1333 {QLatin1String(
"INV_RECP"), QLatin1String(
"FAILURE"),
1334 QLatin1String(
"DECRYPTION_FAILED")}) {
1335 if (status.value(failure) > 0) {
1341 return !status.isEmpty() &&
1342 status.value(QStringLiteral(
"END_ENCRYPTION")) < attempts;
1346 const QString &err) {
1347 QStringList failures;
1348 for (QString line : err.split(QLatin1Char(
'\n'))) {
1349 line.remove(QLatin1Char(
'\r'));
1353 if (line.startsWith(QLatin1String(
"[GNUPG:] INV_RECP ")) ||
1354 line.startsWith(QLatin1String(
"[GNUPG:] FAILURE encrypt"))) {
1359 const QString reason =
gpgErrorMessage(failures.join(QLatin1Char(
'\n')));
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 "
1367 for (
const QString &part : {reason, human}) {
1368 if (!part.isEmpty()) {
1369 body += QStringLiteral(
"\n\n") + part;
1375 QCoreApplication::translate(
"ImitatePass",
"Re-encryption failed"), body);
1381 const QString &err) {
1384 const QString &rel = commit.
rel;
1386 const bool committed =
1389 {
"git",
"diff",
"--cached",
"--name-only",
"--", rel}, &staged,
1391 staged.trimmed().isEmpty();
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);
1411 const QString folder =
1419 QString dirWithoutPassdir;
1420 const auto refusePlaced = [
this](
const QString &placed) {
1424 if (refusePlaced(folder) ||
1425 refusePlaced(folder + QStringLiteral(
"/.gpg-id")) ||
1426 refusePlaced(folder + QStringLiteral(
"/.gpg-id.sig")) ||
1437 const QString inStore =
1440 QDir(inStore).filePath(QStringLiteral(
".gpg-id")))) {
1453 QStringList args = {
"init",
"--path=" + dirWithoutPassdir};
1454 for (
const UserInfo &user : users) {
1456 args.append(user.key_id);
1465 QDir(inStore).filePath(QStringLiteral(
".gpg-id"))))) {
1483 .relativeFilePath(QDir::cleanPath(QDir(path).absolutePath()));
1498auto sameObject(
const QString &a,
const QString &b) ->
bool {
1500 const QString canonical = QFileInfo(a).canonicalFilePath();
1501 return !canonical.isEmpty() &&
1502 canonical.compare(QFileInfo(b).canonicalFilePath(),
1503 Qt::CaseInsensitive) == 0;
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;
1516 const QFileInfo srcInfo(src);
1517 const QFileInfo destInfo(dest);
1523 ?
passName(src,
false) + QLatin1Char(
'/')
1524 :
passName(src, srcInfo.isFile() &&
1525 srcInfo.suffix() == QLatin1String(
"gpg"));
1529 dest, !destInfo.isDir() && destInfo.suffix() == QLatin1String(
"gpg"));
1530 target.
newPath = QDir::cleanPath(
1534 if (!srcInfo.isDir() && !QFileInfo(target.
newPath).isDir()) {
1535 target.
newPath += QLatin1String(
".gpg");
1544 const QString &src,
const QString &dest,
1560 const QFileInfo srcFileInfo(src);
1562 !srcFileInfo.isDir()
1588 const QFileInfo &srcFileInfo,
1589 const QString &dest,
1590 const QString &occupied,
bool force)
1594 if (!force && srcFileInfo.isFile() && QFileInfo(dest).isFile()) {
1602 if (!QFileInfo::exists(occupied)) {
1605 if (sameObject(occupied, src)) {
1609 return occupied == QDir::cleanPath(QDir(src).absolutePath());
1611 if (force && srcFileInfo.isFile() &&
1612 occupied == QDir::cleanPath(QDir(dest).absolutePath())) {
1616 tr(
"%1 already exists, and pass would replace it. Nothing was "
1617 "changed; rename one of them first.")
1618 .arg(QDir::toNativeSeparators(occupied));
1626 const QFileInfo &srcFileInfo,
1632 const bool intoFolder = QFileInfo(target.newPath).isDir();
1645 const QStringList committing =
id ==
PASS_MOVE
1646 ? QStringList{src, target.newPath}
1647 : QStringList{target.newPath};
1661 bool intoFolder) -> QStringList {
1676 emit
statusMsg(tr(
"Search needs the GPG executable to be configured."),
1686 bool readStdout,
bool readStderr) {
1688 readStdout, readStderr);
A stream of bytes held as its first and last kMaxStderrBytes / 2 bytes, with its gpg status records c...
void append(const QByteArray &chunk)
Add what the process wrote next.
auto take() -> QByteArray
Everything kept, and start over.
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...
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.
auto environment() const -> QProcessEnvironment
Return the environment passed to child processes.
auto lastStatusCounts() const -> QHash< QString, qint64 >
The gpg status records on the stderr of the command whose finished() or error() is being emitted,...
void setEnvironment(const QProcessEnvironment &env)
Set the environment passed to all child processes.
The detached signature on a store's .gpg-id: whether the configured signing key is usable,...
void setStoreRoot(const QString &root)
The store the lists and signatures this signer reads belong to.
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.
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.
static auto passReadsDifferently(const QByteArray &contents) -> QString
Why pass would read a .gpg-id differently from parseRecipients(), if it would.
static auto getGpgIdPath(const QString &for_file, const QString &passStore) -> QString
Get .gpg-id file path for a password file.
virtual auto encryptionReaches(const QStringList &recipients) -> std::optional< QStringList >
The keys a gpg encryption to recipients reaches: a throwaway encryption outside the store,...
auto refusePendingPull() -> bool
Refuse a store change while a Git pull is still queued or running.
void releaseAutoPush(const QString &folder)
Release the holds a clean re-encryption of folder covers: those for folder itself and everything unde...
Enums::PROCESS PROCESS
Alias for Enums::PROCESS used throughout this class.
void queueInsert(const QString &entry=QString())
Count one insert that has started queueing but not yet reported.
void queueShow(const QString &file)
Remember what a Show() asked for, so its completion can say so.
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...
auto pushIsAutomatic() const -> bool
Whether the GitPush() running now is an automatic one.
void holdAutoPush(const QString &scope)
Hold automatic pushes of the store that holds scope (autoPushHeld()): its re-encryption did not finis...
void executeWrapper(PROCESS id, const QString &app, const QStringList &args, bool readStdout=true, bool readStderr=true)
Execute external wrapper command.
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...
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.
static auto enabledKeyLines(const QList< UserInfo > &users) -> QStringList
The enabled users' key IDs, as Init() writes them to .gpg-id.
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,...
auto refuseBusyForExpectedList() -> bool
Refuse an Init() under initIfUnchanged() while the executor has work queued or running,...
Executor exec
Internal command executor for queuing and running subprocesses.
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())...
auto refuseChangedList() -> bool
Refuse an Init() under initIfUnchanged() when the folder's list no longer reads as the caller read it...
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).
static auto withoutStatusLines(const QString &err) -> QString
gpg's stderr without its machine-readable [GNUPG:] lines (and without carriage returns),...
auto autoPushHeld() const -> bool
Whether automatic pushes of the current store are held because its last re-encryption did not finish ...
static auto pullTimedOut(int timeoutMs) -> QString
The status-bar text for a blocking pull stopped at its deadline.
QHash< QString, std::optional< QString > > LinkedWalks
virtual void finished(int id, int exitCode, const QString &out, const QString &err)
Handle process completion.
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...
auto refuseKeyLinesHeldTwice(const QStringList &lines) -> bool
Refuse, with critical(), a recipient list with a line that more than one key block holds (keyLinesHel...
static auto getRecipientList(const QString &for_file, const QString &passStore) -> QStringList
Get list of recipients for a password file.
@ ParentsOnly
Only the folders above it: a removal unlinks a link and touches nothing behind it.
@ EntryAndParents
The entry itself and every folder above it in the store.
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.
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...
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.
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
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,...
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,...
auto unrecorded(const QStringList &paths, bool ignored) -> QStringList
What git has not recorded at paths: git status --porcelain lines, through pass git....
auto storeGit(const QStringList &args, QString *out) -> bool override
Run a git command in the store through pass git, blocking.
bool m_pushAfterReencrypt
QQueue< InsertRecord > m_insertPending
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,...
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...
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...
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...
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...
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.
void Show(QString file) override
Show decrypted password.
InsertRecord m_insertDone
The insert whose completion is being handled.
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...
RealPass()
Construct a RealPass instance.
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,...
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...
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()),...
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.
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...
void sendDeferredPush()
Once the last queued init, move or copy has completed, make the push asked for meanwhile (GitPush())....
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.
QQueue< QString > m_reencryptScopes
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...
void GitPull() override
Pull changes from remote.
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 ...
bool m_deferredPushByHand
One of those pushes was asked for by hand: it goes despite a hold.
QQueue< LinkCommit > m_linkCommits
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.
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.
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.
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...
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...
auto listSigner() -> GpgIdSigner
The verifier for signed lists, gpg in the store's environment.
QQueue< QString > m_insertQueue
The entries of the queued inserts, oldest first.
static auto removeTree(const QString &dir) -> bool
Remove dir and everything in it, the way rm -rf does: a symbolic link or NTFS junction,...
static auto endsWithGpg() -> const QRegularExpression &
Returns a regex to match .gpg file extensions.
static auto hasUnreadableName(const QString &dir) -> bool
Whether dir holds an entry whose name is not valid UTF-8.
static constexpr qint64 kMaxGpgIdBytes
Most bytes of a .gpg-id QtPass reads.
static auto isLinkedFolder(const QString &path) -> bool
Whether path names a symbolic link or NTFS junction, with or without a trailing separator (which woul...
static auto joinPath(const QString &dir, const QString &name) -> QString
name in dir, as the file system means it.
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...
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...
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...
auto gpgErrorMessage(const QString &err) -> QString
Maps GPG stderr (which may include –status-fd 2 tokens) to a translated user-friendly encryption erro...
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.
QString passStore
Password-store root path.
QString passExecutable
Path to the pass executable.
bool useGit
Enable git integration.
QString target
The entry's file.
QString rel
The folder, relative to the store.
QProcessEnvironment environment
What pass mv/pass cp is handed and what it then does with it.
QString passSrc
The source name handed to pass.
Stores GPG key info including validity, creation date, and more.
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...