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