• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IJHack / QtPass / 46554154962

01 Dec 2026 01:32AM UTC coverage: 94.549% (+0.003%) from 94.546%
46554154962

push

github

web-flow
Split NativeGrep::matchFile and the RNP locateKey (#2426)

Part of #2157. Behaviour-preserving extractions:

- NativeGrep::matchFile (CCN 25 to 7): decryptForSearch(), windowAround()
  and previewOfMatch() in the anonymous namespace.
- locateKey in the RNP backend (CCN 24 to 14): locateExactKey() for the
  exact-key branch, primariesNamedBy() for the key ID, address and user ID
  lookups.

Signed-off-by: Anne Jan Brouwer <brouwer@annejan.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

44 of 44 new or added lines in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

11395 of 12052 relevant lines covered (94.55%)

24022.43 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.79
/src/nativegrep.cpp
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
NativeGrep::NativeGrep(QObject *parent) : QObject(parent) {}
307 ✔
24

25
NativeGrep::~NativeGrep() {
307 ✔
26
  static constexpr int kThreadTimeoutMs = 5000;
27
  cancel();
307 ✔
28
  QElapsedTimer elapsed;
307 ✔
29
  elapsed.start();
307 ✔
30
  for (const Worker &w : std::as_const(m_workers)) {
307 ✔
UNCOV
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
}
307 ✔
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
auto decryptForSearch(const QProcessEnvironment &env, const QString &gpgExe,
436 ✔
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)
436 ✔
72
          : Util::readRegularFileUnder(storeDir, filePath, kMaxCiphertext);
436 ✔
73
  if (!ciphertext) {
436 ✔
74
    return {};
4 ✔
75
  }
76
  QByteArray decrypted;
432 ✔
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;
432 ✔
81
  gpg.setProcessEnvironment(env);
432 ✔
82
  const int rc = Executor::executeBlockingRaw(
432 ✔
83
      gpg, gpgExe,
84
      QStringList{"-d", "--quiet", "--yes", "--no-encrypt-to", "--batch",
432 ✔
85
                  "--use-agent"} +
6,048 ✔
86
          Pass::maxOutputArgs(),
864 ✔
87
      *ciphertext, &decrypted, nullptr, cancel);
88
  if (rc != 0) {
432 ✔
89
    return {};
45 ✔
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);
387 ✔
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
auto windowAround(QStringView line, QStringView t,
6 ✔
106
                  const QRegularExpressionMatch &m)
107
    -> std::pair<qsizetype, qsizetype> {
108
  const qsizetype at =
109
      qMax<qsizetype>(0, m.capturedStart() - (t.data() - line.data()));
6 ✔
110
  qsizetype start = qBound<qsizetype>(0, at - NativeGrep::kMaxPreviewLength / 4,
6 ✔
111
                                      t.size() - NativeGrep::kMaxPreviewLength);
6 ✔
112
  qsizetype end = start + NativeGrep::kMaxPreviewLength;
6 ✔
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())
6 ✔
116
    --start;
1 ✔
117
  if (end < t.size() && t[end - 1].isHighSurrogate())
6 ✔
118
    ++end;
1 ✔
119
  return {start, end};
6 ✔
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
auto previewOfMatch(QStringView line, QStringView t,
30,159 ✔
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)
59,940 ✔
139
               : FileContent::isOtpLine(whole)) {
29,781 ✔
140
    return QStringLiteral("\n");
3 ✔
141
  }
142
  // Marked, so the window shows it only where the panel would
143
  // (isPasswordMatch()).
144
  const QString mark = password ? QStringLiteral("\n") : QString();
30,156 ✔
145
  if (t.size() <= NativeGrep::kMaxPreviewLength) {
30,156 ✔
146
    return mark + whole;
30,150 ✔
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);
6 ✔
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':');
6 ✔
155
  QString preview;
6 ✔
156
  qsizetype from = start;
6 ✔
157
  if (colon > 0 && start > 0) {
6 ✔
158
    if (colon >= NativeGrep::kMaxPreviewLength / 2) {
3 ✔
159
      return t.first(NativeGrep::kMaxPreviewLength / 2).toString() +
1 ✔
160
             QChar(0x2026) + QStringLiteral(": ") + QChar(0x2026);
3 ✔
161
    }
162
    from = std::max(start, colon + 1);
2 ✔
163
    preview = t.first(colon + 1).toString() + u' ';
4 ✔
164
    if (from > colon + 1)
2 ✔
165
      preview += QChar(0x2026);
1 ✔
166
  } else if (start > 0) {
3 ✔
167
    preview = QChar(0x2026);
2 ✔
168
  }
169
  preview += t.sliced(from, end - from).toString();
5 ✔
170
  if (end < t.size())
5 ✔
171
    preview.append(QChar(0x2026));
4 ✔
172
  return mark + preview;
5 ✔
173
}
174
} // namespace
175

176
auto NativeGrep::matchFile(const QProcessEnvironment &env,
436 ✔
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);
436 ✔
183
  if (plaintext.isEmpty())
436 ✔
184
    return {};
49 ✔
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;
387 ✔
188
  bool first = true;
