QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
nativegrep.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
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
23NativeGrep::NativeGrep(QObject *parent) : QObject(parent) {}
24
26 static constexpr int kThreadTimeoutMs = 5000;
27 cancel();
28 QElapsedTimer elapsed;
29 elapsed.start();
30 for (const Worker &w : std::as_const(m_workers)) {
31 if (w.thread && w.thread->isRunning()) {
32 const int remaining =
33 kThreadTimeoutMs - static_cast<int>(elapsed.elapsed());
34 if (remaining > 0)
35 w.thread->wait(remaining);
36 }
37 }
38}
39
43namespace {
55auto 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 ? Util::readRegularFile(filePath, kMaxCiphertext)
72 : Util::readRegularFileUnder(storeDir, filePath, kMaxCiphertext);
73 if (!ciphertext) {
74 return {};
75 }
76 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 QProcess gpg;
81 gpg.setProcessEnvironment(env);
82 const int rc = Executor::executeBlockingRaw(
83 gpg, gpgExe,
84 QStringList{"-d", "--quiet", "--yes", "--no-encrypt-to", "--batch",
85 "--use-agent"} +
87 *ciphertext, &decrypted, nullptr, cancel);
88 if (rc != 0) {
89 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 return Executor::decodeText(decrypted);
94}
95
105auto windowAround(QStringView line, QStringView t,
106 const QRegularExpressionMatch &m)
107 -> std::pair<qsizetype, qsizetype> {
108 const qsizetype at =
109 qMax<qsizetype>(0, m.capturedStart() - (t.data() - line.data()));
110 qsizetype start = qBound<qsizetype>(0, at - NativeGrep::kMaxPreviewLength / 4,
112 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 if (start > 0 && t[start].isLowSurrogate())
116 --start;
117 if (end < t.size() && t[end - 1].isHighSurrogate())
118 ++end;
119 return {start, end};
120}
121
132auto 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 if (password ? FileContent::isOtpPasswordLine(whole)
139 : FileContent::isOtpLine(whole)) {
140 return QStringLiteral("\n");
141 }
142 // Marked, so the window shows it only where the panel would
143 // (isPasswordMatch()).
144 const QString mark = password ? QStringLiteral("\n") : QString();
145 if (t.size() <= NativeGrep::kMaxPreviewLength) {
146 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 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 const qsizetype colon = password ? -1 : t.indexOf(u':');
155 QString preview;
156 qsizetype from = start;
157 if (colon > 0 && start > 0) {
158 if (colon >= NativeGrep::kMaxPreviewLength / 2) {
159 return t.first(NativeGrep::kMaxPreviewLength / 2).toString() +
160 QChar(0x2026) + QStringLiteral(": ") + QChar(0x2026);
161 }
162 from = std::max(start, colon + 1);
163 preview = t.first(colon + 1).toString() + u' ';
164 if (from > colon + 1)
165 preview += QChar(0x2026);
166 } else if (start > 0) {
167 preview = QChar(0x2026);
168 }
169 preview += t.sliced(from, end - from).toString();
170 if (end < t.size())
171 preview.append(QChar(0x2026));
172 return mark + preview;
173}
174} // namespace
175
176auto 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 decryptForSearch(env, gpgExe, filePath, cancel, storeDir);
183 if (plaintext.isEmpty())
184 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 QStringList matches;
188 bool first = true;
189 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 const QStringView t = line.trimmed();
195 if (t.isEmpty())
196 continue;
197 const QRegularExpressionMatch m = rx.matchView(line);
198 if (!m.hasMatch())
199 continue;
200 if (matches.size() == kMaxMatchesPerEntry) {
201 matches << QString(); // isMoreMarker(): not a match, not counted
202 break;
203 }
204 matches << previewOfMatch(line, t, m, password);
205 }
206 return matches;
207}
208
212auto 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 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 Util::regularFilesUnder(storeDir, QStringList() << "*.gpg");
223 for (const QString &filePath : files) {
224 if (QThread::currentThread()->isInterruptionRequested() ||
225 (cancel != nullptr && cancel->load()))
226 return {};
227 if (total == kMaxMatches) {
228 // The budget is spent and entries remain: the search stopped here.
229 results.append({QString(), {}});
230 break;
231 }
232 QStringList matches =
233 matchFile(env, gpgExe, filePath, rx, cancel, storeDir);
234 if (matches.isEmpty())
235 continue;
236 const bool more = isMoreMarker(matches.constLast());
237 if (more)
238 matches.removeLast();
239 // The store-wide budget: what still fits, and a marker when that cut
240 // the entry short.
241 const int room = kMaxMatches - total;
242 if (matches.size() > room) {
243 matches = matches.mid(0, room);
244 matches << QString();
245 } else if (more) {
246 matches << QString();
247 }
248 total += static_cast<int>(matches.size()) -
249 (isMoreMarker(matches.constLast()) ? 1 : 0);
250 QString entry = QDir(storeDir).relativeFilePath(filePath);
251 if (entry.endsWith(QLatin1String(".gpg")))
252 entry.chop(4);
253 results.append({entry, matches});
254 }
255 return results;
256}
257
266void NativeGrep::search(const QString &pattern, bool caseInsensitive,
267 const QString &gpgExe, const QString &storeDir,
268 const QProcessEnvironment &env) {
269 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 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 if (pattern.trimmed().isEmpty()) {
283 QMetaObject::invokeMethod(
284 this,
285 [this, seq]() {
286 if (m_seq == seq)
287 emit finished({});
288 },
289 Qt::QueuedConnection);
290 return;
291 }
292
293 const QRegularExpression rx(
294 pattern, caseInsensitive ? QRegularExpression::CaseInsensitiveOption
295 : QRegularExpression::PatternOptions{});
296 if (!rx.isValid()) {
297 QMetaObject::invokeMethod(
298 this,
299 [this, seq]() {
300 if (m_seq == seq)
301 emit finished({});
302 },
303 Qt::QueuedConnection);
304 return;
305 }
306 auto emitResults = [self = QPointer<NativeGrep>(this),
307 seq](QList<QPair<QString, QStringList>> results) {
308 if (!self)
309 return;
310 QMetaObject::invokeMethod(
311 self,
312 [self, seq, results = std::move(results)]() {
313 if (self && self->m_seq == seq)
314 emit self->finished(results);
315 },
316 Qt::QueuedConnection);
317 };
318
319 auto cancelFlag = std::make_shared<std::atomic_bool>(false);
320 QThread *thread = QThread::create([gpgExe, storeDir, env, rx, cancelFlag,
321 emitResults = std::move(emitResults)]() {
322 std::move(emitResults)(
323 scanStore(env, gpgExe, storeDir, rx, cancelFlag.get()));
324 });
325
326 m_workers.append({thread, std::move(cancelFlag)});
327 connect(thread, &QThread::finished, thread, &QObject::deleteLater);
328 connect(thread, &QThread::finished, this, [this, thread]() {
329 m_workers.removeIf(
330 [thread](const Worker &w) { return w.thread == thread; });
331 });
332 thread->start();
333}
334
336 for (const Worker &w : std::as_const(m_workers)) {
337 w.cancel->store(true);
338 if (w.thread && w.thread->isRunning())
339 w.thread->requestInterruption();
340 }
341}
static auto executeBlockingRaw(QProcess &process, const QString &app, const QStringList &args, const QByteArray &input, QByteArray *process_out, QString *process_err=nullptr, const std::atomic_bool *cancel=nullptr, int timeoutMs=-1) -> int
executeBlocking() on bytes, for an entry's plaintext: input is written to stdin and stdout returned e...
Definition executor.cpp:690
static auto decodeText(const QByteArray &bytes) -> QString
Decode process output as executeBlocking() does: UTF-8 first, the system encoding when it is not UTF-...
Definition executor.cpp:490
static auto isOtpLine(const QString &line) -> bool
Whether line carries a TOTP shared secret: a bare otpauth:// line, an OTP:/TOTP: field,...
static auto isOtpPasswordLine(const QString &line) -> bool
Whether an entry's first line holds a TOTP shared secret rather than a password.
void finished(const QList< QPair< QString, QStringList > > &results)
The newest search is over.
void search(const QString &pattern, bool caseInsensitive, const QString &gpgExe, const QString &storeDir, const QProcessEnvironment &env)
Start a search; finished() follows asynchronously, also for an empty or invalid pattern (with no resu...
~NativeGrep() override
Interrupt running searches and wait up to five seconds for them.
static constexpr int kMaxMatches
Most matching lines a search collects over the whole store.
Definition nativegrep.h:55
static auto isMoreMarker(const QString &line) -> bool
Whether a line in a result is the marker for "more matches inthis entry" rather than a match.
Definition nativegrep.h:80
static constexpr qsizetype kMaxPreviewLength
Longest preview of a matching line, in UTF-16 code units.
Definition nativegrep.h:68
static constexpr int kMaxMatchesPerEntry
Most matching lines taken from one entry.
Definition nativegrep.h:48
static auto scanStore(const QProcessEnvironment &env, const QString &gpgExe, const QString &storeDir, const QRegularExpression &rx, const std::atomic_bool *cancel=nullptr) -> QList< QPair< QString, QStringList > >
Walk storeDir, decrypt every .gpg file and collect the matches.
int m_seq
Number of the newest search. A worker reports through finished() only when its own number still equal...
Definition nativegrep.h:224
QList< Worker > m_workers
Searches still running, superseded ones included.
Definition nativegrep.h:226
static auto matchFile(const QProcessEnvironment &env, const QString &gpgExe, const QString &filePath, const QRegularExpression &rx, const std::atomic_bool *cancel=nullptr, const QString &storeDir=QString()) -> QStringList
Decrypt one .gpg file and return its trimmed lines matching rx.
void cancel()
Ask running searches to stop without waiting for them: the walk ends at the next file and a gpg that ...
NativeGrep(QObject *parent=nullptr)
Create a searcher.
static auto maxOutputArgs() -> QStringList
The gpg options that enforce kMaxPlaintextBytes.
Definition pass.cpp:1184
static constexpr qint64 kMaxPlaintextBytes
Most bytes of plaintext a gpg decryption may produce.
Definition pass.h:511
Static helpers that have no better home: setting up the process and the Git environment the way pass ...
Definition util.h:40
static auto regularFilesUnder(const QString &dir, const QStringList &nameFilters, QStringList *skipped=nullptr, bool hiddenFiles=false, QStringList *unlisted=nullptr) -> QStringList
Regular files under dir whose name matches one of nameFilters, found by walking only real directories...
Definition util.cpp:1149
static auto readRegularFile(const QString &path, qint64 maxBytes) -> std::optional< QByteArray >
Read path whole, as the regular file it is (openRegularFile()), when it holds at most maxBytes.
Definition util.cpp:1555
Executor, the FIFO queue every gpg, git and pass child process of QtPass goes through,...
Parser for a decrypted password entry: password line, key: value fields, remaining text and the OTP c...
NativeGrep, the content search that decrypts every entry on a worker thread instead of running pass g...
Pass, the abstract password-store backend that RealPass and ImitatePass implement,...
QThread * thread
The thread the search runs on.
Definition nativegrep.h:216
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...