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 what both backends share: the environment the store's
6 : : * processes run in, the refusals for links and paths outside the store, `.gpg-
7 : : * id` lookup, and Pass::finished(), which routes each finished process to its
8 : : * signal.
9 : : */
10 : : #include "pass.h"
11 : :
12 : : #include "entryrecord.h"
13 : : #include "gpgidgeneration.h"
14 : : #include "gpgidsigner.h"
15 : : #include "gpgkeystate.h"
16 : : #include "pathvalidator.h"
17 : : #include "processinfo.h"
18 : : #include "util.h"
19 : : #include <QCoreApplication>
20 : : #include <QDebug>
21 : : #include <QDir>
22 : : #include <QFile>
23 : : #include <QFileInfo>
24 : : #include <QHash>
25 : : #include <QLocale>
26 : : #include <QProcess>
27 : : #include <QRandomGenerator>
28 : : #include <QRegularExpression>
29 : : #include <QSaveFile>
30 : : #include <QScopeGuard>
31 : : #include <QTemporaryDir>
32 : : #include <QTextStream>
33 : : #include <algorithm>
34 : : #include <array>
35 : : #include <optional>
36 : : #include <utility>
37 : :
38 : : #include "qtpasslogging.h"
39 : :
40 : : using Enums::GIT_INIT;
41 : : using Enums::GIT_PULL;
42 : : using Enums::GIT_PUSH;
43 : : using Enums::GPG_GENKEYS;
44 : : using Enums::PASS_COPY;
45 : : using Enums::PASS_INIT;
46 : : using Enums::PASS_INSERT;
47 : : using Enums::PASS_MOVE;
48 : : using Enums::PASS_REMOVE;
49 : : using Enums::PASS_SHOW;
50 : :
51 : : namespace {
52 : : auto fallbackCharset(const QString &input, const QString &fallback) -> QString {
53 [ + + + + ]: 1750 : return input.isEmpty() ? fallback : input;
54 : : }
55 : :
56 : 543 : auto effectiveCharset(const PasswordConfiguration &passConfig) -> QString {
57 : 543 : int sel = passConfig.selected;
58 [ - + ]: 543 : if (sel < 0 || sel >= PasswordConfiguration::CHARSETS_COUNT)
59 : : sel = PasswordConfiguration::ALLCHARS;
60 : : return fallbackCharset(
61 : 543 : passConfig.Characters[sel],
62 : 543 : passConfig.Characters[PasswordConfiguration::ALLCHARS]);
63 : : }
64 : :
65 : : /**
66 : : * @brief Add @p names to WSLENV in @p env, keeping its entries and adding no
67 : : * duplicate.
68 : : * @param env The environment to amend.
69 : : * @param names WSLENV entries, each a variable name with its flags.
70 : : */
71 : 1078 : void mergeIntoWslenv(QProcessEnvironment &env, const QStringList &names) {
72 : 2156 : QStringList parts = env.value(QStringLiteral("WSLENV"))
73 : 1078 : .split(QLatin1Char(':'), Qt::SkipEmptyParts);
74 [ + + ]: 6566 : for (const QString &name : names) {
75 [ + + ]: 5488 : if (!parts.contains(name)) {
76 : : parts.append(name);
77 : : }
78 : : }
79 : 2156 : env.insert(QStringLiteral("WSLENV"), parts.join(QLatin1Char(':')));
80 : 1078 : }
81 : : } // namespace
82 : :
83 : 535 : Pass::Pass() : env(QProcessEnvironment::systemEnvironment()) {
84 : 535 : connect(&exec, &Executor::finished, this, &Pass::finished);
85 : 535 : connect(&exec, &Executor::error, this, &Pass::finished);
86 : :
87 : 535 : connect(&exec, &Executor::starting, this, &Pass::startingExecuteWrapper);
88 : 535 : connect(&exec, &Executor::drained, this, [this] {
89 : : // Idle means the queue is empty and nothing runs, so no insert is in
90 : : // flight: force the pending count to zero. A report that never arrived
91 : : // (the "No such transaction" path in ImitatePass::finished(), or any
92 : : // later change that drops an insert without reporting) would otherwise
93 : : // leave the count one too high for the rest of the session, and every
94 : : // later dialog would take its own report for an earlier one and wait for
95 : : // ever. Idle cannot fall between a dialog's insertsPending() read and its
96 : : // own report, since that insert keeps the executor busy.
97 : 155 : m_insertsPending = 0;
98 : 155 : m_insertedEntries.clear();
99 : 155 : emit idle();
100 : 155 : });
101 : : // Each queued process starts in the environment as the store is then:
102 : : // the Git pin is judged at that moment (dequeuing() comes just before the
103 : : // start, on this thread).
104 : 535 : connect(&exec, &Executor::dequeuing, this, [this](int, bool completes) {
105 [ + + ]: 411 : if (completes) {
106 : 403 : exec.setEnvironment(withCurrentGitPin(env));
107 : : }
108 : 411 : });
109 : : // Merge our vars into WSLENV rather than blindly appending a duplicate
110 : : // entry. WSLENV flags: /p translates the path, /u forwards from Windows
111 : : // into WSL only; /w would be the other direction, from WSL out, and leaves
112 : : // pass inside WSL without the value. Everything updateEnv() sets for pass
113 : : // has to cross, the signing key above all: without it pass does not check
114 : : // the .gpg-id signature.
115 : : const QStringList wslenvVars = {
116 : 1070 : QStringLiteral("PASSWORD_STORE_DIR/p"),
117 : 535 : QStringLiteral("PASSWORD_STORE_SIGNING_KEY/u"),
118 : 535 : QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH/u"),
119 : 535 : QStringLiteral("PASSWORD_STORE_CHARACTER_SET/u"),
120 : 535 : QStringLiteral("PASSWORD_STORE_GPG_OPTS/u"),
121 : 535 : QStringLiteral("GIT_CEILING_DIRECTORIES/p"),
122 : 4280 : QStringLiteral("GIT_LITERAL_PATHSPECS/u")};
123 : 535 : mergeIntoWslenv(env, wslenvVars);
124 : 535 : }
125 : :
126 : 2 : void Pass::executeWrapper(PROCESS id, const QString &app,
127 : : const QStringList &args, bool readStdout,
128 : : bool readStderr) {
129 : 2 : executeWrapper(id, app, args, QString(), readStdout, readStderr);
130 : 2 : }
131 : :
132 : 411 : void Pass::executeWrapper(PROCESS id, const QString &app,
133 : : const QStringList &args, QString input,
134 : : bool readStdout, bool readStderr) {
135 : 411 : beforeExecute(id);
136 : 411 : qCDebug(lcQtPass) << app << loggableArgs(args);
137 : 411 : exec.execute(id, m_settings.passStore, app, args, std::move(input),
138 : : readStdout, readStderr);
139 : 411 : }
140 : :
141 : 4 : auto Pass::loggableArgs(const QStringList &args) -> QStringList {
142 : : // Secrets travel on stdin (Insert's content, KeygenDialog's batch file),
143 : : // never in argv; this keeps the log honest should that ever change.
144 : : static const QStringList secretOptions{
145 : 59 : QStringLiteral("--passphrase"), QStringLiteral("--override-session-key")};
146 : 4 : QStringList out;
147 : : bool hide = false;
148 [ + + ]: 12 : for (const QString &arg : args) {
149 [ + + ]: 8 : if (hide) {
150 : 1 : out << QStringLiteral("<redacted>");
151 : : hide = false;
152 : 1 : continue;
153 : : }
154 [ + + + ]: 14 : if (arg.startsWith(QStringLiteral("otpauth://"))) {
155 : 1 : out << QStringLiteral("<redacted>");
156 : 1 : continue;
157 : : }
158 [ + + + + : 12 : if (arg.startsWith(QStringLiteral("--passphrase=")) ||
+ ]
159 [ + + + - : 11 : arg.startsWith(QStringLiteral("--override-session-key="))) {
- - - ]
160 : 2 : out << arg.left(arg.indexOf(u'=') + 1) + QStringLiteral("<redacted>");
161 : 1 : continue;
162 : : }
163 : : hide = secretOptions.contains(arg);
164 : : out << arg;
165 : : }
166 : 4 : return out;
167 : : }
168 : :
169 : 93 : void Pass::beforeExecute(PROCESS /*id*/) {}
170 : :
171 : 1024 : void Pass::init(const AppSettings &settings) {
172 : 1024 : m_settings = settings;
173 : : // A key exported for pass counts when none is set here: pass checks the
174 : : // list against it, and so do QtPass's own checks. Dropping it turned every
175 : : // check off.
176 : : m_settings.passSigningKey =
177 : 1024 : GpgIdSigner::settingOrExported(m_settings.passSigningKey);
178 : : #ifdef __APPLE__
179 : : // If it exists, prepend gpgtools to PATH
180 : : if (QFile(QStringLiteral("/usr/local/MacGPG2/bin")).exists())
181 : : env.insert(QStringLiteral("PATH"),
182 : : QStringLiteral("/usr/local/MacGPG2/bin:") +
183 : : env.value(QStringLiteral("PATH")));
184 : : // Add missing /usr/local/bin (exact component match, no leading colon)
185 : : const QString currentPath = env.value(QStringLiteral("PATH"));
186 : : if (!currentPath.split(':', Qt::SkipEmptyParts)
187 : : .contains(QStringLiteral("/usr/local/bin"))) {
188 : : env.insert(QStringLiteral("PATH"),
189 : : currentPath.isEmpty()
190 : : ? QStringLiteral("/usr/local/bin")
191 : : : QStringLiteral("/usr/local/bin:") + currentPath);
192 : : }
193 : : #endif
194 : :
195 : : // The configured gpgHome wins over GNUPGHOME only when it exists: a stale
196 : : // one (#1711) fails every gpg call with "No secret key". Clearing the
197 : : // setting restores the inherited value rather than keeping the old path.
198 : 2048 : const QString inheritedHome = QProcessEnvironment::systemEnvironment().value(
199 : 2048 : QStringLiteral("GNUPGHOME"));
200 : 961 : const auto useInheritedHome = [this, &inheritedHome]() {
201 [ + + ]: 961 : if (inheritedHome.isEmpty()) {
202 : 1346 : env.remove(QStringLiteral("GNUPGHOME"));
203 : : } else {
204 : 576 : env.insert(QStringLiteral("GNUPGHOME"), inheritedHome);
205 : : }
206 : 1985 : };
207 [ + + ]: 1024 : if (m_settings.gpgHome.isEmpty()) {
208 : 959 : useInheritedHome();
209 : : } else {
210 : 65 : QDir absHome(m_settings.gpgHome);
211 : 65 : absHome.makeAbsolute();
212 [ + + + ]: 65 : if (absHome.exists()) {
213 : 126 : env.insert(QStringLiteral("GNUPGHOME"), absHome.path());
214 : : } else {
215 [ + + ]: 2 : if (inheritedHome.isEmpty()) {
216 : 2 : qCWarning(lcQtPass) << "gpgHome" << absHome.path()
217 : 1 : << "does not exist; using the default GnuPG home";
218 : 1 : emit statusMsg(tr("Configured GPG home %1 does not exist, using the "
219 : : "default keyring")
220 : 2 : .arg(absHome.path()),
221 : : 5000);
222 : : } else {
223 : 2 : qCWarning(lcQtPass)
224 : 2 : << "gpgHome" << absHome.path() << "does not exist; using GNUPGHOME"
225 : 1 : << inheritedHome << "from the environment";
226 : 1 : emit statusMsg(tr("Configured GPG home %1 does not exist, using "
227 : : "GNUPGHOME %2 from the environment")
228 : 2 : .arg(absHome.path(), inheritedHome),
229 : : 5000);
230 : : }
231 : 2 : useInheritedHome();
232 : : }
233 : 65 : }
234 : : // With signed lists, the entries a store holds when this device first
235 : : // opens it count as saved here (trust on first use), before anything a
236 : : // pusher writes can land: not at the edit check, which would record a
237 : : // renamed folder as saved. Unsigned stores never walk.
238 [ + + ]: 1024 : if (!m_settings.passSigningKey.isEmpty()) {
239 : 44 : EntryRecord::seedStore(m_settings.passStore);
240 : : }
241 : 1024 : }
242 : :
243 : 1211 : auto Pass::generatePassword(unsigned int length, const QString &charset)
244 : : -> QString {
245 [ + + ]: 1211 : if (length == 0) {
246 : 2 : emit critical(tr("Invalid password length"),
247 : 1 : tr("Can't generate password with zero length."));
248 : 1 : return {};
249 : : }
250 : 1210 : QString passwd;
251 [ + + ]: 1210 : if (m_settings.usePwgen) {
252 : : // --secure goes first as it overrides --no-* otherwise
253 : 3 : QStringList args;
254 : 3 : args.append("-1");
255 [ + + ]: 3 : if (!m_settings.lessRandom) {
256 : 4 : args.append("--secure");
257 : : }
258 [ + + + ]: 5 : args.append(m_settings.avoidCapitals ? "--no-capitalize" : "--capitalize");
259 [ + + + ]: 5 : args.append(m_settings.avoidNumbers ? "--no-numerals" : "--numerals");
260 [ + + ]: 3 : if (m_settings.useSymbols) {
261 : 2 : args.append("--symbols");
262 : : }
263 : 3 : args.append(QString::number(length));
264 [ + + + ]: 3 : if (Executor::executeBlocking(m_settings.pwgenExecutable, args, &passwd) ==
265 : : 0) {
266 : 3 : static const QRegularExpression literalNewLines{"[\\n\\r]"};
267 : 2 : passwd.remove(literalNewLines);
268 : : } else {
269 : 1 : passwd.clear();
270 : 1 : qCDebug(lcQtPass) << "pwgen fail";
271 : : // Report it, as the other generation failures do: otherwise Generate
272 : : // does nothing silently and OK then saves an empty (or, on Edit, the
273 : : // old) password.
274 : 1 : emit critical(
275 : 1 : tr("Password generation failed"),
276 : 1 : tr("Could not run pwgen (\"%1\"). Check the pwgen program in the "
277 : : "settings, or turn \"Use pwgen\" off.")
278 : 2 : .arg(m_settings.pwgenExecutable));
279 : : }
280 : : } else {
281 : : // An empty CUSTOM charset falls back to ALLCHARS, not a weak password
282 : : // (#780).
283 : : const QString cs = fallbackCharset(
284 : : charset, m_settings.passwordConfiguration
285 : : .Characters[PasswordConfiguration::ALLCHARS]);
286 [ + + ]: 1207 : if (cs.length() > 0) {
287 : 2412 : passwd = generateRandomPassword(cs, length);
288 : : } else {
289 : 1 : emit critical(
290 : 1 : tr("No characters chosen"),
291 : 1 : tr("Can't generate password, there are no characters to choose from "
292 : : "set in the configuration!"));
293 : : }
294 : : }
295 : : return passwd;
296 : : }
297 : :
298 : 41 : bool Pass::gpgSupportsEd25519(const QString &gpgExecutable) {
299 : : const QString exe =
300 [ + + ]: 41 : gpgExecutable.isEmpty() ? QStringLiteral("gpg") : gpgExecutable;
301 : 41 : QString out, err;
302 [ + + + + : 164 : if (Executor::executeBlocking(exe, {"--version"}, &out, &err) != 0) {
+ + + + -
- - - ]
303 : : return false;
304 : : }
305 : : static const QRegularExpression versionRegex(
306 [ + + + - : 49 : QStringLiteral(R"(gpg \(GnuPG\) (\d+)\.(\d+))"));
+ ]
307 : 39 : QRegularExpressionMatch match = versionRegex.match(out);
308 [ + + + ]: 39 : if (!match.hasMatch()) {
309 : : return false;
310 : : }
311 : 38 : int major = match.captured(1).toInt();
312 : 38 : int minor = match.captured(2).toInt();
313 [ + - + + ]: 38 : return major > 2 || (major == 2 && minor >= 1);
314 : 39 : }
315 : :
316 : : // ed25519 (GnuPG 2.1+) generates much faster than RSA.
317 : 37 : QString Pass::getDefaultKeyTemplate(const QString &gpgExecutable) {
318 [ + + ]: 37 : if (gpgSupportsEd25519(gpgExecutable)) {
319 : 34 : return QStringLiteral("%echo Generating a default key\n"
320 : : "Key-Type: EdDSA\n"
321 : : "Key-Curve: Ed25519\n"
322 : : "Subkey-Type: ECDH\n"
323 : : "Subkey-Curve: Curve25519\n"
324 : : "Name-Real: \n"
325 : : "Name-Comment: QtPass\n"
326 : : "Name-Email: \n"
327 : : "Expire-Date: 0\n"
328 : : "%no-protection\n"
329 : : "%commit\n"
330 : : "%echo done");
331 : : }
332 : 3 : return QStringLiteral("%echo Generating a default key\n"
333 : : "Key-Type: RSA\n"
334 : : "Subkey-Type: RSA\n"
335 : : "Name-Real: \n"
336 : : "Name-Comment: QtPass\n"
337 : : "Name-Email: \n"
338 : : "Expire-Date: 0\n"
339 : : "%no-protection\n"
340 : : "%commit\n"
341 : : "%echo done");
342 : : }
343 : :
344 : : namespace {
345 : 8 : auto resolveWslGpgconfPath(const QString &lastPart) -> QString {
346 : 8 : qsizetype lastSep = lastPart.lastIndexOf('/');
347 [ + + ]: 8 : if (lastSep < 0) {
348 : 5 : lastSep = lastPart.lastIndexOf('\\');
349 : : }
350 [ - + ]: 5 : if (lastSep >= 0) {
351 : 6 : return lastPart.left(lastSep + 1) + "gpgconf";
352 : : }
353 : 5 : return QStringLiteral("gpgconf");
354 : : }
355 : :
356 : 8 : QString findGpgconfInGpgDir(const QString &gpgPath) {
357 : 8 : QFileInfo gpgInfo(gpgPath);
358 [ + + ]: 8 : if (!gpgInfo.isAbsolute()) {
359 : 1 : return {};
360 : : }
361 : :
362 : 7 : QDir dir(gpgInfo.absolutePath());
363 : :
364 : : #ifdef Q_OS_WIN
365 : : QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
366 : : if (candidateExe.isExecutable()) {
367 : : return candidateExe.filePath();
368 : : }
369 : : #endif
370 : :
371 : 7 : QFileInfo candidate(dir.filePath("gpgconf"));
372 [ + + + ]: 7 : if (candidate.isExecutable()) {
373 : 5 : return candidate.filePath();
374 : : }
375 : 2 : return {};
376 : 8 : }
377 : :
378 : : } // namespace
379 : :
380 : 22 : auto Pass::resolveGpgconfCommand(const QString &gpgPath)
381 : : -> ResolvedGpgconfCommand {
382 [ + + ]: 22 : if (gpgPath.trimmed().isEmpty()) {
383 : : return {"gpgconf", {}};
384 : : }
385 : :
386 : : // WSL: gpgconf next to the configured gpg, same distribution, via --exec
387 : : // not the shell. An unparsed form (`wsl sh -c ...`, bare `wsl`) falls back
388 : : // to gpgconf on the Windows PATH.
389 [ + + ]: 21 : if (const auto wsl = Executor::parseWslCommand(gpgPath)) {
390 [ + + + + : 18 : if (!QFileInfo(wsl->command).fileName().startsWith("gpg")) {
+ + ]
391 : : return {"gpgconf", {}};
392 : : }
393 : 16 : const auto gpgconf = wsl->with(resolveWslGpgconfPath(wsl->command));
394 : 0 : return {gpgconf.launcher, gpgconf.argv({})};
395 : 8 : }
396 : :
397 : 12 : const QStringList parts = QProcess::splitCommand(gpgPath);
398 [ - + ]: 12 : if (parts.isEmpty()) {
399 : : return {"gpgconf", {}};
400 : : }
401 : : const QString &first = parts.first();
402 [ + + + + : 33 : if (QFileInfo(first).fileName().compare("wsl", Qt::CaseInsensitive) == 0 ||
+ + - + +
- - - - ]
403 [ + + + + : 30 : QFileInfo(first).fileName().compare("wsl.exe", Qt::CaseInsensitive) ==
+ + + - -
- - - - ]
404 : : 0) {
405 : : return {"gpgconf", {}};
406 : : }
407 : :
408 [ + + - + ]: 9 : if (!first.contains('/') && !first.contains('\\')) {
409 : : return {"gpgconf", {}};
410 : : }
411 : :
412 : 8 : QString gpgconfPath = findGpgconfInGpgDir(first);
413 [ + + ]: 8 : if (!gpgconfPath.isEmpty()) {
414 : 5 : return {std::move(gpgconfPath), {}};
415 : : }
416 : :
417 : : return {"gpgconf", {}};
418 : 22 : }
419 : :
420 : 12 : void Pass::GenerateGPGKeys(QString batch) {
421 : : const QString gpgPath = m_settings.gpgExecutable;
422 [ + + ]: 12 : if (gpgPath.isEmpty()) {
423 : : // The executor would fail an empty executable with a generic process
424 : : // error; the keygen dialog waits for generateGPGKeysFailed and a reason
425 : : // it can show. Queued so we do not re-enter KeygenDialog::done(), which
426 : : // drives key generation synchronously.
427 : 10 : QMetaObject::invokeMethod(
428 : : this,
429 : 10 : [this]() {
430 : 5 : emit generateGPGKeysFailed(tr("No GPG executable configured"));
431 : 5 : emit processErrorExit(1, tr("No GPG executable configured"));
432 : 5 : },
433 : : Qt::QueuedConnection);
434 : : return;
435 : : }
436 : :
437 : : // A stale gpg-agent holding the key database lock causes "database locked"
438 : : // timeouts during key generation.
439 : 2 : ResolvedGpgconfCommand resolvedGpgconf = resolveGpgconfCommand(gpgPath);
440 : : QStringList killArgs = resolvedGpgconf.arguments;
441 : 2 : killArgs << "--kill";
442 : 2 : killArgs << "gpg-agent";
443 : : // Use same environment as key generation to target correct gpg-agent
444 [ + + + ]: 2 : if (Executor::executeBlocking(env, resolvedGpgconf.program, killArgs) != 0) {
445 : 2 : qCWarning(lcQtPass) << "Failed to kill gpg-agent";
446 : : }
447 : :
448 : 16 : executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
449 : : std::move(batch), true, true);
450 : : }
451 : :
452 : : namespace {
453 : : /**
454 : : * @brief The key ID or fingerprint @p line names, as gpg reads it: 8, 16,
455 : : * 40 or 64 hex digits, with an optional 0x and trailing "!", or a
456 : : * fingerprint grouped with spaces as `gpg --fingerprint` prints it.
457 : : * @param line A recipient line.
458 : : * @return The digits in upper case, without 0x, "!" or spaces; empty for
459 : : * any other line.
460 : : */
461 : 6773 : auto keyOfLine(const QString &line) -> QString {
462 : : QString key = line.trimmed();
463 [ + + + ]: 6773 : if (key.endsWith(QLatin1Char('!'))) {
464 : 1 : key.chop(1);
465 : : }
466 [ + + + ]: 6773 : if (key.startsWith(QLatin1String("0x"), Qt::CaseInsensitive)) {
467 : 7 : key.remove(0, 2);
468 : : }
469 : : static const QRegularExpression grouped(
470 [ + + + - : 6787 : QStringLiteral("^[0-9A-Fa-f]{4}(?:\\s+[0-9A-Fa-f]{4})+$"));
+ ]
471 [ + + + + ]: 6773 : if (grouped.match(key).hasMatch()) {
472 : 6 : static const QRegularExpression space(QStringLiteral("\\s"));
473 : 2 : key.remove(space);
474 [ - + - - ]: 2 : if (key.size() != 40 && key.size() != 64) {
475 : 0 : return {};
476 : : }
477 : : }
478 : 7 : static const QRegularExpression hex(QStringLiteral(
479 [ + + + - : 6787 : "^(?:[0-9A-Fa-f]{8}|[0-9A-Fa-f]{16}|[0-9A-Fa-f]{40}|[0-9A-Fa-f]{64})$"));
+ ]
480 [ + + + + ]: 7456 : return hex.match(key).hasMatch() ? key.toUpper() : QString();
481 : : }
482 : :
483 : : /**
484 : : * @brief One key block of a colon listing: its primary fingerprint and
485 : : * name, and the key IDs and fingerprints of the key and its subkeys.
486 : : */
487 : : struct KeyBlock {
488 : : QString primary; ///< Primary fingerprint, upper case.
489 : : QString name; ///< First user ID.
490 : : QStringList keyIds; ///< Key IDs of the key and its subkeys.
491 : : QStringList fprs; ///< Fingerprints of the key and its subkeys.
492 : : };
493 : :
494 : : /**
495 : : * @brief Split a `--with-colons --with-fingerprint
496 : : * --with-subkey-fingerprint` listing into key blocks, once.
497 : : * @param listing The listing.
498 : : * @return The blocks, in listing order.
499 : : */
500 : 296 : auto keyBlocks(const QString &listing) -> QList<KeyBlock> {
501 : 296 : QList<KeyBlock> blocks;
502 : : bool expectPrimary = false;
503 : : const QStringList lines =
504 : 296 : listing.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
505 [ + + ]: 1940 : for (const QString &line : lines) {
506 : 1644 : const QStringList f = line.split(QLatin1Char(':'));
507 : 1644 : const QString type = f.value(0);
508 [ + + ]: 1644 : if (type == QLatin1String("pub")) {
509 : 760 : blocks.append(KeyBlock{});
510 : 760 : blocks.last().keyIds << f.value(4).toUpper();
511 : : expectPrimary = true;
512 [ + + ]: 1264 : } else if (blocks.isEmpty()) {
513 : : continue;
514 [ + + ]: 1142 : } else if (type == QLatin1String("sub")) {
515 : 498 : blocks.last().keyIds << f.value(4).toUpper();
516 : : expectPrimary = false;
517 [ + + ]: 893 : } else if (type == QLatin1String("fpr")) {
518 : 1142 : const QString fpr = f.value(9).toUpper();
519 : 571 : blocks.last().fprs << fpr;
520 [ + + ]: 571 : if (expectPrimary) {
521 : 322 : blocks.last().primary = fpr;
522 : : expectPrimary = false;
523 : : }
524 [ + - + + ]: 644 : } else if (type == QLatin1String("uid") && blocks.last().name.isEmpty()) {
525 : 638 : blocks.last().name = Util::displayable(f.value(9), false);
526 : : }
527 : : }
528 : 296 : return blocks;
529 : : }
530 : :
531 : : /**
532 : : * @brief How a holder is named: its first user ID and key ID (a v4
533 : : * fingerprint's tail, a v5/v6 one's head).
534 : : * @param block The holder.
535 : : * @return The name.
536 : : */
537 : 193 : auto holderName(const KeyBlock &block) -> QString {
538 [ + + ]: 193 : const QString id = block.primary.size() == 64 ? block.primary.left(16)
539 : 193 : : block.primary.right(16);
540 [ + + ]: 193 : return block.name.isEmpty() ? id
541 : 383 : : QStringLiteral("%1 (%2)").arg(block.name, id);
542 : : }
543 : : } // namespace
544 : :
545 : 40 : auto Pass::fullKeyListing(QString *listing) -> int {
546 : : // In the store's environment: the keyring encryption uses.
547 : 40 : QProcess process;
548 : 40 : process.setProcessEnvironment(storeEnvironment());
549 : 320 : return Executor::executeBlocking(
550 : 40 : process, m_settings.gpgExecutable,
551 : 40 : {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
552 : 40 : QStringLiteral("--with-colons"), QStringLiteral("--with-fingerprint"),
553 : 40 : QStringLiteral("--with-subkey-fingerprint"),
554 : 40 : QStringLiteral("--list-keys")},
555 : 80 : QString(), listing);
556 : 40 : }
557 : :
558 : 2 : auto Pass::exportPublicKeys(const QString &gpg, const QStringList &keys,
559 : : QString *out, QString *err) -> int {
560 : 2 : QProcess process;
561 : 2 : process.setProcessEnvironment(storeEnvironment());
562 : 2 : return Executor::executeBlocking(
563 : : process, gpg,
564 : 8 : QStringList{QStringLiteral("--armor"), QStringLiteral("--export")} + keys,
565 : 4 : QString(), out, err);
566 : 2 : }
567 : :
568 : 349 : auto Pass::refuseKeyLinesHeldTwice(const QStringList &lines) -> bool {
569 : : const std::optional<QHash<QString, QStringList>> held =
570 : 349 : keyLinesHeldTwice(lines);
571 [ + + ]: 349 : if (held && held->isEmpty()) {
572 : : return false;
573 : : }
574 [ + + + ]: 15 : emit critical(held ? tr("A recipient key is held twice")
575 : : : tr("Cannot check the recipient keys"),
576 : 5 : describeKeyLinesHeldTwice(held));
577 : 5 : return true;
578 : : }
579 : :
580 : 88 : auto Pass::enabledKeyLines(const QList<UserInfo> &users) -> QStringList {
581 : 88 : QStringList lines;
582 [ + + ]: 187 : for (const UserInfo &user : users) {
583 [ + + ]: 99 : if (user.enabled) {
584 : 97 : lines << user.key_id;
585 : : }
586 : : }
587 : 88 : return lines;
588 : : }
589 : :
590 : 399 : auto Pass::keyLinesHeldTwice(const QStringList &lines)
591 : : -> std::optional<QHash<QString, QStringList>> {
592 [ + + ]: 399 : if (std::none_of(lines.cbegin(), lines.cend(), [](const QString &line) {
593 : 6370 : return !keyOfLine(line).isEmpty();
594 : : })) {
595 : 95 : return QHash<QString, QStringList>();
596 : : }
597 : 304 : QString listing;
598 : 304 : const int rc = fullKeyListing(&listing);
599 : : // A gpg that does not start encrypts to nobody either: the operation
600 : : // fails on its own, as it did before this check. One that starts but
601 : : // cannot list its keyring is not trusted to resolve a key line.
602 [ + + ]: 304 : if (rc == -1) {
603 : 10 : return QHash<QString, QStringList>();
604 : : }
605 [ + + ]: 294 : if (rc != 0) {
606 : 1 : return std::nullopt;
607 : : }
608 : 293 : return keyLinesHeldTwiceIn(lines, listing);
609 : : }
610 : :
611 : 296 : auto Pass::keyLinesHeldTwiceIn(const QStringList &lines, const QString &listing)
612 : : -> QHash<QString, QStringList> {
613 : : // The listing split once, each line looked up in it. A line with "!" is
614 : : // judged the same: gpg then takes exactly the key named, so it cannot be
615 : : // redirected to the other block's own subkey, but naming a key two blocks
616 : : // hold is refused all the same, which is only stricter.
617 : 296 : const QList<KeyBlock> blocks = keyBlocks(listing);
618 : 296 : QHash<QString, QStringList> held;
619 [ + + ]: 699 : for (const QString &line : lines) {
620 : 403 : const QString key = keyOfLine(line);
621 [ + + ]: 403 : if (key.isEmpty()) {
622 : : continue;
623 : : }
624 [ + + + + ]: 379 : const bool isId = key.size() == 8 || key.size() == 16;
625 : 379 : QStringList named;
626 [ + + ]: 931 : for (const KeyBlock &block : blocks) {
627 : : const bool holds =
628 [ + + ]: 552 : isId ? std::any_of(
629 : : block.keyIds.cbegin(), block.keyIds.cend(),
630 : 132 : [&key](const QString &id) { return id.endsWith(key); })
631 : 552 : : block.fprs.contains(key);
632 [ + + ]: 552 : if (holds) {
633 : 386 : named << holderName(block);
634 : : }
635 : : }
636 [ + + ]: 379 : if (named.size() > 1) {
637 : : held.insert(line, named);
638 : : }
639 : : }
640 : 296 : return held;
641 : 0 : }
642 : :
643 : 7 : auto Pass::describeKeyLinesHeldTwice(
644 : : const std::optional<QHash<QString, QStringList>> &held) -> QString {
645 [ + + ]: 7 : if (!held) {
646 : : return tr("gpg could not list the keyring, so QtPass cannot tell whether "
647 : : "each key ID and fingerprint in the recipient list names one "
648 : : "key. Nothing was encrypted.");
649 : : }
650 : 6 : QStringList lines = held->keys();
651 : : lines.sort();
652 : 6 : QStringList parts;
653 [ + + ]: 12 : for (const QString &line : std::as_const(lines)) {
654 : 6 : parts << tr("%1 is held by more than one key: %2")
655 : 12 : .arg(line, held->value(line).join(QStringLiteral(", ")));
656 : : }
657 : 12 : return parts.join(QStringLiteral("\n")) + QStringLiteral("\n\n") +
658 : 6 : tr("gpg may encrypt to any of them, so nothing is encrypted to this "
659 : : "list. A key that holds someone else's key as a subkey was "
660 : : "made to do so: look at it, and delete it if you did not expect "
661 : 6 : "it.");
662 : : }
663 : :
664 : 10 : auto Pass::entryReaders(const QString &path) -> QStringList {
665 : : // As ImitatePass::getKeysFromFile(): --decrypt --list-only, capped, so
666 : : // data that is not encrypted goes nowhere.
667 : 10 : QProcess process;
668 : 10 : process.setProcessEnvironment(storeEnvironment());
669 : 10 : QString status;
670 [ + + + - : 120 : if (Executor::executeBlocking(
- ]
671 : : process, m_settings.gpgExecutable,
672 : 10 : {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
673 : 10 : QStringLiteral("--decrypt"), QStringLiteral("--list-only"),
674 : 10 : QStringLiteral("--max-output"), QStringLiteral("1"),
675 : 10 : QStringLiteral("--status-fd=1"),
676 : 10 : QStringLiteral("--keyid-format=long"), QStringLiteral("--"),
677 : 10 : Executor::translatePathForWsl(path, m_settings.gpgExecutable)},
678 [ + - + ]: 20 : QString(), &status) != 0) {
679 : 0 : return {};
680 : : }
681 : : static const QRegularExpression encTo(
682 [ + + + - : 12 : QStringLiteral("^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
+ ]
683 : 10 : QStringList ids;
684 : : const QStringList lines =
685 : 10 : status.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
686 [ + + ]: 23 : for (const QString &line : lines) {
687 : 13 : const QRegularExpressionMatch match = encTo.match(line);
688 [ + + - ]: 13 : if (match.hasMatch()) {
689 : 26 : ids << match.captured(1).toUpper();
690 : : }
691 : 13 : }
692 : : return ids;
693 : 20 : }
694 : :
695 : 6458 : auto Pass::exactRecipientArg(const QString &line) -> QString {
696 : : static const QRegularExpression bareAddress(
697 [ + + + - : 6468 : QStringLiteral("^[^=<>@*+#&\\s][^<>@\\s]*@[^<>@\\s]+$"));
+ ]
698 : 6458 : return bareAddress.match(line).hasMatch()
699 [ + + ]: 6458 : ? QLatin1Char('<') + line + QLatin1Char('>')
700 : 6473 : : line;
701 : : }
702 : :
703 : 6164 : auto Pass::recipientArgument(const QString &line) const -> QString {
704 : 6164 : return exactRecipientArg(line);
705 : : }
706 : :
707 : 87 : auto Pass::encryptionReaches(const QStringList &recipients)
708 : : -> std::optional<QStringList> {
709 [ - + ]: 87 : if (recipients.isEmpty()) {
710 : 0 : return std::nullopt;
711 : : }
712 : 87 : QTemporaryDir scratch;
713 [ + - + ]: 87 : if (!scratch.isValid()) {
714 : 0 : return std::nullopt;
715 : : }
716 : 87 : const QString &gpg = m_settings.gpgExecutable;
717 : : const QString probe = Executor::translatePathForWsl(
718 [ + + ]: 174 : scratch.filePath(QStringLiteral("probe.gpg")), gpg);
719 : : // --no-throw-keyids: with throw-keyids in gpg.conf the probe would name
720 : : // no one.
721 : 174 : QStringList args{QStringLiteral("--batch"),
722 : 87 : QStringLiteral("--no-tty"),
723 : 87 : QStringLiteral("--yes"),
724 : 87 : QStringLiteral("--quiet"),
725 : 87 : QStringLiteral("--no-throw-keyids"),
726 : 87 : QStringLiteral("--no-auto-key-locate"),
727 : 87 : QStringLiteral("--no-encrypt-to"),
728 : 87 : QStringLiteral("--output"),
729 : : probe,
730 : 1044 : QStringLiteral("--encrypt")};
731 [ + + ]: 6262 : for (const QString &recipient : recipients) {
732 : 12350 : args << QStringLiteral("-r") << recipientArgument(recipient);
733 : : }
734 [ + + + ]: 174 : if (Executor::executeBlocking(gpg, args, QStringLiteral("probe")) != 0) {
735 : 21 : return std::nullopt;
736 : : }
737 : : // As ImitatePass::getKeysFromFile(): --decrypt --list-only, capped.
738 : 66 : QString status;
739 [ + + + - : 792 : if (Executor::executeBlocking(
- ]
740 : : gpg,
741 : 66 : {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
742 : 66 : QStringLiteral("--decrypt"), QStringLiteral("--list-only"),
743 : 66 : QStringLiteral("--max-output"), QStringLiteral("1"),
744 : 66 : QStringLiteral("--status-fd=1"),
745 : 66 : QStringLiteral("--keyid-format=long"), QStringLiteral("--"), probe},
746 [ - + ]: 132 : QString(), &status) != 0) {
747 : 0 : return QStringList();
748 : : }
749 : : static const QRegularExpression encTo(
750 [ + + + - : 74 : QStringLiteral("^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
+ ]
751 : 66 : QStringList ids;
752 : : const QStringList lines =
753 : 66 : status.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
754 [ + + ]: 300 : for (const QString &line : lines) {
755 : 234 : const QRegularExpressionMatch match = encTo.match(line);
756 [ + + + ]: 234 : if (match.hasMatch()) {
757 : 32 : ids << match.captured(1).toUpper();
758 : : }
759 : 234 : }
760 : : return ids;
761 : 87 : }
762 : :
763 : 203 : auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
764 : 1421 : QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
765 [ + + + ]: 535 : args.append(secret ? "--list-secret-keys" : "--list-keys");
766 : :
767 [ + + ]: 6482 : for (const QString &keystring : std::as_const(keystrings)) {
768 [ + + ]: 6279 : if (!keystring.isEmpty()) {
769 : : args.append(keystring);
770 : : }
771 : : }
772 : 203 : QString p_out;
773 [ + + + ]: 203 : if (Executor::executeBlocking(m_settings.gpgExecutable, args, &p_out) != 0) {
774 : 6 : return {};
775 : : }
776 : 197 : return parseGpgColonOutput(p_out, secret);
777 : : }
778 : :
779 : 159 : auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
780 : 318 : return listKeys(QStringList(keystring), secret);
781 : : }
782 : :
783 : : namespace {
784 : :
785 : 130 : auto containsAny(const QString &str, const QStringList &patterns) -> bool {
786 [ + + ]: 360 : for (const QString &p : patterns) {
787 [ + + ]: 252 : if (str.contains(p)) {
788 : : return true;
789 : : }
790 : : }
791 : : return false;
792 : : }
793 : :
794 : : // @p patterns must already be lowercase; only @p str is lowered.
795 : 107 : auto containsAnyCaseInsensitive(const QString &str, const QStringList &patterns)
796 : : -> bool {
797 : : const QString lower = str.toLower();
798 [ + + ]: 265 : for (const QString &p : patterns) {
799 [ + + ]: 169 : if (lower.contains(p)) {
800 : : return true;
801 : : }
802 : : }
803 : : return false;
804 : : }
805 : :
806 : : } // namespace
807 : :
808 : 48 : auto gpgErrorMessage(const QString &err) -> QString {
809 : : // Machine-readable status tokens added by --status-fd 2
810 [ + + + + : 240 : if (containsAny(err, {QStringLiteral("[GNUPG:] KEYEXPIRED"),
+ - - ]
811 : 48 : QStringLiteral("[GNUPG:] INV_RECP 5 ")}))
812 : : return QCoreApplication::translate(
813 : : "Pass", "Encryption failed: GPG key has expired. Please renew or "
814 : 5 : "replace it.");
815 [ + + + + : 215 : if (containsAny(err, {QStringLiteral("[GNUPG:] KEYREVOKED"),
+ - - ]
816 : 43 : QStringLiteral("[GNUPG:] INV_RECP 4 ")}))
817 : : return QCoreApplication::translate(
818 : 4 : "Pass", "Encryption failed: GPG key has been revoked.");
819 [ + + + + : 195 : if (containsAny(err, {QStringLiteral("[GNUPG:] NO_PUBKEY"),
+ - - ]
820 : 39 : QStringLiteral("[GNUPG:] INV_RECP")}))
821 : : return QCoreApplication::translate(
822 : : "Pass", "Encryption failed: recipient GPG key not found or invalid. "
823 : 13 : "Check that the key ID in .gpg-id is correct and imported.");
824 [ + + ]: 26 : if (err.contains(QStringLiteral("[GNUPG:] FAILURE")))
825 : : return QCoreApplication::translate(
826 : 1 : "Pass", "Encryption failed. Check that your GPG key is valid.");
827 : :
828 : : // Locale-dependent fallbacks
829 [ + + + + : 100 : if (containsAnyCaseInsensitive(err, {QLatin1String("key has expired"),
+ - - ]
830 : : QLatin1String("key expired")}))
831 : : return QCoreApplication::translate(
832 : : "Pass", "Encryption failed: GPG key has expired. Please renew or "
833 : 1 : "replace it.");
834 [ + + + + : 96 : if (containsAnyCaseInsensitive(err, {QLatin1String("key has been revoked"),
+ - - ]
835 : : QLatin1String("revoked")}))
836 : : return QCoreApplication::translate(
837 : 1 : "Pass", "Encryption failed: GPG key has been revoked.");
838 : : // pass passes no --status-fd, so this is all gpg says about a key that is
839 : : // present but cannot encrypt: expired, revoked, without an encryption
840 : : // subkey, or not trusted ("There is no assurance this key belongs to the
841 : : // named user"). "Not found ... imported" would send the user the wrong
842 : : // way; gpg's own lines, shown below this, say which it is.
843 [ + + + + : 69 : if (containsAnyCaseInsensitive(err, {QLatin1String("unusable public key")}))
+ - - ]
844 : : return QCoreApplication::translate(
845 : : "Pass", "Encryption failed: a recipient's GPG key cannot be used. It "
846 : : "may have expired or been revoked, have no encryption subkey, "
847 : 3 : "or not be trusted; gpg's message below says which.");
848 [ + + + + : 80 : if (containsAnyCaseInsensitive(err, {QLatin1String("no public key"),
+ - - ]
849 : : QLatin1String("no secret key")}))
850 : : return QCoreApplication::translate(
851 : : "Pass", "Encryption failed: recipient GPG key not found or invalid. "
852 : 5 : "Check that the key ID in .gpg-id is correct and imported.");
853 [ + + + + : 45 : if (containsAnyCaseInsensitive(err, {QLatin1String("encryption failed")}))
+ - - ]
854 : : return QCoreApplication::translate(
855 : 1 : "Pass", "Encryption failed. Check that your GPG key is valid.");
856 : :
857 : 14 : return {};
858 : 0 : }
859 : :
860 : 357 : void Pass::finished(int id, int exitCode, const QString &out,
861 : : const QString &err) {
862 : 357 : auto pid = static_cast<PROCESS>(id);
863 : :
864 : : // Pop the Show() this completion belongs to whether it worked or not, or
865 : : // the next result would be attributed to the wrong file.
866 : 357 : QString shownFile;
867 [ + + + + ]: 357 : if (pid == PASS_SHOW && !m_pendingShows.isEmpty()) {
868 : 82 : shownFile = m_pendingShows.dequeue();
869 : : }
870 : : // Count this insert off, success or failure, before its result goes out, so
871 : : // insertsPending() tracks the inserts still awaiting a report. Each insert
872 : : // reaches here once as PASS_INSERT.
873 : : // Its entry is handed out (reportedInsert()) while the report goes out.
874 : 357 : QString reported;
875 [ + + + + ]: 357 : if (pid == PASS_INSERT && m_insertsPending > 0) {
876 : 127 : --m_insertsPending;
877 [ + - ]: 127 : if (!m_insertedEntries.isEmpty()) {
878 : 127 : reported = m_insertedEntries.dequeue();
879 : : }
880 : : }
881 : : m_reportedInsert = std::move(reported);
882 : 357 : const auto reportedOut = qScopeGuard([this] { m_reportedInsert.clear(); });
883 : :
884 [ + + ]: 357 : if (exitCode != 0) {
885 : 67 : handleProcessError(pid, exitCode, out, err);
886 : : return;
887 : : }
888 : :
889 [ + + ]: 290 : if (pid == PASS_SHOW) {
890 : 52 : emit finishedShow(out, shownFile, exec.lastOutputLossless());
891 : : return;
892 : : }
893 : 238 : emitProcessFinishedSignal(pid, out, err);
894 : : }
895 : :
896 : 67 : void Pass::handleProcessError(PROCESS pid, int exitCode, const QString &out,
897 : : const QString &err) {
898 : : Q_UNUSED(out);
899 : :
900 [ + + ]: 67 : if (pid == PASS_INSERT) {
901 : 20 : const QString friendly = gpgErrorMessage(err);
902 : : const QString why =
903 [ + + + ]: 20 : friendly.isEmpty() ? err : formatInsertError(friendly, err);
904 : 20 : const bool written = insertWritten(err);
905 : 20 : emit insertFailed(why, written);
906 [ + + ]: 20 : if (written) {
907 : : // The entry is in the store; a git step after it failed (a commit
908 : : // that could not be signed, with pass.signcommits, say). The dialog
909 : : // closes on this, so say it here rather than only in the output
910 : : // panel.
911 : 10 : emit critical(tr("Saved, not committed"),
912 : 5 : tr("The entry is saved in the store, but recording it "
913 : : "in git failed. What was reported:\n\n%1")
914 [ + + ]: 10 : .arg(err.trimmed()));
915 : : }
916 : 20 : emit processErrorExit(exitCode, why);
917 : : return;
918 : : }
919 : :
920 [ + + ]: 47 : if (pid == GPG_GENKEYS) {
921 : 1 : emit generateGPGKeysFailed(err);
922 : : }
923 : 47 : emit processErrorExit(exitCode, err);
924 : : }
925 : :
926 : 58 : auto Pass::withoutStatusLines(const QString &err) -> QString {
927 : 58 : QStringList humanLines;
928 [ + + + + : 1667 : for (const QString &line : err.split('\n')) {
+ ]
929 : : QString cleanedLine = line;
930 : 1551 : cleanedLine.remove('\r');
931 [ + + + ]: 1551 : if (!cleanedLine.startsWith(QLatin1String("[GNUPG:]")))
932 : : humanLines.append(cleanedLine);
933 : : }
934 : 58 : return humanLines.join('\n');
935 : : }
936 : :
937 : 7 : auto Pass::formatInsertError(const QString &friendly, const QString &err)
938 : : -> QString {
939 : 14 : const QString humanErr = withoutStatusLines(err).trimmed();
940 [ + + + + ]: 14 : return humanErr.isEmpty() ? friendly : friendly + "\n\n" + humanErr;
941 : : }
942 : :
943 : 238 : void Pass::emitProcessFinishedSignal(PROCESS pid, const QString &out,
944 : : const QString &err) {
945 : : // Only output that cannot contain a secret reaches the generic listeners
946 : : // (the output panel among them); Enums::processInfo is the one table.
947 [ + + ]: 238 : if (pid >= 0 && pid < Enums::PROCESS_COUNT &&
948 [ + + ]: 236 : !Enums::processInfo(pid).secret) {
949 : 122 : emit finishedAnyWithPid(out, err, pid);
950 : : }
951 : :
952 : : // The kind-specific signal. PASS_SHOW is emitted by finished(), which
953 : : // knows the file. Content search runs in-process (NativeGrep), not
954 : : // through `pass grep`, and emits finishedGrep itself.
955 : : using Signal = void (Pass::*)(const QString &, const QString &);
956 : : static const QHash<int, Signal> kSignals{
957 : : {GIT_INIT, &Pass::finishedGitInit},
958 : : {GIT_PULL, &Pass::finishedGitPull},
959 : : {GIT_PUSH, &Pass::finishedGitPush},
960 : : {PASS_INSERT, &Pass::finishedInsert},
961 : : {PASS_REMOVE, &Pass::finishedRemove},
962 : : {PASS_INIT, &Pass::finishedInit},
963 : : {PASS_MOVE, &Pass::finishedMove},
964 : : {PASS_COPY, &Pass::finishedCopy},
965 : : {GPG_GENKEYS, &Pass::finishedGenerateGPGKeys},
966 : 244 : };
967 : : // A store that became a repository after updateEnv() gets its pin now,
968 : : // before anything is staged in it.
969 [ + + ]: 238 : if (pid == GIT_INIT) {
970 : 3 : pinStoreGitAttributes();
971 : : }
972 [ + + ]: 238 : if (const Signal signal = kSignals.value(pid, nullptr)) {
973 : 234 : (this->*signal)(out, err);
974 : : }
975 : 238 : }
976 : :
977 : 4897 : void Pass::setEnvVar(const QString &name, const QString &value) {
978 [ + + ]: 4897 : if (value.isEmpty())
979 : 1623 : env.remove(name);
980 : : else
981 : 3274 : env.insert(name, value);
982 : 4897 : }
983 : :
984 : 543 : void Pass::updateEnv() {
985 : 1086 : setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY"),
986 : 543 : m_settings.passSigningKey);
987 : 1086 : setEnvVar(QStringLiteral("PASSWORD_STORE_DIR"), m_settings.passStore);
988 : : // Every path QtPass hands git names one file or folder: an entry called
989 : : // "a*.gpg" must not make `git rm -f -- a*.gpg` remove every entry that
990 : : // matches. Also reaches the git that pass runs, which passes names the
991 : : // same way.
992 : 1086 : setEnvVar(QStringLiteral("GIT_LITERAL_PATHSPECS"), QStringLiteral("1"));
993 : :
994 : 543 : const PasswordConfiguration &passConfig = m_settings.passwordConfiguration;
995 : 1086 : setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH"),
996 : 543 : QString::number(passConfig.length));
997 : :
998 : 1086 : setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET"),
999 : 543 : effectiveCharset(passConfig));
1000 : :
1001 : : // pass hands PASSWORD_STORE_GPG_OPTS to every gpg it runs: the user's own
1002 : : // options (split as pass's shell splits them: spaces, tabs, newlines),
1003 : : // then the output limit ImitatePass passes directly.
1004 : 553 : static const QRegularExpression whitespace(QStringLiteral("\\s+"));
1005 : 543 : QStringList gpgOpts = QProcessEnvironment::systemEnvironment()
1006 : 1086 : .value(QStringLiteral("PASSWORD_STORE_GPG_OPTS"))
1007 : 543 : .split(whitespace, Qt::SkipEmptyParts);
1008 : 1086 : gpgOpts << maxOutputArgs();
1009 : 1086 : setEnvVar(QStringLiteral("PASSWORD_STORE_GPG_OPTS"),
1010 : 543 : gpgOpts.join(QLatin1Char(' ')));
1011 : :
1012 : : // As pass does: git never looks for a repository above the store's own
1013 : : // parent. A store that is not a repository itself but lies inside one (a
1014 : : // dotfiles repository in the home folder) would otherwise have its entries
1015 : : // committed and pushed there by native git mode. Only in the environment
1016 : : // of the processes QtPass runs for the store, never QtPass's own, which a
1017 : : // file manager or terminal it opens would inherit. pass sets its own
1018 : : // ceiling whatever this says. A store kept inside a larger repository on
1019 : : // purpose opts out (gitUseParentRepository), and then, as without a
1020 : : // store, whatever ceiling QtPass was started with applies.
1021 : : // A ceiling git cannot take as one entry (the parent's path holds the
1022 : : // list separator) is backed by GIT_DIR and GIT_WORK_TREE naming the
1023 : : // store's own repository (Util::gitStoreVariables()); pass unsets those
1024 : : // for itself and keeps its own ceiling.
1025 : 1086 : setEnvVar(QStringLiteral("GIT_DIR"), QString());
1026 : 1086 : setEnvVar(QStringLiteral("GIT_WORK_TREE"), QString());
1027 [ + + + + ]: 543 : if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
1028 : 40 : setEnvVar(QStringLiteral("GIT_CEILING_DIRECTORIES"),
1029 : 40 : qEnvironmentVariable("GIT_CEILING_DIRECTORIES"));
1030 : : } else {
1031 : : const auto variables =
1032 : 523 : Util::gitStoreVariables(m_settings.passStore, m_settings.gitExecutable);
1033 [ + + ]: 1050 : for (const auto &[name, value] : variables) {
1034 : 527 : setEnvVar(name, value);
1035 : : }
1036 : : }
1037 : :
1038 : : // Refuse a repository pushed into the store: git started in a folder laid
1039 : : // out as a bare repository would read its pushed config and run a command
1040 : : // named there. This reaches the git that pass runs too, which inherits the
1041 : : // environment.
1042 : 543 : Util::requireExplicitBareRepository(env);
1043 : : // pass under WSL needs them too: the count and every entry below it.
1044 : 1086 : QStringList gitConfig{QStringLiteral("GIT_CONFIG_COUNT/u")};
1045 [ + - + ]: 1086 : if (env.contains(QStringLiteral("GIT_CONFIG_PARAMETERS"))) {
1046 : 0 : gitConfig << QStringLiteral("GIT_CONFIG_PARAMETERS/u");
1047 : : }
1048 : : const int gitConfigCount =
1049 : 1086 : env.value(QStringLiteral("GIT_CONFIG_COUNT")).toInt();
1050 [ + + ]: 1143 : for (int i = 0; i < gitConfigCount; ++i) {
1051 : 1200 : gitConfig << QStringLiteral("GIT_CONFIG_KEY_%1/u").arg(i)
1052 : 1200 : << QStringLiteral("GIT_CONFIG_VALUE_%1/u").arg(i);
1053 : : }
1054 : 543 : mergeIntoWslenv(env, gitConfig);
1055 : :
1056 : 543 : exec.setEnvironment(env);
1057 : :
1058 : 543 : pinStoreGitAttributes();
1059 : 543 : }
1060 : :
1061 : : namespace {
1062 : : /**
1063 : : * @brief The lines of an `info/attributes` file outside the QtPass block:
1064 : : * the block's own lines after @p marker are dropped, and the
1065 : : * trailing blank lines but one.
1066 : : * @param existing The file's text; empty when it does not exist.
1067 : : * @param marker The line that opens the QtPass block.
1068 : : * @return The lines to keep, each ending in a newline; empty for none.
1069 : : */
1070 : 14 : auto userAttributeLines(const QString &existing, const QString &marker)
1071 : : -> QString {
1072 : 14 : QString preserved;
1073 [ - + ]: 14 : if (existing.isEmpty()) {
1074 : : return preserved;
1075 : : }
1076 : 0 : const QStringList lines = existing.split(QLatin1Char('\n'));
1077 : : bool inBlock = false;
1078 [ # # ]: 0 : for (const QString &line : lines) {
1079 [ # # ]: 0 : if (line == marker) {
1080 : : inBlock = true;
1081 : 0 : continue;
1082 : : }
1083 [ # # ]: 0 : if (inBlock) {
1084 [ # # # # : 0 : if (line.startsWith(QStringLiteral("*.gpg ")) ||
# ]
1085 [ # # # # : 0 : line.startsWith(QStringLiteral(".gpg-id ")) ||
# # # ]
1086 [ # # # # : 0 : line.startsWith(QStringLiteral(".gpg-id.sig "))) {
# # # # #
# # ]
1087 : 0 : continue;
1088 : : }
1089 : : inBlock = false;
1090 : : }
1091 : 0 : preserved += line + QLatin1Char('\n');
1092 : : }
1093 [ # # # ]: 0 : while (preserved.endsWith(QStringLiteral("\n\n"))) {
1094 : 0 : preserved.chop(1);
1095 : : }
1096 : : return preserved;
1097 : : }
1098 : : } // namespace
1099 : :
1100 : 546 : void Pass::pinStoreGitAttributes() {
1101 [ + + ]: 546 : if (m_settings.passStore.isEmpty()) {
1102 : 532 : return;
1103 : : }
1104 : : // Only the common layout, where the store is its own repository, is handled
1105 : : // by writing directly: a ".git" directory. A worktree ".git" file or a store
1106 : : // nested in a larger repository is left as-is rather than risk touching
1107 : : // another repository's attributes.
1108 : : const QString gitDir =
1109 : 1064 : QDir(m_settings.passStore).absoluteFilePath(QStringLiteral(".git"));
1110 [ + + + + ]: 532 : if (!QFileInfo(gitDir).isDir()) {
1111 : : return;
1112 : : }
1113 : :
1114 : : // The marker lets us recognise and refresh our own block without disturbing
1115 : : // anything a user put in info/attributes by hand. Disabling text/eol,
1116 : : // working-tree-encoding, filter and ident keeps Git from rewriting the
1117 : : // bytes gpg produced for these paths - a co-writer can push a .gitattributes
1118 : : // ("*.gpg text", a working-tree-encoding, a filter) that otherwise corrupts
1119 : : // the ciphertext QtPass commits. info/attributes outranks the in-tree file.
1120 : : // diff is left alone: it only changes what Git shows, and pass's own
1121 : : // "*.gpg diff=gpg" gives decrypted diffs.
1122 : : static const QString marker =
1123 : 58 : QStringLiteral("# QtPass: keep encrypted store files byte-for-byte");
1124 : : const QString block =
1125 : 108 : marker + QStringLiteral("\n") +
1126 : 108 : QStringLiteral(
1127 : : "*.gpg -text -filter -ident -working-tree-encoding\n"
1128 : : ".gpg-id -text -filter -ident -working-tree-encoding\n"
1129 : : ".gpg-id.sig -text -filter -ident -working-tree-encoding\n");
1130 : :
1131 : 108 : const QString infoDir = gitDir + QStringLiteral("/info");
1132 : 108 : const QString attrPath = infoDir + QStringLiteral("/attributes");
1133 : :
1134 : 54 : QString existing;
1135 : 54 : QFile attr(attrPath);
1136 [ + + + ]: 54 : if (attr.exists()) {
1137 : : // Unreadable: writing now would drop the user's own lines in it.
1138 [ + - + ]: 40 : if (!attr.open(QIODevice::ReadOnly | QIODevice::Text)) {
1139 : 0 : qCWarning(lcQtPass) << "Cannot read" << attrPath
1140 : 0 : << "to pin attributes:" << attr.errorString();
1141 : 0 : return;
1142 : : }
1143 : 40 : existing = QString::fromUtf8(attr.readAll());
1144 : 40 : attr.close();
1145 [ - + ]: 40 : if (existing.contains(block)) {
1146 : : return; // already pinned and unchanged
1147 : : }
1148 : : }
1149 : :
1150 [ + + - + ]: 28 : if (!QDir().mkpath(infoDir)) {
1151 : 0 : qCWarning(lcQtPass) << "Cannot create" << infoDir << "to pin attributes";
1152 : 0 : return;
1153 : : }
1154 : :
1155 : : // Keep any lines the user added themselves (outside our block), then append a
1156 : : // fresh copy of our block. A previous QtPass block is dropped so an updated
1157 : : // set of lines replaces an older one.
1158 : 14 : const QString preserved = userAttributeLines(existing, marker);
1159 : :
1160 : 14 : QSaveFile out(attrPath);
1161 : 14 : const QByteArray payload = (preserved + block).toUtf8();
1162 [ + + - ]: 28 : if (!out.open(QIODevice::WriteOnly | QIODevice::Text) ||
1163 [ + - + + : 28 : out.write(payload) != payload.size() || !out.commit()) {
- + ]
1164 : 0 : qCWarning(lcQtPass) << "Cannot write" << attrPath
1165 : 0 : << "to pin attributes:" << out.errorString();
1166 : : }
1167 : 68 : }
1168 : :
1169 : 2476 : auto Pass::withCurrentGitPin(QProcessEnvironment base) const
1170 : : -> QProcessEnvironment {
1171 [ + + - + ]: 2476 : if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
1172 : 17 : return base;
1173 : : }
1174 : 4918 : base.remove(QStringLiteral("GIT_DIR"));
1175 : 4918 : base.remove(QStringLiteral("GIT_WORK_TREE"));
1176 : : const auto variables =
1177 : 2459 : Util::gitStoreVariables(m_settings.passStore, m_settings.gitExecutable);
1178 [ + + ]: 4928 : for (const auto &[name, value] : variables) {
1179 : 2469 : base.insert(name, value);
1180 : : }
1181 : 2459 : return base;
1182 : : }
1183 : :
1184 : 1289 : auto Pass::maxOutputArgs() -> QStringList {
1185 : 3867 : return {QStringLiteral("--max-output"), QString::number(kMaxPlaintextBytes)};
1186 : 1289 : }
1187 : :
1188 : : namespace {
1189 : : /// File names compare the way the platform's file system compares them:
1190 : : /// "C:/Store" and "c:/store" are the same directory on Windows.
1191 : : #ifdef Q_OS_WIN
1192 : : constexpr auto kPathCase = Qt::CaseInsensitive;
1193 : : #else
1194 : : constexpr auto kPathCase = Qt::CaseSensitive;
1195 : : #endif
1196 : :
1197 : : /// Whether @p path is @p dir or lies under it.
1198 : 6024 : auto isAtOrUnder(const QString &path, const QString &dir,
1199 : : const QString &dirPrefix) -> bool {
1200 [ + + + + ]: 11081 : return path.compare(dir, kPathCase) == 0 ||
1201 : 5057 : path.startsWith(dirPrefix, kPathCase);
1202 : : }
1203 : :
1204 : : /// Where the lookup of a .gpg-id starts and the store that bounds it.
1205 : : struct GpgIdLookup {
1206 : : QDir start;
1207 : : /// The folder whose list is wanted, whether it exists or not.
1208 : : QString folder;
1209 : : QString storeDir;
1210 : : QString storePrefix;
1211 : : };
1212 : :
1213 : : /// The folder whose list @p for_file wants: its own for a folder, its
1214 : : /// folder's for an entry.
1215 : 1406 : auto gpgIdLookup(const QString &for_file, const QString &passStore)
1216 : : -> GpgIdLookup {
1217 : 1406 : const QString normalizedFile = QDir::fromNativeSeparators(for_file);
1218 : : // Inside the store means at a path boundary: "/store-other/x" is not
1219 : : // under "/store", however the prefix compares.
1220 : : const QString storeDir =
1221 : 1406 : QDir::cleanPath(QDir::fromNativeSeparators(passStore));
1222 : 1406 : const QString storePrefix = storeDir.endsWith(QLatin1Char('/'))
1223 [ - + ]: 1406 : ? storeDir
1224 : 1406 : : storeDir + QLatin1Char('/');
1225 : 1406 : const QString cleanFile = QDir::cleanPath(normalizedFile);
1226 : 1406 : const bool insideStore = isAtOrUnder(cleanFile, storeDir, storePrefix);
1227 : : // A relative name is one inside the store; an absolute path outside it
1228 : : // stays what it is and the walk stops at once.
1229 : : const QString fullPath =
1230 [ + + + - ]: 21 : insideStore || (QDir::isAbsolutePath(cleanFile) &&
1231 : 5 : !cleanFile.startsWith(QLatin1Char(':')))
1232 [ + + ]: 1406 : ? cleanFile
1233 : 11 : : storePrefix + cleanFile;
1234 : : // A folder (trailing separator, which cleanPath() dropped, or an existing
1235 : : // directory) wants its own list; an entry wants its folder's.
1236 : : const bool isFolder =
1237 [ + + + + : 1406 : normalizedFile.endsWith(QLatin1Char('/')) || QFileInfo(fullPath).isDir();
+ ]
1238 : : // A folder that does not exist yet (an entry saved into a new folder, a
1239 : : // move to one) starts the walk at its nearest existing ancestor in the
1240 : : // store, as pass's set_gpg_recipients does: otherwise the walk ended at
1241 : : // once and the store root's list was taken over the one in between.
1242 : : const QString folder =
1243 [ + + + + : 3536 : QDir::cleanPath(isFolder ? fullPath : QFileInfo(fullPath).absolutePath());
+ + + -
- ]
1244 : : QString start = folder;
1245 [ + + - ]: 1442 : while (!QFileInfo::exists(start) &&
1246 [ + + + + : 2866 : isAtOrUnder(QDir::cleanPath(start), storeDir, storePrefix) &&
+ - + + ]
1247 [ + + + - : 1442 : QDir::cleanPath(start) != storeDir) {
- ]
1248 : 36 : start = QFileInfo(start).absolutePath();
1249 : : }
1250 : 1406 : return {QDir(start), folder, storeDir, storePrefix};
1251 : 1406 : }
1252 : :
1253 : : /// Whether @p candidate can be its folder's .gpg-id: a regular file, as
1254 : : /// pass looks for (test -f), so a folder under the name is passed over as
1255 : : /// pass passes it. A link under the name is not: whoever planted it chose
1256 : : /// the recipients elsewhere.
1257 : 2496 : auto isOwnGpgId(const QFileInfo &candidate) -> bool {
1258 [ + + + + : 3227 : return candidate.isFile() && !candidate.isSymLink() &&
- + ]
1259 : 731 : !candidate.isJunction();
1260 : : }
1261 : :
1262 : : /// Walk up from the lookup's start to the first folder inside the store
1263 : : /// that has its own .gpg-id; nothing when none does. A link under the name
1264 : : /// is skipped, so the parent's list applies instead.
1265 : 799 : auto nearestGpgId(const GpgIdLookup &lookup) -> std::optional<QString> {
1266 : 799 : QDir dir = lookup.start;
1267 [ + + - + : 4828 : while (dir.exists() && isAtOrUnder(QDir::cleanPath(dir.absolutePath()),
+ + - + +
- - - - ]
1268 : 1207 : lookup.storeDir, lookup.storePrefix)) {
1269 : 1035 : const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
1270 [ + + + ]: 1035 : if (isOwnGpgId(candidate)) {
1271 : 627 : return candidate.absoluteFilePath();
1272 : : }
1273 [ + + - ]: 408 : if (!dir.cdUp()) {
1274 : : break;
1275 : : }
1276 : 1035 : }
1277 : 172 : return std::nullopt;
1278 : 799 : }
1279 : :
1280 : : } // namespace
1281 : :
1282 : 327 : auto Pass::heldScopes() -> QSet<QString> & {
1283 : 333 : static QSet<QString> scopes;
1284 : 327 : return scopes;
1285 : : }
1286 : :
1287 : 327 : auto Pass::scopePath(const QString &path) const -> QString {
1288 : 654 : return QDir::cleanPath(QDir(m_settings.passStore).absoluteFilePath(path));
1289 : : }
1290 : :
1291 : 76 : auto Pass::autoPushHeld() const -> bool {
1292 : 76 : const QString store = scopePath(QString());
1293 : 76 : const QSet<QString> &scopes = heldScopes();
1294 : 76 : return std::any_of(scopes.cbegin(), scopes.cend(),
1295 : 588 : [&store](const QString &s) {
1296 : 1176 : return isAtOrUnder(s, store, store + QLatin1Char('/'));
1297 : 76 : });
1298 : : }
1299 : :
1300 : 16 : void Pass::GitPushAutomatic() {
1301 : 16 : m_pushIsAutomatic = true;
1302 : 16 : GitPush();
1303 : 16 : m_pushIsAutomatic = false;
1304 : 16 : }
1305 : :
1306 : 12 : auto Pass::pushIsAutomatic() const -> bool { return m_pushIsAutomatic; }
1307 : :
1308 : 126 : void Pass::holdAutoPush(const QString &scope) {
1309 : 126 : heldScopes().insert(scopePath(scope));
1310 : 126 : }
1311 : :
1312 : 125 : void Pass::releaseAutoPush(const QString &folder) {
1313 : 125 : const QString root = scopePath(folder);
1314 : 125 : QSet<QString> &scopes = heldScopes();
1315 : : for (auto it = scopes.begin(); it != scopes.end();) {
1316 [ + + + + ]: 3238 : it = isAtOrUnder(*it, root, root + QLatin1Char('/')) ? scopes.erase(it)
1317 : 1619 : : std::next(it);
1318 : : }
1319 : 125 : }
1320 : :
1321 : 912 : auto Pass::refuseLinkedPath(const QString &path, LinkScope scope,
1322 : : PathSpelling spelling) -> bool {
1323 : 912 : const QString full = Util::joinPath(m_settings.passStore, path);
1324 : : // The link check below walks only under the store as configured: a path
1325 : : // spelled through the root's link target would get no more than the
1326 : : // entry itself judged. No caller makes one; say so if one starts to.
1327 [ + + + + ]: 1508 : if (spelling == PathSpelling::Configured &&
1328 : 596 : PathValidator::isTargetSpelled(m_settings.passStore, full)) {
1329 : 4 : qCWarning(lcQtPass)
1330 : : << "Path spelled through the store root's link target, not as the "
1331 : : "store is configured; Pass operations expect the configured "
1332 : 2 : "spelling:"
1333 : 2 : << full;
1334 : : }
1335 [ + + + ]: 912 : if (!Util::isUnderLink(full, m_settings.passStore,
1336 : : scope == LinkScope::EntryAndParents)) {
1337 : : return false;
1338 : : }
1339 : : const QString why =
1340 : 0 : tr("%1 is, or lies behind, a symbolic link or junction. What that "
1341 : : "points to is not part of the password store and is left alone.")
1342 : 62 : .arg(QDir::toNativeSeparators(QDir::cleanPath(full)));
1343 : 31 : refuseAsNotPartOfStore(why);
1344 : : return true;
1345 : : }
1346 : :
1347 : 103 : auto Pass::refuseFolderOutsideStore(const QString &folder, QString *relative)
1348 : : -> bool {
1349 [ + + ]: 103 : if (const std::optional<QString> inStore =
1350 : 103 : PathValidator::storeRelativePath(m_settings.passStore, folder)) {
1351 [ + - ]: 98 : if (relative != nullptr) {
1352 : 98 : *relative = *inStore;
1353 : : }
1354 : : return false;
1355 : : }
1356 : 5 : refuseAsNotPartOfStore(
1357 : 5 : tr("%1 is not inside the password store. Recipients are set for the "
1358 : : "store or a folder in it.")
1359 [ + + + ]: 10 : .arg(QDir::toNativeSeparators(QDir::cleanPath(folder))));
1360 : 5 : return true;
1361 : : }
1362 : :
1363 : 976 : auto Pass::unfinishedGitOperationReason() -> QString {
1364 [ + + ]: 976 : if (!m_settings.useGit) {
1365 : 668 : return {};
1366 : : }
1367 : : // One git call names the path of each marker file or directory, whether or
1368 : : // not it exists; the backend runs it in the store (ImitatePass with
1369 : : // `-C <store>`, RealPass through `pass git`). The markers, paired with the
1370 : : // operation each one means, in the order git prints them back.
1371 : : // The names are Git's own commands, which the user then runs with --abort or
1372 : : // --continue; the translator comments say so.
1373 : : const std::array<std::pair<QLatin1String, QString>, 6> markers{{
1374 : : //: The Git command `git rebase`, inserted into "in the middle of a %1".
1375 : : //: Best kept as Git's command name.
1376 : 308 : {QLatin1String("rebase-merge"), tr("rebase")},
1377 : : //: The Git command `git rebase`, inserted into "in the middle of a %1".
1378 : : //: Best kept as Git's command name.
1379 : 308 : {QLatin1String("rebase-apply"), tr("rebase")},
1380 : : //: The Git command `git merge`, inserted into "in the middle of a %1".
1381 : : //: Best kept as Git's command name.
1382 : 308 : {QLatin1String("MERGE_HEAD"), tr("merge")},
1383 : : //: The Git command `git cherry-pick`, inserted into "in the middle of a
1384 : : //: %1". Best kept as Git's command name.
1385 : 308 : {QLatin1String("CHERRY_PICK_HEAD"), tr("cherry-pick")},
1386 : : //: The Git command `git revert`, inserted into "in the middle of a %1".
1387 : : //: Best kept as Git's command name.
1388 : 308 : {QLatin1String("REVERT_HEAD"), tr("revert")},
1389 : : // A multi-commit cherry-pick or revert keeps its sequencer state after a
1390 : : // conflict resolution is committed, when CHERRY_PICK_HEAD/REVERT_HEAD is
1391 : : // already gone but `--continue` has more commits to apply. Checked last,
1392 : : // so the specific head above names the operation when it is still there.
1393 : : //: The Git commands `git cherry-pick` and `git revert`, inserted into
1394 : : //: "in the middle of a %1". Best kept as Git's command names.
1395 : 308 : {QLatin1String("sequencer"), tr("cherry-pick or revert")},
1396 : 0 : }};
1397 : 616 : QStringList args{QStringLiteral("rev-parse")};
1398 [ + + ]: 2156 : for (const auto &marker : markers) {
1399 : 1848 : args << QStringLiteral("--git-path") << marker.first;
1400 : : }
1401 : 308 : QString out;
1402 [ + + + ]: 308 : if (!storeGit(args, &out)) {
1403 : : // Git is off, the store is not a repository, or git could not be asked:
1404 : : // nothing is refused, as the operation would run anyway.
1405 : 17 : return {};
1406 : : }
1407 : 291 : const QStringList paths = out.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
1408 [ + + - + ]: 977 : for (int i = 0; i < paths.size() && i < static_cast<int>(markers.size());
1409 : : ++i) {
1410 : : const QString path = paths.at(i).trimmed();
1411 : : const QString full = QDir::isAbsolutePath(path)
1412 [ - + ]: 693 : ? path
1413 : 693 : : QDir(m_settings.passStore).filePath(path);
1414 [ + + + ]: 693 : if (!QFileInfo::exists(full)) {
1415 : : continue;
1416 : : }
1417 : : //: %1 is a Git command name: rebase, merge, cherry-pick, revert, or
1418 : : //: "cherry-pick or revert".
1419 : 7 : return tr("The password store's Git repository is in the middle of a %1. "
1420 : : "Finish or abort it with Git before changing the password store, "
1421 : : "or what you change may be lost.")
1422 : 7 : .arg(markers.at(static_cast<size_t>(i)).second);
1423 : : }
1424 : 284 : return {};
1425 : : }
1426 : :
1427 : 238 : auto Pass::refusePendingPull() -> bool {
1428 [ + + + + ]: 307 : if (!m_settings.useGit || !exec.hasQueued(Enums::GIT_PULL)) {
1429 : : return false;
1430 : : }
1431 : : const QString why =
1432 : : tr("The password store is being updated (a Git pull is in progress). "
1433 : : "Wait until it has finished, then try again.");
1434 : : // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
1435 : : // and is released by processErrorExit(); a refusal starts nothing.
1436 : 5 : emit startingExecuteWrapper();
1437 : 5 : emit critical(tr("Update in progress"), why);
1438 : 5 : emit processErrorExit(1, why);
1439 : : return true;
1440 : : }
1441 : :
1442 : 12 : auto Pass::initIfUnchanged(const QString &path, const QList<UserInfo> &users,
1443 : : const QString &dir, const QString &passStore,
1444 : : const RecipientsForEditing &read) -> bool {
1445 : 12 : m_expectedList = ExpectedList{dir, passStore, read.state, read.recipients};
1446 : 12 : m_expectedListRefused = false;
1447 : : const auto done = qScopeGuard([this] { m_expectedList.reset(); });
1448 : 12 : Init(path, users);
1449 : 12 : return !m_expectedListRefused;
1450 : : }
1451 : :
1452 : 88 : auto Pass::refuseChangedList() -> bool {
1453 [ + + ]: 88 : if (!m_expectedList) {
1454 : : return false;
1455 : : }
1456 : : // A copy: recipientsForEditing() is a member call, after which the
1457 : : // optional cannot be known to hold a value any more.
1458 : 5 : const ExpectedList expected = *m_expectedList;
1459 : : const RecipientsForEditing now =
1460 : 5 : recipientsForEditing(expected.dir, expected.passStore);
1461 [ + - + + ]: 5 : if (now.state == expected.state && now.recipients == expected.recipients) {
1462 : : return false;
1463 : : }
1464 : : const QString why =
1465 : : tr("The recipient list of this folder changed after the users dialog "
1466 : : "read it, for example through an update from Git. Nothing was "
1467 : : "written. Open the dialog again to see the new list.");
1468 : 3 : m_expectedListRefused = true;
1469 : 3 : emit startingExecuteWrapper();
1470 : 3 : emit critical(tr("Recipients not changed"), why);
1471 : 3 : emit processErrorExit(1, why);
1472 : : return true;
1473 : 5 : }
1474 : :
1475 : 40 : auto Pass::refuseBusyForExpectedList() -> bool {
1476 [ + + ]: 40 : if (!m_expectedList || exec.isIdle()) {
1477 : : return false;
1478 : : }
1479 : : const QString why =
1480 : : tr("Another operation is still running. Wait until it has finished, "
1481 : : "then save the recipients again.");
1482 : 1 : m_expectedListRefused = true;
1483 : 1 : emit startingExecuteWrapper();
1484 : 1 : emit critical(tr("Recipients not changed"), why);
1485 : 1 : emit processErrorExit(1, why);
1486 : : return true;
1487 : : }
1488 : :
1489 : 707 : auto Pass::refuseUnfinishedGitOperation() -> bool {
1490 : 707 : const QString why = unfinishedGitOperationReason();
1491 [ + + ]: 707 : if (why.isEmpty()) {
1492 : : return false;
1493 : : }
1494 : : // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
1495 : : // and is released by finished()/processErrorExit(); a refusal starts
1496 : : // nothing, so it emits both ends.
1497 : 5 : emit startingExecuteWrapper();
1498 : 5 : emit critical(tr("Unfinished Git operation"), why);
1499 : 5 : emit processErrorExit(1, why);
1500 : : return true;
1501 : : }
1502 : :
1503 : 36 : void Pass::refuseAsNotPartOfStore(const QString &why) {
1504 : : // The interface arms itself when an operation starts and is released by
1505 : : // finished or processErrorExit; a refusal starts nothing, so emits both.
1506 : 36 : emit startingExecuteWrapper();
1507 : 36 : emit critical(tr("Not part of the store"), why);
1508 : 36 : emit processErrorExit(1, why);
1509 : 36 : }
1510 : :
1511 : 799 : auto Pass::getGpgIdPath(const QString &for_file, const QString &passStore)
1512 : : -> QString {
1513 : 1598 : return nearestGpgId(gpgIdLookup(for_file, passStore))
1514 : : .value_or(
1515 [ + + + + ]: 3196 : QDir(QDir::fromNativeSeparators(passStore)).filePath(".gpg-id"));
1516 : : }
1517 : :
1518 : 265 : auto Pass::refuseSkippedGpgId(const QString &file, bool signing,
1519 : : const QString &except, SkippedWalks *walks)
1520 : : -> bool {
1521 : : // Without a signing key the parent's list applies, as it does for pass.
1522 [ + + ]: 265 : if (!signing) {
1523 : : return false;
1524 : : }
1525 : 54 : QString recordError;
1526 : : const std::optional<QString> skipped =
1527 : 54 : skippedGpgId(file, m_settings.passStore, &recordError, walks);
1528 [ + + + + ]: 54 : if (!skipped || (!except.isEmpty() &&
1529 [ + + + + : 56 : QDir::cleanPath(*skipped) == QDir::cleanPath(except))) {
+ + - - ]
1530 : : return false;
1531 : : }
1532 : : // The strings keep the context they were translated in.
1533 [ - + ]: 4 : if (!recordError.isEmpty()) {
1534 : 0 : emit critical(QCoreApplication::translate(
1535 : : "ImitatePass", "Cannot check the recipient list"),
1536 : 0 : QCoreApplication::translate(
1537 : : "ImitatePass", "%1 Whether %2 was removed cannot be "
1538 : : "told, so nothing was encrypted.")
1539 [ # # ]: 0 : .arg(recordError, QDir::toNativeSeparators(*skipped)));
1540 : 0 : return true;
1541 : : }
1542 : 4 : emit critical(
1543 : 8 : QCoreApplication::translate("ImitatePass", "Recipient list missing"),
1544 : 4 : QCoreApplication::translate(
1545 : : "ImitatePass",
1546 : : "The signed recipient list %1 is missing or is not a regular file. "
1547 : : "QtPass does not fall back to a parent folder's list for it: that "
1548 : : "list was not signed for this folder. If a link is under that name, "
1549 : : "remove it. Then open Users for that folder and save its "
1550 : : "recipients, which writes and signs a fresh list.")
1551 [ + + ]: 8 : .arg(QDir::toNativeSeparators(*skipped)));
1552 : 4 : return true;
1553 : : }
1554 : :
1555 : 77 : auto Pass::verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile,
1556 : : QByteArray *contents, QString *why) const -> bool {
1557 [ + + ]: 77 : if (!signer.verifyFile(gpgIdFile, contents)) {
1558 : : // A good signature refused for its key (held by two key blocks) says
1559 : : // why, and what to do.
1560 [ + + + + : 22 : if (why != nullptr && !signer.refusal().isEmpty()) {
+ + ]
1561 : 1 : *why = signer.refusal();
1562 : : }
1563 : 18 : return false;
1564 : : }
1565 : : // Authentic and unmodified is not the same as current: an older signed
1566 : : // list put back into the store is refused once this device has seen a
1567 : : // newer one, and one signed for another folder is refused here.
1568 : 59 : QString reason;
1569 [ + + + ]: 59 : if (GpgIdGeneration::accept(gpgIdFile, *contents, m_settings.passStore,
1570 : : &reason) != GpgIdGeneration::Verdict::Accepted) {
1571 [ + + ]: 19 : if (why != nullptr) {
1572 : : *why = std::move(reason);
1573 : : }
1574 : 19 : return false;
1575 : : }
1576 : : return true;
1577 : : }
1578 : :
1579 : 459 : auto Pass::gpgIdVerdictIn(const QString &dir) -> std::optional<SkippedWalk> {
1580 : 918 : const QFileInfo candidate(dir + QStringLiteral("/.gpg-id"));
1581 [ + + + ]: 459 : if (isOwnGpgId(candidate)) {
1582 : 34 : return SkippedWalk{std::nullopt, QString()};
1583 : : }
1584 : : // A link under the name (dangling or not), or nothing under it where
1585 : : // this device accepted a list before: both are the folder's list gone,
1586 : : // not a folder that never had one.
1587 [ + + + + : 442 : if (candidate.isSymLink() || candidate.isJunction()) {
- + ]
1588 : 10 : return SkippedWalk{candidate.absoluteFilePath(), QString()};
1589 : : }
1590 : : // An unreadable record is not "never seen": whether a list was accepted
1591 : : // here cannot be told, so this folder is refused too (fail closed), with
1592 : : // the record's own reason for the caller to show.
1593 : 437 : QString why;
1594 : : const std::optional<bool> seen =
1595 : 874 : GpgIdGeneration::seen(candidate.absoluteFilePath(), &why);
1596 [ + + ]: 437 : if (!seen) {
1597 : 2 : return SkippedWalk{candidate.absoluteFilePath(),
1598 : : why.isEmpty()
1599 [ - + ]: 1 : ? tr("The generation record of the recipient lists "
1600 : : "cannot be read.")
1601 : : : why};
1602 : : }
1603 [ + + ]: 436 : if (*seen) {
1604 : 24 : return SkippedWalk{candidate.absoluteFilePath(), QString()};
1605 : : }
1606 : 424 : return std::nullopt;
1607 : 459 : }
1608 : :
1609 : 287 : auto Pass::skippedGpgId(const QString &forFile, const QString &passStore,
1610 : : QString *recordError, SkippedWalks *walks)
1611 : : -> std::optional<QString> {
1612 : 287 : const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
1613 : : // A folder's answer depends only on it and the folders above it: kept
1614 : : // for every folder climbed, a tree check asks each one record lookup,
1615 : : // where climbing again from every folder cost depth squared.
1616 : 287 : QStringList climbed;
1617 : : // By value: on a hit they come out of walks, which the inserts below
1618 : : // may rehash.
1619 : : // NOLINTBEGIN(performance-unnecessary-value-param): by value, see above.
1620 : 287 : const auto answer = [&climbed, walks, recordError](
1621 : : std::optional<QString> skipped, QString why) {
1622 : : // NOLINTEND(performance-unnecessary-value-param)
1623 [ + + ]: 287 : if (walks != nullptr) {
1624 [ + + ]: 430 : for (const QString &folder : std::as_const(climbed)) {
1625 : 430 : walks->insert(folder, {skipped, why});
1626 : : }
1627 : : }
1628 [ + + + + ]: 287 : if (recordError != nullptr && !why.isEmpty()) {
1629 : : *recordError = std::move(why);
1630 : : }
1631 : 287 : return skipped;
1632 : 287 : };
1633 : : // The same walk as nearestGpgId(), stopping at the list it finds, and
1634 : : // short of the store root: the root's own list has no parent to fall
1635 : : // back to, and the signature check refuses it when it is missing. It
1636 : : // starts at the folder asked for, not at its nearest existing one: a
1637 : : // folder removed together with its list is asked of the record too.
1638 : : QString dir = lookup.folder;
1639 [ + + + ]: 711 : while (dir.startsWith(lookup.storePrefix, kPathCase)) {
1640 [ + + ]: 657 : if (walks != nullptr) {
1641 [ + + ]: 413 : if (const auto known = walks->constFind(dir);
1642 : : known != walks->constEnd()) {
1643 : 396 : return answer(known->skipped, known->recordError);
1644 : : }
1645 : : }
1646 : : climbed << dir;
1647 [ + + + ]: 459 : if (const std::optional<SkippedWalk> found = gpgIdVerdictIn(dir)) {
1648 : 70 : return answer(found->skipped, found->recordError);
1649 : : }
1650 : 848 : const QString parent = QDir::cleanPath(QFileInfo(dir).absolutePath());
1651 [ + - ]: 424 : if (parent == dir) {
1652 : : break;
1653 : : }
1654 : 424 : dir = parent;
1655 : : }
1656 : 108 : return answer(std::nullopt, QString());
1657 : 287 : }
1658 : :
1659 : 320 : auto Pass::linkedGpgId(const QString &forFile, const QString &passStore,
1660 : : LinkedWalks *walks) -> std::optional<QString> {
1661 : 320 : const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
1662 : : // As in skippedGpgId(): a folder's answer depends only on it and the
1663 : : // folders above it, so a tree check climbs each folder once instead of
1664 : : // once per folder below it.
1665 : 320 : QStringList climbed;
1666 : 320 : const auto answer = [&climbed, walks](std::optional<QString> linked) {
1667 [ + + ]: 320 : if (walks != nullptr) {
1668 [ + + ]: 407 : for (const QString &folder : std::as_const(climbed)) {
1669 : 236 : walks->insert(folder, linked);
1670 : : }
1671 : : }
1672 : 320 : return linked;
1673 : 320 : };
1674 : : // The walk of nearestGpgId(), root included, stopping at the list it
1675 : : // finds.
1676 : 320 : QDir dir = lookup.start;
1677 [ + + - ]: 1186 : while (dir.exists()) {
1678 : 1186 : const QString here = QDir::cleanPath(dir.absolutePath());
1679 [ + + + ]: 1186 : if (!isAtOrUnder(here, lookup.storeDir, lookup.storePrefix)) {
1680 : : break;
1681 : : }
1682 [ + + ]: 1090 : if (walks != nullptr) {
1683 : : // By value: the inserts in answer() may rehash walks.
1684 [ + + ]: 324 : if (const auto known = walks->constFind(here);
1685 : : known != walks->constEnd()) {
1686 : 176 : return answer(std::optional<QString>(*known));
1687 : : }
1688 : : }
1689 : : climbed << here;
1690 : 1002 : const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
1691 [ + + + ]: 1002 : if (isOwnGpgId(candidate)) {
1692 : 174 : return answer(std::nullopt);
1693 : : }
1694 [ + + + + : 915 : if (candidate.isSymLink() || candidate.isJunction()) {
+ - ]
1695 : 98 : return answer(candidate.absoluteFilePath());
1696 : : }
1697 [ + + - ]: 866 : if (!dir.cdUp()) {
1698 : : break;
1699 : : }
1700 : 1002 : }
1701 : 192 : return answer(std::nullopt);
1702 : 640 : }
1703 : :
1704 : : namespace {
1705 : :
1706 : : /// What the Users dialog may preselect for a verified list, given what the
1707 : : /// generation record says about it.
1708 : 7 : auto judgedRecipients(GpgIdGeneration::Verdict verdict,
1709 : : const QByteArray &contents, const QString &gpgIdPath,
1710 : : const QString &why) -> Pass::RecipientsForEditing {
1711 : : using RecipientsForEditing = Pass::RecipientsForEditing;
1712 : 7 : RecipientsForEditing result;
1713 [ + + + - ]: 7 : switch (verdict) {
1714 : 1 : case GpgIdGeneration::Verdict::Accepted:
1715 : 1 : result.state = RecipientsForEditing::State::Verified;
1716 : 1 : result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1717 : 1 : break;
1718 : 1 : case GpgIdGeneration::Verdict::Rollback:
1719 : : // Authentic and this folder's, only older: the recovery goes through
1720 : : // this dialog, so it is preselected, with the reason in view.
1721 : 1 : result.state = RecipientsForEditing::State::VerifiedRollback;
1722 : 1 : result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1723 : 1 : result.warning = why;
1724 : 1 : break;
1725 : 5 : case GpgIdGeneration::Verdict::Unbound:
1726 : : case GpgIdGeneration::Verdict::Conflict:
1727 : : case GpgIdGeneration::Verdict::WrongFolder:
1728 : : case GpgIdGeneration::Verdict::WrongStore:
1729 : : case GpgIdGeneration::Verdict::Malformed:
1730 : : case GpgIdGeneration::Verdict::RecordUnavailable:
1731 : : // Signed, but not shown to be this folder's list, not a list to trust,
1732 : : // or nothing to judge it by: preselecting it would sign it in.
1733 : 5 : result.state = RecipientsForEditing::State::Rejected;
1734 : : result.warning =
1735 : 5 : Pass::tr("%1 Nothing is preselected: saving would sign whatever is "
1736 : : "in it. Select the recipients yourself.")
1737 : 10 : .arg(why);
1738 : 5 : break;
1739 : : }
1740 : 7 : return result;
1741 : : }
1742 : :
1743 : : } // namespace
1744 : :
1745 : 90 : auto Pass::recipientsForEditing(const QString &dir, const QString &passStore)
1746 : : -> RecipientsForEditing {
1747 : 90 : RecipientsForEditing result;
1748 [ + + ]: 90 : const QString folder = dir.isEmpty() ? QString() : dir;
1749 : 90 : const QString gpgIdPath = getGpgIdPath(folder, passStore);
1750 : : GpgIdSigner signer(m_settings.gpgExecutable,
1751 [ + + ]: 270 : GpgIdSigner::keysFromSetting(m_settings.passSigningKey));
1752 : : signer.setStoreRoot(passStore);
1753 [ + + ]: 90 : if (!signer.enabled()) {
1754 : : // A list that is there but cannot be read as one (too large, not a
1755 : : // regular file, unreadable) is not an empty list: preselecting nothing
1756 : : // without a word would let OK write a new list over it, and later
1757 : : // re-encryptions drop whoever it named.
1758 : : // Read once and parsed from those bytes: a second read could find
1759 : : // something else under the name. A link counts as there, dangling too.
1760 : 80 : const QFileInfo info(gpgIdPath);
1761 [ + + + + : 80 : if (!info.exists() && !info.isSymLink()) {
+ + ]
1762 : : result.state = RecipientsForEditing::State::Unsigned;
1763 : 18 : return result;
1764 : : }
1765 : : const std::optional<QByteArray> bytes = Util::readRegularFileInStore(
1766 : 62 : passStore, gpgIdPath, Util::kMaxGpgIdBytes);
1767 [ + + ]: 62 : if (!bytes) {
1768 : 2 : result.state = RecipientsForEditing::State::Rejected;
1769 : : result.warning =
1770 : 2 : tr("%1 cannot be read as a recipient list (a regular file of at "
1771 : : "most %2), so nothing is preselected. Check it before choosing "
1772 : : "recipients here: OK writes a new list over it.")
1773 : 2 : .arg(gpgIdPath,
1774 [ + + ]: 4 : QLocale().formattedDataSize(Util::kMaxGpgIdBytes));
1775 : 2 : return result;
1776 : : }
1777 : : result.state = RecipientsForEditing::State::Unsigned;
1778 : 60 : result.recipients = parseRecipients(*bytes, gpgIdPath);
1779 : 60 : const QString misread = passReadsDifferently(*bytes);
1780 [ + + ]: 60 : if (!misread.isEmpty()) {
1781 : : //: %1 is the list's path, %2 says what is wrong with it.
1782 : : result.warning =
1783 : 3 : tr("pass reads %1 differently from this dialog (%2), so it may "
1784 : : "encrypt to recipients not shown here. QtPass will not encrypt "
1785 : : "with it through pass: check the recipients, then OK writes the "
1786 : : "list anew.")
1787 : 6 : .arg(gpgIdPath, misread);
1788 : : }
1789 : 60 : return result;
1790 : 80 : }
1791 : 10 : QString recordError;
1792 [ + + ]: 10 : if (const std::optional<QString> skipped =
1793 : 10 : skippedGpgId(folder, passStore, &recordError)) {
1794 : : // The folder's own list was removed or replaced by a link (or the record
1795 : : // that would tell cannot be read): the list the walk found further up
1796 : : // was not signed for this folder, so preselecting it would sign it in
1797 : : // here with one click.
1798 : 1 : result.state = RecipientsForEditing::State::Rejected;
1799 : : result.warning =
1800 : : recordError.isEmpty()
1801 [ + - + - ]: 2 : ? tr("The recipient list %1 is missing or is not a regular file, "
1802 : : "so nothing is preselected: the list of a parent folder was "
1803 : : "not signed for this one. Select this folder's recipients "
1804 : : "yourself; OK writes and signs a fresh list.")
1805 : : .arg(*skipped)
1806 : 1 : : tr("%1 Nothing is preselected: whether %2 was removed cannot "
1807 : : "be told.")
1808 : : .arg(recordError, *skipped);
1809 : 1 : return result;
1810 : : }
1811 [ + + + ]: 9 : if (!QFileInfo::exists(gpgIdPath)) {
1812 : : // A folder without a list yet (new store, new profile): nothing to
1813 : : // verify and nothing to preselect.
1814 : 1 : result.state = RecipientsForEditing::State::Verified;
1815 : 1 : return result;
1816 : : }
1817 : 8 : QByteArray contents;
1818 [ + + + ]: 8 : if (!signer.verifyFile(gpgIdPath, &contents)) {
1819 : 1 : result.state = RecipientsForEditing::State::Rejected;
1820 : : result.warning =
1821 : 1 : tr("The recipient list %1 does not verify against the signing key, "
1822 : : "so nothing is preselected: saving would sign whatever is in it. "
1823 : : "Select the recipients yourself; OK writes and signs a fresh list.")
1824 : 2 : .arg(gpgIdPath);
1825 : 1 : return result;
1826 : : }
1827 : 7 : QString why;
1828 : : const GpgIdGeneration::Verdict verdict =
1829 : 7 : GpgIdGeneration::accept(gpgIdPath, contents, passStore, &why);
1830 : 7 : return judgedRecipients(verdict, contents, gpgIdPath, why);
1831 : 90 : }
1832 : :
1833 : 62 : auto Pass::getRecipientList(const QString &for_file, const QString &passStore)
1834 : : -> QStringList {
1835 : 62 : const QString gpgIdPath = getGpgIdPath(for_file, passStore);
1836 : : // The root .gpg-id comes back whatever it is; a link is not a list.
1837 [ + + + ]: 62 : if (Util::isLinkedFolder(gpgIdPath)) {
1838 : 1 : return {};
1839 : : }
1840 : : const std::optional<QByteArray> bytes =
1841 : 61 : Util::readRegularFileInStore(passStore, gpgIdPath, Util::kMaxGpgIdBytes);
1842 [ + + ]: 61 : if (!bytes) {
1843 : 34 : return {};
1844 : : }
1845 : 27 : return parseRecipients(*bytes, gpgIdPath);
1846 : : }
1847 : :
1848 : 361 : auto Pass::parseRecipients(const QByteArray &contents,
1849 : : const QString &sourceName) -> QStringList {
1850 : 361 : QStringList recipients;
1851 : : const QString text = QString::fromUtf8(contents);
1852 [ + + + + : 7316 : for (const QString &line : text.split(QLatin1Char('\n'))) {
+ ]
1853 : 13910 : QString recipient = line.split(QLatin1Char('#')).first().trimmed();
1854 [ + + ]: 6955 : if (recipient.isEmpty()) {
1855 : 463 : continue;
1856 : : }
1857 [ + + + ]: 6492 : if (!Util::isValidKeyId(recipient)) {
1858 : : // Never drop a recipient silently: the list is written back verbatim
1859 : : // by UsersDialog, so a skipped line disappears from .gpg-id.
1860 : 4 : qCWarning(lcQtPass) << "Skipping unusable recipient in" << sourceName
1861 : 2 : << ":" << recipient;
1862 : 2 : continue;
1863 : 2 : }
1864 : : recipients += recipient;
1865 : : }
1866 : 361 : return recipients;
1867 : : }
1868 : :
1869 : 107 : auto Pass::passReadsDifferently(const QByteArray &contents) -> QString {
1870 [ + + ]: 107 : if (contents.startsWith("\xEF\xBB\xBF")) {
1871 : : return tr("it starts with a byte-order mark");
1872 : : }
1873 [ + + ]: 106 : if (contents.contains('\0')) {
1874 : : return tr("it holds a NUL byte");
1875 : : }
1876 [ + + ]: 104 : if (contents.contains('\r')) {
1877 : : return tr("it has Windows line ends (a carriage return)");
1878 : : }
1879 : : const QString text = QString::fromUtf8(contents);
1880 [ + + ]: 103 : if (text.toUtf8() != contents) {
1881 : : return tr("it is not valid UTF-8");
1882 : : }
1883 : 102 : const QStringList lines = text.split(QLatin1Char('\n'));
1884 [ + + ]: 6432 : for (qsizetype i = 0; i < lines.size(); ++i) {
1885 : : const QString &line = lines.at(i);
1886 : 6340 : const QString recipient = line.left(line.indexOf(QLatin1Char('#')));
1887 [ + + + + ]: 132806 : for (const QChar c : recipient) {
1888 : : // read strips blanks and tabs; trimmed() strips every space.
1889 [ + + + + : 126473 : if (c.isSpace() && c != QLatin1Char(' ') && c != QLatin1Char('\t')) {
+ + ]
1890 : 7 : return tr("line %1 holds whitespace other than blanks and tabs")
1891 : 7 : .arg(i + 1);
1892 : : }
1893 : : }
1894 : : const QString trimmed = recipient.trimmed();
1895 [ + + + ]: 6333 : if (trimmed.startsWith(QLatin1Char('-'))) {
1896 : 2 : return tr("line %1 starts with a dash").arg(i + 1);
1897 : : }
1898 : : // The text after the last line feed: read hands it over but the loop
1899 : : // ends without using it.
1900 [ + + + + ]: 6331 : if (i == lines.size() - 1 && !trimmed.isEmpty()) {
1901 : : return tr("its last line has no line end");
1902 : : }
1903 : : }
1904 : 92 : return {};
1905 : : }
1906 : :
1907 : : /* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
1908 : : */
1909 : :
1910 : 7620 : auto Pass::boundedRandom(quint32 bound) -> quint32 {
1911 [ + + ]: 7620 : if (bound < 2) {
1912 : : return 0;
1913 : : }
1914 : :
1915 : : quint32 randval;
1916 : : // arc4random_uniform-style rejection against modulo bias: drop values
1917 : : // below 2^32 % bound, which (1 + ~bound) % bound computes in quint32.
1918 : 7616 : const quint32 rejectionThreshold = (1 + ~bound) % bound;
1919 : :
1920 : : do {
1921 : : randval = QRandomGenerator::system()->generate();
1922 [ - + ]: 7616 : } while (randval < rejectionThreshold);
1923 : :
1924 : 7616 : return randval % bound;
1925 : : }
1926 : :
1927 : 1209 : auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1928 : : -> QString {
1929 [ + + + + ]: 1209 : if (charset.isEmpty() || length == 0U) {
1930 : 2 : return {};
1931 : : }
1932 : 1207 : QString out;
1933 [ + + ]: 8827 : for (unsigned int i = 0; i < length; ++i) {
1934 : 7620 : out.append(charset.at(static_cast<int>(
1935 : 7620 : boundedRandom(static_cast<quint32>(charset.length())))));
1936 : : }
1937 : : return out;
1938 : : }
1939 : :
1940 : 2 : auto Pass::pullTimedOut(int timeoutMs) -> QString {
1941 : : // The count in a variable first: older lupdate versions lose a tr() with
1942 : : // template arguments among its arguments.
1943 : 2 : const int seconds = (timeoutMs + 999) / 1000;
1944 : : return tr("Git pull did not finish within %n second(s); editing the entry "
1945 : : "as it is here.",
1946 : 2 : nullptr, seconds);
1947 : : }
|