Branch data Line data Source code
1 : : // SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
2 : : // SPDX-License-Identifier: GPL-3.0-or-later
3 : : /**
4 : : * @file
5 : : * @brief Implements NativeGrep: the store walk, the per-file gpg runs and the
6 : : * hand-over of results from the worker thread.
7 : : */
8 : : #include "nativegrep.h"
9 : : #include "executor.h"
10 : : #include "filecontent.h"
11 : : #include "pass.h"
12 : : #include "util.h"
13 : : #include <QDir>
14 : : #include <QElapsedTimer>
15 : : #include <QPointer>
16 : : #include <QProcess>
17 : : #include <QRegularExpression>
18 : : #include <QStringTokenizer>
19 : : #include <QThread>
20 : : #include <algorithm>
21 : : #include <utility>
22 : :
23 : 355 : NativeGrep::NativeGrep(QObject *parent) : QObject(parent) {}
24 : :
25 : 355 : NativeGrep::~NativeGrep() {
26 : : static constexpr int kThreadTimeoutMs = 5000;
27 : 355 : cancel();
28 : 355 : QElapsedTimer elapsed;
29 : 355 : elapsed.start();
30 [ + + ]: 356 : for (const Worker &w : std::as_const(m_workers)) {
31 [ + - - + ]: 1 : if (w.thread && w.thread->isRunning()) {
32 : : const int remaining =
33 : 0 : kThreadTimeoutMs - static_cast<int>(elapsed.elapsed());
34 [ # # ]: 0 : if (remaining > 0)
35 : 0 : w.thread->wait(remaining);
36 : : }
37 : : }
38 : 355 : }
39 : :
40 : : /**
41 : : * @brief Decrypt one .gpg file and return lines matching rx.
42 : : */
43 : : namespace {
44 : : /**
45 : : * @brief Decrypt the entry @p filePath for a search: read without following
46 : : * a link, capped, and handed to gpg on stdin.
47 : : * @param env Environment for gpg.
48 : : * @param gpgExe The gpg executable.
49 : : * @param filePath The entry.
50 : : * @param cancel Stops gpg when set; may be null.
51 : : * @param storeDir The store, whose folders are opened without following a
52 : : * link; empty to read @p filePath as it is named.
53 : : * @return The plaintext, or empty when it could not be read or decrypted.
54 : : */
55 : 436 : auto decryptForSearch(const QProcessEnvironment &env, const QString &gpgExe,
56 : : const QString &filePath, const std::atomic_bool *cancel,
57 : : const QString &storeDir) -> QString {
58 : : // Read here, without following a link, and handed to gpg on stdin: the
59 : : // name was listed as a regular file when the search began, and a pull
60 : : // since may have put a link there (or on a folder on the way). gpg given
61 : : // the name would follow it and decrypt a file outside the store into the
62 : : // results. With the store given, every folder on the way down is opened
63 : : // without following a link, so none can be swapped between a check and
64 : : // the read. The cap is on what decrypts; the ciphertext of an entry just
65 : : // under it is a little larger.
66 : : constexpr qint64 kCiphertextMargin = 1024LL * 1024;
67 : : constexpr qint64 kMaxCiphertext =
68 : : Pass::kMaxPlaintextBytes + kCiphertextMargin;
69 : : const std::optional<QByteArray> ciphertext =
70 : : storeDir.isEmpty()
71 [ + + ]: 436 : ? Util::readRegularFile(filePath, kMaxCiphertext)
72 : 436 : : Util::readRegularFileUnder(storeDir, filePath, kMaxCiphertext);
73 [ + + ]: 436 : if (!ciphertext) {
74 : 4 : return {};
75 : : }
76 : 432 : QByteArray decrypted;
77 : : // The QProcess overload is the one that takes the cancel flag; it polls
78 : : // the flag while waiting and terminates (then kills) gpg from this thread,
79 : : // the one that owns the process.
80 : 432 : QProcess gpg;
81 : 432 : gpg.setProcessEnvironment(env);
82 : 432 : const int rc = Executor::executeBlockingRaw(
83 : : gpg, gpgExe,
84 : 432 : QStringList{"-d", "--quiet", "--yes", "--no-encrypt-to", "--batch",
85 : 6048 : "--use-agent"} +
86 : 864 : Pass::maxOutputArgs(),
87 : : *ciphertext, &decrypted, nullptr, cancel);
88 [ + + ]: 432 : if (rc != 0) {
89 : 45 : return {};
90 : : }
91 : : // Decoded as executeBlocking() decoded it before: UTF-8, else the system
92 : : // encoding, so an entry in a Windows code page is still searched.
93 : 387 : return Executor::decodeText(decrypted);
94 : 432 : }
95 : :
96 : : /**
97 : : * @brief The part of a long line a result shows: up to
98 : : * NativeGrep::kMaxPreviewLength characters around the match, a little
99 : : * context before it, never half a surrogate pair at either edge.
100 : : * @param line The line, without its line ending.
101 : : * @param t @p line trimmed (a view into it).
102 : : * @param m The match in @p line.
103 : : * @return Start and end of the window in @p t.
104 : : */
105 : 6 : auto windowAround(QStringView line, QStringView t,
106 : : const QRegularExpressionMatch &m)
107 : : -> std::pair<qsizetype, qsizetype> {
108 : : const qsizetype at =
109 : 6 : qMax<qsizetype>(0, m.capturedStart() - (t.data() - line.data()));
110 : 6 : qsizetype start = qBound<qsizetype>(0, at - NativeGrep::kMaxPreviewLength / 4,
111 [ + + ]: 6 : t.size() - NativeGrep::kMaxPreviewLength);
112 : 6 : qsizetype end = start + NativeGrep::kMaxPreviewLength;
113 : : // Never half a surrogate pair (an emoji, CJK Extension B) at either
114 : : // edge: the window takes the whole character.
115 [ + + + + ]: 6 : if (start > 0 && t[start].isLowSurrogate())
116 : 1 : --start;
117 [ + + + + ]: 6 : if (end < t.size() && t[end - 1].isHighSurrogate())
118 : 1 : ++end;
119 : 6 : return {start, end};
120 : : }
121 : :
122 : : /**
123 : : * @brief What the results show for a matching @p line: an OTP marker, the
124 : : * line, or a window of it around the match that keeps a field's name.
125 : : * @param line The line, without its line ending.
126 : : * @param t @p line trimmed (a view into it).
127 : : * @param m The match in @p line.
128 : : * @param password Whether it is the entry's first line, the password.
129 : : * @return The result line, marked as NativeGrep::isOtpMarker() and
130 : : * NativeGrep::isPasswordMatch() read it.
131 : : */
132 : 30159 : auto previewOfMatch(QStringView line, QStringView t,
133 : : const QRegularExpressionMatch &m, bool password)
134 : : -> QString {
135 : : // A shared secret is never shown, as in the display panel: only that
136 : : // there was a match (isOtpMarker()).
137 : : const QString whole = t.toString();
138 [ + + + + : 59940 : if (password ? FileContent::isOtpPasswordLine(whole)
+ ]
139 : 29781 : : FileContent::isOtpLine(whole)) {
140 : 3 : return QStringLiteral("\n");
141 : : }
142 : : // Marked, so the window shows it only where the panel would
143 : : // (isPasswordMatch()).
144 [ + + ]: 30156 : const QString mark = password ? QStringLiteral("\n") : QString();
145 [ + + ]: 30156 : if (t.size() <= NativeGrep::kMaxPreviewLength) {
146 : 30150 : return mark + whole;
147 : : }
148 : : // A window of the line that holds the match, a little context before
149 : : // it; "…" marks what was left out on either side.
150 : 6 : const auto [start, end] = windowAround(line, t, m);
151 : : // A field's name decides whether its value is hidden, so a window that
152 : : // cuts into a `name: value` line keeps the whole name in front. A name
153 : : // too long for that is shown cut, and then none of the value is.
154 [ + - ]: 6 : const qsizetype colon = password ? -1 : t.indexOf(u':');
155 : 6 : QString preview;
156 : 6 : qsizetype from = start;
157 [ + + + - ]: 6 : if (colon > 0 && start > 0) {
158 [ + + ]: 3 : if (colon >= NativeGrep::kMaxPreviewLength / 2) {
159 : 1 : return t.first(NativeGrep::kMaxPreviewLength / 2).toString() +
160 : 3 : QChar(0x2026) + QStringLiteral(": ") + QChar(0x2026);
161 : : }
162 : 2 : from = std::max(start, colon + 1);
163 : 4 : preview = t.first(colon + 1).toString() + u' ';
164 [ + + ]: 2 : if (from > colon + 1)
165 : 1 : preview += QChar(0x2026);
166 [ + + ]: 3 : } else if (start > 0) {
167 : 2 : preview = QChar(0x2026);
168 : : }
169 : 5 : preview += t.sliced(from, end - from).toString();
170 [ + + ]: 5 : if (end < t.size())
171 : 4 : preview.append(QChar(0x2026));
172 : 5 : return mark + preview;
173 : : }
174 : : } // namespace
175 : :
176 : 436 : auto NativeGrep::matchFile(const QProcessEnvironment &env,
177 : : const QString &gpgExe, const QString &filePath,
178 : : const QRegularExpression &rx,
179 : : const std::atomic_bool *cancel,
180 : : const QString &storeDir) -> QStringList {
181 : : const QString plaintext =
182 : 436 : decryptForSearch(env, gpgExe, filePath, cancel, storeDir);
183 [ + + ]: 436 : if (plaintext.isEmpty())
184 : 49 : return {};
185 : : // Line by line over the text, never a list of every line (a compressed
186 : : // entry can expand into tens of millions), and a bounded number taken.
187 : 387 : QStringList matches;
188 : : bool first = true;
189 [ + + + + ]: 60927 : for (QStringView line : QStringView(plaintext).tokenize(u'\n')) {
190 : : // The password is the first line, empty or not.
191 : : const bool password = std::exchange(first, false);
192 : : if (line.endsWith(u'\r'))
193 : : line.chop(1);
194 : 60641 : const QStringView t = line.trimmed();
195 [ + + ]: 60641 : if (t.isEmpty())
196 : 30381 : continue;
197 : 30269 : const QRegularExpressionMatch m = rx.matchView(line);
198 [ + + + ]: 30269 : if (!m.hasMatch())
199 : : continue;
200 [ + + ]: 30260 : if (matches.size() == kMaxMatchesPerEntry) {
201 : 101 : matches << QString(); // isMoreMarker(): not a match, not counted
202 : : break;
203 : : }
204 : 30159 : matches << previewOfMatch(line, t, m, password);
205 : 30269 : }
206 : : return matches;
207 : : }
208 : :
209 : : /**
210 : : * @brief Walk the store, decrypt every .gpg file, collect matches.
211 : : */
212 : 20 : auto NativeGrep::scanStore(const QProcessEnvironment &env,
213 : : const QString &gpgExe, const QString &storeDir,
214 : : const QRegularExpression &rx,
215 : : const std::atomic_bool *cancel)
216 : : -> QList<QPair<QString, QStringList>> {
217 : 20 : QList<QPair<QString, QStringList>> results;
218 : : int total = 0; // matching lines, the markers not counted
219 : : // Regular files only: a link or junction is not an entry, and searching
220 : : // through one would decrypt files outside the store.
221 : : const QStringList files =
222 : 60 : Util::regularFilesUnder(storeDir, QStringList() << "*.gpg");
223 [ + + ]: 446 : for (const QString &filePath : files) {
224 [ + + + + : 435 : if (QThread::currentThread()->isInterruptionRequested() ||
+ + ]
225 [ - + ]: 81 : (cancel != nullptr && cancel->load()))
226 : 7 : return {};
227 [ + + ]: 428 : if (total == kMaxMatches) {
228 : : // The budget is spent and entries remain: the search stopped here.
229 : 4 : results.append({QString(), {}});
230 : 2 : break;
231 : : }
232 : : QStringList matches =
233 : 426 : matchFile(env, gpgExe, filePath, rx, cancel, storeDir);
234 [ + + ]: 426 : if (matches.isEmpty())
235 : : continue;
236 : : const bool more = isMoreMarker(matches.constLast());
237 [ + + ]: 380 : if (more)
238 : 100 : matches.removeLast();
239 : : // The store-wide budget: what still fits, and a marker when that cut
240 : : // the entry short.
241 : 380 : const int room = kMaxMatches - total;
242 [ + + ]: 380 : if (matches.size() > room) {
243 : 1 : matches = matches.mid(0, room);
244 : 2 : matches << QString();
245 [ + + ]: 379 : } else if (more) {
246 : 200 : matches << QString();
247 : : }
248 : 380 : total += static_cast<int>(matches.size()) -
249 [ + + ]: 380 : (isMoreMarker(matches.constLast()) ? 1 : 0);
250 : 380 : QString entry = QDir(storeDir).relativeFilePath(filePath);
251 [ + + - ]: 380 : if (entry.endsWith(QLatin1String(".gpg")))
252 : 380 : entry.chop(4);
253 : 380 : results.append({entry, matches});
254 : : }
255 : : return results;
256 : : }
257 : :
258 : : /**
259 : : * @brief Start a search on a worker thread.
260 : : *
261 : : * Results are emitted on the owner's thread via QMetaObject::invokeMethod. A
262 : : * sequence counter discards results from superseded searches; the previous
263 : : * search is asked to stop but not waited for, since blocking the UI thread
264 : : * while gpg decrypts would freeze the interface.
265 : : */
266 : 16 : void NativeGrep::search(const QString &pattern, bool caseInsensitive,
267 : : const QString &gpgExe, const QString &storeDir,
268 : : const QProcessEnvironment &env) {
269 : 16 : cancel();
270 : :
271 : : // Advance the sequence before any early return so in-flight workers from the
272 : : // previous query fail the seq check and cannot publish stale results.
273 : 16 : const int seq = ++m_seq;
274 : :
275 : : // Use trimmed() rather than isEmpty(): a whitespace-only string is a valid
276 : : // regex that matches every non-empty line, which is almost never intentional
277 : : // and would decrypt the entire store.
278 : : //
279 : : // Both early returns post finished() via Qt::QueuedConnection so that the
280 : : // signal is always delivered asynchronously after search() returns, matching
281 : : // the contract of the threaded path.
282 [ - + ]: 16 : if (pattern.trimmed().isEmpty()) {
283 : 0 : QMetaObject::invokeMethod(
284 : : this,
285 : 0 : [this, seq]() {
286 [ # # ]: 0 : if (m_seq == seq)
287 : 0 : emit finished({});
288 : 0 : },
289 : : Qt::QueuedConnection);
290 : 1 : return;
291 : : }
292 : :
293 : : const QRegularExpression rx(
294 : : pattern, caseInsensitive ? QRegularExpression::CaseInsensitiveOption
295 [ + + ]: 16 : : QRegularExpression::PatternOptions{});
296 [ + + + ]: 16 : if (!rx.isValid()) {
297 : 1 : QMetaObject::invokeMethod(
298 : : this,
299 : 1 : [this, seq]() {
300 [ + - ]: 1 : if (m_seq == seq)
301 : 2 : emit finished({});
302 : 1 : },
303 : : Qt::QueuedConnection);
304 : : return;
305 : : }
306 : 15 : auto emitResults = [self = QPointer<NativeGrep>(this),
307 : 15 : seq](QList<QPair<QString, QStringList>> results) {
308 [ + - ]: 15 : if (!self)
309 : : return;
310 : 15 : QMetaObject::invokeMethod(
311 : : self,
312 : 45 : [self, seq, results = std::move(results)]() {
313 [ + - + - ]: 30 : if (self && self->m_seq == seq)
314 : 15 : emit self->finished(results);
315 : 15 : },
316 : : Qt::QueuedConnection);
317 : 15 : };
318 : :
319 : 15 : auto cancelFlag = std::make_shared<std::atomic_bool>(false);
320 [ + + - - ]: 30 : QThread *thread = QThread::create([gpgExe, storeDir, env, rx, cancelFlag,
321 : : emitResults = std::move(emitResults)]() {
322 : 15 : std::move(emitResults)(
323 : 15 : scanStore(env, gpgExe, storeDir, rx, cancelFlag.get()));
324 : 15 : });
325 : :
326 : 30 : m_workers.append({thread, std::move(cancelFlag)});
327 : 15 : connect(thread, &QThread::finished, thread, &QObject::deleteLater);
328 [ + - - ]: 15 : connect(thread, &QThread::finished, this, [this, thread]() {
329 : 14 : m_workers.removeIf(
330 [ - + - - ]: 14 : [thread](const Worker &w) { return w.thread == thread; });
331 : : });
332 : 15 : thread->start();
333 : 31 : }
334 : :
335 : 782 : void NativeGrep::cancel() {
336 [ + + ]: 791 : for (const Worker &w : std::as_const(m_workers)) {
337 : : w.cancel->store(true);
338 [ + - + + ]: 9 : if (w.thread && w.thread->isRunning())
339 : 8 : w.thread->requestInterruption();
340 : : }
341 : 782 : }
|