Branch data Line data Source code
1 : : // SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2 : : // SPDX-License-Identifier: GPL-3.0-or-later
3 : : /**
4 : : * @file
5 : : * @brief Implements ImitatePass: the gpg and git command sequences behind each
6 : : * operation, the transactions that group them, and the re-encryption worker
7 : : * thread.
8 : : */
9 : : #include "imitatepass.h"
10 : : #include "entryrecord.h"
11 : : #include "executor.h"
12 : : #include "gpgidgeneration.h"
13 : : #include "passbackendfactory.h"
14 : : #include "util.h"
15 : : #include <QCryptographicHash>
16 : : #include <QDateTime>
17 : : #include <QDir>
18 : : #include <QElapsedTimer>
19 : : #include <QFile>
20 : : #include <QFileInfo>
21 : : #include <QLocale>
22 : : #include <QPointer>
23 : : #include <QProcess>
24 : : #include <QRegularExpression>
25 : : #include <QThread>
26 : : #include <QTimer>
27 : : #include <algorithm>
28 : : #include <utility>
29 : :
30 : : #include "qtpasslogging.h"
31 : :
32 : : using Enums::CLIPBOARD_ALWAYS;
33 : : using Enums::CLIPBOARD_NEVER;
34 : : using Enums::CLIPBOARD_ON_DEMAND;
35 : : using Enums::GIT_ADD;
36 : : using Enums::GIT_COMMIT;
37 : : using Enums::GIT_COPY;
38 : : using Enums::GIT_INIT;
39 : : using Enums::GIT_MOVE;
40 : : using Enums::GIT_PULL;
41 : : using Enums::GIT_PUSH;
42 : : using Enums::GIT_RM;
43 : : using Enums::GPG_GENKEYS;
44 : : using Enums::INVALID;
45 : : using Enums::PASS_COPY;
46 : : using Enums::PASS_GREP;
47 : : using Enums::PASS_INIT;
48 : : using Enums::PASS_INSERT;
49 : : using Enums::PASS_MOVE;
50 : : using Enums::PASS_REMOVE;
51 : : using Enums::PASS_SHOW;
52 : : using Enums::PROCESS_COUNT;
53 : :
54 : 292 : ImitatePass::ImitatePass() : m_grep(this) {
55 : 292 : connect(&m_grep, &NativeGrep::finished, this, &ImitatePass::finishedGrep);
56 : 292 : }
57 : :
58 : 299 : ImitatePass::~ImitatePass() {
59 : : // Grep workers wind down meanwhile; m_grep's destructor waits for them.
60 : 292 : m_grep.cancel();
61 : : // The re-encryption worker calls members, so join it with no timeout; it
62 : : // ends its own blocked process on the flag (see execBlocking()).
63 [ + + + - ]: 292 : if (m_reencryptThread && m_reencryptThread->isRunning()) {
64 : : m_reencryptCancel.store(true);
65 : 6 : m_reencryptThread->wait();
66 : : }
67 : 883 : }
68 : :
69 : : // The helpers are shared by the owning thread and the worker; thread affinity
70 : : // tells them apart. Only the worker touches its QProcess, so a cancel can
71 : : // never hit an exited process or a reused pid.
72 : 1836 : auto ImitatePass::prepareBlocking(QProcess &process)
73 : : -> const std::atomic_bool * {
74 : : // In the store's environment: the git ceiling QtPass's own does not
75 : : // carry.
76 [ + + ]: 1836 : if (QThread::currentThread() == thread()) {
77 : 795 : process.setProcessEnvironment(storeEnvironment());
78 : 795 : return nullptr;
79 : : }
80 : 1041 : process.setProcessEnvironment(withCurrentGitPin(m_reencryptEnv));
81 : 1041 : return &m_reencryptCancel;
82 : : }
83 : :
84 : 1429 : auto ImitatePass::execBlocking(const QString &app, const QStringList &args,
85 : : const QString &input, QString *process_out,
86 : : QString *process_err) -> int {
87 : 1429 : QProcess process;
88 : 1429 : const std::atomic_bool *cancel = prepareBlocking(process);
89 : 1429 : return Executor::executeBlocking(process, app, args, input, process_out,
90 : 1429 : process_err, cancel);
91 : 1429 : }
92 : :
93 : 403 : auto ImitatePass::execBlockingRaw(const QString &app, const QStringList &args,
94 : : const QByteArray &input,
95 : : QByteArray *process_out) -> int {
96 : 403 : QProcess process;
97 : 403 : const std::atomic_bool *cancel = prepareBlocking(process);
98 : 403 : return Executor::executeBlockingRaw(process, app, args, input, process_out,
99 : 403 : nullptr, cancel);
100 : 403 : }
101 : :
102 : 1069 : auto ImitatePass::execBlocking(const QString &app, const QStringList &args,
103 : : QString *process_out, QString *process_err)
104 : : -> int {
105 : 2138 : return execBlocking(app, args, QString(), process_out, process_err);
106 : : }
107 : :
108 : 1409 : auto ImitatePass::translatePathForWsl(const QString &path,
109 : : const QString &exe) const -> QString {
110 : 1409 : return Executor::translatePathForWsl(path, exe);
111 : : }
112 : :
113 : 291 : auto ImitatePass::storeGit(const QStringList &args, QString *out) -> bool {
114 [ + - + + ]: 291 : if (!m_settings.useGit || m_settings.gitExecutable.isEmpty()) {
115 : : return false;
116 : : }
117 : : // -C the store: executeBlocking sets no working directory, so git would
118 : : // otherwise run in QtPass's launch directory.
119 : 276 : const QString store = pgit(m_settings.passStore);
120 : 276 : return execBlocking(m_settings.gitExecutable,
121 : 1104 : QStringList{QStringLiteral("-C"), store} + args, out,
122 : 276 : nullptr) == 0;
123 : : }
124 : :
125 : 732 : auto ImitatePass::pgit(const QString &path) const -> QString {
126 : 732 : return translatePathForWsl(path, m_settings.gitExecutable);
127 : : }
128 : :
129 : 677 : auto ImitatePass::pgpg(const QString &path) const -> QString {
130 : 677 : return translatePathForWsl(path, m_settings.gpgExecutable);
131 : : }
132 : :
133 : 2 : void ImitatePass::GitInit() {
134 : 8 : executeGit(GIT_INIT, {"init", pgit(m_settings.passStore)});
135 : 4 : }
136 : :
137 : 16 : void ImitatePass::GitPull() {
138 [ + + ]: 16 : if (gitReady()) {
139 : 56 : executeGit(GIT_PULL, {"pull"});
140 : : }
141 : 16 : }
142 : :
143 : : // Blocks until git finishes.
144 : 6 : void ImitatePass::GitPull_b(int timeoutMs) {
145 [ + + ]: 6 : if (!gitReady())
146 : 2 : return;
147 : : // -C the store: executeBlocking sets no working directory, so without it
148 : : // git would run in QtPass's launch directory and pull an unrelated
149 : : // repository, or fail with "not a git repository".
150 : 4 : QString err;
151 : 4 : QProcess process;
152 : 4 : const std::atomic_bool *cancel = prepareBlocking(process);
153 : 4 : QElapsedTimer timer;
154 : 4 : timer.start();
155 : : const int rc =
156 : 20 : Executor::executeBlocking(process, m_settings.gitExecutable,
157 : 4 : {"-C", pgit(m_settings.passStore), "pull"},
158 : 8 : QString(), nullptr, &err, cancel, timeoutMs);
159 [ + + + + ]: 4 : if (rc != 0 && timer.elapsed() >= timeoutMs) {
160 : 2 : emit statusMsg(pullTimedOut(timeoutMs), 5000);
161 [ + + ]: 3 : } else if (rc != 0) {
162 : 4 : emit statusMsg(tr("Git pull failed: %1").arg(err.trimmed()), 5000);
163 : : }
164 : 8 : }
165 : :
166 : 37 : void ImitatePass::GitPush() {
167 : : // Now it would send the new .gpg-id with entries still encrypted to the
168 : : // previous recipients, a key just removed among them, also when the run
169 : : // then fails, and push a clean run twice. The same for a move whose
170 : : // re-encryption is not decided yet, or waits for the run in flight.
171 [ + + + + : 37 : if ((m_reencryptActive && !m_reencryptPushing) || !m_pendingMoves.isEmpty() ||
+ + - + ]
172 : : !m_movedToReencrypt.isEmpty()) {
173 : 8 : m_pushAfterReencrypt = true;
174 [ + - + + ]: 8 : m_deferredPushByHand = m_deferredPushByHand || !pushIsAutomatic();
175 : 8 : return;
176 : : }
177 [ + + ]: 29 : if (gitReady()) {
178 : 108 : executeGit(GIT_PUSH, {"push"});
179 : : }
180 : : }
181 : :
182 : 207 : void ImitatePass::sendDeferredPush() {
183 [ + + + + : 207 : if (!m_pushAfterReencrypt || m_reencryptActive || !m_pendingMoves.isEmpty() ||
+ - + - ]
184 : : !m_movedToReencrypt.isEmpty()) {
185 : : return;
186 : : }
187 : 4 : const bool byHand = m_deferredPushByHand;
188 : 4 : m_pushAfterReencrypt = false;
189 : 4 : m_deferredPushByHand = false;
190 [ + + + + ]: 4 : if (!byHand && autoPushHeld()) {
191 : 1 : emit statusMsg(tr("Not pushing: an earlier re-encryption in this "
192 : : "store did not finish"),
193 : : 5000);
194 : 1 : return;
195 : : }
196 : 3 : GitPush();
197 : : }
198 : :
199 : 207 : void ImitatePass::startMovedReencrypts() {
200 : : // A run refused at its start (reencryptPath() said why) leaves the next.
201 [ + + + + ]: 221 : while (!m_reencryptActive && !m_movedToReencrypt.isEmpty()) {
202 : 14 : const QString scope = m_movedToReencrypt.takeFirst();
203 : : // What the user moved is re-encrypted whatever it was encrypted to.
204 : 28 : m_reencryptTrusted = {QDir::cleanPath(scope)};
205 : 14 : reencryptPath(scope);
206 [ + + ]: 14 : if (!m_reencryptActive) {
207 : 1 : m_reencryptTrusted.clear();
208 : : // What moved is still encrypted for the recipients it came from: the
209 : : // automatic push after the move waits, as after a run that did not
210 : : // finish. A push by hand still goes.
211 : 1 : holdAutoPush(scope);
212 : : }
213 : : }
214 : 207 : sendDeferredPush();
215 : 221 : }
216 : :
217 : 82 : void ImitatePass::Show(QString file) {
218 [ + + + ]: 164 : if (refuseLinkedPath(file + ".gpg")) {
219 : 4 : return;
220 : : }
221 : : queueShow(file);
222 : 78 : file = m_settings.passStore + file + ".gpg";
223 : : QStringList args = {"-d", "--quiet", "--yes", "--no-encrypt-to",
224 : 1014 : "--batch", "--use-agent"};
225 : 234 : args << maxOutputArgs() << QStringLiteral("--") << pgpg(file);
226 : 156 : executeGpg(PASS_SHOW, args);
227 : : }
228 : :
229 : : namespace {
230 : :
231 : : /// Cap on the entries listed in one aggregated re-encryption dialog.
232 : : constexpr int kReencryptMaxListedFailures = 15;
233 : :
234 : : /**
235 : : * @brief The arguments of every gpg encrypt call: @p leading, then encrypt
236 : : * to exactly @p recipients from stdin into @p output. --no-encrypt-to keeps
237 : : * an `encrypt-to` line in the user's gpg.conf from adding a recipient the
238 : : * (possibly signed) .gpg-id does not list; --compress-algo=none mirrors
239 : : * pass(1). --no-textmode keeps a `textmode` line from storing the entry as
240 : : * text, which a decrypt hands back without its carriage returns: the entry
241 : : * is stored as the bytes given.
242 : : */
243 : : /// Stands for a recipient no key ID names: one gpg encrypted to without
244 : : /// saying whom, or whoever left a list gpg can no longer encrypt to.
245 : : constexpr QLatin1StringView kUnknownReader("?");
246 : :
247 : 270 : auto encryptArgs(QStringList leading, const QString &output,
248 : : const QStringList &recipients) -> QStringList {
249 : 1080 : leading << "-eq" << "--compress-algo=none" << "--no-encrypt-to"
250 : 810 : << "--no-textmode" << "--output" << output;
251 [ + + ]: 564 : for (const QString &recipient : recipients) {
252 : : // A bare address as gpg's exact form, not a pattern.
253 : 882 : leading << "-r" << Pass::exactRecipientArg(recipient);
254 : : }
255 : 540 : leading << "-";
256 : 270 : return leading;
257 : : }
258 : :
259 : : } // namespace
260 : :
261 : 115 : auto ImitatePass::recipientsForEntry(const QString &file,
262 : : QStringList *recipients) -> bool {
263 : 115 : recipients->clear();
264 [ + + + + ]: 115 : if (refuseSkippedGpgId(file, gpgIdSigner().enabled())) {
265 : : return false;
266 : : }
267 : 113 : QString why;
268 [ + + + + ]: 226 : if (!loadVerifiedRecipients(Pass::getGpgIdPath(file, m_settings.passStore),
269 : : recipients, &why)) {
270 : 7 : emit critical(tr("Check .gpg-id file signature!"), why);
271 : 7 : return false;
272 : : }
273 [ + + ]: 106 : if (recipients->isEmpty()) {
274 : 2 : emit critical(tr("Can not edit"),
275 : 0 : tr("Could not read encryption key to use, .gpg-id "
276 : : "file missing or invalid."));
277 : 1 : return false;
278 : : }
279 : : return true;
280 : : }
281 : :
282 : 21 : auto ImitatePass::readersAnEditWouldAdd(const QString &file) -> EditReaders {
283 : : // The path Insert() writes, read as decryptEntry() reads it; anything
284 : : // that cannot be told is left to Insert() to refuse or carry out.
285 : : const QString path =
286 : 21 : QDir::cleanPath(Util::joinPath(m_settings.passStore, file) + ".gpg");
287 : 21 : const QFileInfo entry(path);
288 [ + + + + : 21 : if (!entry.isFile() || entry.isSymLink()) {
- + ]
289 : 3 : return {};
290 : : }
291 : 18 : const QString gpgIdPath = Pass::getGpgIdPath(path, m_settings.passStore);
292 : 18 : QStringList recipients;
293 : 18 : QString why;
294 [ + + + + : 18 : if (!loadVerifiedRecipients(gpgIdPath, &recipients, &why) ||
+ ]
295 : : recipients.isEmpty()) {
296 : 2 : return {};
297 : : }
298 : 16 : QHash<QString, QString> primaries;
299 : 16 : QHash<QString, QString> names;
300 : : const std::optional<QSet<QString>> now =
301 : 16 : keysEncryptedTo(recipients, primaries, names);
302 [ + + + + ]: 31 : if (!now || now->contains(kUnknownReader)) {
303 : 2 : return {};
304 : : }
305 : : // With each key's ID: two keys can carry the same name, and a list that
306 : : // swapped one for the other while the question was open must not read
307 : : // as unchanged.
308 : 12 : const auto named = [&names](const QSet<QString> &fprs) {
309 : 12 : QStringList who;
310 : : for (const QString &fpr : fprs) {
311 [ + + + + : 23 : who << (names.contains(fpr) ? QStringLiteral("%1 (%2)").arg(
+ + - - ]
312 [ + + + + : 24 : names.value(fpr), fpr.right(16))
+ + + - -
- - - - ]
313 : : : fpr.right(16));
314 : : }
315 : : who.sort();
316 : 12 : return who;
317 : 14 : };
318 : : // The entry's recipient IDs are written by whoever can push. With signed
319 : : // lists, an entry whose folder takes a parent's list, at a path this
320 : : // device never saved, may be a folder renamed past its own list with an
321 : : // ID added for the attacker: asked about whatever its IDs say.
322 : : const bool inherited =
323 : 28 : QDir::cleanPath(gpgIdPath) !=
324 : 28 : QDir::cleanPath(QDir(entry.absolutePath()).filePath(".gpg-id"));
325 : : // Never seeded here: what the check finds may be the pusher's renamed
326 : : // folder. A store not seeded yet knows nothing, so it asks.
327 [ + + + + : 27 : if (gpgIdSigner().enabled() && inherited && !EntryRecord::known(path)) {
+ + + + +
+ ]
328 : : return {named(*now), true};
329 : : }
330 : 13 : const QStringList ids = getKeysFromFile(path);
331 [ + + ]: 13 : if (ids.isEmpty()) {
332 : 1 : return {};
333 : : }
334 : : const bool hidden =
335 : 12 : std::all_of(ids.cbegin(), ids.cend(), [](const QString &id) {
336 [ + + ]: 13 : return id == QLatin1String("0000000000000000");
337 : : });
338 [ + + ]: 12 : if (hidden) {
339 : : return {{tr("anyone on the list: the entry's recipients cannot be told")},
340 : 1 : false};
341 : : }
342 : : QSet<QString> gaining = *now;
343 : 11 : gaining.subtract(primaryKeysOf(ids, primaries, names));
344 : : return {named(gaining), false};
345 : 51 : }
346 : :
347 : 120 : void ImitatePass::Insert(QString file, QString newValue, bool overwrite) {
348 : : // The dialog names a new entry relative to the store; gpg used to resolve
349 : : // that in its working directory. Everything below works on the one path.
350 : 120 : file = QDir::cleanPath(Util::joinPath(m_settings.passStore, file) + ".gpg");
351 [ + + ]: 120 : if (refuseLinkedPath(file)) {
352 : 100 : return;
353 : : }
354 [ + + ]: 118 : if (refuseUnfinishedGitOperation()) {
355 : : return;
356 : : }
357 : : // gpg used to refuse an existing output without --yes; it writes
358 : : // elsewhere now, so the check is ours here, and again at the rename.
359 : 116 : const QFileInfo target(file);
360 [ + + + + : 116 : if (!overwrite && (target.exists() || target.isSymLink())) {
+ + - + ]
361 : 3 : emit critical(tr("Cannot add"), tr("%1 already exists.").arg(file));
362 : 1 : return;
363 : : }
364 : 115 : QStringList recipients;
365 [ + + + ]: 115 : if (!recipientsForEntry(file, &recipients)) {
366 : : return;
367 : : }
368 : : // gpg never opens a store path for output: a co-writer could make it a link
369 : : // after refuseLinkedPath(). gpg writes into a 0700 directory of our own and
370 : : // placeEncryptedFile() brings the bytes in via an open handle and a rename.
371 : : auto scratch = std::make_shared<QTemporaryDir>();
372 [ + + + ]: 105 : if (!scratch->isValid()) {
373 : 2 : emit critical(tr("Cannot write"),
374 : 1 : tr("Cannot create a temporary directory: %1")
375 [ + + ]: 2 : .arg(scratch->errorString()));
376 : 1 : return;
377 : : }
378 : : // A line two key blocks hold may encrypt to either. Asked last, so a
379 : : // refusal for anything else runs no gpg.
380 [ + + + ]: 104 : if (refuseKeyLinesHeldTwice(recipients)) {
381 : : return;
382 : : }
383 : 204 : const QString output = scratch->filePath(QStringLiteral("entry.gpg"));
384 : 102 : TransactionHelper trans(&m_transaction, PASS_INSERT);
385 : : const QStringList args =
386 : 816 : encryptArgs({"--batch", "--status-fd", "2"}, pgpg(output), recipients);
387 : 102 : m_pendingInserts.enqueue({std::move(scratch), output, file, overwrite});
388 : : // Past every refusal: this insert is now queued and will report once.
389 : : queueInsert(file);
390 : 102 : executeGpg(PASS_INSERT, args, newValue);
391 [ + + + ]: 102 : if (!gitReady()) {
392 : : return;
393 : : }
394 : : // -f so the store's own .gitignore (a tracked file any co-writer of a
395 : : // shared store can push) cannot keep an entry untracked. An ignored,
396 : : // uncommitted entry is expendable to Git: a later pull that needs its path
397 : : // deletes it, and the typed secret is then in no file and no commit. Edits
398 : : // are staged too: an entry left ignored and untracked by an older version
399 : : // would otherwise fail the commit below. On a tracked path the add is a
400 : : // no-op.
401 : 120 : executeGit(GIT_ADD, {"add", "-f", "--", pgit(file)});
402 [ + + + + : 79 : gitCommit(file, QString(overwrite ? "Edit" : "Add") + " for " +
+ ]
403 [ + + + ]: 60 : commitName(file) + " using QtPass.");
404 : 238 : }
405 : :
406 : 99 : auto ImitatePass::commitArgs() -> QStringList {
407 : : // As pass's git_commit(): -S when the store (or the user's git config)
408 : : // sets pass.signcommits. A commit that cannot be signed then fails, as
409 : : // with pass, rather than going in unsigned.
410 : 99 : QString out;
411 [ + + + - : 792 : const bool sign = execBlocking(m_settings.gitExecutable,
- - - ]
412 : 99 : {"-C", pgit(m_settings.passStore), "config",
413 : : "--bool", "--get", "pass.signcommits"},
414 [ + + ]: 99 : &out) == 0 &&
415 [ + - - ]: 143 : out.trimmed() == QLatin1String("true");
416 [ + + + + : 313 : return sign ? QStringList{"commit", "-S"} : QStringList{"commit"};
+ + + + +
+ + + + +
- - - - -
- - - ]
417 : 99 : }
418 : :
419 : 26 : void ImitatePass::gitCommit(const QString &file, const QString &msg) {
420 : 78 : gitCommit(QStringList{file}, msg);
421 : 26 : }
422 : :
423 : 46 : void ImitatePass::gitCommit(const QStringList &files, const QString &msg) {
424 : 276 : QStringList args = commitArgs() + QStringList{"-m", msg, "--"};
425 [ + + ]: 112 : for (const QString &file : files) {
426 : 132 : args << pgit(file);
427 : : }
428 : 92 : executeGit(GIT_COMMIT, args);
429 : 138 : }
430 : :
431 : 20 : void ImitatePass::Remove(QString file, bool isDir) {
432 : : // No trailing separator: "link/" makes git look for what is behind the
433 : : // link ("pathspec did not match") and rm follow it.
434 : 20 : file = QDir::cleanPath(m_settings.passStore + file);
435 [ + + ]: 20 : if (!isDir) {
436 : 10 : file += ".gpg";
437 : : }
438 : : // A link itself may go; anything behind one is not the store's to delete.
439 [ + + ]: 20 : if (refuseLinkedPath(file, LinkScope::ParentsOnly)) {
440 : 10 : return;
441 : : }
442 [ + - + + ]: 18 : if (refuseUnfinishedGitOperation() || refusePendingPull()) {
443 : 1 : return;
444 : : }
445 : : // As in Move(): no message box inside the transaction, so it holds only
446 : : // the Git commands.
447 : 17 : const QString path = commitName(file);
448 [ + + + ]: 17 : if (Util::isLinkedFolder(file)) {
449 : : // Unlink it here, never through a recursive rm: the link goes, what it
450 : : // points to stays. Git then only has to forget it, if it knew it.
451 [ + + + ]: 7 : if (!Util::removeTree(file)) {
452 : 2 : emit critical(tr("Delete failed"),
453 : 2 : tr("Could not remove the link %1.").arg(file));
454 : 1 : return;
455 : : }
456 : : // Only when git knew it: a commit matching nothing (a link never
457 : : // committed) exits 1 and reads as a failed removal. ls-files reads the
458 : : // index, so it still answers now that the link is gone.
459 [ + + + + : 6 : if (gitReady() && gitTracks(file)) {
+ + ]
460 : 1 : TransactionHelper trans(&m_transaction, PASS_REMOVE);
461 : 7 : executeGit(GIT_RM, {"rm", "-q", "--cached", "--", pgit(file)});
462 : 2 : gitCommit(file, "Remove for " + path + " using QtPass.");
463 : : }
464 : 6 : return;
465 : : }
466 [ + + + ]: 10 : if (gitReady()) {
467 : 2 : TransactionHelper trans(&m_transaction, PASS_REMOVE);
468 [ + + + - : 12 : executeGit(GIT_RM, {"rm", (isDir ? "-rf" : "-f"), "--", pgit(file)});
- ]
469 : 4 : gitCommit(file, "Remove for " + path + " using QtPass.");
470 : : } else {
471 : : // Without Git nothing else reports a failure: git rm would print its own.
472 [ + + ]: 8 : if (isDir) {
473 : : // Never QDir::removeRecursively(): it follows a junction inside the
474 : : // folder and empties whatever that points to.
475 [ + + + ]: 3 : if (!Util::removeTree(file)) {
476 : : // As rm -rf, it went on past what it could not remove: the folder
477 : : // is still there, without the entries that could go.
478 : 2 : emit critical(tr("Delete failed"),
479 : 1 : tr("Could not remove all of %1. What could be removed "
480 : : "is gone; check what is left in it.")
481 : 2 : .arg(file));
482 : : }
483 : : } else {
484 : 5 : QFile entry(file);
485 [ + + + ]: 5 : if (!entry.remove()) {
486 : 2 : emit critical(
487 : 2 : tr("Delete failed"),
488 [ + + ]: 4 : tr("Could not remove %1: %2").arg(file, entry.errorString()));
489 : : }
490 : 5 : }
491 : : }
492 : 5 : }
493 : :
494 : 685 : auto ImitatePass::gpgIdSigner() -> GpgIdSigner {
495 : : GpgIdSigner signer{m_settings.gpgExecutable,
496 : 1370 : GpgIdSigner::keysFromSetting(m_settings.passSigningKey),
497 : 685 : [this](const QString &app, const QStringList &args,
498 : : const QString &input, QString *out, QString *err) {
499 : 257 : return execBlocking(app, args, input, out, err);
500 : 685 : }};
501 : 685 : signer.setStoreRoot(m_settings.passStore);
502 : 685 : return signer;
503 : : }
504 : :
505 : 28 : auto ImitatePass::addGenerationHeader(const QString &gpgIdFile,
506 : : const GpgIdSigner &signer,
507 : : QByteArray *contents) -> bool {
508 : : const std::optional<QString> folder =
509 : 28 : GpgIdGeneration::folderOf(gpgIdFile, m_settings.passStore);
510 [ - + ]: 28 : if (!folder) {
511 : 0 : emit critical(tr("Cannot update"),
512 : 0 : 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.")
515 : 0 : .arg(gpgIdFile));
516 : 0 : return false;
517 : : }
518 : : // The list on disk counts only if it is this folder's own, verified list:
519 : : // a signature vouches for the bytes, the folder line for the place.
520 : 28 : std::optional<qint64> verifiedOnDisk;
521 : 28 : std::optional<QString> storeOnDisk;
522 : 28 : QByteArray current;
523 [ + + + ]: 28 : if (signer.verifyFile(gpgIdFile, ¤t)) {
524 : 9 : const auto header = GpgIdGeneration::parse(current);
525 [ + - + - : 9 : if (header && (!header->folder || *header->folder == *folder)) {
+ + ]
526 : 8 : verifiedOnDisk = header->generation;
527 : : // The store's id comes only from a list this store accepts. A refused
528 : : // one (a rollback, a conflict) may be another store's, signed with
529 : : // the same key and copied in: taking its id over would make the list
530 : : // saved now one of that store too. Its generation still counts, so the
531 : : // next one is above it. Without the record, which it is cannot be
532 : : // told: a store id made up now could split the store from devices
533 : : // that know its own.
534 : 8 : QString unavailable;
535 : 8 : const GpgIdGeneration::Verdict verdict = GpgIdGeneration::accept(
536 : : gpgIdFile, current, m_settings.passStore, &unavailable);
537 [ - + ]: 8 : if (verdict == GpgIdGeneration::Verdict::RecordUnavailable) {
538 : 0 : emit critical(tr("Cannot update"), unavailable);
539 : : return false;
540 : : }
541 [ + + ]: 8 : if (verdict == GpgIdGeneration::Verdict::Accepted) {
542 : : storeOnDisk = header->store;
543 : : }
544 : : }
545 : : }
546 : 28 : QString why;
547 : : // The store's id: the one this device knows, else the one this store's
548 : : // lists already carry (#2050).
549 : : const std::optional<QString> store =
550 : 28 : GpgIdGeneration::storeIdFor(m_settings.passStore, storeOnDisk, &why);
551 [ - + ]: 28 : if (!store) {
552 : 0 : emit critical(tr("Cannot update"), why);
553 : 0 : return false;
554 : : }
555 : : const std::optional<qint64> generation =
556 : 28 : GpgIdGeneration::reserveNext(gpgIdFile, verifiedOnDisk, &why);
557 [ - + ]: 28 : if (!generation) {
558 : 0 : emit critical(tr("Cannot update"), why);
559 : 0 : return false;
560 : : }
561 : : *contents =
562 : 28 : GpgIdGeneration::withHeader(*generation, *folder, *contents, *store);
563 : 28 : return true;
564 : : }
565 : :
566 : 52 : auto ImitatePass::writeGpgIdFile(const QString &gpgIdFile,
567 : : const QList<UserInfo> &users,
568 : : QByteArray *written) -> bool {
569 : 52 : QByteArray contents;
570 : : bool secret_selected = false;
571 [ + + ]: 113 : for (const UserInfo &user : users) {
572 [ + + ]: 61 : if (user.enabled) {
573 : 60 : contents += (user.key_id + "\n").toUtf8();
574 : 60 : secret_selected |= user.have_secret;
575 : : }
576 : : }
577 : : // Without a signing key the plain list stays (GpgIdGeneration).
578 : 52 : const GpgIdSigner signer = gpgIdSigner();
579 [ + + + + : 52 : if (signer.enabled() && !addGenerationHeader(gpgIdFile, signer, &contents)) {
- ]
580 : : return false;
581 : : }
582 : : // Whole or not at all, owner-only (it names the store's keys); a link
583 : : // planted since Init's check is replaced, not written through.
584 : 52 : QString writeError;
585 [ + + + ]: 52 : if (!Util::writeFileReplacing(gpgIdFile, contents, true, &writeError)) {
586 : 1 : emit critical(tr("Cannot update"), writeError);
587 : 1 : return false;
588 : : }
589 [ + + ]: 51 : if (written != nullptr) {
590 : 47 : *written = contents;
591 : : }
592 [ + + ]: 51 : if (signer.enabled()) {
593 : : // From now on these bytes are this generation. The list is signed either
594 : : // way (unsigned is refused everywhere); if the record could not take them
595 : : // (another writer, record busy), the user is told to save once more.
596 : 28 : QString why;
597 [ + - + ]: 28 : if (!GpgIdGeneration::recordWritten(gpgIdFile, contents, &why)) {
598 : 0 : qCWarning(lcQtPass) << "Could not record the written .gpg-id:" << why;
599 : 0 : emit critical(
600 : 0 : tr("Recipient list written, but not recorded"),
601 : 0 : tr("%1 Save the recipients once more to get through.").arg(why));
602 : : }
603 : : }
604 [ + + ]: 51 : if (!secret_selected) {
605 : 14 : emit critical(
606 : 7 : tr("Check selected users!"),
607 : 7 : tr("None of the selected keys have a secret key available.\n"
608 : : "You will not be able to decrypt any newly added passwords!"));
609 : : }
610 : : return true;
611 : 52 : }
612 : :
613 : 28 : auto ImitatePass::signGpgIdFile(const QString &gpgIdFile,
614 : : const QByteArray &contents) -> bool {
615 : 28 : const GpgIdSigner signer = gpgIdSigner();
616 : 28 : QString why;
617 [ + + + ]: 28 : if (!signer.sign(gpgIdFile, contents, &why)) {
618 [ + + ]: 6 : emit critical(
619 : 3 : tr("GPG signing failed!"),
620 : 3 : why.trimmed().isEmpty()
621 [ + + + + ]: 9 : ? tr("Failed to sign %1.").arg(gpgIdFile)
622 [ + + + + : 7 : : tr("Failed to sign %1: %2").arg(gpgIdFile, why.trimmed()));
+ + - - -
- - - ]
623 : 3 : return false;
624 : : }
625 : 25 : QByteArray signedBytes;
626 [ + - + ]: 25 : if (!signer.verifyFile(gpgIdFile, &signedBytes)) {
627 : 0 : emit critical(tr("Check .gpg-id file signature!"),
628 : 0 : tr("Signature for %1 is invalid.").arg(gpgIdFile));
629 : 0 : return false;
630 : : }
631 : : return true;
632 : 28 : }
633 : :
634 : : // Synchronous on purpose: queued on the async executor, the add/commit raced
635 : : // reencryptPath()'s blocking backup commit for index.lock and either left the
636 : : // .gpg-id untracked or found nothing to commit.
637 : 13 : auto ImitatePass::gitAddGpgId(const QString &gpgIdFile,
638 : : const QString &gpgIdSigFile, QString *out,
639 : : QString *err) -> int {
640 : : const QString git = m_settings.gitExecutable;
641 : 13 : const QString store = pgit(m_settings.passStore);
642 : 35 : auto run = [&](const QStringList &args) -> int {
643 : 35 : QString runOut;
644 : 35 : QString runErr;
645 : : const int rc =
646 : 140 : execBlocking(git, QStringList{"-C", store} + args, &runOut, &runErr);
647 [ + - ]: 35 : if (out != nullptr) {
648 : 35 : out->append(runOut);
649 : : }
650 [ + - ]: 35 : if (err != nullptr) {
651 : 35 : err->append(runErr);
652 : : }
653 : 35 : return rc;
654 : 35 : };
655 : 26 : QStringList paths{pgit(gpgIdFile)};
656 [ + + ]: 13 : if (!gpgIdSigFile.isEmpty()) {
657 : 12 : paths << pgit(gpgIdSigFile);
658 : : }
659 : : // add stages new and modified files alike; already-clean ones are a no-op.
660 : 104 : int rc = run(QStringList{"add", "-f", "--"} + paths);
661 [ + + ]: 13 : if (rc != 0) {
662 : : return rc;
663 : : }
664 : : // Re-initialising with the same recipients changes nothing; that is not a
665 : : // failure, and `git commit` would make it one. diff --quiet: 0 nothing
666 : : // staged, 1 something staged, anything else is git failing.
667 : 120 : rc = run(QStringList{"diff", "--cached", "--quiet", "--"} + paths);
668 [ + + ]: 12 : if (rc == 0) {
669 : : return 0;
670 : : }
671 [ + + ]: 11 : if (rc != 1) {
672 : : return rc;
673 : : }
674 : 30 : return run(commitArgs() +
675 : 10 : QStringList{"-m",
676 : 10 : "Added " + commitName(gpgIdFile) + " using QtPass.",
677 : 70 : "--"} +
678 : 10 : paths);
679 : 33 : }
680 : :
681 : 3 : auto ImitatePass::gitTracks(const QString &file) -> bool {
682 [ + + + - : 24 : return execBlocking(m_settings.gitExecutable,
- ]
683 : 3 : {"-C", pgit(m_settings.passStore), "ls-files",
684 : 6 : "--error-unmatch", "--", pgit(file)}) == 0;
685 : 3 : }
686 : :
687 : 58 : auto ImitatePass::refuseLinkedGpgIdFolder(const QString &path) -> bool {
688 : : // A link planted later is replaced, not written through: the writes stage
689 : : // and rename.
690 : 58 : const QString folder = QDir::cleanPath(path);
691 : : // Init() places a folder spelled through a linked root's target itself.
692 : : const auto refusePlaced = [this](const QString &placed) {
693 : 171 : return refuseLinkedPath(placed, LinkScope::EntryAndParents,
694 : : PathSpelling::PlacedByCaller);
695 : : };
696 [ + + ]: 57 : return refusePlaced(path) ||
697 [ + + + + : 173 : refusePlaced(folder + QStringLiteral("/.gpg-id")) ||
+ + + - -
- - ]
698 : 228 : refusePlaced(folder + QStringLiteral("/.gpg-id.sig"));
699 : : }
700 : :
701 : 47 : auto ImitatePass::settleSignature(const QString &gpgIdFile,
702 : : const QByteArray &written,
703 : : const GpgIdSigner &signer, bool useGit,
704 : : QString *sigToCommit) -> bool {
705 : 47 : const QString gpgIdSigFile = gpgIdFile + ".sig";
706 [ + + ]: 47 : if (signer.enabled()) {
707 [ + + + ]: 28 : if (!signGpgIdFile(gpgIdFile, written)) {
708 : : return false;
709 : : }
710 : 25 : *sigToCommit = gpgIdSigFile;
711 : 25 : return true;
712 : : }
713 [ + + + ]: 19 : if (!QFile::exists(gpgIdSigFile)) {
714 : : return true;
715 : : }
716 : : // Signing was switched off; the removal goes into the same commit.
717 [ + + + - : 2 : const bool tracked = useGit && gitTracks(gpgIdSigFile);
+ ]
718 [ + - + ]: 2 : if (!QFile::remove(gpgIdSigFile)) {
719 : 0 : emit critical(
720 : 0 : tr("Cannot update"),
721 : 0 : tr("Failed to remove the old signature %1.").arg(gpgIdSigFile));
722 : 0 : return false;
723 : : }
724 [ + + ]: 2 : if (tracked) {
725 : 1 : *sigToCommit = gpgIdSigFile;
726 : : }
727 : : return true;
728 : : }
729 : :
730 : 264 : auto ImitatePass::fullKeyListing(QString *listing) -> int {
731 : 264 : QString err;
732 : 2112 : return execBlocking(m_settings.gpgExecutable,
733 : 264 : {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
734 : 264 : QStringLiteral("--with-colons"),
735 : 264 : QStringLiteral("--with-fingerprint"),
736 : 264 : QStringLiteral("--with-subkey-fingerprint"),
737 : 264 : QStringLiteral("--list-keys")},
738 : 264 : listing, &err);
739 : : }
740 : :
741 : 58 : void ImitatePass::Init(QString path, const QList<UserInfo> &users) {
742 : : // The .gpg-id is written as path + ".gpg-id": without the trailing
743 : : // separator (the context menu hands over a cleaned path) that would be a
744 : : // file beside the folder, not the folder's own list. A relative path names
745 : : // a folder in the store, as it does for pass, not one in the working
746 : : // directory.
747 : 58 : path = Util::joinPath(m_settings.passStore, path);
748 : : // Cleaned before any check: the checks clean what they look at, and the
749 : : // write must go to the same place. Left as /store/link/../team/, the
750 : : // system resolves link first and writes beside wherever it points.
751 : 58 : path = Util::normalizeFolderPath(QDir::cleanPath(path));
752 : 58 : QString inStore;
753 [ + + + + : 114 : if (refuseLinkedGpgIdFolder(path) ||
+ ]
754 : 56 : refuseFolderOutsideStore(path, &inStore)) {
755 : 5 : return;
756 : : }
757 : : // A pull still queued would land after the new list is written: as with
758 : : // pass, nothing is changed until it has finished.
759 [ + + - + : 53 : if (refuseUnfinishedGitOperation() || refusePendingPull()) {
+ + ]
760 : 1 : return;
761 : : }
762 : : // From here on in the store's own spelling, the same folder: one spelled
763 : : // through the target of a linked store root is not under the store as
764 : : // named, so each entry's nearest list was looked up past the new one and
765 : : // the entries were encrypted to the store root's.
766 : 52 : path = Util::normalizeFolderPath(
767 [ + + ]: 52 : QDir::cleanPath(Util::joinPath(m_settings.passStore, inStore)));
768 : 52 : const GpgIdSigner signer = gpgIdSigner();
769 : 52 : const QString gpgIdFile = path + ".gpg-id";
770 [ + + + ]: 52 : if (refuseInitBeforeWrite(gpgIdFile, signer)) {
771 : : return;
772 : : }
773 : 47 : const bool useGit = gitReady();
774 : : // What the folder's entries were encrypted to until now: the run below
775 : : // re-encrypts those to the new list and leaves any other for the user.
776 : 47 : const std::optional<PreviousList> previous = previousListOf(path, gpgIdFile);
777 : : // A line two key blocks hold may encrypt to either: refused after the
778 : : // other checks, so a refusal for them runs no gpg, and before anything
779 : : // is written.
780 [ + + + - : 94 : if (refuseKeyLinesHeldTwice(enabledKeyLines(users))) {
- - ]
781 : : return;
782 : : }
783 : 47 : QByteArray written;
784 : 47 : QString sigToCommit;
785 [ + + - ]: 47 : if (!writeGpgIdFile(gpgIdFile, users, &written)) {
786 : : return;
787 : : }
788 : : // The new list is on disk: held from here, so a stop before the run (a
789 : : // signature that fails, a refused start) leaves it out of a later backup
790 : : // commit's push; a clean run of this folder releases it.
791 : 47 : holdAutoPush(path);
792 [ + + + ]: 47 : if (!settleSignature(gpgIdFile, written, signer, useGit, &sigToCommit)) {
793 : : return;
794 : : }
795 : :
796 : 44 : QString gitOut;
797 : 44 : QString gitErr;
798 [ + + + + ]: 44 : if (useGit && m_settings.addGPGId) {
799 : : // Commit the .gpg-id (and .sig) before re-encrypting to it: the backup
800 : : // commit only takes tracked files (#1685) and addFolder does not stage
801 : : // it, so entries were pushed without their recipients file (#1682).
802 : 13 : const int gitExit = gitAddGpgId(gpgIdFile, sigToCommit, &gitOut, &gitErr);
803 [ + + ]: 13 : if (gitExit != 0) {
804 : 4 : reencryptAfterFailedCommit(path, gitExit, gitOut, gitErr, gpgIdFile,
805 : : previous);
806 : : return;
807 : : }
808 : : }
809 : 40 : m_writtenGpgId = WrittenGpgId{gpgIdFile, std::move(written)};
810 : 40 : keepPreviousList(gpgIdFile, previous);
811 : 40 : reencryptPath(path);
812 [ - + ]: 40 : if (!m_reencryptActive) {
813 : : // Refused before it started; reencryptPath() said why. The list it
814 : : // replaced still tells whom the change removed.
815 : : m_writtenGpgId.reset();
816 : : }
817 : : // finishedInit once the .gpg-id landed in git, as the async path did.
818 [ + + ]: 40 : if (useGit) {
819 : 10 : Pass::finished(PASS_INIT, 0, gitOut, gitErr);
820 : : }
821 : 52 : }
822 : :
823 : 44 : void ImitatePass::keepPreviousList(
824 : : const QString &gpgIdFile, const std::optional<PreviousList> &previous) {
825 [ + - ]: 44 : if (m_reencryptActive) {
826 : : return;
827 : : }
828 : : // A list replaced earlier whose run did not finish stays the one to go
829 : : // by: it, not the one in between, tells whom the changes removed.
830 [ - + - - ]: 44 : if (!(m_previousList && m_previousList->gpgIdFile == gpgIdFile)) {
831 : : m_previousList = previous;
832 : : }
833 : : }
834 : :
835 : 4 : void ImitatePass::reencryptAfterFailedCommit(
836 : : const QString &path, int gitExit, const QString &gitOut,
837 : : const QString &gitErr, const QString &gpgIdFile,
838 : : const std::optional<PreviousList> &previous) {
839 : 4 : Pass::finished(PASS_INIT, gitExit, gitOut, gitErr);
840 : : // The new list is on disk either way. Stopping here left every entry
841 : : // readable by whoever was just removed from it, so re-encrypt without
842 : : // Git and say the change is not committed. Putting the old list back
843 : : // is no way out: with signing the generation record has moved on and
844 : : // would refuse it as a rollback.
845 : : const QString why = gitErr.trimmed();
846 : 4 : keepPreviousList(gpgIdFile, previous);
847 : 4 : reencryptWithoutGit(
848 [ + + + + : 14 : path, why.isEmpty() ? tr("Git exited with code %1.").arg(gitExit) : why);
- - ]
849 : 4 : }
850 : :
851 : 52 : auto ImitatePass::refuseInitBeforeWrite(const QString &gpgIdFile,
852 : : const GpgIdSigner &signer) -> bool {
853 : : // A running re-encryption cannot take a second folder: the new list would
854 : : // be written and its entries left encrypted to the old recipients, which
855 : : // for a removed person means they can still read them. Nothing is written.
856 [ + + ]: 52 : if (m_reencryptActive) {
857 : 3 : emit critical(tr("Recipients not changed"),
858 : 1 : tr("A re-encryption is still running. Wait until it has "
859 : : "finished, then save the recipients again."));
860 : 1 : return true;
861 : : }
862 [ + + + + ]: 51 : if (signer.enabled() && !signer.haveSecretKey()) {
863 : 3 : emit critical(tr("No signing key!"),
864 : 1 : tr("None of the secret signing keys is available.\n"
865 : : "You will not be able to change the user list!"));
866 : 1 : return true;
867 : : }
868 : :
869 : : // Each name free or a regular file, before anything is written: a folder
870 : : // named .gpg-id.sig stopped the change after the new list was on disk,
871 : : // which was then neither committed nor were the entries re-encrypted to
872 : : // it, while the dialog had closed as if done. Links were refused above.
873 [ + + + - : 297 : for (const QString &name : {gpgIdFile, gpgIdFile + QStringLiteral(".sig")}) {
- ]
874 [ + + + + : 99 : if (const QFileInfo info(name); info.exists() && !info.isFile()) {
+ + + ]
875 : 6 : emit critical(tr("Recipients not changed"),
876 : 2 : tr("%1 is not a regular file, so the recipients were not "
877 : : "changed. Move it out of the way, then save the "
878 : : "recipients again.")
879 [ + + ]: 4 : .arg(QDir::toNativeSeparators(name)));
880 : : return true;
881 : 99 : }
882 : 150 : }
883 : : // The last point before the write: a list that changed since the users
884 : : // dialog read it is not replaced by the old one plus the change.
885 : 48 : return refuseChangedList();
886 : : }
887 : :
888 : 47 : auto ImitatePass::previousListOf(const QString &path, const QString &gpgIdFile)
889 : : -> std::optional<PreviousList> {
890 : 47 : QStringList before;
891 : 47 : if (loadVerifiedRecipients(
892 : 94 : Pass::getGpgIdPath(QDir(path).filePath(QStringLiteral("x.gpg")),
893 : 47 : m_settings.passStore),
894 [ + + - + ]: 47 : &before, nullptr) &&
895 : : !before.isEmpty()) {
896 : 52 : return PreviousList{gpgIdFile, std::move(before)};
897 : : }
898 : 21 : return std::nullopt;
899 : : }
900 : :
901 : 299 : auto ImitatePass::loadVerifiedRecipients(const QString &gpgIdFile,
902 : : QStringList *recipients, QString *why)
903 : : -> bool {
904 : 299 : recipients->clear();
905 [ + + ]: 299 : if (why != nullptr) {
906 : 502 : *why = tr("Signature for %1 is invalid.").arg(gpgIdFile);
907 : : }
908 : : // A link under the .gpg-id name is not the store's list: with signing
909 : : // off it reads as missing, with signing on verifyFile() refuses it.
910 [ + + ]: 299 : if (Util::isLinkedFolder(gpgIdFile)) {
911 : 1 : return !gpgIdSigner().enabled();
912 : : }
913 : 298 : QByteArray contents;
914 : 298 : const GpgIdSigner signer = gpgIdSigner();
915 [ + + ]: 298 : if (signer.enabled()) {
916 [ + + + ]: 57 : if (!verifySignedList(signer, gpgIdFile, &contents, why)) {
917 : : return false;
918 : : }
919 : : } else {
920 [ + + + + : 241 : if (const QFileInfo info(gpgIdFile); !info.exists() && !info.isSymLink()) {
+ + - ]
921 : : // No file is not a bad signature; the empty list says it all.
922 : : return true;
923 : 241 : }
924 : : // Bounded, only a regular file, and no folder on the way followed:
925 : : // see Util::readRegularFileInStore().
926 : : std::optional<QByteArray> bytes = Util::readRegularFileInStore(
927 : 239 : m_settings.passStore, gpgIdFile, Util::kMaxGpgIdBytes);
928 [ + + ]: 239 : if (!bytes) {
929 [ + - ]: 2 : if (why != nullptr) {
930 : 2 : *why = tr("%1 cannot be read as a recipient list (a regular file "
931 : : "of at most %2).")
932 : 4 : .arg(gpgIdFile,
933 [ + + ]: 4 : QLocale().formattedDataSize(Util::kMaxGpgIdBytes));
934 : : }
935 : : return false;
936 : : }
937 : : contents = *std::move(bytes);
938 : : }
939 : 266 : *recipients = Pass::parseRecipients(contents, gpgIdFile);
940 : 266 : return true;
941 : 298 : }
942 : :
943 : 42 : void ImitatePass::reportUnrestorable(const QString &path,
944 : : QStringList &problems) {
945 : 42 : problems << tr("%1 is not a regular file and was not restored. Look "
946 : : "at it and remove it, then re-encrypt again.")
947 : 84 : .arg(path);
948 : 42 : }
949 : :
950 : 5 : void ImitatePass::dropStaleTemporary(const QString &path) {
951 : : // A crash's temporary is picked up by a run an hour later.
952 : 10 : if (QFileInfo(path).lastModified() >
953 [ + + + ]: 10 : QDateTime::currentDateTime().addSecs(-3600)) {
954 : 1 : qCDebug(lcQtPass) << "Leaving a recent temporary alone:" << path;
955 : 1 : return;
956 : : }
957 [ + + ]: 4 : if (!QFile::remove(path)) {
958 : 2 : qCWarning(lcQtPass) << "Could not remove stale temporary" << path;
959 : : }
960 : : }
961 : :
962 : 4 : auto ImitatePass::restoreBackup(const QString &path, QStringList &problems)
963 : : -> bool {
964 : : // Belt and braces: the walker only lists regular files.
965 : 4 : const QFileInfo backup(path);
966 [ + + - + : 4 : if (backup.isSymLink() || !backup.isFile()) {
- + ]
967 : 0 : reportUnrestorable(path, problems);
968 : : return false;
969 : : }
970 : : const QString original =
971 : 4 : path.chopped(QStringLiteral(".reencrypt.bak").size());
972 [ + + + ]: 4 : if (QFileInfo::exists(original)) {
973 : 2 : 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 : 2 : .arg(path, original);
977 : 2 : return false;
978 : : }
979 : : // Qt's rename opens the destination for writing when a plain rename
980 : : // fails, and follows a symbolic link holding the name, writing the
981 : : // backup's bytes wherever the link points: outside the store. A co-writer
982 : : // can push such a dangling link (it passes the exists() check above, since
983 : : // its target does not exist yet). Util::replaceFile renames at the path
984 : : // level and refuses the link itself, never following it.
985 [ + + + ]: 2 : if (!Util::replaceFile(path, original, false)) {
986 : 1 : problems << tr("%1 is missing and its backup %2 could not be renamed "
987 : : "back. Rename it by hand, then re-encrypt again.")
988 : 1 : .arg(original, path);
989 : 1 : return false;
990 : : }
991 : 2 : qCWarning(lcQtPass) << "Restored" << original << "from" << path;
992 : 2 : emit statusMsg(tr("Restored %1 from the backup an interrupted "
993 : : "re-encryption left behind.")
994 : 2 : .arg(original),
995 : : 5000);
996 : 1 : return true;
997 : 4 : }
998 : :
999 : 167 : auto ImitatePass::recoverReencryptLeftovers(const QString &dir) -> bool {
1000 : : // .qtpass-XXXXXX.tmp is today's staging name; 1.8.x replaced entries via
1001 : : // X.gpg.reencrypt.tmp and .bak in two renames, builds up to 2.0 wrote
1002 : : // X.gpg.XXXXXX.tmp. A .tmp is never a source of truth; a .bak is the only
1003 : : // copy when X.gpg is missing, and one of two valid ones when it is not.
1004 : : //
1005 : : // Regular files only: renaming a link under a leftover name into an entry's
1006 : : // place would re-encrypt whatever it points to. Links come back in
1007 : : // `skipped`; linked directories are left to reencryptFiles() to mention.
1008 : 334 : const QStringList leftoverNames{QStringLiteral(".qtpass-??????.tmp"),
1009 : 167 : QStringLiteral("*.gpg.reencrypt.tmp"),
1010 : 167 : QStringLiteral("*.gpg.??????.tmp"),
1011 : 835 : QStringLiteral("*.gpg.reencrypt.bak")};
1012 : 54 : const auto isTemporary = [](const QString &path) {
1013 : 108 : return path.endsWith(QStringLiteral(".tmp"));
1014 : : };
1015 : 167 : QStringList skipped;
1016 : : // Hidden files included: the staged name starts with a dot.
1017 : : const QStringList leftovers = Util::regularFilesUnder(
1018 [ + + ]: 167 : QDir::cleanPath(dir), leftoverNames, &skipped, true);
1019 : : // One report for all of them: a box per leftover opened each from inside
1020 : : // the one before (a modal box runs the next queued critical()), and a
1021 : : // store with thousands of them overflowed the stack.
1022 : 167 : QStringList problems;
1023 [ + + ]: 214 : for (const QString &path : std::as_const(skipped)) {
1024 [ + + + + : 94 : if (!QDir::match(leftoverNames, QFileInfo(path).fileName())) {
+ ]
1025 : 2 : continue;
1026 : : }
1027 : : // Removing a link removes the link, never what it points to; a junction
1028 : : // or a directory symlink on Windows is a directory entry and goes with
1029 : : // rmdir.
1030 [ + + + ]: 45 : if (isTemporary(path)) {
1031 [ + + + + : 5 : if (!QFile::remove(path) && !QDir().rmdir(path)) {
+ + - + +
+ + - - -
- ]
1032 : 2 : qCWarning(lcQtPass) << "Could not remove stale temporary" << path;
1033 : : }
1034 : 3 : continue;
1035 : 3 : }
1036 : 42 : reportUnrestorable(path, problems);
1037 : : }
1038 [ + + ]: 176 : for (const QString &path : leftovers) {
1039 [ + + + ]: 9 : if (isTemporary(path)) {
1040 : 5 : dropStaleTemporary(path);
1041 : : } else {
1042 : 4 : restoreBackup(path, problems);
1043 : : }
1044 : : }
1045 [ + + ]: 167 : if (problems.isEmpty()) {
1046 : : return true;
1047 : : }
1048 : : const qsizetype count = problems.size();
1049 [ + + ]: 5 : if (count == 1) {
1050 : 8 : emit critical(tr("Leftover from an earlier re-encryption"),
1051 : : problems.first());
1052 : 4 : return false;
1053 : : }
1054 : 1 : QStringList listed = problems.mid(0, kReencryptMaxListedFailures);
1055 [ + - ]: 1 : if (count > listed.size()) {
1056 : 1 : listed << tr("... and %n more", nullptr,
1057 : 1 : static_cast<int>(count - listed.size()));
1058 : : }
1059 : 2 : emit critical(tr("Leftovers from an earlier re-encryption"),
1060 : 1 : tr("%n leftover(s) of an earlier re-encryption need a look "
1061 : : "before the run can start:",
1062 : 1 : nullptr, static_cast<int>(count)) +
1063 [ + + + + ]: 3 : "\n\n" + listed.join("\n\n"));
1064 : : return false;
1065 : : }
1066 : :
1067 : 125 : auto ImitatePass::verifyGpgIdForDir(const QString &file,
1068 : : QHash<QString, QStringList> &verified,
1069 : : QStringList &gpgId) -> bool {
1070 : : // Before the cache: two folders can resolve to the same list, and only
1071 : : // one of them may have had its own.
1072 [ + + + + ]: 125 : if (refuseSkippedGpgId(file, gpgIdSigner().enabled())) {
1073 : : return false;
1074 : : }
1075 : 123 : const QString gpgIdPath = Pass::getGpgIdPath(file, m_settings.passStore);
1076 : : // Keyed by .gpg-id, so every file under it gets exactly the list its
1077 : : // signature covered.
1078 : 123 : const auto cached = verified.constFind(gpgIdPath);
1079 : : if (cached != verified.constEnd()) {
1080 : : gpgId = cached.value();
1081 : 3 : return true;
1082 : : }
1083 : 120 : QStringList recipients;
1084 : 120 : QString why;
1085 [ + + + ]: 120 : if (!loadVerifiedRecipients(gpgIdPath, &recipients, &why)) {
1086 : : // An interrupted gpg is a cancel, not a bad signature.
1087 [ + - ]: 1 : if (!m_reencryptCancel.load())
1088 : 2 : emit critical(tr("Check .gpg-id file signature!"), why);
1089 : 1 : return false;
1090 : : }
1091 : : // Once per list, as the cache holds it.
1092 [ + + + ]: 119 : if (refuseKeyLinesHeldTwice(recipients)) {
1093 : : return false;
1094 : : }
1095 : : recipients.sort();
1096 : : verified.insert(gpgIdPath, recipients);
1097 : : gpgId = std::move(recipients);
1098 : 118 : return true;
1099 : : }
1100 : :
1101 : : // From gpg's status lines on stdout, one ENC_TO per recipient, rather than
1102 : : // its human messages on stderr: stderr is capped (Executor::CappedOutput),
1103 : : // and a listing cut short there could match the folder's list while the
1104 : : // entry is still encrypted to a recipient it left out, so its
1105 : : // re-encryption was skipped. stdout is read whole.
1106 : 228 : auto ImitatePass::getKeysFromFile(const QString &fileName) -> QStringList {
1107 : : // --decrypt, as pass has it: --list-only is an option, not a command, and
1108 : : // without a command gpg guesses one. A file that is OpenPGP data but not
1109 : : // encrypted it then saved under the entry's name without ".gpg": in the
1110 : : // store, and through a link under that name, over an existing file. With
1111 : : // --decrypt such data goes to standard output, capped at one byte, which
1112 : : // cannot make a whole status line. "--" keeps a file name that starts with
1113 : : // a dash from being read as an option.
1114 : 456 : const QStringList args = {QStringLiteral("--batch"),
1115 : 228 : QStringLiteral("--no-secmem-warning"),
1116 : 228 : QStringLiteral("--no-permission-warning"),
1117 : 228 : QStringLiteral("--decrypt"),
1118 : 228 : QStringLiteral("--list-only"),
1119 : 228 : QStringLiteral("--max-output"),
1120 : 228 : QStringLiteral("1"),
1121 : 228 : QStringLiteral("--status-fd=1"),
1122 : 228 : QStringLiteral("--keyid-format=long"),
1123 : 228 : QStringLiteral("--"),
1124 : 2736 : pgpg(fileName)};
1125 : 228 : QString status;
1126 : 228 : QString err;
1127 : : const int result =
1128 : 228 : execBlocking(m_settings.gpgExecutable, args, &status, &err);
1129 [ + + ]: 228 : if (result != 0) {
1130 : 33 : return {};
1131 : : }
1132 : : static const QRegularExpression encTo(
1133 [ + + + - : 197 : QStringLiteral("^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
+ ]
1134 : 195 : QStringList actualKeys;
1135 : : const QStringList lines =
1136 : 195 : status.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
1137 [ + + ]: 3534 : for (const QString &line : lines) {
1138 : 3339 : const QRegularExpressionMatch match = encTo.match(line);
1139 [ + + + ]: 3339 : if (match.hasMatch()) {
1140 : 6312 : actualKeys << match.captured(1).toUpper();
1141 : : }
1142 : 3339 : }
1143 : : actualKeys.sort();
1144 : : return actualKeys;
1145 : 228 : }
1146 : :
1147 : : namespace {
1148 : :
1149 : : /**
1150 : : * @brief Reads a colon listing of public keys into the two maps.
1151 : : * @param out The output of `gpg --with-colons --fixed-list-mode --list-keys`.
1152 : : * @param primaries Gets the long ID of each key and subkey, upper case, to
1153 : : * the fingerprint of its primary key.
1154 : : * @param names Gets the fingerprint of each primary key to its first user
1155 : : * ID, made displayable.
1156 : : */
1157 : 50 : void mapKeyListing(const QString &out, QHash<QString, QString> &primaries,
1158 : : QHash<QString, QString> &names) {
1159 : 50 : QString primaryFpr;
1160 : 50 : QStringList pendingIds;
1161 : : bool inPrimary = false;
1162 [ + + + + : 591 : for (const QString &line : out.split(Util::newLinesRegex())) {
+ + ]
1163 : 541 : const QStringList f = line.split(QLatin1Char(':'));
1164 : 541 : const QString type = f.value(0);
1165 [ + + ]: 541 : if (type == QLatin1String("pub")) {
1166 : : inPrimary = true;
1167 : 101 : primaryFpr.clear();
1168 : 404 : pendingIds = {f.value(4).toUpper()};
1169 [ + + ]: 440 : } else if (type == QLatin1String("sub")) {
1170 : : inPrimary = false;
1171 : 154 : pendingIds << f.value(4).toUpper();
1172 [ + + + + : 363 : } else if (type == QLatin1String("fpr") && inPrimary &&
+ - ]
1173 : : primaryFpr.isEmpty()) {
1174 : 202 : primaryFpr = f.value(9).toUpper();
1175 [ + + + - ]: 265 : } else if (type == QLatin1String("uid") && !primaryFpr.isEmpty() &&
1176 [ + + ]: 98 : !names.contains(primaryFpr)) {
1177 : 190 : names.insert(primaryFpr, Util::displayable(f.value(9), false));
1178 : : }
1179 [ + + ]: 541 : if (!primaryFpr.isEmpty()) {
1180 [ + + ]: 581 : for (const QString &id : std::as_const(pendingIds)) {
1181 [ + + ]: 178 : if (!id.isEmpty()) {
1182 : : primaries.insert(id, primaryFpr);
1183 : : }
1184 : : }
1185 : 403 : pendingIds.clear();
1186 : : }
1187 : : }
1188 : 50 : }
1189 : :
1190 : : } // namespace
1191 : :
1192 : 117 : auto ImitatePass::primaryKeysOf(const QStringList &ids,
1193 : : QHash<QString, QString> &primaries,
1194 : : QHash<QString, QString> &names)
1195 : : -> QSet<QString> {
1196 : : // One listing of every public key, on first use: the long ID of each key
1197 : : // and subkey to the fingerprint of its primary key, and that key's first
1198 : : // user ID for the question.
1199 : : if (primaries.isEmpty()) {
1200 : 56 : QString out;
1201 : 56 : QString err;
1202 [ + + + - : 336 : if (execBlocking(m_settings.gpgExecutable,
- ]
1203 : 56 : {QStringLiteral("--batch"),
1204 : 56 : QStringLiteral("--with-colons"),
1205 : 56 : QStringLiteral("--fixed-list-mode"),
1206 : 56 : QStringLiteral("--list-keys")},
1207 : : &out, &err) == 0) {
1208 : 50 : mapKeyListing(out, primaries, names);
1209 : : }
1210 : : }
1211 : : // A key gpg does not know (a hidden recipient, one not imported) is no
1212 : : // one this folder's list can name: left out.
1213 : : QSet<QString> result;
1214 [ + + ]: 270 : for (const QString &id : ids) {
1215 : 306 : const QString fpr = primaries.value(id.toUpper());
1216 [ + + ]: 153 : if (!fpr.isEmpty()) {
1217 : 142 : result.insert(fpr);
1218 : : }
1219 : : }
1220 : 117 : return result;
1221 : : }
1222 : :
1223 : 22 : auto ImitatePass::entryHash(const QString &file) const -> QByteArray {
1224 : : // Read as decryptEntry() reads it: a regular file, no link followed.
1225 : : const std::optional<QByteArray> bytes = Util::readRegularFileInStore(
1226 : 22 : m_settings.passStore, file, kMaxPlaintextBytes + 1024LL * 1024);
1227 [ + + ]: 22 : return bytes ? QCryptographicHash::hash(*bytes, QCryptographicHash::Sha256)
1228 : 22 : : QByteArray();
1229 : : }
1230 : :
1231 : 63 : auto ImitatePass::keysEncryptedTo(const QStringList &recipients,
1232 : : QHash<QString, QString> &primaries,
1233 : : QHash<QString, QString> &names, bool lookUp)
1234 : : -> std::optional<QSet<QString>> {
1235 : : // What `-r` makes of the list, groups, `!` suffixes and key lookups
1236 : : // included: a throwaway encryption with the same arguments as a real one,
1237 : : // outside the store, read back for its recipients.
1238 : 63 : QTemporaryDir scratch;
1239 [ + - + ]: 63 : if (!scratch.isValid()) {
1240 : 0 : return std::nullopt;
1241 : : }
1242 : 126 : const QString probe = scratch.filePath(QStringLiteral("probe.gpg"));
1243 : : // --no-throw-keyids for the probe only: with throw-keyids in gpg.conf it
1244 : : // would name no one, and nobody would count as gaining.
1245 : 63 : QStringList leading{QStringLiteral("--yes"), QStringLiteral("--batch"),
1246 : 252 : QStringLiteral("--no-throw-keyids")};
1247 [ + + ]: 63 : if (!lookUp) {
1248 : 6 : leading << QStringLiteral("--no-auto-key-locate");
1249 : : }
1250 : 63 : if (execBlockingRaw(m_settings.gpgExecutable,
1251 : 126 : encryptArgs(std::move(leading), pgpg(probe), recipients),
1252 [ + + + ]: 126 : QByteArrayLiteral("probe"), nullptr) != 0) {
1253 : 5 : return std::nullopt;
1254 : : }
1255 : 58 : const QStringList ids = getKeysFromFile(probe);
1256 [ + + ]: 58 : if (ids.isEmpty()) {
1257 : : // gpg encrypted but its recipients could not be read back: someone the
1258 : : // entry does not reach, as far as anyone can tell.
1259 : 2 : return QSet<QString>{kUnknownReader};
1260 : : }
1261 : 57 : QSet<QString> keys = primaryKeysOf(ids, primaries, names);
1262 : : // A key gpg encrypted to but did not list (fetched for the probe, say)
1263 : : // still counts, under its ID: no entry is taken to be readable by it.
1264 [ + + ]: 138 : for (const QString &id : ids) {
1265 [ + + ]: 81 : if (!primaries.contains(id.toUpper())) {
1266 : 12 : keys.insert(id.toUpper());
1267 : : }
1268 : : }
1269 : : return keys;
1270 : 63 : }
1271 : :
1272 : 137 : auto ImitatePass::decryptEntry(const QString &fileName, QByteArray *plaintext,
1273 : : QString *why) -> bool {
1274 : : // Read here, without following a link, and handed to gpg on stdin: the
1275 : : // name was listed as a regular file before the run, and a pull since may
1276 : : // have put a link there. gpg given the name would follow it, and the
1277 : : // file it points to would be re-encrypted for this folder's recipients.
1278 : : // The cap is on what decrypts; the ciphertext of an entry just under it
1279 : : // is a little larger (packet headers, one session key per recipient).
1280 : : constexpr qint64 kCiphertextMargin = 1024LL * 1024;
1281 : : // Every folder on the way down from the store is opened without
1282 : : // following a link too (readRegularFileUnder()), so none can become one
1283 : : // between a check and the read. The name may be spelled through the
1284 : : // target of a linked store root; anything under neither is refused.
1285 : : constexpr qint64 kMaxCiphertext = kMaxPlaintextBytes + kCiphertextMargin;
1286 : : const std::optional<QByteArray> ciphertext = Util::readRegularFileInStore(
1287 : 137 : m_settings.passStore, fileName, kMaxCiphertext);
1288 [ + + ]: 137 : if (!ciphertext) {
1289 : 3 : qCDebug(lcQtPass) << "Not a regular file any more, or too large:"
1290 : 0 : << fileName;
1291 [ + + ]: 3 : if (why != nullptr) {
1292 : 1 : *why = tr("%1 is no longer a regular file, or is too large, and was "
1293 : : "not re-encrypted.")
1294 : 2 : .arg(fileName);
1295 : : }
1296 : 3 : return false;
1297 : : }
1298 : : const QStringList args =
1299 : 134 : QStringList{"-d", "--quiet", "--yes", "--no-encrypt-to",
1300 : 1876 : "--batch", "--use-agent"} +
1301 : 268 : maxOutputArgs();
1302 : 134 : if (execBlockingRaw(m_settings.gpgExecutable, args, *ciphertext, plaintext) !=
1303 [ + + + + ]: 134 : 0 ||
1304 : : plaintext->isEmpty()) {
1305 : 27 : qCDebug(lcQtPass) << "Decrypt error on re-encrypt for:" << fileName;
1306 : 27 : return false;
1307 : : }
1308 : : // No newline added: an entry is re-encrypted as it was, as pass(1) does
1309 : : // (gpg -d | gpg -e); a binary key without one would have grown a byte.
1310 : : return true;
1311 : : }
1312 : :
1313 : 105 : auto ImitatePass::encryptFor(const QString &output,
1314 : : const QStringList &recipients,
1315 : : const QByteArray &plaintext) -> bool {
1316 : : const QStringList args =
1317 : 630 : encryptArgs({"--yes", "--batch"}, pgpg(output), recipients);
1318 [ + + + ]: 105 : if (execBlockingRaw(m_settings.gpgExecutable, args, plaintext, nullptr) !=
1319 : : 0) {
1320 : 4 : qCDebug(lcQtPass) << "Encrypt error on re-encrypt, output:" << output;
1321 : 4 : return false;
1322 : : }
1323 : : return true;
1324 : : }
1325 : :
1326 : 101 : auto ImitatePass::ciphertextHolds(const QString &ciphertext,
1327 : : const QByteArray &plaintext) -> bool {
1328 : 101 : QByteArray decrypted;
1329 : : const QStringList args =
1330 : 1010 : QStringList{"-d", "--quiet", "--batch", "--use-agent"} + maxOutputArgs() +
1331 : 505 : QStringList{QStringLiteral("--"), pgpg(ciphertext)};
1332 [ + + + ]: 202 : if (execBlockingRaw(m_settings.gpgExecutable, args, QByteArray(),
1333 [ + + + + ]: 101 : &decrypted) != 0 ||
1334 : : decrypted.isEmpty()) {
1335 : 2 : qCDebug(lcQtPass) << "Verification failed for:" << ciphertext;
1336 : 2 : return false;
1337 : : }
1338 : : // Defence in depth: gpg said it encrypted, and this is what comes back.
1339 : : // Exact: gpg returns the bytes it was given. Compared as text, the check
1340 : : // passed for an entry that had lost bytes, as both sides lost the same.
1341 [ + + ]: 99 : if (decrypted != plaintext) {
1342 : 2 : qCDebug(lcQtPass) << "Verification content mismatch for:" << ciphertext;
1343 : 2 : return false;
1344 : : }
1345 : : return true;
1346 : 101 : }
1347 : :
1348 : 89 : auto ImitatePass::commitReencrypted(const QString &fileName) -> bool {
1349 [ + + ]: 89 : if (!reencryptUsesGit()) {
1350 : : return true;
1351 : : }
1352 : : // -C the store so git runs there rather than in QtPass's launch directory
1353 : : // (executeBlocking sets no working directory).
1354 : 36 : const QString store = pgit(m_settings.passStore);
1355 [ + + + + : 252 : if (execBlocking(m_settings.gitExecutable,
+ - - ]
1356 : : {"-C", store, "add", "--", pgit(fileName)}) != 0) {
1357 : : // The file on disk is re-encrypted correctly; only the repository is
1358 : : // now behind. Report it so the caller counts this file as failed and
1359 : : // the run is not pushed.
1360 : 1 : qCDebug(lcQtPass) << "git add failed after re-encrypting:" << fileName;
1361 : 1 : return false;
1362 : : }
1363 : 35 : const QString path = commitName(fileName);
1364 [ + + + ]: 70 : if (execBlocking(m_settings.gitExecutable,
1365 : 175 : QStringList{"-C", store} + commitArgs() +
1366 : 35 : QStringList{"-m",
1367 : 35 : "Re-encrypt for " + path + " using QtPass.",
1368 [ + + + - : 280 : "--", pgit(fileName)}) != 0) {
- ]
1369 : 1 : qCDebug(lcQtPass) << "git commit failed after re-encrypting:" << fileName;
1370 : 1 : return false;
1371 : : }
1372 : : return true;
1373 : 177 : }
1374 : :
1375 : 133 : auto ImitatePass::reencryptSingleFile(const QString &fileName,
1376 : : const QStringList &recipients,
1377 : : QString *why) -> bool {
1378 : 133 : qCDebug(lcQtPass) << "reencrypt" << fileName << "for" << recipients.size()
1379 : 0 : << "recipients";
1380 [ - + ]: 133 : if (recipients.isEmpty()) {
1381 : 0 : emit critical(tr("Can not edit"),
1382 : 0 : tr("Could not read encryption key to use, .gpg-id "
1383 : : "file missing or invalid."));
1384 : 0 : return false;
1385 : : }
1386 : 133 : QByteArray plaintext;
1387 [ + + + ]: 133 : if (!decryptEntry(fileName, &plaintext, why)) {
1388 : : return false;
1389 : : }
1390 : :
1391 : : // gpg writes outside the store, into a 0700 directory with an unguessable
1392 : : // name no co-writer can pre-create or link; placeEncryptedFile() then
1393 : : // replaces the entry in one rename, as in Insert().
1394 : 105 : QTemporaryDir scratch;
1395 [ + - + ]: 105 : if (!scratch.isValid()) {
1396 : 0 : qCDebug(lcQtPass) << "Cannot create a scratch directory for re-encrypting"
1397 : 0 : << fileName;
1398 : 0 : return false;
1399 : : }
1400 : 210 : const QString tempPath = scratch.filePath(QStringLiteral("reencrypted.tmp"));
1401 [ + + + + : 206 : if (!encryptFor(tempPath, recipients, plaintext) ||
+ ]
1402 : 101 : !ciphertextHolds(tempPath, plaintext)) {
1403 : 8 : return false;
1404 : : }
1405 : :
1406 : : // Another client may have removed the entry while gpg ran; the rename
1407 : : // would bring it back under its old name. Best effort: the check and the
1408 : : // replace are two steps, as pass's own write is.
1409 : 97 : const QFileInfo still(fileName);
1410 [ + + + + : 97 : if (!still.exists() && !still.isSymLink()) {
- + ]
1411 : 1 : qCDebug(lcQtPass) << "Entry vanished before it could be replaced:"
1412 : 0 : << fileName;
1413 : 1 : return false;
1414 : : }
1415 [ + + + ]: 96 : if (!placeEncryptedFile(tempPath, fileName, true, why)) {
1416 : : // Reported once, in the run's summary: an unwritable folder fails every
1417 : : // entry alike. The old ciphertext stays unless the post-rename check
1418 : : // failed, and then `why` says so.
1419 [ + - + + ]: 14 : if (why != nullptr && !why->contains(fileName)) {
1420 : : // Every reason but the copy's names the entry; that one names the
1421 : : // file gpg wrote, in a scratch directory the user never sees.
1422 : 2 : *why = tr("%1 could not be re-encrypted: %2").arg(fileName, *why);
1423 : : }
1424 : 7 : return false;
1425 : : }
1426 : 89 : return commitReencrypted(fileName);
1427 : 202 : }
1428 : :
1429 : : namespace {
1430 : : /**
1431 : : * @brief Whether `git status --porcelain` output lists an unmerged path.
1432 : : *
1433 : : * Porcelain v1 marks one with the status letters DD, AU, UD, UA, DU, AA or
1434 : : * UU: a conflict that a merge, rebase, cherry-pick or `git stash pop` left
1435 : : * unresolved.
1436 : : * @param porcelain The output of `git status --porcelain`.
1437 : : * @return true when at least one path is unmerged.
1438 : : */
1439 : 55 : auto listsUnmergedPath(const QString &porcelain) -> bool {
1440 : 55 : const QStringList lines = porcelain.split(u'\n', Qt::SkipEmptyParts);
1441 [ + + ]: 69 : for (const QString &line : lines) {
1442 [ + + ]: 22 : if (line.size() < 2) {
1443 : : continue;
1444 : : }
1445 : : const QChar x = line.at(0);
1446 : : const QChar y = line.at(1);
1447 [ + + + + : 21 : if (x == u'U' || y == u'U' || (x == y && (x == u'A' || x == u'D'))) {
+ + + + +
+ ]
1448 : : return true;
1449 : : }
1450 : : }
1451 : : return false;
1452 : : }
1453 : : } // namespace
1454 : :
1455 : 167 : auto ImitatePass::createBackupCommit() -> bool {
1456 [ + + ]: 167 : if (!reencryptUsesGit()) {
1457 : : return true;
1458 : : }
1459 : 112 : emit statusMsg(tr("Creating backup commit"), 2000);
1460 : : const QString git = m_settings.gitExecutable;
1461 : : // -C the store: executeBlocking sets no working directory, so git would
1462 : : // run in QtPass's launch directory, possibly an unrelated repository.
1463 : 56 : const QString store = pgit(m_settings.passStore);
1464 : : // Tracked files only: an untracked plaintext export or swap file must not
1465 : : // be swept into a commit that autoPush sends to the shared remote.
1466 : 56 : QString statusOut;
1467 [ + + + + : 392 : if (execBlocking(
+ - - ]
1468 : : git, {"-C", store, "status", "--porcelain", "--untracked-files=no"},
1469 : : &statusOut) != 0) {
1470 : : // An interrupted git is a cancel, not a failure worth a dialog.
1471 [ + - ]: 1 : if (!m_reencryptCancel.load())
1472 : 1 : emit critical(
1473 : 1 : tr("Backup commit failed"),
1474 : 1 : tr("Could not inspect git status. Re-encryption was aborted."));
1475 : 1 : return false;
1476 : : }
1477 : : // An unresolved conflict needs no merge or rebase in progress: a
1478 : : // `git stash pop` that conflicted leaves none of the markers the earlier
1479 : : // checks look for. `add -u` would record the work tree, conflict markers
1480 : : // and all, as the resolution, and the backup commit would be pushed.
1481 : : // The repository-wide status, not `ls-files` (which stops at the store's
1482 : : // folder): `add -u` stages a repository above the store as a whole.
1483 [ + + + ]: 55 : if (listsUnmergedPath(statusOut)) {
1484 [ + - ]: 8 : if (!m_reencryptCancel.load())
1485 : 16 : emit critical(tr("Unfinished Git operation"),
1486 : 8 : tr("The password store's Git repository has unmerged "
1487 : : "files. Resolve the conflict with Git before "
1488 : : "re-encrypting."));
1489 : 8 : return false;
1490 : : }
1491 : : // The store only: in a repository above it, a modified tracked file
1492 : : // outside the store is not the store's to back up, and autoPush would
1493 : : // publish it. `.` is the store, as git runs with -C the store.
1494 : 47 : QString storeStatus;
1495 [ + + + + : 423 : if (execBlocking(git,
+ - - ]
1496 : : {"-C", store, "status", "--porcelain",
1497 : : "--untracked-files=no", "--", "."},
1498 : : &storeStatus) != 0) {
1499 [ + - ]: 1 : if (!m_reencryptCancel.load())
1500 : 1 : emit critical(
1501 : 1 : tr("Backup commit failed"),
1502 : 1 : tr("Could not inspect git status. Re-encryption was aborted."));
1503 : 1 : return false;
1504 : : }
1505 [ + + ]: 46 : if (!storeStatus.trimmed().isEmpty()) {
1506 [ + + + + : 80 : if (execBlocking(git, {"-C", store, "add", "-u", "--", "."}) != 0 ||
+ + + + +
- - - - ]
1507 [ + + + + : 74 : execBlocking(git, QStringList{"-C", store} + commitArgs() +
+ + + + +
+ + + + -
- - - - -
- - - - -
- - - ]
1508 : 9 : QStringList{"-m", "Backup before re-encryption",
1509 [ + + + + : 89 : "--", "."}) != 0) {
+ + + + +
+ - - - -
- - - - ]
1510 [ + - ]: 3 : if (!m_reencryptCancel.load())
1511 : 6 : emit critical(tr("Backup commit failed"),
1512 : 3 : tr("Re-encryption was aborted because a git backup "
1513 : : "could not be created."));
1514 : 3 : return false;
1515 : : }
1516 : : }
1517 : : return true;
1518 : 232 : }
1519 : :
1520 : : /**
1521 : : * @brief Outcome of one reencryptPath() run; filled on the worker thread
1522 : : * and consumed by finishReencrypt() on the owning thread.
1523 : : */
1524 : : struct ImitatePass::ReencryptResult {
1525 : : int total = 0; ///< `.gpg` files found under the directory.
1526 : : int checked = 0; ///< Files whose recipients were inspected.
1527 : : int reencrypted = 0; ///< Files rewritten for the current recipients.
1528 : : QStringList rewritten; ///< Those files, for EntryRecord.
1529 : : QStringList failed; ///< One line per file that could not be
1530 : : ///< re-encrypted: its path, or the reason (which
1531 : : ///< names the path) when there is one to give.
1532 : : bool cancelled = false; ///< Stopped early by cancelReencryptPath(); the
1533 : : ///< interrupted file, if any, is not in `failed`.
1534 : : bool aborted = false; ///< Stopped early on an error already reported.
1535 : : QStringList unexpected; ///< Entries left alone: re-encrypting them
1536 : : ///< would give them to someone on the list who
1537 : : ///< cannot read them now (unexpectedRecipients()).
1538 : : QStringList unexpectedDetails; ///< For each of those, who would gain it
1539 : : ///< (and who removed still reads it).
1540 : : QList<QByteArray> unexpectedHashes; ///< Their contents' SHA-256, which
1541 : : ///< reencryptAlso() holds them to.
1542 : : QList<QSet<QString>> unexpectedReaders; ///< The list's keys each was
1543 : : ///< named against.
1544 : : QHash<QString, QSet<QString>> stillReadByRemoved; ///< Of those, each one a
1545 : : ///< removed recipient
1546 : : ///< still reads, by whom.
1547 : : QStringList walked; ///< Entries whose recipients the run judged.
1548 : : };
1549 : :
1550 : : /// Per list: the primary keys gpg encrypts to now (none when it cannot),
1551 : : /// and those it encrypted to before Init() replaced the list (the same when
1552 : : /// it did not, or when the old list no longer resolves).
1553 : 40 : struct ImitatePass::ListKeys {
1554 : : std::optional<QSet<QString>> now; ///< Encrypted to now, if gpg can.
1555 : : QSet<QString> before; ///< Encrypted to before Init().
1556 : : bool beforeUnknown = false; ///< Init() replaced a list gpg cannot
1557 : : ///< encrypt to: who left it is unknown.
1558 : : };
1559 : :
1560 : : /// What one run has learnt about who reads what: each key ID's primary
1561 : : /// key, a name for the question, and each list's keys.
1562 : : struct ImitatePass::WhoReads {
1563 : : QHash<QString, QString> primaries; ///< Key ID to primary fingerprint.
1564 : : QHash<QString, QString> names; ///< Primary fingerprint to a name.
1565 : : QHash<QString, ListKeys> lists; ///< `.gpg-id` path to its keys.
1566 : : };
1567 : :
1568 : : /// How re-encrypting one entry changes who can read it.
1569 : 155 : struct ImitatePass::ReaderChange {
1570 : : bool gains = false; ///< Someone not added by this change gains it.
1571 : : QSet<QString> gaining; ///< Those, by primary fingerprint.
1572 : : QSet<QString> losing; ///< Removed recipients who still read it.
1573 : : QSet<QString> listNow; ///< The list's keys now.
1574 : : };
1575 : :
1576 : : namespace {
1577 : : /// Poll interval while waiting for queued git commands to drain.
1578 : : constexpr int kReencryptRetryMs = 100;
1579 : : } // namespace
1580 : :
1581 : 8 : void ImitatePass::reencryptPath(const QString &dir,
1582 : : const AppSettings &settings) {
1583 [ + + ]: 8 : if (!m_reencryptActive) {
1584 : 7 : init(settings);
1585 : 7 : updateEnv();
1586 : : }
1587 : 8 : reencryptPath(dir);
1588 : 8 : }
1589 : :
1590 : 182 : void ImitatePass::reencryptPath(const QString &dir) {
1591 [ + + ]: 182 : if (m_reencryptActive) {
1592 : 3 : emit statusMsg(tr("A re-encryption is already running"), 3000);
1593 : 3 : return;
1594 : : }
1595 : : // The store root may be a link; a folder inside that is, or lies behind,
1596 : : // one is not part of the store. MainWindow refuses it too; this covers
1597 : : // Init().
1598 [ + + ]: 179 : if (Util::isUnderLink(dir, m_settings.passStore)) {
1599 : 6 : emit critical(tr("Not a folder of the store"),
1600 : 2 : 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 [ + + + ]: 4 : .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
1604 : 2 : emit endReencryptPath();
1605 : 2 : return;
1606 : : }
1607 [ + + ]: 177 : if (refuseUnfinishedGitOperation()) {
1608 : : // Re-encrypting now would run createBackupCommit()'s `git add -u` and
1609 : : // conclude the stopped merge; refuse before the worker starts.
1610 : 2 : emit endReencryptPath();
1611 : 2 : return;
1612 : : }
1613 : 175 : m_reencryptActive = true;
1614 : 175 : m_reencryptScope = dir;
1615 : : m_reencryptCancel.store(false);
1616 [ + + ]: 350 : emit statusMsg(QFileInfo(dir).isDir()
1617 [ + + + + ]: 525 : ? tr("Re-encrypting from folder %1").arg(dir)
1618 : 188 : : tr("Re-encrypting %1").arg(dir),
1619 : : 3000);
1620 : 175 : emit startReencryptPath();
1621 : 175 : startReencryptWorker(dir);
1622 : : }
1623 : :
1624 : : // The worker's kill() after the grace period is needed: terminate() is only
1625 : : // SIGTERM, or WM_CLOSE on Windows, which a console gpg ignores.
1626 : 8 : void ImitatePass::cancelReencryptPath() {
1627 [ + + ]: 8 : if (!m_reencryptActive)
1628 : : return;
1629 : : m_reencryptCancel.store(true);
1630 : : }
1631 : :
1632 : : // Init(), Move() and Copy() queue async git commands right before
1633 : : // reencryptPath(); the worker's blocking git would fight them for the index
1634 : : // lock, so wait for the queue to drain. The other backend's too: with pass
1635 : : // as the backend an Update's `pass git pull` runs on RealPass's queue, and
1636 : : // the run listed the store while that pull could still change it.
1637 : 183 : void ImitatePass::startReencryptWorker(const QString &dir) {
1638 [ + + ]: 183 : if (m_reencryptCancel.load()) {
1639 : 1 : ReencryptResult result;
1640 : 1 : result.cancelled = true;
1641 : 1 : finishReencrypt(result);
1642 : : return;
1643 : 1 : }
1644 [ + + ]: 177 : if (!exec.isIdle() || !PassBackendFactory::isIdle()) {
1645 : 9 : QTimer::singleShot(kReencryptRetryMs, this,
1646 : 26 : [this, dir]() { startReencryptWorker(dir); });
1647 : 9 : return;
1648 : : }
1649 : : // Re-check now the queue is idle: a pull queued earlier through the
1650 : : // asynchronous GitPull() may have finished during the wait and left a
1651 : : // conflict. reencryptPath() checked before scheduling, but that was before
1652 : : // such a pull could run; starting the worker now would let its backup commit
1653 : : // conclude the stopped operation. The refusal already reported it, so finish
1654 : : // as an aborted run (clears m_reencryptActive, emits endReencryptPath).
1655 [ - + ]: 173 : if (refuseUnfinishedGitOperation()) {
1656 : 0 : ReencryptResult result;
1657 : 0 : result.aborted = true;
1658 : 0 : finishReencrypt(result);
1659 : : return;
1660 : 0 : }
1661 : :
1662 : : // The worker calls member functions, so `this` must outlive it: the
1663 : : // destructor cancels and joins m_reencryptThread. `self` only guards the
1664 : : // queued completion, which may run after the thread object is gone.
1665 : : QPointer<ImitatePass> self(this);
1666 : : // The worker's own copy: env is the owning thread's to change meanwhile.
1667 : 173 : updateEnv();
1668 : 173 : m_reencryptEnv = storeEnvironment();
1669 : 173 : QThread *thread = QThread::create([this, self = std::move(self), dir]() {
1670 : 173 : ReencryptResult result = reencryptFiles(dir);
1671 : 173 : QMetaObject::invokeMethod(
1672 : : self,
1673 : 859 : [self, result = std::move(result)]() {
1674 [ + - ]: 167 : if (self)
1675 : 167 : self->finishReencrypt(result);
1676 : 167 : },
1677 : : Qt::QueuedConnection);
1678 : 173 : });
1679 : 173 : m_reencryptThread = thread;
1680 : 173 : connect(thread, &QThread::finished, this, [this, thread]() {
1681 [ + + ]: 167 : if (m_reencryptThread == thread)
1682 : 165 : m_reencryptThread = nullptr;
1683 : : });
1684 : 173 : connect(thread, &QThread::finished, thread, &QObject::deleteLater);
1685 : 173 : thread->start();
1686 : : }
1687 : :
1688 : : /**
1689 : : * @brief Pull before re-encryption when automatic pulling is configured.
1690 : : * @return true if no pull is needed, the pull succeeds, or a failed pull leaves
1691 : : * no unmerged files and HEAD not behind its upstream; false otherwise.
1692 : : */
1693 : 173 : auto ImitatePass::pullBeforeReencrypt() -> bool {
1694 [ + + + + ]: 173 : if (!m_settings.autoPull || !reencryptUsesGit()) {
1695 : 162 : return true;
1696 : : }
1697 : 11 : emit statusMsg(tr("Updating password-store"), 2000);
1698 [ + + + + : 55 : if (execBlocking(m_settings.gitExecutable,
+ - - ]
1699 : 11 : {"-C", pgit(m_settings.passStore), "pull"}) == 0) {
1700 : : return true;
1701 : : }
1702 : : // A pull that could not reach the remote leaves the store as it was; one
1703 : : // that stopped in a merge leaves conflict markers and an unmerged index,
1704 : : // and re-encrypting on top of that would commit the mess.
1705 : 5 : QString unmerged;
1706 [ + + + + : 30 : if (execBlocking(m_settings.gitExecutable,
+ - - ]
1707 : : {"-C", pgit(m_settings.passStore), "ls-files", "--unmerged"},
1708 : : &unmerged) != 0) {
1709 : : // Unknown is not clean: the pull may have stopped in a merge.
1710 : 2 : emit critical(tr("Git pull failed"),
1711 : 1 : tr("Could not check the store for unmerged files after the "
1712 : : "pull. Check it with git before re-encrypting."));
1713 : 1 : return false;
1714 : : }
1715 [ + + ]: 4 : if (!unmerged.trimmed().isEmpty()) {
1716 : 2 : emit critical(tr("Git pull failed"),
1717 : 0 : tr("The pull left the store with unmerged files. Resolve "
1718 : : "the conflict before re-encrypting."));
1719 : 1 : return false;
1720 : : }
1721 : : // A third kind: the fetch got the commits and the checkout then failed at
1722 : : // one path (a link git could not create, say). Git leaves HEAD and the
1723 : : // index where they were, but the pulled versions of the other files are
1724 : : // already in the work tree, and the backup commit would take them as the
1725 : : // user's own, signed with the user's key. HEAD still behind the upstream
1726 : : // after a failed pull means the pull may have got that far. No upstream
1727 : : // (rev-list fails) means there was nothing to merge.
1728 : 3 : QString behind;
1729 [ + + + + : 21 : if (execBlocking(m_settings.gitExecutable,
+ - - -
- ]
1730 : : {"-C", pgit(m_settings.passStore), "rev-list", "--count",
1731 : : "HEAD..@{upstream}"},
1732 [ + + + + ]: 5 : &behind) == 0 &&
1733 [ - - ]: 3 : behind.trimmed().toInt() > 0) {
1734 : 2 : emit critical(tr("Git pull failed"),
1735 : 1 : 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 "
1738 : : "re-encrypting."));
1739 : 1 : return false;
1740 : : }
1741 : 2 : emit statusMsg(tr("Git pull failed, re-encrypting the store as it is"), 5000);
1742 : 2 : return true;
1743 : 19 : }
1744 : :
1745 : 150 : auto ImitatePass::entriesToReencrypt(const QString &dir, QStringList *failed)
1746 : : -> QStringList {
1747 : : // Regular files only: a symlink or junction is not a password entry, and
1748 : : // following one would decrypt and rewrite something outside the store.
1749 : : // One entry (what a move moved): itself, when it is one.
1750 [ + + + ]: 150 : if (const QFileInfo one(dir); !one.isDir()) {
1751 [ + + - + : 26 : if (one.isFile() && !Util::isLinkedFolder(dir) &&
+ - + + ]
1752 [ + + + + : 39 : one.fileName().endsWith(QLatin1String(".gpg"))) {
- - ]
1753 : 24 : return {one.filePath()};
1754 : : }
1755 : 1 : return {};
1756 : 150 : }
1757 : 137 : QStringList skipped;
1758 : 137 : QStringList unlisted;
1759 : : // A dot-named entry (.env.gpg) too, as with `pass init`: left out, it
1760 : : // stayed encrypted to a recipient just removed while the run reported
1761 : : // success. A hidden folder (.git, a sync tool's .stversions) stays closed.
1762 : : const QStringList files = Util::regularFilesUnder(
1763 [ + + ]: 411 : dir, QStringList() << "*.gpg", &skipped, true, &unlisted);
1764 : : // A folder that cannot be read looked empty, and the run reported success
1765 : : // over it with its entries still encrypted to the old recipients (a key
1766 : : // just removed among them). Each is a failure: the dialog names it and
1767 : : // nothing is pushed.
1768 [ + + ]: 139 : for (const QString &folder : std::as_const(unlisted)) {
1769 : 2 : *failed << tr("%1 could not be read: its entries were not re-encrypted")
1770 : 4 : .arg(QDir::toNativeSeparators(folder));
1771 : : }
1772 [ + + ]: 137 : if (!skipped.isEmpty()) {
1773 : 4 : 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())),
1776 : : 5000);
1777 : : }
1778 : : return files;
1779 : 12 : }
1780 : :
1781 : 125 : auto ImitatePass::recipientsForDir(const QString &fileName,
1782 : : QHash<QString, QStringList> &verified,
1783 : : QStringList &gpgId, ReencryptResult &result)
1784 : : -> bool {
1785 [ + + ]: 125 : if (!verifyGpgIdForDir(fileName, verified, gpgId)) {
1786 [ - + ]: 4 : if (m_reencryptCancel.load()) {
1787 : 0 : result.cancelled = true;
1788 : : } else {
1789 : 4 : result.aborted = true;
1790 : : }
1791 : 4 : return false;
1792 : : }
1793 [ + + ]: 121 : if (gpgId.isEmpty() && !verified.isEmpty()) {
1794 : 3 : emit critical(tr("GPG ID verification failed"),
1795 : 1 : tr("Could not verify .gpg-id for directory."));
1796 : 1 : result.aborted = true;
1797 : 1 : return false;
1798 : : }
1799 : : return true;
1800 : : }
1801 : :
1802 : : // Worker thread: only blocking helpers, nothing touching `exec` or the
1803 : : // transaction state; signals reach the GUI queued. A helper failing while the
1804 : : // cancel flag is set was interrupted: its file is neither checked nor failed.
1805 : 173 : auto ImitatePass::reencryptFiles(const QString &dir) -> ReencryptResult {
1806 : 173 : ReencryptResult result;
1807 [ + + + ]: 173 : if (!startReencryptRun(dir, result)) {
1808 : : return result;
1809 : : }
1810 : :
1811 : 150 : QStringList files = entriesToReencrypt(dir, &result.failed);
1812 : : // A run the user agreed to takes the entries they were shown, no more.
1813 : : if (!m_reencryptAgreed.isEmpty()) {
1814 [ + + ]: 12 : files.erase(std::remove_if(files.begin(), files.end(),
1815 : : [this](const QString &file) {
1816 [ + + - - ]: 10 : return !m_reencryptAgreed.contains(file);
1817 : : }),
1818 : 6 : files.end());
1819 : : }
1820 : 150 : result.total = static_cast<int>(files.size());
1821 : 150 : emit reencryptProgress(0, result.total);
1822 : :
1823 : 150 : QString currentDir;
1824 : 150 : QHash<QString, QStringList> gpgIdFilesVerified;
1825 : 150 : QStringList gpgId;
1826 : 150 : WhoReads who;
1827 [ + + ]: 302 : for (const QString &fileName : std::as_const(files)) {
1828 [ + + ]: 167 : if (m_reencryptCancel.load()) {
1829 : 2 : result.cancelled = true;
1830 : 10 : break;
1831 : : }
1832 : 165 : const QString fileDir = QFileInfo(fileName).path();
1833 [ + + ]: 165 : if (fileDir != currentDir) {
1834 [ + + + ]: 125 : if (!recipientsForDir(fileName, gpgIdFilesVerified, gpgId, result)) {
1835 : : return result;
1836 : : }
1837 : 120 : currentDir = fileDir;
1838 : : }
1839 [ + + + ]: 160 : if (!reencryptEntry(fileName, gpgId, who, result)) {
1840 : 8 : result.cancelled = true;
1841 : : break;
1842 : : }
1843 : 152 : result.checked++;
1844 : 152 : emit reencryptProgress(result.checked, result.total);
1845 : : }
1846 : : return result;
1847 : 300 : }
1848 : :
1849 : 173 : auto ImitatePass::startReencryptRun(const QString &dir, ReencryptResult &result)
1850 : : -> bool {
1851 [ + + ]: 173 : if (!pullBeforeReencrypt()) {
1852 : 3 : result.aborted = true;
1853 : 3 : return false;
1854 : : }
1855 : : // The GUI-thread checks ran before this worker's own pull.
1856 : : // pullBeforeReencrypt refuses an unmerged index, but a pull that stopped in a
1857 : : // rebase can leave a rebase-merge/rebase-apply state with no unmerged entry
1858 : : // yet; the backup commit's `git add -u` would then conclude it. Re-check
1859 : : // here, before any write, with the non-emitting detection (the refusal is
1860 : : // reported once, as an aborted run).
1861 [ + + ]: 170 : if (const QString midOp = unfinishedGitOperationReason(); !midOp.isEmpty()) {
1862 [ + - ]: 1 : if (!m_reencryptCancel.load()) {
1863 : 2 : emit critical(tr("Unfinished Git operation"), midOp);
1864 : : }
1865 : 1 : result.aborted = true;
1866 : : return false;
1867 : : }
1868 : : // reencryptPath() checked the folder before the pull; a pulled commit can
1869 : : // have made it, or a folder above it, a link since. Recovery and the walk
1870 : : // below would then rename and remove files beyond the store.
1871 [ + + ]: 169 : if (Util::isUnderLink(dir, m_settings.passStore)) {
1872 : 2 : emit critical(tr("Not part of the store"),
1873 : 1 : 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 [ + + + ]: 2 : .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
1877 : 1 : result.aborted = true;
1878 : 1 : return false;
1879 : : }
1880 : :
1881 : : // Init() wrote the recipients the user ticked and committed them. A pull
1882 : : // that merged another change to the same list cleanly (a line removed
1883 : : // here, one added there) would have the run encrypt to keys nobody chose
1884 : : // in the dialog, and without a signing key nothing else notices.
1885 [ + + ]: 168 : if (m_writtenGpgId) {
1886 : : const std::optional<QByteArray> now = Util::readRegularFileInStore(
1887 : 40 : m_settings.passStore, m_writtenGpgId->file, Util::kMaxGpgIdBytes);
1888 [ + - + + ]: 40 : if (!now || *now != m_writtenGpgId->bytes) {
1889 [ + - ]: 1 : if (!m_reencryptCancel.load()) {
1890 : 1 : emit critical(
1891 : 1 : tr("Recipients changed by the pull"),
1892 : 1 : 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 "
1897 : : "save.")
1898 [ + + ]: 2 : .arg(QDir::toNativeSeparators(
1899 [ + + ]: 2 : QFileInfo(m_writtenGpgId->file).path())));
1900 : : }
1901 : 1 : result.aborted = true;
1902 : : return false;
1903 : : }
1904 : : }
1905 : :
1906 : : // Leftovers of an interrupted run first: a restored entry then goes into
1907 : : // the backup commit like everything else, and a stale temporary does not.
1908 [ + + ]: 167 : if (!recoverReencryptLeftovers(dir)) {
1909 : 5 : result.aborted = true;
1910 : 5 : return false;
1911 : : }
1912 : :
1913 [ + + ]: 162 : if (!createBackupCommit()) {
1914 [ - + ]: 12 : if (m_reencryptCancel.load()) {
1915 : 0 : result.cancelled = true;
1916 : : } else {
1917 : 12 : result.aborted = true;
1918 : : }
1919 : 12 : return false;
1920 : : }
1921 : : return true;
1922 : : }
1923 : :
1924 : 33 : auto ImitatePass::isTrustedEntry(const QString &fileName,
1925 : : const QSet<QString> &listNow) const -> bool {
1926 : : // What the user moved or copied in is taken as it is; what they agreed to
1927 : : // in reencryptAlso() only while its bytes are the ones they were shown.
1928 [ + + ]: 33 : if (std::any_of(m_reencryptTrusted.cbegin(), m_reencryptTrusted.cend(),
1929 : 12 : [&fileName](const QString &trusted) {
1930 [ + + ]: 12 : return fileName == trusted ||
1931 : 13 : fileName.startsWith(trusted + QLatin1Char('/'));
1932 : : })) {
1933 : : return true;
1934 : : }
1935 : 21 : const auto agreed = m_reencryptAgreed.constFind(fileName);
1936 : : // An entry that cannot be read as a regular file hashes to nothing,
1937 : : // which matches no agreement.
1938 [ + - + + ]: 8 : return agreed != m_reencryptAgreed.constEnd() && !agreed->hash.isEmpty() &&
1939 : 28 : agreed->readers == listNow && entryHash(fileName) == agreed->hash;
1940 : : }
1941 : :
1942 : 49 : auto ImitatePass::listKeysFor(const QString &gpgIdPath,
1943 : : const QStringList &gpgId, WhoReads &who)
1944 : : -> const ListKeys & {
1945 [ + + ]: 49 : if (const auto known = who.lists.constFind(gpgIdPath);
1946 : : known != who.lists.constEnd()) {
1947 : 9 : return *known;
1948 : : }
1949 : : ListKeys fresh;
1950 : 80 : fresh.now = keysEncryptedTo(gpgId, who.primaries, who.names);
1951 : : std::optional<QSet<QString>> before = fresh.now;
1952 [ + + + - ]: 40 : if (m_previousList && m_previousList->gpgIdFile == gpgIdPath) {
1953 : 10 : before = keysEncryptedTo(m_previousList->recipients, who.primaries,
1954 : : who.names, false);
1955 : : }
1956 : : // A previous list gpg cannot encrypt to, or one whose probe names
1957 : : // nobody it can tell, exempts no one, and leaves unknown who was
1958 : : // taken off it.
1959 [ + + - + ]: 78 : if (before && before->contains(kUnknownReader)) {
1960 : : before.reset();
1961 : : }
1962 [ + + + + ]: 80 : fresh.before = before ? *before : fresh.now.value_or(QSet<QString>());
1963 : 40 : fresh.beforeUnknown = !before;
1964 : 40 : return *who.lists.insert(gpgIdPath, fresh);
1965 : : }
1966 : :
1967 : 49 : auto ImitatePass::readerChangeOf(const QString &fileName,
1968 : : const QStringList &keys, const ListKeys &lk,
1969 : : WhoReads &who) -> ReaderChange {
1970 : : ReaderChange change;
1971 [ + - ]: 49 : if (!lk.now) {
1972 : : return change;
1973 : : }
1974 : : change.listNow = *lk.now;
1975 : 49 : const QSet<QString> readers = primaryKeysOf(keys, who.primaries, who.names);
1976 : : change.gaining = *lk.now;
1977 : 49 : change.gaining.subtract(readers);
1978 : : // Whom this change added gains every entry of the folder, as it
1979 : : // should.
1980 : : QSet<QString> added = *lk.now;
1981 : 49 : added.subtract(lk.before);
1982 : 49 : change.gaining.subtract(added);
1983 [ + - ]: 49 : change.gains = !change.gaining.isEmpty();
1984 : : // Who was taken off the list and still reads it, if it is skipped:
1985 : : // by this change, or by an earlier one that left it so (and is not
1986 : : // back on it now).
1987 : : QSet<QString> removed = lk.before;
1988 : 98 : removed.unite(m_removedReaders.value(fileName));
1989 : 49 : removed.subtract(*lk.now);
1990 [ + + ]: 49 : if (lk.beforeUnknown) {
1991 : 4 : removed.insert(kUnknownReader);
1992 : : }
1993 : : // A recipient ID that names no known key (hidden by throw-keyids,
1994 : : // or not in the keyring) may be anyone removed. When every ID is
1995 : : // known, only those removed who are among them still read it.
1996 : : const bool readersKnown =
1997 : 106 : std::all_of(keys.cbegin(), keys.cend(), [&who](const QString &id) {
1998 : 57 : return who.primaries.contains(id.toUpper());
1999 : : });
2000 [ + + ]: 49 : if (!readersKnown) {
2001 : : change.losing = std::move(removed);
2002 : : } else {
2003 : : change.losing = readers;
2004 : 47 : change.losing.intersect(removed);
2005 : : // Who was taken off is not known (an old list gpg could not
2006 : : // encrypt to, or an earlier run that could not tell): any
2007 : : // reader no longer on the list may be one.
2008 [ + + ]: 47 : if (removed.contains(kUnknownReader)) {
2009 : : QSet<QString> off = readers;
2010 : 2 : off.subtract(*lk.now);
2011 : 2 : change.losing.unite(off);
2012 : : }
2013 : : }
2014 : : return change;
2015 : 0 : }
2016 : :
2017 : 18 : auto ImitatePass::namedReaders(const QSet<QString> &fprs,
2018 : : const QHash<QString, QString> &names)
2019 : : -> QString {
2020 : 18 : QStringList who;
2021 : : for (const QString &fpr : fprs) {
2022 [ - + ]: 19 : if (fpr == kUnknownReader) {
2023 : 0 : who << tr("a recipient gpg does not name");
2024 : 0 : continue;
2025 : : }
2026 : 38 : who << names.value(fpr, fpr.right(16));
2027 : : }
2028 : : who.sort();
2029 : 36 : return who.join(QStringLiteral(", "));
2030 : : }
2031 : :
2032 : 15 : auto ImitatePass::holdForAgreement(const QString &fileName,
2033 : : const QStringList &keys,
2034 : : const ReaderChange &change,
2035 : : const WhoReads &who, ReencryptResult &result)
2036 : : -> bool {
2037 : 15 : const QByteArray shownHash = entryHash(fileName);
2038 [ + + ]: 15 : if (shownHash.isEmpty()) {
2039 : : // gpg lists its recipients, but its bytes cannot be held to a yes
2040 : : // (over the read cap, or no longer a regular file): reported as
2041 : : // left, not asked about, or the question would come back after
2042 : : // every yes.
2043 : 1 : 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).")
2046 : 2 : .arg(fileName,
2047 [ + + ]: 2 : namedReaders(change.gaining, who.names));
2048 : : if (!change.losing.isEmpty()) {
2049 : 0 : result.stillReadByRemoved.insert(fileName, change.losing);
2050 : : }
2051 : 1 : return true;
2052 : : }
2053 : : const bool hidden =
2054 [ + - ]: 14 : !keys.isEmpty() &&
2055 [ + - ]: 14 : std::all_of(keys.cbegin(), keys.cend(), [](const QString &id) {
2056 [ - + ]: 14 : return id == QLatin1String("0000000000000000");
2057 : : });
2058 : 14 : result.unexpected << fileName;
2059 : 14 : result.unexpectedHashes << shownHash;
2060 : 14 : result.unexpectedReaders << change.listNow;
2061 : : QString detail = hidden
2062 [ - + + + ]: 28 : ? tr("its recipients cannot be told (hidden key IDs); "
2063 : : "it would become readable by %1")
2064 : 28 : .arg(namedReaders(change.gaining, who.names))
2065 : 14 : : tr("would become readable by %1")
2066 : 42 : .arg(namedReaders(change.gaining, who.names));
2067 : : if (!change.losing.isEmpty()) {
2068 : : // Named only where the entry's recipients say so; otherwise it
2069 : : // may be.
2070 : : detail +=
2071 : 3 : QStringLiteral("; ") +
2072 : 6 : (change.losing.contains(kUnknownReader) ||
2073 [ - + ]: 3 : !std::all_of(keys.cbegin(), keys.cend(),
2074 : 4 : [&who](const QString &id) {
2075 : 4 : return who.primaries.contains(id.toUpper());
2076 : : })
2077 [ + - + ]: 6 : ? tr("may still be readable by someone taken off "
2078 : : "the list")
2079 : 3 : : tr("still readable by %1, who was removed")
2080 [ + + + - : 12 : .arg(namedReaders(change.losing, who.names)));
+ - - - -
- ]
2081 : 3 : result.stillReadByRemoved.insert(fileName, change.losing);
2082 : : }
2083 : 14 : result.unexpectedDetails << detail;
2084 : : return false;
2085 : : }
2086 : :
2087 : 160 : auto ImitatePass::reencryptEntry(const QString &fileName,
2088 : : const QStringList &gpgId, WhoReads &who,
2089 : : ReencryptResult &result) -> bool {
2090 : : // A pull since the listing may have put a link under the name, or in
2091 : : // place of a folder on the way to it. gpg given the name reads the
2092 : : // target, and one already encrypted for these recipients would pass the
2093 : : // comparison without a word.
2094 : : bool keepRecord = false;
2095 : 160 : const QFileInfo entry(fileName);
2096 [ + + + + : 318 : if (entry.isSymLink() || !entry.isFile() ||
+ - + + ]
2097 : 158 : Util::isUnderLink(fileName, m_settings.passStore)) {
2098 : 4 : result.failed << tr("%1 is no longer a regular file, or lies behind a "
2099 : : "link, and was not re-encrypted.")
2100 : 8 : .arg(fileName);
2101 [ + + + ]: 156 : } else if (const QStringList keys = getKeysFromFile(fileName);
2102 : : keys != gpgId) {
2103 : : // Re-encrypting hands the entry to this folder's recipients. Someone
2104 : : // on the list who cannot read it yet, and whom this change did not
2105 : : // add, gains it: an entry copied in from a folder they cannot read
2106 : : // is left for the user to agree to. Taking readers away (a removed
2107 : : // recipient, a rotated subkey) needs no question. Who reads it now is
2108 : : // what its recipient IDs say, which a writer can add to: this stops a
2109 : : // copy, not a crafted entry (SECURITY.md).
2110 : : ReaderChange change;
2111 : : // No recipients gpg can list: not an entry it can decrypt either, so
2112 : : // the attempt below fails without handing anything over.
2113 [ + + ]: 155 : if (!keys.isEmpty()) {
2114 : 98 : change = readerChangeOf(
2115 : : fileName, keys,
2116 : 98 : listKeysFor(Pass::getGpgIdPath(fileName, m_settings.passStore), gpgId,
2117 : : who),
2118 : 49 : who);
2119 : : }
2120 [ + + ]: 155 : if (m_reencryptCancel.load()) {
2121 : : return false;
2122 : : }
2123 : 147 : QString why;
2124 [ + + + + : 147 : if (change.gains && !isTrustedEntry(fileName, change.listNow)) {
+ ]
2125 : 15 : keepRecord = holdForAgreement(fileName, keys, change, who, result);
2126 [ + + + ]: 132 : } else if (reencryptSingleFile(fileName, gpgId, &why)) {
2127 : 87 : result.reencrypted++;
2128 : 87 : result.rewritten << fileName;
2129 [ - + ]: 45 : } else if (m_reencryptCancel.load()) {
2130 : : // Interrupted by the cancel: the file is untouched, not failed.
2131 : : return false;
2132 : : } else {
2133 : : // The reason names the entry itself when there is one to give.
2134 [ + + ]: 45 : result.failed << (why.isEmpty() ? fileName : why);
2135 : : // Not rewritten: whoever was removed still reads it.
2136 : : keepRecord = true;
2137 : : }
2138 : 155 : }
2139 [ + + ]: 148 : if (!keepRecord) {
2140 : 106 : result.walked << fileName;
2141 : : }
2142 : : return true;
2143 : 160 : }
2144 : :
2145 : : // No push after a cancel, abort or per-file failure: a partially re-encrypted
2146 : : // store must not reach the remote before the user inspects it.
2147 : 168 : void ImitatePass::finishReencrypt(const ReencryptResult &result) {
2148 : : // Written by this device now, under the list they were re-encrypted to.
2149 : 168 : EntryRecord::remember(result.rewritten);
2150 : 168 : reportFailedEntries(result.failed);
2151 : : // A run of only the entries the user agreed to settles those, not the
2152 : : // rest of the folder's holds (settleAutoPushHold()).
2153 : 168 : const bool agreedRun = !m_reencryptAgreed.isEmpty();
2154 : 168 : const bool stillRead = settleAutoPushHold(result, agreedRun);
2155 : 168 : reportReencryptOutcome(result, stillRead);
2156 [ + + ]: 168 : if (m_uncommittedGpgId) {
2157 : 4 : const UncommittedGpgId uncommitted = *m_uncommittedGpgId;
2158 : : m_uncommittedGpgId.reset();
2159 : 4 : reportUncommittedGpgId(uncommitted.folder, uncommitted.gitError,
2160 [ - + + + ]: 4 : !result.cancelled && !result.aborted &&
2161 [ + - - + ]: 7 : result.failed.isEmpty() &&
2162 : : result.unexpected.isEmpty());
2163 : : }
2164 : : m_writtenGpgId.reset();
2165 : : // Whom the change removed is known only from the list it replaced: kept
2166 : : // until a full run of the folder has judged every entry, so a cancelled
2167 : : // or stopped one does not forget it.
2168 [ + + + + : 168 : if (!result.cancelled && !result.aborted && !agreedRun) {
+ + ]
2169 : : m_previousList.reset();
2170 : : }
2171 : 168 : m_reencryptTrusted.clear();
2172 : 168 : m_reencryptAgreed.clear();
2173 : 168 : rememberUnexpected(result);
2174 : : // No push after a cancel or abort; otherwise one asked for meanwhile is
2175 : : // still to make (by a run to come, or once a pending move settles).
2176 [ + + + + ]: 168 : if (result.cancelled || result.aborted) {
2177 : 34 : m_pushAfterReencrypt = false;
2178 : 34 : m_deferredPushByHand = false;
2179 : : }
2180 : : const QString scope = m_reencryptScope;
2181 : 168 : m_reencryptActive = false;
2182 : 168 : emit endReencryptPath();
2183 : : // Asked after the run is over, so the interface is free for the question;
2184 : : // the entries were not touched, so nothing waits on the answer.
2185 [ + + + - : 168 : if (!result.unexpected.isEmpty() && !result.cancelled && !result.aborted) {
+ - ]
2186 : 11 : emit unexpectedRecipients(scope, result.unexpected,
2187 : 11 : result.unexpectedDetails);
2188 : : }
2189 : 168 : startMovedReencrypts();
2190 : 168 : }
2191 : :
2192 : 168 : void ImitatePass::reportFailedEntries(const QStringList &failed) {
2193 [ + + ]: 168 : if (failed.isEmpty()) {
2194 : 140 : return;
2195 : : }
2196 : 28 : QStringList listed = failed.mid(0, kReencryptMaxListedFailures);
2197 : 28 : const int more = static_cast<int>(failed.size() - listed.size());
2198 [ + + ]: 28 : if (more > 0) {
2199 : 1 : listed << tr("... and %n more", nullptr, more);
2200 : : }
2201 : 84 : emit critical(tr("Re-encryption failed"),
2202 : 28 : tr("%n file(s) could not be re-encrypted:", nullptr,
2203 : 28 : static_cast<int>(failed.size())) +
2204 [ + + + ]: 56 : "\n\n" + listed.join('\n'));
2205 : : }
2206 : :
2207 : 168 : auto ImitatePass::settleAutoPushHold(const ReencryptResult &result,
2208 : : bool agreedRun) -> bool {
2209 : : // The recipients change is committed already: a run that did not finish
2210 : : // leaves entries for the previous recipients, which the next automatic
2211 : : // push (after any edit) would publish with it. A clean run releases only
2212 : : // the holds of what it covered. Also without Git: a recipients change
2213 : : // left uncommitted now is swept into a later commit (the next run's
2214 : : // backup commit) once Git is on, and pushed with it.
2215 : : // An entry left alone that a removed recipient still reads keeps the
2216 : : // automatic push waiting, as a failed one does: the change is not done.
2217 : : // Kept per entry across runs, until one re-encrypts it, finds nobody
2218 : : // removed reading it, or it is gone. A run of only the entries the user
2219 : : // agreed to settles those, not the rest of the folder's holds.
2220 [ + + ]: 274 : for (const QString &file : result.walked) {
2221 : 106 : m_removedReaders.remove(file);
2222 : : }
2223 : 168 : for (auto it = result.stillReadByRemoved.cbegin();
2224 : : it != result.stillReadByRemoved.cend(); ++it) {
2225 : 3 : m_removedReaders.insert(it.key(), it.value());
2226 : : }
2227 : 168 : for (auto it = m_removedReaders.begin(); it != m_removedReaders.end();) {
2228 [ + - ]: 6 : it = QFileInfo::exists(it.key()) ? std::next(it)
2229 : 3 : : m_removedReaders.erase(it);
2230 : : }
2231 : 168 : const QString heldScope = QDir::cleanPath(m_reencryptScope);
2232 : 168 : const QString heldPrefix = heldScope + QLatin1Char('/');
2233 : : const bool stillRead =
2234 : 168 : std::any_of(m_removedReaders.keyBegin(), m_removedReaders.keyEnd(),
2235 : 3 : [&heldScope, &heldPrefix](const QString &file) {
2236 [ + - + - ]: 3 : return file == heldScope || file.startsWith(heldPrefix);
2237 : : });
2238 [ + + + + : 168 : if (result.cancelled || result.aborted || !result.failed.isEmpty() ||
+ + + + ]
2239 : : stillRead) {
2240 : 64 : holdAutoPush(m_reencryptScope);
2241 [ + + ]: 104 : } else if (!agreedRun) {
2242 : 98 : releaseAutoPush(m_reencryptScope);
2243 : : }
2244 : 168 : return stillRead;
2245 : : }
2246 : :
2247 : 168 : void ImitatePass::reportReencryptOutcome(const ReencryptResult &result,
2248 : : bool stillRead) {
2249 [ + + ]: 168 : if (result.cancelled) {
2250 : 12 : emit statusMsg(tr("Re-encryption cancelled: %1 of %2 files checked, "
2251 : : "%3 re-encrypted, %4 failed")
2252 : 6 : .arg(result.checked)
2253 : 6 : .arg(result.total)
2254 : 6 : .arg(result.reencrypted)
2255 : 18 : .arg(result.failed.size()),
2256 : : 5000);
2257 [ + + ]: 162 : } else if (!result.aborted) {
2258 [ + + ]: 134 : if (!result.failed.isEmpty()) {
2259 : 54 : emit statusMsg(tr("Re-encryption completed: %1 succeeded, %2 failed")
2260 : 27 : .arg(result.reencrypted)
2261 : 81 : .arg(result.failed.size()),
2262 : : 5000);
2263 : : } else {
2264 : 107 : emit statusMsg(tr("Re-encryption completed: %1 files re-encrypted")
2265 : 214 : .arg(result.reencrypted),
2266 : : 3000);
2267 : : }
2268 : : // With a moved entry's run still to come, that one pushes at its end.
2269 : 132 : if (m_movedToReencrypt.isEmpty() &&
2270 [ + + + + : 134 : (m_settings.autoPush || m_pushAfterReencrypt) && reencryptUsesGit()) {
+ + + + ]
2271 : 20 : m_pushAfterReencrypt = false;
2272 : 20 : m_deferredPushByHand = false;
2273 [ - + ]: 20 : if (stillRead) {
2274 : 0 : emit statusMsg(tr("Not pushing: an entry left as it is is still "
2275 : : "readable by a removed recipient"),
2276 : : 5000);
2277 [ + + + + ]: 20 : } else if (result.failed.isEmpty() && autoPushHeld()) {
2278 : : // Clean here, but another folder's run did not finish.
2279 : 2 : emit statusMsg(tr("Not pushing: an earlier re-encryption in this "
2280 : : "store did not finish"),
2281 : : 5000);
2282 [ + + ]: 19 : } else if (result.failed.isEmpty()) {
2283 : 14 : emit statusMsg(tr("Updating password-store"), 2000);
2284 : 14 : m_reencryptPushing = true;
2285 : 14 : GitPush();
2286 : 14 : m_reencryptPushing = false;
2287 : : } else {
2288 : 10 : emit statusMsg(tr("Not pushing: %n file(s) failed to re-encrypt",
2289 : : nullptr, static_cast<int>(result.failed.size())),
2290 : : 5000);
2291 : : }
2292 : : }
2293 : : }
2294 : 168 : }
2295 : :
2296 : 168 : void ImitatePass::rememberUnexpected(const ReencryptResult &result) {
2297 : : // What was named, with the bytes it was named for: reencryptAlso() holds
2298 : : // the user's yes to those.
2299 : 168 : m_lastUnexpected.clear();
2300 [ + + ]: 182 : for (qsizetype i = 0; i < result.unexpected.size(); ++i) {
2301 : : m_lastUnexpected.insert(result.unexpected.at(i),
2302 : 28 : Agreed{result.unexpectedHashes.value(i),
2303 : : result.unexpectedReaders.value(i)});
2304 : : }
2305 : 168 : }
2306 : :
2307 : 8 : void ImitatePass::reencryptAlso(const QString &dir, const QStringList &files,
2308 : : const AppSettings &settings) {
2309 [ + + ]: 8 : if (m_reencryptActive) {
2310 : 1 : emit statusMsg(tr("A re-encryption is already running"), 3000);
2311 : 1 : return;
2312 : : }
2313 : : // Each with the bytes the user was shown it with: one changed since (a
2314 : : // pull, a co-writer) is named again rather than taken.
2315 : 7 : m_reencryptAgreed.clear();
2316 [ + + ]: 16 : for (const QString &file : files) {
2317 : 9 : const auto shown = m_lastUnexpected.constFind(QDir::cleanPath(file));
2318 : : if (shown != m_lastUnexpected.constEnd()) {
2319 : : m_reencryptAgreed.insert(shown.key(), shown.value());
2320 : : }
2321 : : }
2322 : : if (m_reencryptAgreed.isEmpty()) {
2323 : : // MainWindow locked the interface for the run that does not start.
2324 : 1 : emit statusMsg(tr("Nothing to re-encrypt: those entries were not named "
2325 : : "by the last run"),
2326 : : 5000);
2327 : 1 : emit endReencryptPath();
2328 : 1 : return;
2329 : : }
2330 : 6 : reencryptPath(dir, settings);
2331 [ - + ]: 6 : if (!m_reencryptActive) {
2332 : 0 : m_reencryptAgreed.clear();
2333 : : }
2334 : : }
2335 : :
2336 : 292 : auto ImitatePass::reencryptUsesGit() const -> bool {
2337 [ + + + + ]: 292 : return gitConfigured() && !m_uncommittedGpgId;
2338 : : }
2339 : :
2340 : 4 : void ImitatePass::reencryptWithoutGit(const QString &dir,
2341 : : const QString &gitError) {
2342 [ - + ]: 4 : if (m_reencryptActive) {
2343 : : // The run in flight was started with its own Git mode; this folder is
2344 : : // not part of it.
2345 : 0 : reportUncommittedGpgId(dir, gitError, false);
2346 : 0 : return;
2347 : : }
2348 : 4 : m_uncommittedGpgId = UncommittedGpgId{dir, gitError};
2349 : 4 : reencryptPath(dir);
2350 [ + - - + ]: 4 : if (m_uncommittedGpgId && !m_reencryptActive) {
2351 : : // Refused before it started; reencryptPath() said why.
2352 : : m_uncommittedGpgId.reset();
2353 : 0 : reportUncommittedGpgId(dir, gitError, false);
2354 : : }
2355 : : }
2356 : :
2357 : 4 : void ImitatePass::reportUncommittedGpgId(const QString &dir,
2358 : : const QString &gitError,
2359 : : bool reencrypted) {
2360 : 4 : const QString folder = QDir::toNativeSeparators(QDir::cleanPath(dir));
2361 [ + + ]: 4 : if (reencrypted) {
2362 : 6 : emit critical(
2363 : 3 : tr("Recipients not committed"),
2364 : 3 : 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 : 6 : .arg(folder, gitError));
2369 : : return;
2370 : : }
2371 : 2 : emit critical(
2372 : 1 : tr("Recipients not committed"),
2373 : 1 : 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 : 2 : .arg(folder, gitError));
2379 : : }
2380 : :
2381 : 77 : auto ImitatePass::resolveMoveDestination(const QString &src,
2382 : : const QString &dest, bool force)
2383 : : -> QString {
2384 : 77 : QFileInfo srcFileInfo(src);
2385 : 77 : QFileInfo destFileInfo(dest);
2386 : 77 : QString destFile;
2387 : 77 : QString srcFileBaseName = srcFileInfo.fileName();
2388 : :
2389 [ + + + ]: 77 : if (srcFileInfo.isFile()) {
2390 [ + + + ]: 60 : if (destFileInfo.isFile()) {
2391 [ + + ]: 13 : if (!force) {
2392 : 4 : qCDebug(lcQtPass) << "Destination file already exists";
2393 : 4 : return {};
2394 : : }
2395 : 9 : destFile = dest;
2396 [ + + + ]: 47 : } else if (destFileInfo.isDir()) {
2397 : 38 : destFile = Util::joinPath(dest, srcFileBaseName);
2398 : : } else {
2399 : 28 : destFile = dest;
2400 : : }
2401 : :
2402 : : // Case-sensitive: only an actual ".gpg" entry already carries the suffix.
2403 : : // A neighbouring file like "login.GPG" is a different name, so it must not
2404 : : // be chopped to "login" and re-suffixed to the real "login.gpg" entry,
2405 : : // which the forced move would then overwrite.
2406 [ + + + ]: 56 : if (destFile.endsWith(QLatin1String(".gpg"))) {
2407 : 39 : destFile.chop(4);
2408 : : }
2409 : 56 : destFile.append(".gpg");
2410 [ + + + ]: 17 : } else if (srcFileInfo.isDir()) {
2411 [ + + + ]: 14 : if (destFileInfo.isDir()) {
2412 : 10 : destFile = Util::joinPath(dest, srcFileBaseName);
2413 [ + + + ]: 9 : } else if (destFileInfo.isFile()) {
2414 : 1 : qCDebug(lcQtPass) << "Destination is a file";
2415 : 1 : return {};
2416 : : } else {
2417 : 8 : destFile = dest;
2418 : : }
2419 : : } else {
2420 : 3 : qCDebug(lcQtPass) << "Source file does not exist";
2421 : 3 : return {};
2422 : : }
2423 : : return destFile;
2424 : 77 : }
2425 : :
2426 : 20 : void ImitatePass::executeMoveGit(const QString &src, const QString &destFile,
2427 : : bool force) {
2428 : 20 : QStringList args;
2429 : 20 : args << "mv";
2430 [ + + ]: 20 : if (force) {
2431 : 6 : args << "-f";
2432 : : }
2433 : 80 : args << "--" << pgit(src) << pgit(destFile);
2434 : 20 : executeGit(GIT_MOVE, args);
2435 : :
2436 : : // The move alone: with no path, the commit took whatever else was
2437 : : // staged.
2438 : 80 : gitCommit(QStringList{src, destFile},
2439 : 20 : QString("Moved for %1 to %2 using QtPass.")
2440 [ + + + ]: 40 : .arg(commitName(src), commitName(destFile)));
2441 : 20 : }
2442 : :
2443 : 130 : auto ImitatePass::commitName(const QString &path) const -> QString {
2444 : 130 : QString name = QDir(m_settings.passStore).relativeFilePath(path);
2445 : : // Not under the store as spelled (a copy from elsewhere, the store's
2446 : : // other spelling through a link, another drive): "../.." or an absolute
2447 : : // path would carry the local layout too, so the file name alone.
2448 [ + - + + : 258 : if (name == QLatin1String("..") || name.startsWith(QLatin1String("../")) ||
+ - + ]
2449 : : QDir::isAbsolutePath(name)) {
2450 : 4 : name = QFileInfo(path).fileName();
2451 : : }
2452 : 130 : name.replace(Util::endsWithGpg(), "");
2453 : 130 : return name;
2454 : : }
2455 : :
2456 : 56 : void ImitatePass::Move(const QString src, const QString dest,
2457 : : const bool force) {
2458 : : // Cleaned once, so the checks and the rename see one path: every check
2459 : : // removes ".." as text, while rename(2) follows a link first and applies
2460 : : // ".." after it, so "link/../x" was judged as <store>/x and landed beside
2461 : : // the link's target.
2462 : 56 : const QString from = QDir::cleanPath(src);
2463 : 56 : const QString to = QDir::cleanPath(dest);
2464 [ + + + + : 56 : if (refuseLinkedPath(from) || refuseLinkedPath(to)) {
+ + ]
2465 : 2 : return;
2466 : : }
2467 [ + + - + : 54 : if (refuseUnfinishedGitOperation() || refusePendingPull()) {
+ + ]
2468 : 1 : return;
2469 : : }
2470 : : // No message box opens inside the transaction: a process queued while one
2471 : : // is open (an entry opened from a search another instance forwarded) would
2472 : : // be booked as a step of the move, and its decrypted output reported as
2473 : : // the move's, which is not secret. So every check runs first, and the
2474 : : // transaction holds only the Git commands.
2475 : 53 : const QString destFile = resolveMoveDestination(from, to, force);
2476 [ + + ]: 53 : if (destFile.isEmpty()) {
2477 : : return;
2478 : : }
2479 [ + + + ]: 50 : if (refuseLinkedPath(destFile)) {
2480 : : return;
2481 : : }
2482 : :
2483 [ + + + ]: 49 : if (refuseOverlappingMove(from, destFile)) {
2484 : : return;
2485 : : }
2486 : :
2487 : 41 : qCDebug(lcQtPass) << "Move Source: " << from;
2488 : 41 : qCDebug(lcQtPass) << "Move Destination: " << destFile;
2489 : :
2490 : 41 : const bool folder = QFileInfo(from).isDir();
2491 : 41 : PendingMove move{from, destFile,
2492 : 41 : QDir::cleanPath(getGpgIdPath(from, m_settings.passStore)),
2493 : 41 : std::nullopt};
2494 : :
2495 [ + + + ]: 41 : if (gitReady()) {
2496 : : // Settled in finished() once the move's commands have run: only then
2497 : : // is it known whether git mv moved anything, and which list applies
2498 : : // where it landed (a move queued before this one may create that
2499 : : // folder). Every Move() through Git ends in one PASS_MOVE.
2500 : : m_pendingMoves.enqueue(move);
2501 : 20 : TransactionHelper trans(&m_transaction, PASS_MOVE);
2502 : 20 : executeMoveGit(from, destFile, force);
2503 : : return;
2504 : : }
2505 : : // A forced move replaces the destination entry in the one rename, as
2506 : : // git mv -f does: removing it first lost it when the rename then failed
2507 : : // (and lost the entry itself, moved onto its own name). A folder is never
2508 : : // replaced, forced or not. Without Git nothing else reports a failure.
2509 [ + + + ]: 21 : const bool moved = force && !folder ? Util::replaceFile(from, destFile, true)
2510 : 21 : : QDir().rename(from, destFile);
2511 [ + + ]: 21 : if (!moved) {
2512 : 4 : emit critical(tr("Move failed"),
2513 : 2 : tr("Could not move %1 to %2.").arg(from, destFile));
2514 : 2 : return;
2515 : : }
2516 : 19 : move.landed = true;
2517 : 19 : reencryptMoved(move);
2518 : 19 : startMovedReencrypts();
2519 : 41 : }
2520 : :
2521 : 49 : auto ImitatePass::refuseOverlappingMove(const QString &src,
2522 : : const QString &destFile) -> bool {
2523 : : #ifdef Q_OS_WIN
2524 : : constexpr auto cs = Qt::CaseInsensitive;
2525 : : #else
2526 : : constexpr auto cs = Qt::CaseSensitive;
2527 : : #endif
2528 : : // The same path, or one inside the other.
2529 : 27 : const auto overlap = [](const QString &a, const QString &b) {
2530 : 27 : const QString x = QDir::cleanPath(a);
2531 : 27 : const QString y = QDir::cleanPath(b);
2532 [ + + + + : 54 : return x.compare(y, cs) == 0 || x.startsWith(y + QLatin1Char('/'), cs) ||
+ + ]
2533 : 76 : y.startsWith(x + QLatin1Char('/'), cs);
2534 : : };
2535 : : QStringList busy = m_movedToReencrypt;
2536 [ + + ]: 55 : for (const PendingMove &move : std::as_const(m_pendingMoves)) {
2537 : 6 : busy << move.src << move.destFile;
2538 : : }
2539 [ + + ]: 49 : if (m_reencryptActive) {
2540 : 4 : busy << m_reencryptScope;
2541 : : }
2542 [ + + ]: 57 : for (const QString &path : std::as_const(busy)) {
2543 [ + + + + : 16 : if (overlap(path, src) || overlap(path, destFile)) {
+ + ]
2544 : 24 : emit critical(tr("Move not started"),
2545 : 8 : tr("%1 is still being moved or re-encrypted. Move it "
2546 : : "again once that has finished.")
2547 [ + + + ]: 16 : .arg(QDir::toNativeSeparators(QDir::cleanPath(path))));
2548 : : return true;
2549 : : }
2550 : : }
2551 : : return false;
2552 : : }
2553 : :
2554 : 39 : void ImitatePass::reencryptMoved(const PendingMove &move) {
2555 : : // Only a move whose git mv (or rename) succeeded: one that failed, or
2556 : : // never ran, moved nothing, and re-encrypting the destination would
2557 : : // rewrite the entry that was there. Not the source name: something may
2558 : : // be written under it again before the move settles.
2559 : : if (move.landed != true) {
2560 : 25 : return;
2561 : : }
2562 : : // The user moved it here: a path saved from this device.
2563 : 111 : EntryRecord::remember({move.destFile});
2564 : 37 : const QFileInfo landed(move.destFile);
2565 [ + + + + : 37 : if (!landed.exists() || Util::isLinkedFolder(move.destFile)) {
+ - ]
2566 : 5 : return;
2567 : : }
2568 : : // As `pass mv`, what moved is encrypted for the recipients where it
2569 : : // landed. Not needed when the same list applies there (a rename, a move
2570 : : // within its folder's reach) or a folder took its own list along.
2571 : : const QString toList =
2572 : 32 : QDir::cleanPath(getGpgIdPath(move.destFile, m_settings.passStore));
2573 [ + + + + ]: 49 : if (toList == move.fromList ||
2574 : 17 : (landed.isDir() &&
2575 [ + + + + : 47 : toList == QDir::cleanPath(QDir(move.destFile).filePath(".gpg-id")))) {
+ + + + +
+ + + - -
- - - - ]
2576 : : return;
2577 : : }
2578 : : // The entry alone, or the folder: not its neighbours, which this move
2579 : : // did not touch. One run at a time: behind the one in flight, if any.
2580 : 14 : const QString scope = QDir::cleanPath(move.destFile);
2581 [ + - ]: 14 : if (!m_movedToReencrypt.contains(scope)) {
2582 : : m_movedToReencrypt << scope;
2583 : : }
2584 : 37 : }
2585 : :
2586 : 18 : auto ImitatePass::copyDestination(const QString &src, const QString &dest,
2587 : : bool force) -> QString {
2588 : 5 : const auto refuse = [this, &src](const QString &to) {
2589 : 15 : emit critical(tr("Copy failed"),
2590 : 5 : tr("Could not copy %1 to %2.").arg(src, to));
2591 : 5 : return QString();
2592 : 18 : };
2593 : : // Like `pass cp`, dest may be an existing folder (a drag-and-drop copy hands
2594 : : // over the folder, not the new file name). Resolve the real target the same
2595 : : // way Move does: into the folder, .gpg appended, no clobbering without force.
2596 : 18 : QString destFile = resolveMoveDestination(src, dest, force);
2597 [ + + ]: 18 : if (destFile.isEmpty()) {
2598 : 3 : return refuse(dest);
2599 : : }
2600 : : // A link planted under that name (dangling ones pass exists()) is not an
2601 : : // entry to write.
2602 [ + + + ]: 15 : if (refuseLinkedPath(destFile)) {
2603 : 2 : return {};
2604 : : }
2605 : 13 : const QFileInfo destFileInfo(destFile);
2606 : : // A folder destination that is the source's own folder resolves to the
2607 : : // source itself; with force that would replace the only copy with itself.
2608 : : // And resolveMoveDestination only sees a clash when dest names the file.
2609 [ + + + + : 39 : if (QFileInfo(src) == destFileInfo || (!force && destFileInfo.exists())) {
+ + + + +
+ ]
2610 : 2 : return refuse(destFile);
2611 : : }
2612 : : return destFile;
2613 : 13 : }
2614 : :
2615 : 21 : void ImitatePass::Copy(const QString src, const QString dest,
2616 : : const bool force) {
2617 : : // Cleaned once, as in Move().
2618 : 21 : const QString from = QDir::cleanPath(src);
2619 : 21 : const QString to = QDir::cleanPath(dest);
2620 : : // QFile::copy reads through a link: the target's bytes would become an
2621 : : // entry of the store.
2622 [ + + + + : 21 : if (refuseLinkedPath(from) || refuseLinkedPath(to)) {
+ + ]
2623 : 2 : return;
2624 : : }
2625 [ + + - + : 19 : if (refuseUnfinishedGitOperation() || refusePendingPull()) {
+ + ]
2626 : 1 : return;
2627 : : }
2628 : : // As in Move(): no message box inside the transaction.
2629 : 18 : const QString destFile = copyDestination(from, to, force);
2630 [ + + ]: 18 : if (destFile.isEmpty()) {
2631 : : return;
2632 : : }
2633 : : // git has no "cp": copy on disk in both modes, then stage. Synchronous and
2634 : : // atomic (Util::copyFileReplacing follows no link), so it exists before the
2635 : : // re-encryption below and a forced overwrite survives a half-way failure;
2636 : : // without force nothing is replaced, not even what appeared since the check.
2637 : 11 : QString why;
2638 [ + + + ]: 11 : if (!Util::copyFileReplacing(from, destFile, force, &why)) {
2639 : 2 : emit critical(tr("Copy failed"),
2640 : 2 : tr("Could not copy %1 to %2.").arg(from, destFile) + "\n" +
2641 : 1 : why);
2642 : : return;
2643 : : }
2644 : : // The user copied it here: a path saved from this device.
2645 : 30 : EntryRecord::remember({destFile});
2646 [ + + + ]: 10 : if (gitReady()) {
2647 : 2 : TransactionHelper trans(&m_transaction, PASS_COPY);
2648 : 12 : executeGit(GIT_COPY, {"add", "-f", "--", pgit(destFile)});
2649 : 4 : gitCommit(destFile, QString("Copied from %1 to %2 using QtPass.")
2650 [ + + + ]: 4 : .arg(commitName(from), commitName(destFile)));
2651 : : }
2652 : 10 : const QFileInfo written(destFile);
2653 : : // What the user copied is re-encrypted whatever it was encrypted to. Not
2654 : : // while a run is active: its worker reads the list (and refuses this one).
2655 : 10 : const bool idle = !m_reencryptActive;
2656 [ + + ]: 10 : if (idle) {
2657 : 36 : m_reencryptTrusted = {QDir::cleanPath(written.absoluteFilePath())};
2658 : : }
2659 [ + - + ]: 10 : if (written.isDir()) {
2660 : 0 : reencryptPath(written.absoluteFilePath());
2661 [ + + - ]: 10 : } else if (written.isFile()) {
2662 : 20 : reencryptPath(written.dir().path());
2663 : : }
2664 [ + + - + ]: 10 : if (idle && !m_reencryptActive) {
2665 : 0 : m_reencryptTrusted.clear();
2666 : : }
2667 : 21 : }
2668 : :
2669 : 180 : void ImitatePass::executeGpg(PROCESS id, const QStringList &args, QString input,
2670 : : bool readStdout, bool readStderr) {
2671 : 180 : executeWrapper(id, m_settings.gpgExecutable, args, std::move(input),
2672 : : readStdout, readStderr);
2673 : 180 : }
2674 : :
2675 : : // useGit can be on with no gitExecutable (fresh setup, git removed later);
2676 : : // handing that to the Executor used to wedge the queue (#1682).
2677 : 292 : auto ImitatePass::gitConfigured() const -> bool {
2678 [ + + + + ]: 292 : return m_settings.useGit && !m_settings.gitExecutable.isEmpty();
2679 : : }
2680 : :
2681 : : // Tells the user once per operation why git was skipped, so the store
2682 : : // silently drifting from git does not go unnoticed.
2683 : 267 : auto ImitatePass::gitReady() -> bool {
2684 [ + + + + ]: 267 : if (m_settings.useGit && m_settings.gitExecutable.isEmpty()) {
2685 : 10 : emit statusMsg(tr("Git executable not configured, skipping git"), 3000);
2686 : 10 : return false;
2687 : : }
2688 : : return m_settings.useGit;
2689 : : }
2690 : :
2691 : 134 : void ImitatePass::executeGit(PROCESS id, const QStringList &args, QString input,
2692 : : bool readStdout, bool readStderr) {
2693 : : // Callers check gitReady() first; an empty executable that still gets here
2694 : : // is reported by the Executor instead of wedging the queue (#1682).
2695 : 134 : executeWrapper(id, m_settings.gitExecutable, args, std::move(input),
2696 : : readStdout, readStderr);
2697 : 134 : }
2698 : :
2699 : : // Only PASS_* processes reach Pass::finished, so to the interface this looks
2700 : : // the same as RealPass.
2701 : 307 : void ImitatePass::finished(int id, int exitCode, const QString &out,
2702 : : const QString &err) {
2703 : 307 : qCDebug(lcQtPass) << "Imitate Pass";
2704 : : QString error = err;
2705 : : // A move's git mv runs first in its transaction, so in order: the first
2706 : : // pending move without an answer is this one's.
2707 [ + + ]: 307 : if (id == GIT_MOVE) {
2708 [ + + - ]: 20 : for (PendingMove &move : m_pendingMoves) {
2709 [ + - ]: 20 : if (!move.landed) {
2710 : 20 : move.landed = exitCode == 0;
2711 : 20 : break;
2712 : : }
2713 : : }
2714 : : }
2715 [ + + + - ]: 307 : if (id == PASS_INSERT && !m_pendingInserts.isEmpty()) {
2716 : : // Insert()'s gpg step: place the ciphertext before the queued git steps
2717 : : // run (the executor starts the next item only after this returns). On
2718 : : // failure it fails like a gpg error: git steps cancelled below.
2719 : : // No dialog here: it would spin the event loop and run git steps first.
2720 : 102 : exitCode = placePendingInsert(exitCode, &error);
2721 : : }
2722 : 307 : PROCESS pid = m_transaction.transactionIsOver(static_cast<PROCESS>(id));
2723 : 307 : m_transactionOutput.append(out);
2724 : :
2725 [ + + ]: 307 : if (exitCode == 0) {
2726 [ + + ]: 262 : if (pid == INVALID) {
2727 : : return;
2728 : : }
2729 : : } else {
2730 [ + + ]: 52 : while (pid == INVALID) {
2731 : 7 : id = exec.cancelNext();
2732 [ - + ]: 7 : if (id == -1) {
2733 : : // this is probably irrecoverable and shall not happen
2734 : 0 : qCDebug(lcQtPass) << "No such transaction!";
2735 : 0 : return;
2736 : : }
2737 : 7 : pid = m_transaction.transactionIsOver(static_cast<PROCESS>(id));
2738 : : }
2739 : : }
2740 : 249 : Pass::finished(pid, exitCode, m_transactionOutput, error);
2741 : 249 : m_transactionOutput.clear();
2742 [ + + + - ]: 249 : if (pid == PASS_MOVE && !m_pendingMoves.isEmpty()) {
2743 : 20 : reencryptMoved(m_pendingMoves.dequeue());
2744 : 20 : startMovedReencrypts();
2745 : : }
2746 : : }
2747 : :
2748 : 102 : auto ImitatePass::placePendingInsert(int exitCode, QString *error) -> int {
2749 : : const PendingInsert pending = m_pendingInserts.dequeue();
2750 : : // The flag answers for this insert, the one whose gpg step just ended, not
2751 : : // for whichever Insert() was called last: with two inserts queued, a gpg
2752 : : // failure of the second must report written=false even though the first
2753 : : // was placed. Cleared here, before placement, and set only on success.
2754 : 102 : m_insertPlaced = false;
2755 [ + + ]: 102 : if (exitCode != 0) {
2756 : : return exitCode;
2757 : : }
2758 : : // Insert() checked the repository when the save was requested, but a
2759 : : // pull queued before it (the asynchronous Update button) may have run
2760 : : // and stopped in a conflict while this gpg step encrypted. Placing the
2761 : : // entry and committing it now would land it in the unfinished operation,
2762 : : // where `git rebase --abort` would drop it. Re-check and, if so, fail the
2763 : : // save instead of placing it; finished() cancels the queued git steps.
2764 : 99 : const QString midOp = unfinishedGitOperationReason();
2765 [ + + ]: 99 : if (!midOp.isEmpty()) {
2766 : 1 : *error = midOp;
2767 : 1 : return 1;
2768 : : }
2769 : 196 : m_insertPlaced = placeEncryptedFile(pending.output, pending.file,
2770 : 98 : pending.overwrite, error);
2771 [ + + ]: 98 : if (!m_insertPlaced) {
2772 : : return 1;
2773 : : }
2774 : 285 : EntryRecord::remember({pending.file});
2775 : 95 : return 0;
2776 : 102 : }
2777 : :
2778 : 194 : auto ImitatePass::placeEncryptedFile(const QString &output, const QString &file,
2779 : : bool overwrite, QString *error) -> bool {
2780 [ + + + ]: 194 : if (QFileInfo(output).size() <= 0) {
2781 : : // gpg reported success and wrote nothing: not an entry.
2782 : 4 : *error = tr("gpg wrote no ciphertext for %1.").arg(file);
2783 : 2 : return false;
2784 : : }
2785 : : // A link planted since the check is replaced as an entry; without
2786 : : // overwrite, anything new under the name fails the add.
2787 : 192 : return Util::copyFileReplacing(output, file, overwrite, error);
2788 : : }
2789 : :
2790 : 318 : void ImitatePass::beforeExecute(PROCESS id) {
2791 : 318 : m_transaction.transactionAdd(id);
2792 : 318 : }
2793 : :
2794 : : // PCRE, as for RealPass (see Pass::Grep). Runs on a NativeGrep thread; the
2795 : : // result arrives on this thread as finishedGrep.
2796 : 14 : void ImitatePass::Grep(QString pattern, bool caseInsensitive) {
2797 : 28 : m_grep.search(pattern, caseInsensitive, m_settings.gpgExecutable,
2798 : 14 : m_settings.passStore, exec.environment());
2799 : 14 : }
|