189
  for (QStringView line : QStringView(plaintext).tokenize(u'\n')) {
60,927 ✔
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();
60,641 ✔
195
    if (t.isEmpty())
60,641 ✔
196
      continue;
30,381 ✔
197
    const QRegularExpressionMatch m = rx.matchView(line);
30,269 ✔
198
    if (!m.hasMatch())
30,269 ✔
199
      continue;
200
    if (matches.size() == kMaxMatchesPerEntry) {
30,260 ✔
201
      matches << QString(); // isMoreMarker(): not a match, not counted
101 ✔
202
      break;
203
    }
204
    matches << previewOfMatch(line, t, m, password);
30,159 ✔
205
  }
30,269 ✔
206
  return matches;
207
}
208

209
/**
210
 * @brief Walk the store, decrypt every .gpg file, collect matches.
211
 */
212
auto NativeGrep::scanStore(const QProcessEnvironment &env,
20 ✔
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;
20 ✔
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");
60 ✔
223
  for (const QString &filePath : files) {
446 ✔
224
    if (QThread::currentThread()->isInterruptionRequested() ||
435 ✔
225
        (cancel != nullptr && cancel->load()))
81 ✔
226
      return {};
7 ✔
227
    if (total == kMaxMatches) {
428 ✔
228
      // The budget is spent and entries remain: the search stopped here.
229
      results.append({QString(), {}});
4 ✔
230
      break;
2 ✔
231
    }
232
    QStringList matches =
233
        matchFile(env, gpgExe, filePath, rx, cancel, storeDir);
426 ✔
234
    if (matches.isEmpty())
426 ✔
235
      continue;
236
    const bool more = isMoreMarker(matches.constLast());
237
    if (more)
380 ✔
238
      matches.removeLast();
100 ✔
239
    // The store-wide budget: what still fits, and a marker when that cut
240
    // the entry short.
241
    const int room = kMaxMatches - total;
380 ✔
242
    if (matches.size() > room) {
380 ✔
243
      matches = matches.mid(0, room);
1 ✔
244
      matches << QString();
2 ✔
245
    } else if (more) {
379 ✔
246
      matches << QString();
200 ✔
247
    }
248
    total += static_cast<int>(matches.size()) -
380 ✔
249
             (isMoreMarker(matches.constLast()) ? 1 : 0);
380 ✔
250
    QString entry = QDir(storeDir).relativeFilePath(filePath);
380 ✔
251
    if (entry.endsWith(QLatin1String(".gpg")))
380 ✔
252
      entry.chop(4);
380 ✔
253
    results.append({entry, matches});
380 ✔
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
void NativeGrep::search(const QString &pattern, bool caseInsensitive,
16 ✔
267
                        const QString &gpgExe, const QString &storeDir,
268
                        const QProcessEnvironment &env) {
269
  cancel();
16 ✔
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;
16 ✔
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()) {
16 ✔
283
    QMetaObject::invokeMethod(
×
284
        this,
285
        [this, seq]() {
×
286
          if (m_seq == seq)
×
287
            emit finished({});
×
288
        },
×
289
        Qt::QueuedConnection);
290
    return;
1 ✔
291
  }
292

293
  const QRegularExpression rx(
294
      pattern, caseInsensitive ? QRegularExpression::CaseInsensitiveOption
295
                               : QRegularExpression::PatternOptions{});
16 ✔
296
  if (!rx.isValid()) {
16 ✔
297
    QMetaObject::invokeMethod(
1 ✔
298
        this,
299
        [this, seq]() {
1 ✔
300
          if (m_seq == seq)
1 ✔
301
            emit finished({});
2 ✔
302
        },
1 ✔
303
        Qt::QueuedConnection);
304
    return;
305
  }
306
  QPointer<NativeGrep> self(this);
307

308
  auto emitResults = [self, seq](QList<QPair<QString, QStringList>> results) {
30 ✔
309
    if (!self)
15 ✔
310
      return;
311
    QMetaObject::invokeMethod(
15 ✔
312
        self,
313
        [self, seq, results = std::move(results)]() {
45 ✔
314
          if (self && self->m_seq == seq)
30 ✔
315
            emit self->finished(results);
15 ✔
316
        },
15 ✔
317
        Qt::QueuedConnection);
318
  };
15 ✔
319

320
  auto cancelFlag = std::make_shared<std::atomic_bool>(false);
15 ✔
321
  QThread *thread = QThread::create([gpgExe, storeDir, env, rx, cancelFlag,
30 ✔
322
                                     emitResults = std::move(emitResults)]() {
323
    std::move(emitResults)(
15 ✔
324
        scanStore(env, gpgExe, storeDir, rx, cancelFlag.get()));
15 ✔
325
  });
15 ✔
326

327
  m_workers.append({thread, cancelFlag});
30 ✔
328
  connect(thread, &QThread::finished, thread, &QObject::deleteLater);
15 ✔
329
  connect(thread, &QThread::finished, this, [this, thread]() {
15 ✔
330
    m_workers.removeIf(
15 ✔
331
        [thread](const Worker &w) { return w.thread == thread; });
15 ✔
332
  });
333
  thread->start();
15 ✔
334
}
31 ✔
335

336
void NativeGrep::cancel() {
686 ✔
337
  for (const Worker &w : std::as_const(m_workers)) {
694 ✔
338
    w.cancel->store(true);
339
    if (w.thread && w.thread->isRunning())
8 ✔
340
      w.thread->requestInterruption();
8 ✔
341
  }
342
}
686 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc