14#include <QElapsedTimer>
17#include <QRegularExpression>
18#include <QStringTokenizer>
26 static constexpr int kThreadTimeoutMs = 5000;
28 QElapsedTimer elapsed;
31 if (w.thread && w.thread->isRunning()) {
33 kThreadTimeoutMs -
static_cast<int>(elapsed.elapsed());
35 w.thread->wait(remaining);
55auto decryptForSearch(
const QProcessEnvironment &env,
const QString &gpgExe,
56 const QString &filePath,
const std::atomic_bool *cancel,
57 const QString &storeDir) -> QString {
66 constexpr qint64 kCiphertextMargin = 1024LL * 1024;
67 constexpr qint64 kMaxCiphertext =
69 const std::optional<QByteArray> ciphertext =
72 :
Util::readRegularFileUnder(storeDir, filePath, kMaxCiphertext);
81 gpg.setProcessEnvironment(env);
84 QStringList{
"-d",
"--quiet",
"--yes",
"--no-encrypt-to",
"--batch",
87 *ciphertext, &decrypted,
nullptr, cancel);
105auto windowAround(QStringView line, QStringView t,
106 const QRegularExpressionMatch &m)
107 -> std::pair<qsizetype, qsizetype> {
109 qMax<qsizetype>(0, m.capturedStart() - (t.data() - line.data()));
115 if (start > 0 && t[start].isLowSurrogate())
117 if (end < t.size() && t[end - 1].isHighSurrogate())
132auto previewOfMatch(QStringView line, QStringView t,
133 const QRegularExpressionMatch &m,
bool password)
137 const QString whole = t.toString();
140 return QStringLiteral(
"\n");
144 const QString mark = password ? QStringLiteral(
"\n") : QString();
150 const auto [start, end] = windowAround(line, t, m);
154 const qsizetype colon = password ? -1 : t.indexOf(u
':');
156 qsizetype from = start;
157 if (colon > 0 && start > 0) {
160 QChar(0x2026) + QStringLiteral(
": ") + QChar(0x2026);
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);
169 preview += t.sliced(from, end - from).toString();
171 preview.append(QChar(0x2026));
172 return mark + preview;
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())
189 for (QStringView line : QStringView(plaintext).tokenize(u
'\n')) {
191 const bool password = std::exchange(first,
false);
192 if (line.endsWith(u
'\r'))
194 const QStringView t = line.trimmed();
197 const QRegularExpressionMatch m = rx.matchView(line);
201 matches << QString();
204 matches << previewOfMatch(line, t, m, password);
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;
221 const QStringList files =
223 for (
const QString &filePath : files) {
224 if (QThread::currentThread()->isInterruptionRequested() ||
229 results.append({QString(), {}});
232 QStringList matches =
234 if (matches.isEmpty())
238 matches.removeLast();
242 if (matches.size() > room) {
243 matches = matches.mid(0, room);
244 matches << QString();
246 matches << QString();
248 total +=
static_cast<int>(matches.size()) -
250 QString entry = QDir(storeDir).relativeFilePath(filePath);
251 if (entry.endsWith(QLatin1String(
".gpg")))
253 results.append({entry, matches});
267 const QString &gpgExe,
const QString &storeDir,
268 const QProcessEnvironment &env) {
273 const int seq = ++
m_seq;
282 if (pattern.trimmed().isEmpty()) {
283 QMetaObject::invokeMethod(
289 Qt::QueuedConnection);
293 const QRegularExpression rx(
294 pattern, caseInsensitive ? QRegularExpression::CaseInsensitiveOption
295 : QRegularExpression::PatternOptions{});
297 QMetaObject::invokeMethod(
303 Qt::QueuedConnection);
306 auto emitResults = [self = QPointer<NativeGrep>(
this),
307 seq](QList<QPair<QString, QStringList>> results) {
310 QMetaObject::invokeMethod(
312 [self, seq, results = std::move(results)]() {
313 if (self && self->m_seq == seq)
314 emit self->finished(results);
316 Qt::QueuedConnection);
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()));
326 m_workers.append({thread, std::move(cancelFlag)});
327 connect(thread, &QThread::finished, thread, &QObject::deleteLater);
328 connect(thread, &QThread::finished,
this, [
this, thread]() {
330 [thread](
const Worker &w) {
return w.
thread == thread; });
337 w.cancel->store(
true);
338 if (w.thread && w.thread->isRunning())
339 w.thread->requestInterruption();
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...
static auto decodeText(const QByteArray &bytes) -> QString
Decode process output as executeBlocking() does: UTF-8 first, the system encoding when it is not UTF-...
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.
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.
static constexpr qsizetype kMaxPreviewLength
Longest preview of a matching line, in UTF-16 code units.
static constexpr int kMaxMatchesPerEntry
Most matching lines taken from one entry.
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...
QList< Worker > m_workers
Searches still running, superseded ones included.
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.
static constexpr qint64 kMaxPlaintextBytes
Most bytes of plaintext a gpg decryption may produce.
Static helpers that have no better home: setting up the process and the Git environment the way pass ...
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...
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.
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.
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...