15#include <QCryptographicHash>
18#include <QElapsedTimer>
24#include <QRegularExpression>
73 ->
const std::atomic_bool * {
76 if (QThread::currentThread() == thread()) {
85 const QString &input, QString *process_out,
86 QString *process_err) ->
int {
94 const QByteArray &input,
95 QByteArray *process_out) ->
int {
103 QString *process_out, QString *process_err)
105 return execBlocking(app, args, QString(), process_out, process_err);
109 const QString &exe)
const -> QString {
121 QStringList{QStringLiteral(
"-C"), store} + args, out,
157 {
"-C", pgit(m_settings.passStore),
"pull"},
158 QString(),
nullptr, &err, cancel, timeoutMs);
159 if (rc != 0 && timer.elapsed() >= timeoutMs) {
161 }
else if (rc != 0) {
162 emit
statusMsg(tr(
"Git pull failed: %1").arg(err.trimmed()), 5000);
191 emit
statusMsg(tr(
"Not pushing: an earlier re-encryption in this "
192 "store did not finish"),
223 QStringList args = {
"-d",
"--quiet",
"--yes",
"--no-encrypt-to",
224 "--batch",
"--use-agent"};
232constexpr int kReencryptMaxListedFailures = 15;
245constexpr QLatin1StringView kUnknownReader(
"?");
247auto encryptArgs(QStringList leading,
const QString &output,
248 const QStringList &recipients) -> QStringList {
249 leading <<
"-eq" <<
"--compress-algo=none" <<
"--no-encrypt-to"
250 <<
"--no-textmode" <<
"--output" << output;
251 for (
const QString &recipient : recipients) {
262 QStringList *recipients) ->
bool {
270 emit
critical(tr(
"Check .gpg-id file signature!"), why);
273 if (recipients->isEmpty()) {
275 tr(
"Could not read encryption key to use, .gpg-id "
276 "file missing or invalid."));
287 const QFileInfo entry(path);
288 if (!entry.isFile() || entry.isSymLink()) {
292 QStringList recipients;
295 recipients.isEmpty()) {
298 QHash<QString, QString> primaries;
299 QHash<QString, QString> names;
300 const std::optional<QSet<QString>> now =
302 if (!now || now->contains(kUnknownReader)) {
308 const auto named = [&names](
const QSet<QString> &fprs) {
310 for (
const QString &fpr : fprs) {
311 who << (names.contains(fpr) ? QStringLiteral(
"%1 (%2)").arg(
312 names.value(fpr), fpr.right(16))
322 const bool inherited =
323 QDir::cleanPath(gpgIdPath) !=
324 QDir::cleanPath(QDir(entry.absolutePath()).filePath(
".gpg-id"));
328 return {named(*now),
true};
335 std::all_of(ids.cbegin(), ids.cend(), [](
const QString &
id) {
336 return id == QLatin1String(
"0000000000000000");
339 return {{tr(
"anyone on the list: the entry's recipients cannot be told")},
342 QSet<QString> gaining = *now;
344 return {named(gaining),
false};
359 const QFileInfo target(file);
360 if (!overwrite && (target.exists() || target.isSymLink())) {
361 emit
critical(tr(
"Cannot add"), tr(
"%1 already exists.").arg(file));
364 QStringList recipients;
371 auto scratch = std::make_shared<QTemporaryDir>();
372 if (!scratch->isValid()) {
374 tr(
"Cannot create a temporary directory: %1")
375 .arg(scratch->errorString()));
383 const QString output = scratch->filePath(QStringLiteral(
"entry.gpg"));
385 const QStringList args =
386 encryptArgs({
"--batch",
"--status-fd",
"2"},
pgpg(output), recipients);
402 gitCommit(file, QString(overwrite ?
"Edit" :
"Add") +
" for " +
412 {
"-C", pgit(m_settings.passStore),
"config",
413 "--bool",
"--get",
"pass.signcommits"},
415 out.trimmed() == QLatin1String(
"true");
416 return sign ? QStringList{
"commit",
"-S"} : QStringList{
"commit"};
424 QStringList args =
commitArgs() + QStringList{
"-m", msg,
"--"};
425 for (
const QString &file : files) {
453 tr(
"Could not remove the link %1.").arg(file));
462 gitCommit(file,
"Remove for " + path +
" using QtPass.");
469 gitCommit(file,
"Remove for " + path +
" using QtPass.");
479 tr(
"Could not remove all of %1. What could be removed "
480 "is gone; check what is left in it.")
485 if (!entry.remove()) {
488 tr(
"Could not remove %1: %2").arg(file, entry.errorString()));
497 [
this](
const QString &app,
const QStringList &args,
498 const QString &input, QString *out, QString *err) {
507 QByteArray *contents) ->
bool {
508 const std::optional<QString> folder =
512 tr(
"%1 is not inside the password store, or a folder "
513 "name on the way holds a line break or another control "
514 "character, which a signed list cannot record.")
520 std::optional<qint64> verifiedOnDisk;
521 std::optional<QString> storeOnDisk;
523 if (signer.verifyFile(gpgIdFile, ¤t)) {
525 if (header && (!header->folder || *header->folder == *folder)) {
526 verifiedOnDisk = header->generation;
536 gpgIdFile, current,
m_settings.passStore, &unavailable);
538 emit
critical(tr(
"Cannot update"), unavailable);
542 storeOnDisk = header->store;
549 const std::optional<QString> store =
552 emit
critical(tr(
"Cannot update"), why);
555 const std::optional<qint64> generation =
558 emit
critical(tr(
"Cannot update"), why);
567 const QList<UserInfo> &users,
568 QByteArray *written) ->
bool {
570 bool secret_selected =
false;
571 for (
const UserInfo &user : users) {
573 contents += (user.key_id +
"\n").toUtf8();
574 secret_selected |= user.have_secret;
586 emit
critical(tr(
"Cannot update"), writeError);
589 if (written !=
nullptr) {
598 qCWarning(lcQtPass) <<
"Could not record the written .gpg-id:" << why;
600 tr(
"Recipient list written, but not recorded"),
601 tr(
"%1 Save the recipients once more to get through.").arg(why));
604 if (!secret_selected) {
606 tr(
"Check selected users!"),
607 tr(
"None of the selected keys have a secret key available.\n"
608 "You will not be able to decrypt any newly added passwords!"));
614 const QByteArray &contents) ->
bool {
617 if (!signer.
sign(gpgIdFile, contents, &why)) {
619 tr(
"GPG signing failed!"),
620 why.trimmed().isEmpty()
621 ? tr(
"Failed to sign %1.").arg(gpgIdFile)
622 : tr(
"Failed to sign %1: %2").arg(gpgIdFile, why.trimmed()));
625 QByteArray signedBytes;
626 if (!signer.
verifyFile(gpgIdFile, &signedBytes)) {
627 emit
critical(tr(
"Check .gpg-id file signature!"),
628 tr(
"Signature for %1 is invalid.").arg(gpgIdFile));
638 const QString &gpgIdSigFile, QString *out,
639 QString *err) ->
int {
642 auto run = [&](
const QStringList &args) ->
int {
646 execBlocking(git, QStringList{
"-C", store} + args, &runOut, &runErr);
647 if (out !=
nullptr) {
650 if (err !=
nullptr) {
655 QStringList paths{
pgit(gpgIdFile)};
656 if (!gpgIdSigFile.isEmpty()) {
657 paths <<
pgit(gpgIdSigFile);
660 int rc = run(QStringList{
"add",
"-f",
"--"} + paths);
667 rc = run(QStringList{
"diff",
"--cached",
"--quiet",
"--"} + paths);
676 "Added " +
commitName(gpgIdFile) +
" using QtPass.",
683 {
"-C", pgit(m_settings.passStore),
"ls-files",
684 "--error-unmatch",
"--", pgit(file)}) == 0;
690 const QString folder = QDir::cleanPath(path);
692 const auto refusePlaced = [
this](
const QString &placed) {
696 return refusePlaced(path) ||
697 refusePlaced(folder + QStringLiteral(
"/.gpg-id")) ||
698 refusePlaced(folder + QStringLiteral(
"/.gpg-id.sig"));
702 const QByteArray &written,
704 QString *sigToCommit) ->
bool {
705 const QString gpgIdSigFile = gpgIdFile +
".sig";
706 if (signer.enabled()) {
710 *sigToCommit = gpgIdSigFile;
713 if (!QFile::exists(gpgIdSigFile)) {
717 const bool tracked = useGit &&
gitTracks(gpgIdSigFile);
718 if (!QFile::remove(gpgIdSigFile)) {
721 tr(
"Failed to remove the old signature %1.").arg(gpgIdSigFile));
725 *sigToCommit = gpgIdSigFile;
733 {QStringLiteral(
"--batch"), QStringLiteral(
"--no-tty"),
734 QStringLiteral(
"--with-colons"),
735 QStringLiteral(
"--with-fingerprint"),
736 QStringLiteral(
"--with-subkey-fingerprint"),
737 QStringLiteral(
"--list-keys")},
769 const QString gpgIdFile = path +
".gpg-id";
776 const std::optional<PreviousList> previous =
previousListOf(path, gpgIdFile);
792 if (!
settleSignature(gpgIdFile, written, signer, useGit, &sigToCommit)) {
802 const int gitExit =
gitAddGpgId(gpgIdFile, sigToCommit, &gitOut, &gitErr);
824 const QString &gpgIdFile,
const std::optional<PreviousList> &previous) {
836 const QString &path,
int gitExit,
const QString &gitOut,
837 const QString &gitErr,
const QString &gpgIdFile,
838 const std::optional<PreviousList> &previous) {
845 const QString why = gitErr.trimmed();
848 path, why.isEmpty() ? tr(
"Git exited with code %1.").arg(gitExit) : why);
857 emit
critical(tr(
"Recipients not changed"),
858 tr(
"A re-encryption is still running. Wait until it has "
859 "finished, then save the recipients again."));
862 if (signer.enabled() && !signer.haveSecretKey()) {
863 emit
critical(tr(
"No signing key!"),
864 tr(
"None of the secret signing keys is available.\n"
865 "You will not be able to change the user list!"));
873 for (
const QString &name : {gpgIdFile, gpgIdFile + QStringLiteral(
".sig")}) {
874 if (
const QFileInfo info(name); info.exists() && !info.isFile()) {
875 emit
critical(tr(
"Recipients not changed"),
876 tr(
"%1 is not a regular file, so the recipients were not "
877 "changed. Move it out of the way, then save the "
879 .arg(QDir::toNativeSeparators(name)));
889 -> std::optional<PreviousList> {
902 QStringList *recipients, QString *why)
905 if (why !=
nullptr) {
906 *why = tr(
"Signature for %1 is invalid.").arg(gpgIdFile);
920 if (
const QFileInfo info(gpgIdFile); !info.exists() && !info.isSymLink()) {
929 if (why !=
nullptr) {
930 *why = tr(
"%1 cannot be read as a recipient list (a regular file "
937 contents = *std::move(bytes);
944 QStringList &problems) {
945 problems << tr(
"%1 is not a regular file and was not restored. Look "
946 "at it and remove it, then re-encrypt again.")
952 if (QFileInfo(path).lastModified() >
953 QDateTime::currentDateTime().addSecs(-3600)) {
954 qCDebug(lcQtPass) <<
"Leaving a recent temporary alone:" << path;
957 if (!QFile::remove(path)) {
958 qCWarning(lcQtPass) <<
"Could not remove stale temporary" << path;
965 const QFileInfo backup(path);
966 if (backup.isSymLink() || !backup.isFile()) {
970 const QString original =
971 path.chopped(QStringLiteral(
".reencrypt.bak").size());
972 if (QFileInfo::exists(original)) {
973 problems << tr(
"%1 exists next to %2. Both are encrypted copies of the "
974 "entry; check which one you want and delete the other, "
975 "then re-encrypt again.")
976 .arg(path, original);
986 problems << tr(
"%1 is missing and its backup %2 could not be renamed "
987 "back. Rename it by hand, then re-encrypt again.")
988 .arg(original, path);
991 qCWarning(lcQtPass) <<
"Restored" << original <<
"from" << path;
992 emit
statusMsg(tr(
"Restored %1 from the backup an interrupted "
993 "re-encryption left behind.")
1008 const QStringList leftoverNames{QStringLiteral(
".qtpass-??????.tmp"),
1009 QStringLiteral(
"*.gpg.reencrypt.tmp"),
1010 QStringLiteral(
"*.gpg.??????.tmp"),
1011 QStringLiteral(
"*.gpg.reencrypt.bak")};
1012 const auto isTemporary = [](
const QString &path) {
1013 return path.endsWith(QStringLiteral(
".tmp"));
1015 QStringList skipped;
1018 QDir::cleanPath(dir), leftoverNames, &skipped,
true);
1022 QStringList problems;
1023 for (
const QString &path : std::as_const(skipped)) {
1024 if (!QDir::match(leftoverNames, QFileInfo(path).fileName())) {
1030 if (isTemporary(path)) {
1031 if (!QFile::remove(path) && !QDir().rmdir(path)) {
1032 qCWarning(lcQtPass) <<
"Could not remove stale temporary" << path;
1038 for (
const QString &path : leftovers) {
1039 if (isTemporary(path)) {
1045 if (problems.isEmpty()) {
1048 const qsizetype count = problems.size();
1050 emit
critical(tr(
"Leftover from an earlier re-encryption"),
1054 QStringList listed = problems.mid(0, kReencryptMaxListedFailures);
1055 if (count > listed.size()) {
1056 listed << tr(
"... and %n more",
nullptr,
1057 static_cast<int>(count - listed.size()));
1059 emit
critical(tr(
"Leftovers from an earlier re-encryption"),
1060 tr(
"%n leftover(s) of an earlier re-encryption need a look "
1061 "before the run can start:",
1062 nullptr,
static_cast<int>(count)) +
1063 "\n\n" + listed.join(
"\n\n"));
1068 QHash<QString, QStringList> &verified,
1069 QStringList &gpgId) ->
bool {
1078 const auto cached = verified.constFind(gpgIdPath);
1079 if (cached != verified.constEnd()) {
1080 gpgId = cached.value();
1083 QStringList recipients;
1088 emit
critical(tr(
"Check .gpg-id file signature!"), why);
1096 verified.insert(gpgIdPath, recipients);
1097 gpgId = std::move(recipients);
1114 const QStringList args = {QStringLiteral(
"--batch"),
1115 QStringLiteral(
"--no-secmem-warning"),
1116 QStringLiteral(
"--no-permission-warning"),
1117 QStringLiteral(
"--decrypt"),
1118 QStringLiteral(
"--list-only"),
1119 QStringLiteral(
"--max-output"),
1120 QStringLiteral(
"1"),
1121 QStringLiteral(
"--status-fd=1"),
1122 QStringLiteral(
"--keyid-format=long"),
1123 QStringLiteral(
"--"),
1132 static const QRegularExpression encTo(
1133 QStringLiteral(
"^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
1134 QStringList actualKeys;
1135 const QStringList lines =
1137 for (
const QString &line : lines) {
1138 const QRegularExpressionMatch match = encTo.match(line);
1139 if (match.hasMatch()) {
1140 actualKeys << match.captured(1).toUpper();
1157void mapKeyListing(
const QString &out, QHash<QString, QString> &primaries,
1158 QHash<QString, QString> &names) {
1160 QStringList pendingIds;
1161 bool inPrimary =
false;
1163 const QStringList f = line.split(QLatin1Char(
':'));
1164 const QString type = f.value(0);
1165 if (type == QLatin1String(
"pub")) {
1168 pendingIds = {f.value(4).toUpper()};
1169 }
else if (type == QLatin1String(
"sub")) {
1171 pendingIds << f.value(4).toUpper();
1172 }
else if (type == QLatin1String(
"fpr") && inPrimary &&
1173 primaryFpr.isEmpty()) {
1174 primaryFpr = f.value(9).toUpper();
1175 }
else if (type == QLatin1String(
"uid") && !primaryFpr.isEmpty() &&
1176 !names.contains(primaryFpr)) {
1179 if (!primaryFpr.isEmpty()) {
1180 for (
const QString &
id : std::as_const(pendingIds)) {
1181 if (!
id.isEmpty()) {
1182 primaries.insert(
id, primaryFpr);
1193 QHash<QString, QString> &primaries,
1194 QHash<QString, QString> &names)
1199 if (primaries.isEmpty()) {
1203 {QStringLiteral(
"--batch"),
1204 QStringLiteral(
"--with-colons"),
1205 QStringLiteral(
"--fixed-list-mode"),
1206 QStringLiteral(
"--list-keys")},
1208 mapKeyListing(out, primaries, names);
1213 QSet<QString> result;
1214 for (
const QString &
id : ids) {
1215 const QString fpr = primaries.value(
id.toUpper());
1216 if (!fpr.isEmpty()) {
1227 return bytes ? QCryptographicHash::hash(*bytes, QCryptographicHash::Sha256)
1232 QHash<QString, QString> &primaries,
1233 QHash<QString, QString> &names,
bool lookUp)
1234 -> std::optional<QSet<QString>> {
1238 QTemporaryDir scratch;
1239 if (!scratch.isValid()) {
1240 return std::nullopt;
1242 const QString probe = scratch.filePath(QStringLiteral(
"probe.gpg"));
1245 QStringList leading{QStringLiteral(
"--yes"), QStringLiteral(
"--batch"),
1246 QStringLiteral(
"--no-throw-keyids")};
1248 leading << QStringLiteral(
"--no-auto-key-locate");
1251 encryptArgs(std::move(leading),
pgpg(probe), recipients),
1252 QByteArrayLiteral(
"probe"),
nullptr) != 0) {
1253 return std::nullopt;
1256 if (ids.isEmpty()) {
1259 return QSet<QString>{kUnknownReader};
1264 for (
const QString &
id : ids) {
1265 if (!primaries.contains(
id.toUpper())) {
1266 keys.insert(
id.toUpper());
1273 QString *why) ->
bool {
1280 constexpr qint64 kCiphertextMargin = 1024LL * 1024;
1287 m_settings.passStore, fileName, kMaxCiphertext);
1289 qCDebug(lcQtPass) <<
"Not a regular file any more, or too large:"
1291 if (why !=
nullptr) {
1292 *why = tr(
"%1 is no longer a regular file, or is too large, and was "
1293 "not re-encrypted.")
1298 const QStringList args =
1299 QStringList{
"-d",
"--quiet",
"--yes",
"--no-encrypt-to",
1300 "--batch",
"--use-agent"} +
1304 plaintext->isEmpty()) {
1305 qCDebug(lcQtPass) <<
"Decrypt error on re-encrypt for:" << fileName;
1314 const QStringList &recipients,
1315 const QByteArray &plaintext) ->
bool {
1316 const QStringList args =
1317 encryptArgs({
"--yes",
"--batch"},
pgpg(output), recipients);
1320 qCDebug(lcQtPass) <<
"Encrypt error on re-encrypt, output:" << output;
1327 const QByteArray &plaintext) ->
bool {
1328 QByteArray decrypted;
1329 const QStringList args =
1330 QStringList{
"-d",
"--quiet",
"--batch",
"--use-agent"} +
maxOutputArgs() +
1331 QStringList{QStringLiteral(
"--"),
pgpg(ciphertext)};
1334 decrypted.isEmpty()) {
1335 qCDebug(lcQtPass) <<
"Verification failed for:" << ciphertext;
1341 if (decrypted != plaintext) {
1342 qCDebug(lcQtPass) <<
"Verification content mismatch for:" << ciphertext;
1356 {
"-C", store,
"add",
"--", pgit(fileName)}) != 0) {
1360 qCDebug(lcQtPass) <<
"git add failed after re-encrypting:" << fileName;
1367 "Re-encrypt for " + path +
" using QtPass.",
1368 "--",
pgit(fileName)}) != 0) {
1369 qCDebug(lcQtPass) <<
"git commit failed after re-encrypting:" << fileName;
1376 const QStringList &recipients,
1377 QString *why) ->
bool {
1378 qCDebug(lcQtPass) <<
"reencrypt" << fileName <<
"for" << recipients.size()
1380 if (recipients.isEmpty()) {
1382 tr(
"Could not read encryption key to use, .gpg-id "
1383 "file missing or invalid."));
1386 QByteArray plaintext;
1394 QTemporaryDir scratch;
1395 if (!scratch.isValid()) {
1396 qCDebug(lcQtPass) <<
"Cannot create a scratch directory for re-encrypting"
1400 const QString tempPath = scratch.filePath(QStringLiteral(
"reencrypted.tmp"));
1401 if (!
encryptFor(tempPath, recipients, plaintext) ||
1409 const QFileInfo still(fileName);
1410 if (!still.exists() && !still.isSymLink()) {
1411 qCDebug(lcQtPass) <<
"Entry vanished before it could be replaced:"
1419 if (why !=
nullptr && !why->contains(fileName)) {
1422 *why = tr(
"%1 could not be re-encrypted: %2").arg(fileName, *why);
1439auto listsUnmergedPath(
const QString &porcelain) ->
bool {
1440 const QStringList lines = porcelain.split(u
'\n', Qt::SkipEmptyParts);
1441 for (
const QString &line : lines) {
1442 if (line.size() < 2) {
1445 const QChar x = line.at(0);
1446 const QChar y = line.at(1);
1447 if (x == u
'U' || y == u
'U' || (x == y && (x == u
'A' || x == u
'D'))) {
1459 emit
statusMsg(tr(
"Creating backup commit"), 2000);
1460 const QString git =
m_settings.gitExecutable;
1468 git, {
"-C", store,
"status",
"--porcelain",
"--untracked-files=no"},
1473 tr(
"Backup commit failed"),
1474 tr(
"Could not inspect git status. Re-encryption was aborted."));
1483 if (listsUnmergedPath(statusOut)) {
1485 emit
critical(tr(
"Unfinished Git operation"),
1486 tr(
"The password store's Git repository has unmerged "
1487 "files. Resolve the conflict with Git before "
1494 QString storeStatus;
1496 {
"-C", store,
"status",
"--porcelain",
1497 "--untracked-files=no",
"--",
"."},
1498 &storeStatus) != 0) {
1501 tr(
"Backup commit failed"),
1502 tr(
"Could not inspect git status. Re-encryption was aborted."));
1505 if (!storeStatus.trimmed().isEmpty()) {
1506 if (
execBlocking(git, {
"-C", store,
"add",
"-u",
"--",
"."}) != 0 ||
1508 QStringList{
"-m",
"Backup before re-encryption",
1511 emit
critical(tr(
"Backup commit failed"),
1512 tr(
"Re-encryption was aborted because a git backup "
1513 "could not be created."));
1554 std::optional<QSet<QString>>
now;
1578constexpr int kReencryptRetryMs = 100;
1592 emit
statusMsg(tr(
"A re-encryption is already running"), 3000);
1599 emit
critical(tr(
"Not a folder of the store"),
1600 tr(
"%1 is, or lies behind, a symbolic link or junction. What "
1601 "that points to is not part of the password store and "
1602 "was not re-encrypted.")
1603 .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
1617 ? tr(
"Re-encrypting from folder %1").arg(dir)
1618 : tr(
"Re-encrypting %1").arg(dir),
1645 QTimer::singleShot(kReencryptRetryMs,
this,
1665 QPointer<ImitatePass> self(
this);
1669 QThread *thread = QThread::create([
this, self = std::move(self), dir]() {
1671 QMetaObject::invokeMethod(
1673 [self, result = std::move(result)]() {
1675 self->finishReencrypt(result);
1677 Qt::QueuedConnection);
1680 connect(thread, &QThread::finished,
this, [
this, thread]() {
1684 connect(thread, &QThread::finished, thread, &QObject::deleteLater);
1697 emit
statusMsg(tr(
"Updating password-store"), 2000);
1699 {
"-C", pgit(m_settings.passStore),
"pull"}) == 0) {
1707 {
"-C", pgit(m_settings.passStore),
"ls-files",
"--unmerged"},
1710 emit
critical(tr(
"Git pull failed"),
1711 tr(
"Could not check the store for unmerged files after the "
1712 "pull. Check it with git before re-encrypting."));
1715 if (!unmerged.trimmed().isEmpty()) {
1716 emit
critical(tr(
"Git pull failed"),
1717 tr(
"The pull left the store with unmerged files. Resolve "
1718 "the conflict before re-encrypting."));
1730 {
"-C", pgit(m_settings.passStore),
"rev-list",
"--count",
1731 "HEAD..@{upstream}"},
1733 behind.trimmed().toInt() > 0) {
1734 emit
critical(tr(
"Git pull failed"),
1735 tr(
"The pull stopped before the store was up to date with "
1736 "its remote, and may have left files of the pulled "
1737 "commits in it. Check the store with git before "
1741 emit
statusMsg(tr(
"Git pull failed, re-encrypting the store as it is"), 5000);
1750 if (
const QFileInfo one(dir); !one.isDir()) {
1752 one.fileName().endsWith(QLatin1String(
".gpg"))) {
1753 return {one.filePath()};
1757 QStringList skipped;
1758 QStringList unlisted;
1763 dir, QStringList() <<
"*.gpg", &skipped,
true, &unlisted);
1768 for (
const QString &folder : std::as_const(unlisted)) {
1769 *failed << tr(
"%1 could not be read: its entries were not re-encrypted")
1770 .arg(QDir::toNativeSeparators(folder));
1772 if (!skipped.isEmpty()) {
1773 emit
statusMsg(tr(
"%n entr(y/ies) skipped: a symlink, junction or special "
1774 "file is not part of the store.",
1775 "",
static_cast<int>(skipped.size())),
1782 QHash<QString, QStringList> &verified,
1787 result.cancelled =
true;
1789 result.aborted =
true;
1793 if (gpgId.isEmpty() && !verified.isEmpty()) {
1794 emit
critical(tr(
"GPG ID verification failed"),
1795 tr(
"Could not verify .gpg-id for directory."));
1796 result.aborted =
true;
1814 files.erase(std::remove_if(files.begin(), files.end(),
1815 [
this](
const QString &file) {
1816 return !m_reencryptAgreed.contains(file);
1820 result.
total =
static_cast<int>(files.size());
1824 QHash<QString, QStringList> gpgIdFilesVerified;
1827 for (
const QString &fileName : std::as_const(files)) {
1832 const QString fileDir = QFileInfo(fileName).path();
1833 if (fileDir != currentDir) {
1837 currentDir = fileDir;
1852 result.aborted =
true;
1863 emit
critical(tr(
"Unfinished Git operation"), midOp);
1865 result.aborted =
true;
1872 emit
critical(tr(
"Not part of the store"),
1873 tr(
"%1 is, or lies behind, a symbolic link or junction "
1874 "after pulling. What that points to is not part of the "
1875 "password store and is left alone.")
1876 .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
1877 result.aborted =
true;
1891 tr(
"Recipients changed by the pull"),
1892 tr(
"The pull changed the recipients of %1 after you saved "
1893 "them, so nothing was re-encrypted: entries in it may still "
1894 "be encrypted to the previous recipients, and anyone you "
1895 "just removed may still be able to read them. Open the users "
1896 "dialog for that folder again, check the recipients, and "
1898 .arg(QDir::toNativeSeparators(
1901 result.aborted =
true;
1909 result.aborted =
true;
1915 result.cancelled =
true;
1917 result.aborted =
true;
1925 const QSet<QString> &listNow)
const ->
bool {
1929 [&fileName](
const QString &trusted) {
1930 return fileName == trusted ||
1931 fileName.startsWith(trusted + QLatin1Char(
'/'));
1939 agreed->readers == listNow &&
entryHash(fileName) == agreed->hash;
1943 const QStringList &gpgId,
WhoReads &who)
1945 if (
const auto known = who.lists.constFind(gpgIdPath);
1946 known != who.lists.constEnd()) {
1951 std::optional<QSet<QString>> before = fresh.
now;
1959 if (before && before->contains(kUnknownReader)) {
1962 fresh.
before = before ? *before : fresh.
now.value_or(QSet<QString>());
1964 return *who.lists.insert(gpgIdPath, fresh);
1968 const QStringList &keys,
const ListKeys &lk,
1975 const QSet<QString> readers =
primaryKeysOf(keys, who.primaries, who.names);
1977 change.
gaining.subtract(readers);
1980 QSet<QString> added = *lk.now;
1981 added.subtract(lk.before);
1982 change.
gaining.subtract(added);
1987 QSet<QString> removed = lk.before;
1989 removed.subtract(*lk.now);
1990 if (lk.beforeUnknown) {
1991 removed.insert(kUnknownReader);
1996 const bool readersKnown =
1997 std::all_of(keys.cbegin(), keys.cend(), [&who](
const QString &
id) {
1998 return who.primaries.contains(id.toUpper());
2000 if (!readersKnown) {
2001 change.
losing = std::move(removed);
2004 change.
losing.intersect(removed);
2008 if (removed.contains(kUnknownReader)) {
2009 QSet<QString> off = readers;
2010 off.subtract(*lk.now);
2011 change.
losing.unite(off);
2018 const QHash<QString, QString> &names)
2021 for (
const QString &fpr : fprs) {
2022 if (fpr == kUnknownReader) {
2023 who << tr(
"a recipient gpg does not name");
2026 who << names.value(fpr, fpr.right(16));
2029 return who.join(QStringLiteral(
", "));
2033 const QStringList &keys,
2037 const QByteArray shownHash =
entryHash(fileName);
2038 if (shownHash.isEmpty()) {
2043 result.failed << tr(
"%1 was not re-encrypted: it would become "
2044 "readable by %2, and it cannot be read to ask "
2045 "about it (too large, or not a regular file).")
2048 if (!change.losing.isEmpty()) {
2049 result.stillReadByRemoved.insert(fileName, change.losing);
2055 std::all_of(keys.cbegin(), keys.cend(), [](
const QString &
id) {
2056 return id == QLatin1String(
"0000000000000000");
2058 result.unexpected << fileName;
2059 result.unexpectedHashes << shownHash;
2060 result.unexpectedReaders << change.listNow;
2061 QString detail = hidden
2062 ? tr(
"its recipients cannot be told (hidden key IDs); "
2063 "it would become readable by %1")
2065 : tr(
"would become readable by %1")
2067 if (!change.losing.isEmpty()) {
2071 QStringLiteral(
"; ") +
2072 (change.losing.contains(kUnknownReader) ||
2073 !std::all_of(keys.cbegin(), keys.cend(),
2074 [&who](
const QString &
id) {
2075 return who.primaries.contains(id.toUpper());
2077 ? tr(
"may still be readable by someone taken off "
2079 : tr(
"still readable by %1, who was removed")
2081 result.stillReadByRemoved.insert(fileName, change.losing);
2083 result.unexpectedDetails << detail;
2088 const QStringList &gpgId,
WhoReads &who,
2094 bool keepRecord =
false;
2095 const QFileInfo entry(fileName);
2096 if (entry.isSymLink() || !entry.isFile() ||
2098 result.failed << tr(
"%1 is no longer a regular file, or lies behind a "
2099 "link, and was not re-encrypted.")
2113 if (!keys.isEmpty()) {
2127 result.reencrypted++;
2128 result.rewritten << fileName;
2134 result.failed << (why.isEmpty() ? fileName : why);
2140 result.walked << fileName;
2161 result.
failed.isEmpty() &&
2193 if (failed.isEmpty()) {
2196 QStringList listed = failed.mid(0, kReencryptMaxListedFailures);
2197 const int more =
static_cast<int>(failed.size() - listed.size());
2199 listed << tr(
"... and %n more",
nullptr, more);
2201 emit
critical(tr(
"Re-encryption failed"),
2202 tr(
"%n file(s) could not be re-encrypted:",
nullptr,
2203 static_cast<int>(failed.size())) +
2204 "\n\n" + listed.join(
'\n'));
2208 bool agreedRun) ->
bool {
2220 for (
const QString &file : result.walked) {
2223 for (
auto it = result.stillReadByRemoved.cbegin();
2224 it != result.stillReadByRemoved.cend(); ++it) {
2228 it = QFileInfo::exists(it.key()) ? std::next(it)
2232 const QString heldPrefix = heldScope + QLatin1Char(
'/');
2233 const bool stillRead =
2235 [&heldScope, &heldPrefix](
const QString &file) {
2236 return file == heldScope || file.startsWith(heldPrefix);
2238 if (result.cancelled || result.aborted || !result.failed.isEmpty() ||
2241 }
else if (!agreedRun) {
2250 emit
statusMsg(tr(
"Re-encryption cancelled: %1 of %2 files checked, "
2251 "%3 re-encrypted, %4 failed")
2255 .arg(result.
failed.size()),
2258 if (!result.
failed.isEmpty()) {
2259 emit
statusMsg(tr(
"Re-encryption completed: %1 succeeded, %2 failed")
2261 .arg(result.
failed.size()),
2264 emit
statusMsg(tr(
"Re-encryption completed: %1 files re-encrypted")
2274 emit
statusMsg(tr(
"Not pushing: an entry left as it is is still "
2275 "readable by a removed recipient"),
2279 emit
statusMsg(tr(
"Not pushing: an earlier re-encryption in this "
2280 "store did not finish"),
2282 }
else if (result.
failed.isEmpty()) {
2283 emit
statusMsg(tr(
"Updating password-store"), 2000);
2288 emit
statusMsg(tr(
"Not pushing: %n file(s) failed to re-encrypt",
2289 nullptr,
static_cast<int>(result.
failed.size())),
2300 for (qsizetype i = 0; i < result.
unexpected.size(); ++i) {
2302 Agreed{result.unexpectedHashes.value(i),
2303 result.unexpectedReaders.value(i)});
2310 emit
statusMsg(tr(
"A re-encryption is already running"), 3000);
2316 for (
const QString &file : files) {
2324 emit
statusMsg(tr(
"Nothing to re-encrypt: those entries were not named "
2341 const QString &gitError) {
2358 const QString &gitError,
2360 const QString folder = QDir::toNativeSeparators(QDir::cleanPath(dir));
2363 tr(
"Recipients not committed"),
2364 tr(
"The recipients of %1 were changed and its entries were "
2365 "re-encrypted to them, but the Git commit failed:\n\n%2\n\n"
2366 "The change is not committed or pushed yet. Fix the Git problem, "
2367 "then commit the changes, or save the recipients again.")
2368 .arg(folder, gitError));
2372 tr(
"Recipients not committed"),
2373 tr(
"The recipients of %1 were changed, but the Git commit "
2374 "failed:\n\n%2\n\nRe-encryption did not complete, so some or all "
2375 "entries are still encrypted to the previous recipients, who can "
2376 "still read them. Nothing was committed or pushed. Fix the Git "
2377 "problem, then save the recipients again.")
2378 .arg(folder, gitError));
2382 const QString &dest,
bool force)
2384 QFileInfo srcFileInfo(src);
2385 QFileInfo destFileInfo(dest);
2387 QString srcFileBaseName = srcFileInfo.fileName();
2389 if (srcFileInfo.isFile()) {
2390 if (destFileInfo.isFile()) {
2392 qCDebug(lcQtPass) <<
"Destination file already exists";
2396 }
else if (destFileInfo.isDir()) {
2406 if (destFile.endsWith(QLatin1String(
".gpg"))) {
2409 destFile.append(
".gpg");
2410 }
else if (srcFileInfo.isDir()) {
2411 if (destFileInfo.isDir()) {
2413 }
else if (destFileInfo.isFile()) {
2414 qCDebug(lcQtPass) <<
"Destination is a file";
2420 qCDebug(lcQtPass) <<
"Source file does not exist";
2433 args <<
"--" <<
pgit(src) <<
pgit(destFile);
2439 QString(
"Moved for %1 to %2 using QtPass.")
2444 QString name = QDir(
m_settings.passStore).relativeFilePath(path);
2448 if (name == QLatin1String(
"..") || name.startsWith(QLatin1String(
"../")) ||
2449 QDir::isAbsolutePath(name)) {
2450 name = QFileInfo(path).fileName();
2462 const QString from = QDir::cleanPath(src);
2463 const QString to = QDir::cleanPath(dest);
2476 if (destFile.isEmpty()) {
2487 qCDebug(lcQtPass) <<
"Move Source: " << from;
2488 qCDebug(lcQtPass) <<
"Move Destination: " << destFile;
2490 const bool folder = QFileInfo(from).isDir();
2510 : QDir().rename(from, destFile);
2513 tr(
"Could not move %1 to %2.").arg(from, destFile));
2522 const QString &destFile) ->
bool {
2524 constexpr auto cs = Qt::CaseInsensitive;
2526 constexpr auto cs = Qt::CaseSensitive;
2529 const auto overlap = [](
const QString &a,
const QString &b) {
2530 const QString x = QDir::cleanPath(a);
2531 const QString y = QDir::cleanPath(b);
2532 return x.compare(y, cs) == 0 || x.startsWith(y + QLatin1Char(
'/'), cs) ||
2533 y.startsWith(x + QLatin1Char(
'/'), cs);
2537 busy << move.src << move.destFile;
2542 for (
const QString &path : std::as_const(busy)) {
2543 if (overlap(path, src) || overlap(path, destFile)) {
2544 emit
critical(tr(
"Move not started"),
2545 tr(
"%1 is still being moved or re-encrypted. Move it "
2546 "again once that has finished.")
2547 .arg(QDir::toNativeSeparators(QDir::cleanPath(path))));
2559 if (move.
landed !=
true) {
2564 const QFileInfo landed(move.
destFile);
2571 const QString toList =
2575 toList == QDir::cleanPath(QDir(move.
destFile).filePath(
".gpg-id")))) {
2580 const QString scope = QDir::cleanPath(move.
destFile);
2587 bool force) -> QString {
2588 const auto refuse = [
this, &src](
const QString &to) {
2590 tr(
"Could not copy %1 to %2.").arg(src, to));
2597 if (destFile.isEmpty()) {
2598 return refuse(dest);
2605 const QFileInfo destFileInfo(destFile);
2609 if (QFileInfo(src) == destFileInfo || (!force && destFileInfo.exists())) {
2610 return refuse(destFile);
2618 const QString from = QDir::cleanPath(src);
2619 const QString to = QDir::cleanPath(dest);
2630 if (destFile.isEmpty()) {
2640 tr(
"Could not copy %1 to %2.").arg(from, destFile) +
"\n" +
2649 gitCommit(destFile, QString(
"Copied from %1 to %2 using QtPass.")
2652 const QFileInfo written(destFile);
2659 if (written.isDir()) {
2661 }
else if (written.isFile()) {
2670 bool readStdout,
bool readStderr) {
2672 readStdout, readStderr);
2685 emit
statusMsg(tr(
"Git executable not configured, skipping git"), 3000);
2692 bool readStdout,
bool readStderr) {
2696 readStdout, readStderr);
2702 const QString &err) {
2703 qCDebug(lcQtPass) <<
"Imitate Pass";
2704 QString error = err;
2710 move.landed = exitCode == 0;
2725 if (exitCode == 0) {
2734 qCDebug(lcQtPass) <<
"No such transaction!";
2755 if (exitCode != 0) {
2765 if (!midOp.isEmpty()) {
2779 bool overwrite, QString *error) ->
bool {
2780 if (QFileInfo(output).size() <= 0) {
2782 *error = tr(
"gpg wrote no ciphertext for %1.").arg(file);
static void remember(const QStringList &paths)
Record entries this device has just written.
static auto known(const QString &entryFile) -> bool
Whether this device saved entryFile, or found it there when the store was seeded.
auto isIdle() const -> bool
Whether no command is running and nothing is queued.
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.
static auto translatePathForWsl(const QString &path, const QString &exe) -> QString
Translate a native path for a WSL-routed executable.
auto environment() const -> QProcessEnvironment
Return the environment passed to child processes.
static auto executeBlockingRaw(QProcess &process, const QString &app, const QStringList &args, const QByteArray &input, QByteArray *process_out, QString *process_err=nullptr, const std::atomic_bool *cancel=nullptr, int timeoutMs=-1) -> int
executeBlocking() on bytes, for an entry's plaintext: input is written to stdin and stdout returned e...
auto cancelNext() -> int
Cancel the next queued command without executing it.
static auto accept(const QString &gpgIdFile, const QByteArray &contents, const QString &storeRoot, QString *error=nullptr) -> Verdict
Decide about a verified list: its folder against where it sits, its generation against the remembered...
static auto folderOf(const QString &gpgIdFile, const QString &storeRoot) -> std::optional< QString >
The store-relative folder of gpgIdFile, as written in and compared against the folder line: ....
static auto reserveNext(const QString &gpgIdFile, std::optional< qint64 > verifiedOnDisk, QString *error=nullptr) -> std::optional< qint64 >
Reserve the generation to write next for gpgIdFile: one above both what this device remembers and ver...
static auto recordWritten(const QString &gpgIdFile, const QByteArray &contents, QString *error=nullptr) -> bool
Record the bytes just written for gpgIdFile, so that this device recognises its own list afterwards a...
Verdict
The outcome of accept(). Only Accepted means the list may be used; the others say why not,...
@ Accepted
Folder, generation and record all agree; remembered.
@ RecordUnavailable
The record could not be read or written.
static auto withHeader(qint64 generation, const QString &folder, const QByteArray &recipients, const QString &store={}) -> QByteArray
A complete list: the header in front of the recipients.
static auto parse(const QByteArray &contents, QString *error=nullptr) -> std::optional< Header >
The header a .gpg-id's bytes declare.
static auto storeIdFor(const QString &storeRoot, const std::optional< QString > &onDisk, QString *error=nullptr) -> std::optional< QString >
The store id to write into a list of storeRoot: the one this device knows the store by; else onDisk,...
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.
auto sign(const QString &gpgIdFile, const QByteArray &contents, QString *error=nullptr) const -> bool
Write <file>.sig, a detached signature by the first key over contents, the bytes the caller just wrot...
auto verifyFile(const QString &gpgIdFile, QByteArray *contents) const -> bool
Read gpgIdFile and verify it against <file>.sig.
static auto keysFromSetting(const QString &passSigningKey) -> QStringList
Split the settings value into keys, upper-cased the way gpg prints fingerprints.
RAII helper for wrapping operations in transactions.
auto commitReencrypted(const QString &fileName) -> bool
Stage and commit a re-encrypted entry, when the store is a Git repository QtPass manages.
auto reencryptEntry(const QString &fileName, const QStringList &gpgId, WhoReads &who, ReencryptResult &result) -> bool
Check one entry and re-encrypt it to gpgId when it is not encrypted to those keys yet,...
QHash< QString, Agreed > m_reencryptAgreed
auto prepareBlocking(QProcess &process) -> const std::atomic_bool *
Give process the environment for the calling thread: the store's on the owning thread,...
auto createBackupCommit() -> bool
Create git backup commit before re-encryption.
auto previousListOf(const QString &path, const QString &gpgIdFile) -> std::optional< PreviousList >
The verified list the entries of path were encrypted to before Init() replaces it,...
auto primaryKeysOf(const QStringList &ids, QHash< QString, QString > &primaries, QHash< QString, QString > &names) -> QSet< QString >
The primary keys behind key IDs from an entry (ENC_TO).
void finishReencrypt(const ReencryptResult &result)
Report the outcome of a run and emit endReencryptPath().
void Remove(QString file, bool isDir) override
Remove password.
QString m_transactionOutput
stdout of the steps of the transaction in flight, collected by finished() and handed on,...
auto execBlocking(const QString &app, const QStringList &args, const QString &input=QString(), QString *process_out=nullptr, QString *process_err=nullptr) -> int
Executor::executeBlocking() for the re-encryption helpers.
auto refuseOverlappingMove(const QString &src, const QString &destFile) -> bool
Refuse a move of src to destFile that touches what an earlier move or a re-encryption still has to se...
void GitInit() override
Initialize Git repository.
auto recipientsForEntry(const QString &file, QStringList *recipients) -> bool
The recipients to encrypt file to: its folder's .gpg-id, verified when a signing key is set.
void executeGpg(PROCESS id, const QStringList &args, QString input=QString(), bool readStdout=true, bool readStderr=true)
Execute GPG command.
auto reencryptSingleFile(const QString &fileName, const QStringList &recipients, QString *why) -> bool
Re-encrypt single file with new recipients.
void reportUncommittedGpgId(const QString &dir, const QString &gitError, bool reencrypted)
Tell the user that the recipients of dir changed on disk but the change is not committed,...
QHash< QString, Agreed > m_lastUnexpected
auto keysEncryptedTo(const QStringList &recipients, QHash< QString, QString > &primaries, QHash< QString, QString > &names, bool lookUp=true) -> std::optional< QSet< QString > >
The primary keys gpg encrypts to for recipients, found by a throwaway encryption outside the store wi...
auto placePendingInsert(int exitCode, QString *error) -> int
Finish the oldest pending insert after its gpg step: place the ciphertext with placeEncryptedFile(),...
auto copyDestination(const QString &src, const QString &dest, bool force) -> QString
The file a copy of src to dest writes: like pass cp, into an existing folder with ....
auto fullKeyListing(QString *listing) -> int override
Pass::fullKeyListing() in the calling thread's environment, so a re-encryption run's worker lists the...
bool m_reencryptActive
Set while a re-encryption run is pending or on the worker thread.
void reportUnrestorable(const QString &path, QStringList &problems)
Note for the user that a leftover is not a regular file and was left.
void startReencryptWorker(const QString &dir)
Start the worker thread once the Executor queue is idle.
auto writeGpgIdFile(const QString &gpgIdFile, const QList< UserInfo > &users, QByteArray *written=nullptr) -> bool
Write the enabled recipients to a .gpg-id, atomically: a write that fails halfway (full disk,...
auto commitArgs() -> QStringList
The start of a git commit for the store: "commit", and "-S" when git config pass.signcommits is true ...
auto verifyGpgIdForDir(const QString &file, QHash< QString, QStringList > &verified, QStringList &gpgId) -> bool
Recipients for the directory of file, from its verified .gpg-id.
void Grep(QString pattern, bool caseInsensitive) override
Search all password content by GPG-decrypting each .gpg file.
void Insert(QString file, QString newValue, bool overwrite) override
Insert new password.
auto recipientsForDir(const QString &fileName, QHash< QString, QStringList > &verified, QStringList &gpgId, ReencryptResult &result) -> bool
The verified recipients for the folder fileName sits in.
auto gitTracks(const QString &file) -> bool
Check whether git already tracks a file in the store.
~ImitatePass() override
Cancel a running content search, and cancel and join a running re-encryption worker,...
void cancelReencryptPath()
Ask a running reencryptPath() to stop.
QStringList m_reencryptTrusted
auto execBlockingRaw(const QString &app, const QStringList &args, const QByteArray &input, QByteArray *process_out) -> int
execBlocking() on bytes (Executor::executeBlockingRaw()), for an entry's plaintext,...
ImitatePass()
Construct the backend and connect its content search.
auto listKeysFor(const QString &gpgIdPath, const QStringList &gpgId, WhoReads &who) -> const ListKeys &
The keys of the list at gpgIdPath, worked out once per run.
auto gitReady() -> bool
gitConfigured() plus a status message when git is enabled but no executable is configured.
bool m_reencryptPushing
Set while finishReencrypt() pushes, so GitPush() does not hold it.
void executeGit(PROCESS id, const QStringList &args, QString input=QString(), bool readStdout=true, bool readStderr=true)
Execute git command.
QStringList m_movedToReencrypt
void Init(QString path, const QList< UserInfo > &users) override
Initialize store.
auto loadVerifiedRecipients(const QString &gpgIdFile, QStringList *recipients, QString *why=nullptr) -> bool
Read a .gpg-id, verify its detached signature and parse the recipients from the bytes that were verif...
auto readerChangeOf(const QString &fileName, const QStringList &keys, const ListKeys &lk, WhoReads &who) -> ReaderChange
Who would gain an entry by re-encrypting it to its list, other than those this change added,...
void Copy(const QString src, const QString dest, const bool force) override
Copy password file.
QThread * m_reencryptThread
The re-encryption worker while it runs, null otherwise. The destructor sets m_reencryptCancel and joi...
void rememberUnexpected(const ReencryptResult &result)
Keep what the run named in unexpectedRecipients(), with the bytes and readers it was named for: reenc...
auto holdForAgreement(const QString &fileName, const QStringList &keys, const ReaderChange &change, const WhoReads &who, ReencryptResult &result) -> bool
Leave an entry that would gain readers for the user: named in the question after the run,...
QQueue< PendingMove > m_pendingMoves
Moves through Git, in order, each settled when its PASS_MOVE ends.
auto reencryptFiles(const QString &dir) -> ReencryptResult
Worker-thread body: scan dir and re-encrypt stale files.
auto startReencryptRun(const QString &dir, ReencryptResult &result) -> bool
The checks a run makes after its own pull, before it writes: no unfinished Git operation,...
auto encryptFor(const QString &output, const QStringList &recipients, const QByteArray &plaintext) -> bool
Encrypt plaintext to recipients, into output.
auto placeEncryptedFile(const QString &output, const QString &file, bool overwrite, QString *error) -> bool
Bring the ciphertext gpg wrote to output into the store as file (Util::copyFileReplacing): through a ...
auto settleSignature(const QString &gpgIdFile, const QByteArray &written, const GpgIdSigner &signer, bool useGit, QString *sigToCommit) -> bool
Bring the signature in line with the list just written: a new one when signing is on,...
QString m_reencryptScope
The folder the re-encryption in flight covers, for the push hold.
SimpleTransaction m_transaction
auto entryHash(const QString &file) const -> QByteArray
SHA-256 of an entry's bytes, read as a regular file without following a link.
void unexpectedRecipients(const QString &dir, const QStringList &files, const QStringList &details)
A run left files alone: re-encrypting one would let someone on its folder's list read it who cannot n...
auto settleAutoPushHold(const ReencryptResult &result, bool agreedRun) -> bool
Bring the record of entries a removed recipient still reads up to date with a run,...
auto signGpgIdFile(const QString &gpgIdFile, const QByteArray &contents) -> bool
Sign a .gpg-id with the configured key and verify the result; failures are reported through critical(...
bool m_pushAfterReencrypt
QProcessEnvironment m_reencryptEnv
void reencryptProgress(int current, int total)
Re-encryption progress: current of total files checked.
void reencryptAfterFailedCommit(const QString &path, int gitExit, const QString &gitOut, const QString &gitErr, const QString &gpgIdFile, const std::optional< PreviousList > &previous)
After Init() wrote the new list but could not commit it: report Git's failure and re-encrypt without ...
void executeMoveGit(const QString &src, const QString &destFile, bool force)
Execute git move operation.
void endReencryptPath()
A reencryptPath() run is over, whether it finished, failed, was cancelled or was refused; the main wi...
auto translatePathForWsl(const QString &path, const QString &exe) const -> QString
Translate path for the given exe when WSL-routed: wraps in wslpath substitution, otherwise returns pa...
void finished(int id, int exitCode, const QString &out, const QString &err) override
Handle process completion.
void reencryptWithoutGit(const QString &dir, const QString &gitError)
Re-encrypt dir to the .gpg-id Init() wrote although its commit failed, without any Git step (they wou...
auto addGenerationHeader(const QString &gpgIdFile, const GpgIdSigner &signer, QByteArray *contents) -> bool
Put the generation header on a list that is about to be signed: reserve a generation above what this ...
auto restoreBackup(const QString &path, QStringList &problems) -> bool
Put a 1.8.x backup back in its entry's place when the entry is missing; report it when both exist (bo...
void startMovedReencrypts()
Start the runs in m_movedToReencrypt, one at a time, while none is in flight; then send a deferred pu...
auto gitAddGpgId(const QString &gpgIdFile, const QString &gpgIdSigFile, QString *out, QString *err) -> int
Stage a .gpg-id and, when given, its .sig, and commit both in one commit, so no commit in the history...
std::optional< UncommittedGpgId > m_uncommittedGpgId
void reencryptAlso(const QString &dir, const QStringList &files, const AppSettings &settings)
Re-encrypt files in dir after the user agreed to it.
std::atomic< bool > m_reencryptCancel
void GitPull() override
Pull from remote.
void reencryptMoved(const PendingMove &move)
Queue a re-encryption of what move moved, if it moved and another .gpg-id applies where it landed; a ...
auto refuseLinkedGpgIdFolder(const QString &path) -> bool
Refuse a folder, or a .gpg-id/.gpg-id.sig in it, that is a link: writing there would reach outside th...
auto decryptEntry(const QString &fileName, QByteArray *plaintext, QString *why) -> bool
Decrypt fileName for re-encryption.
auto refuseInitBeforeWrite(const QString &gpgIdFile, const GpgIdSigner &signer) -> bool
The checks Init() runs before it writes anything: no re-encryption running, the signing key's secret ...
void reportReencryptOutcome(const ReencryptResult &result, bool stillRead)
The status line for a run, and the push after it when one is due and nothing holds it.
auto isTrustedEntry(const QString &fileName, const QSet< QString > &listNow) const -> bool
Whether an entry that would gain readers is taken without a question: the user moved or copied it in,...
void Show(QString file) override
Show decrypted password.
std::optional< WrittenGpgId > m_writtenGpgId
auto pgpg(const QString &path) const -> QString
Translate path for gpg when WSL-routed: wraps in wslpath substitution, otherwise returns path unchang...
static auto namedReaders(const QSet< QString > &fprs, const QHash< QString, QString > &names) -> QString
The names of fprs for a question or a failure, sorted.
auto entriesToReencrypt(const QString &dir, QStringList *failed) -> QStringList
The entries under dir a run considers, telling the user about anything skipped for not being a regula...
auto storeGit(const QStringList &args, QString *out) -> bool override
Run git with -C <store> in the store, blocking.
QQueue< PendingInsert > m_pendingInserts
The inserts whose gpg step has not ended yet, oldest first.
void GitPull_b(int timeoutMs) override
Run git pull in the store and wait for it, at most timeoutMs.
auto readersAnEditWouldAdd(const QString &file) -> EditReaders override
Who saving over an existing entry would let read it who may not now.
QHash< QString, QSet< QString > > m_removedReaders
auto ciphertextHolds(const QString &ciphertext, const QByteArray &plaintext) -> bool
Decrypt ciphertext again and compare it with plaintext, byte for byte, so nothing replaces an entry u...
NativeGrep m_grep
Background search over the decrypted store; relays to finishedGrep.
auto resolveMoveDestination(const QString &src, const QString &dest, bool force) -> QString
Resolve destination for move operation.
auto recoverReencryptLeftovers(const QString &dir) -> bool
Deal with what a crashed or failed earlier run left under dir before touching anything: stale tempora...
void GitPush() override
Push to remote. While a re-encryption runs the push is held (Users â–¸ OK and a copy ask for it as soon...
void Move(const QString src, const QString dest, const bool force) override
Move password file.
void sendDeferredPush()
Make the push GitPush() deferred, once no run is in flight and no move is waiting; an automatic one o...
void dropStaleTemporary(const QString &path)
Remove a stale temporary a crashed run left, unless it was modified within the hour: on a shared stor...
bool m_deferredPushByHand
std::optional< PreviousList > m_previousList
void startReencryptPath()
A reencryptPath() run is about to start its worker thread.
void reportFailedEntries(const QStringList &failed)
Tell the user which entries a run could not re-encrypt, the first few by name.
auto getKeysFromFile(const QString &fileName) -> QStringList
Read recipients from file.
auto commitName(const QString &path) const -> QString
How a commit message names a file of the store: relative to the store, without .gpg ("work/bank",...
auto reencryptUsesGit() const -> bool
gitConfigured(), unless the current run is one reencryptWithoutGit() started.
auto gitConfigured() const -> bool
Git is enabled and an executable is configured.
void reencryptPath(const QString &dir)
Re-encrypt entire directory.
auto pgit(const QString &path) const -> QString
Translate path for git when WSL-routed: wraps in wslpath substitution, otherwise returns path unchang...
void keepPreviousList(const QString &gpgIdFile, const std::optional< PreviousList > &previous)
Take previous as the PreviousList of the run Init() starts for gpgIdFile, unless a run is active or a...
auto pullBeforeReencrypt() -> bool
Pull before a run, when the store is a Git repository and automatic pulling is on.
void gitCommit(const QString &file, const QString &msg)
Commit one path to git.
void beforeExecute(PROCESS id) override
Open a transaction for every execution.
auto gpgIdSigner() -> GpgIdSigner
The signer for this store's .gpg-id, bound to the configured gpg and signing keys and to execBlocking...
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 ...
static auto isIdle() -> bool
Whether neither backend runs or waits for anything: after a switch of backend the previous one is kep...
auto storeEnvironment() const -> QProcessEnvironment
The environment QtPass runs the store's processes in.
AppSettings m_settings
Application settings snapshot injected at init() time.
static auto getGpgIdPath(const QString &for_file, const QString &passStore) -> QString
Get .gpg-id file path for a password file.
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",...
auto unfinishedGitOperationReason() -> QString
The unfinished git operation in progress in the store, if any.
@ 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.
static auto maxOutputArgs() -> QStringList
The gpg options that enforce kMaxPlaintextBytes.
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.
static auto exactRecipientArg(const QString &line) -> QString
A bare mail address in gpg's exact form, <address>; any other line as written.
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.
static auto enabledKeyLines(const QList< UserInfo > &users) -> QStringList
The enabled users' key IDs, as Init() writes them to .gpg-id.
Executor exec
Internal command executor for queuing and running subprocesses.
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())...
void init(const AppSettings &settings)
Initialize the Pass instance with a settings snapshot.
auto refuseChangedList() -> bool
Refuse an Init() under initIfUnchanged() when the folder's list no longer reads as the caller read it...
auto withCurrentGitPin(QProcessEnvironment base) const -> QProcessEnvironment
base with GIT_DIR and GIT_WORK_TREE as the store is now (Util::gitStoreVariables()),...
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.
void updateEnv()
Update environment for subprocesses.
void idle()
Nothing of the store's runs or waits any more (isIdle()).
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 constexpr qint64 kMaxPlaintextBytes
Most bytes of plaintext a gpg decryption may produce.
@ 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.
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 transactionAdd(Enums::PROCESS process)
Note that process has been queued.
auto transactionIsOver(Enums::PROCESS current) -> Enums::PROCESS
Tell whether the process that just finished ends the oldest pending transaction, and take that transa...
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 isUnderLink(const QString &path, const QString &storeRoot, bool includeSelf=true) -> bool
Whether the way from storeRoot down to path passes through a symbolic link or NTFS junction: path its...
static auto writeFileReplacing(const QString &path, const QByteArray &bytes, bool replace, QString *error=nullptr) -> bool
Write bytes as the file path through stageFileReplacing().
static auto regularFilesUnder(const QString &dir, const QStringList &nameFilters, QStringList *skipped=nullptr, bool hiddenFiles=false, QStringList *unlisted=nullptr) -> QStringList
Regular files under dir whose name matches one of nameFilters, found by walking only real directories...
static constexpr qint64 kMaxGpgIdBytes
Most bytes of a .gpg-id QtPass reads.
static auto displayable(const QString &text, bool lineBreaks=true) -> QString
text with the characters that change how the text around them reads replaced by U+FFFD,...
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 replaceFile(const QString &from, const QString &to, bool replace) -> bool
Give the file at from the name to, atomically and without following anything: the operating system's ...
static auto joinPath(const QString &dir, const QString &name) -> QString
name in dir, as the file system means it.
static auto copyFileReplacing(const QString &src, const QString &dst, bool replace, QString *error=nullptr) -> bool
Copy the regular file src to the name dst through stageFileReplacing(): src is read through a handle ...
static auto newLinesRegex() -> const QRegularExpression &
Returns a regex to match newline characters.
static auto normalizeFolderPath(const QString &path) -> QString
Ensure a folder path always ends with '/'.
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...
EntryRecord: the entry paths this device has saved, kept outside the store.
Executor, the FIFO queue every gpg, git and pass child process of QtPass goes through,...
Rollback detection for signed .gpg-id files: the generation counter and the record of what was last s...
ImitatePass, the backend that does what pass does by running gpg and git itself.
PassBackendFactory, which constructs the two Pass backends on demand and hands out the one the settin...
The "qtpass" logging category.
Plain value-object holding all flat QtPass configuration.
QString gpgExecutable
Path to the gpg/gpg2 executable.
QString passStore
Password-store root path.
QString gitExecutable
Path to the git executable.
bool useGit
Enable git integration.
bool addGPGId
Auto-add .gpg-id files to git.
What the user was shown for an entry: its bytes and its folder's keys.
std::optional< QSet< QString > > now
Encrypted to now, if gpg can.
QSet< QString > before
Encrypted to before Init().
QString file
The entry's path in the store, where output goes.
bool overwrite
Whether an entry already at file may be replaced.
QString output
The ciphertext file gpg writes, inside scratch.
A move whose re-encryption is decided once it has run.
QString destFile
Where to: the entry's .gpg file, or the folder.
std::optional< bool > landed
Whether its git mv succeeded, once that has run (finished()).
The list a folder had before Init() replaced it, for the run it starts. It tells whom the change adde...
How re-encrypting one entry changes who can read it.
QSet< QString > gaining
Those, by primary fingerprint.
QSet< QString > losing
Removed recipients who still read it.
QSet< QString > listNow
The list's keys now.
bool gains
Someone not added by this change gains it.
Outcome of one reencryptPath() run; filled on the worker thread and consumed by finishReencrypt() on ...
int reencrypted
Files rewritten for the current recipients.
QStringList unexpectedDetails
QList< QByteArray > unexpectedHashes
int checked
Files whose recipients were inspected.
int total
.gpg files found under the directory.
QList< QSet< QString > > unexpectedReaders
QHash< QString, QSet< QString > > stillReadByRemoved
QStringList walked
Entries whose recipients the run judged.
bool aborted
Stopped early on an error already reported.
QStringList rewritten
Those files, for EntryRecord.
A .gpg-id Init() wrote but could not commit.
QString folder
The folder whose recipients changed.
QString gitError
What Git said when the commit failed.
QHash< QString, QString > names
Primary fingerprint to a name.
QHash< QString, QString > primaries
Key ID to primary fingerprint.
QHash< QString, ListKeys > lists
.gpg-id path to its keys.
The .gpg-id Init() wrote for the run it starts: the recipients the user ticked, as written.
What saving over an existing entry would change about who reads it (readersAnEditWouldAdd()).
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...