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

IJHack / QtPass / 45716347781

25 Nov 2026 10:48PM UTC coverage: 94.778% (-0.03%) from 94.806%
45716347781

push

github

web-flow
Windows: read a cloud placeholder entry, still refuse links (#2342)

Util::openRegularFile refused every reparse point on Windows. A file that
a cloud provider such as OneDrive keeps online only carries one, so
content search skipped such an entry and re-encryption reported it as
unreadable.

A name surrogate (symbolic link, junction, mount point) is still
refused. Any other reparse point is opened a second time without
FILE_FLAG_OPEN_REPARSE_POINT, so the provider can fetch the content, and
read only when both handles have the same volume and 128-bit file ID
(FILE_ID_INFO) and the second one is a regular disk file. The folder
walk in readRegularFileUnder refuses the same name surrogates.

Not tested against a real cloud filter: CI has none.

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

10164 of 10724 relevant lines covered (94.78%)

26000.88 hits per line

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

94.24
/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) {}
275 ✔
24

25
NativeGrep::~NativeGrep() {
275 ✔
26
  static constexpr int kThreadTimeoutMs = 5000;
27
  cancel();
275 ✔
28
  QElapsedTimer elapsed;
275 ✔
29
  elapsed.start();
275 ✔
30
  for (const Worker &w : std::as_const(m_workers)) {
276 ✔
31
    if (w.thread && w.thread->isRunning()) {
1 ✔
32
      const int remaining =
33
          kThreadTimeoutMs - static_cast<int>(elapsed.elapsed());
×
34
      if (remaining > 0)
×
35
        w.thread->wait(remaining);
×
36
    }
37
  }
38
}
275 ✔
39

40
/**
41
 * @brief Decrypt one .gpg file and return lines matching rx.
42
 */
43
auto NativeGrep::matchFile(const QProcessEnvironment &env,
436 ✔
44
                           const QString &gpgExe, const QString &filePath,
45
                           const QRegularExpression &rx,
46
                           const std::atomic_bool *cancel,
47
                           const QString &storeDir) -> QStringList {
48
  // Read here, without following a link, and handed to gpg on stdin: the
49
  // name was listed as a regular file when the search began, and a pull
50
  // since may have put a link there (or on a folder on the way). gpg given
51
  // the name would follow it and decrypt a file outside the store into the
52
  // results. With the store given, every folder on the way down is opened
53
  // without following a link, so none can be swapped between a check and
54
  // the read. The cap is on what decrypts; the ciphertext of an entry just
55
  // under it is a little larger.
56
  constexpr qint64 kCiphertextMargin = 1024LL * 1024;
57
  constexpr qint64 kMaxCiphertext =
58
      Pass::kMaxPlaintextBytes + kCiphertextMargin;
59
  const std::optional<QByteArray> ciphertext =
60
      storeDir.isEmpty()
61
          ? Util::readRegularFile(filePath, kMaxCiphertext)
436 ✔
62
          : Util::readRegularFileUnder(storeDir, filePath, kMaxCiphertext);
436 ✔
63
  if (!ciphertext) {
436 ✔
64
    return {};
4 ✔
65
  }
66
  QByteArray decrypted;
432 ✔
67
  // The QProcess overload is the one that takes the cancel flag; it polls
68
  // the flag while waiting and terminates (then kills) gpg from this thread,
69
  // the one that owns the process.
70
  QProcess gpg;
432 ✔
71
  gpg.setProcessEnvironment(env);
432 ✔
72
  const int rc = Executor::executeBlockingRaw(
432 ✔
73
      gpg, gpgExe,
74
      QStringList{"-d", "--quiet", "--yes", "--no-encrypt-to", "--batch",
432 ✔
75
                  "--use-agent"} +
6,048 ✔
76
          Pass::maxOutputArgs(),
864 ✔
77
      *ciphertext, &decrypted, nullptr, cancel);
78
  // Decoded as executeBlocking() decoded it before: UTF-8, else the system
79
  // encoding, so an entry in a Windows code page is still searched.
80
  const QString plaintext = Executor::decodeText(decrypted);
432 ✔
81
  if (rc != 0 || plaintext.isEmpty())
432 ✔
82
    return {};
45 ✔
83
  // Line by line over the text, never a list of every line (a compressed
84
  // entry can expand into tens of millions), and a bounded number taken.
85
  QStringList matches;
387 ✔
86
  bool first = true;
87
  for (QStringView line : QStringView(plaintext).tokenize(u'\n')) {
60,927 ✔
88
    // The password is the first line, empty or not.
89
    const bool password = std::exchange(first, false);
90
    if (line.endsWith(u'\r'))
91
      line.chop(1);
92
    const QStringView t = line.trimmed();
60,641 ✔
93
    if (t.isEmpty())
60,641 ✔
94
      continue;
60,535 ✔
95
    const QRegularExpressionMatch m = rx.matchView(line);
30,269 ✔
96
    if (!m.hasMatch())
30,269 ✔
97
      continue;
9 ✔
98
    if (matches.size() == kMaxMatchesPerEntry) {
30,260 ✔
99
      matches << QString(); // isMoreMarker(): not a match, not counted
101 ✔
100
      break;
101
    }
102
    // A shared secret is never shown, as in the display panel: only that
103
    // there was a match (isOtpMarker()).
104
    const QString whole = t.toString();
105
    if (password ? FileContent::isOtpPasswordLine(whole)
59,940 ✔
106
                 : FileContent::isOtpLine(whole)) {
29,781 ✔
107
      matches << QStringLiteral("\n");
3 ✔
108
      continue;
3 ✔
109
    }
110
    // Marked, so the window shows it only where the panel would
111
    // (isPasswordMatch()).
112
    const QString mark = password ? QStringLiteral("\n") : QString();
30,156 ✔
113
    if (t.size() <= kMaxPreviewLength) {
30,156 ✔
114
      matches << mark + whole;
30,150 ✔
115
      continue;
30,150 ✔
116
    }
117
    // A window of the line that holds the match, a little context before
118
    // it; "…" marks what was left out on either side.
119
    const qsizetype at =
120
        qMax<qsizetype>(0, m.capturedStart() - (t.data() - line.data()));
6 ✔
121
    qsizetype start = qBound<qsizetype>(0, at - kMaxPreviewLength / 4,
6 ✔
122
                                        t.size() - kMaxPreviewLength);
6 ✔
123
    qsizetype end = start + kMaxPreviewLength;
6 ✔
124
    // Never half a surrogate pair (an emoji, CJK Extension B) at either
125
    // edge: the window takes the whole character.
126
    if (start > 0 && t[start].isLowSurrogate())
6 ✔
127
      --start;
1 ✔
128
    if (end < t.size() && t[end - 1].isHighSurrogate())
6 ✔
129
      ++end;
1 ✔
130
    // A field's name decides whether its value is hidden, so a window that
131
    // cuts into a `name: value` line keeps the whole name in front. A name
132
    // too long for that is shown cut, and then none of the value is.
133
    const qsizetype colon = password ? -1 : t.indexOf(u':');
6 ✔
134
    QString preview;
6 ✔
135
    qsizetype from = start;
6 ✔
136
    if (colon > 0 && start > 0) {
6 ✔
137
      if (colon >= kMaxPreviewLength / 2) {
3 ✔
138
        matches << t.first(kMaxPreviewLength / 2).toString() + QChar(0x2026) +
3 ✔
139
                       QStringLiteral(": ") + QChar(0x2026);
3 ✔
140
        continue;
141
      }
142
      from = std::max(start, colon + 1);
2 ✔
143
      preview = t.first(colon + 1).toString() + u' ';
4 ✔
144
      if (from > colon + 1)
2 ✔
145
        preview += QChar(0x2026);
1 ✔
146
    } else if (start > 0) {
3 ✔
147
      preview = QChar(0x2026);
2 ✔
148
    }
149
    preview += t.sliced(from, end - from).toString();
5 ✔
150
    if (end < t.size())
5 ✔
151
      preview.append(QChar(0x2026));
4 ✔
152
    matches << mark + preview;
10 ✔
153
  }
30,269 ✔
154
  return matches;
155
}
432 ✔
156

157
/**
158
 * @brief Walk the store, decrypt every .gpg file, collect matches.
159
 */
160
auto NativeGrep::scanStore(const QProcessEnvironment &env,
20 ✔
161
                           const QString &gpgExe, const QString &storeDir,
162
                           const QRegularExpression &rx,
163
                           const std::atomic_bool *cancel)
164
    -> QList<QPair<QString, QStringList>> {
165
  QList<QPair<QString, QStringList>> results;
20 ✔
166
  int total = 0; // matching lines, the markers not counted
167
  // Regular files only: a link or junction is not an entry, and searching
168
  // through one would decrypt files outside the store.
169
  const QStringList files =
170
      Util::regularFilesUnder(storeDir, QStringList() << "*.gpg");
60 ✔
171
  for (const QString &filePath : files) {
446 ✔
172
    if (QThread::currentThread()->isInterruptionRequested() ||
435 ✔
173
        (cancel != nullptr && cancel->load()))
81 ✔
174
      return {};
7 ✔
175
    if (total == kMaxMatches) {
428 ✔
176
      // The budget is spent and entries remain: the search stopped here.
177
      results.append({QString(), {}});
4 ✔
178
      break;
2 ✔
179
    }
180
    QStringList matches =
181
        matchFile(env, gpgExe, filePath, rx, cancel, storeDir);
426 ✔
182
    if (matches.isEmpty())
426 ✔
183
      continue;
184
    const bool more = isMoreMarker(matches.constLast());
185
    if (more)
380 ✔
186
      matches.removeLast();
100 ✔
187
    // The store-wide budget: what still fits, and a marker when that cut
188
    // the entry short.
189
    const int room = kMaxMatches - total;
380 ✔
190
    if (matches.size() > room) {
380 ✔
191
      matches = matches.mid(0, room);
1 ✔
192
      matches << QString();
2 ✔
193
    } else if (more) {
379 ✔
194
      matches << QString();
200 ✔
195
    }
196
    total += static_cast<int>(matches.size()) -
380 ✔
197
             (isMoreMarker(matches.constLast()) ? 1 : 0);
380 ✔
198
    QString entry = QDir(storeDir).relativeFilePath(filePath);
380 ✔
199
    if (entry.endsWith(QLatin1String(".gpg")))
380 ✔
200
      entry.chop(4);
380 ✔
201
    results.append({entry, matches});
380 ✔
202
  }
203
  return results;
204
}
205

206
/**
207
 * @brief Start a search on a worker thread.
208
 *
209
 * Results are emitted on the owner's thread via QMetaObject::invokeMethod. A
210
 * sequence counter discards results from superseded searches; the previous
211
 * search is asked to stop but not waited for, since blocking the UI thread
212
 * while gpg decrypts would freeze the interface.
213
 */
214
void NativeGrep::search(const QString &pattern, bool caseInsensitive,
16 ✔
215
                        const QString &gpgExe, const QString &storeDir,
216
                        const QProcessEnvironment &env) {
217
  cancel();
16 ✔
218

219
  // Advance the sequence before any early return so in-flight workers from the
220
  // previous query fail the seq check and cannot publish stale results.
221
  const int seq = ++m_seq;
16 ✔
222

223
  // Use trimmed() rather than isEmpty(): a whitespace-only string is a valid
224
  // regex that matches every non-empty line, which is almost never intentional
225
  // and would decrypt the entire store.
226
  //
227
  // Both early returns post finished() via Qt::QueuedConnection so that the
228
  // signal is always delivered asynchronously after search() returns, matching
229
  // the contract of the threaded path.
230
  if (pattern.trimmed().isEmpty()) {
16 ✔
231
    QMetaObject::invokeMethod(
×
232
        this,
233
        [this, seq]() {
×
234
          if (m_seq == seq)
×
235
            emit finished({});
×
236
        },
×
237
        Qt::QueuedConnection);
238
    return;
1 ✔
239
  }
240

241
  const QRegularExpression rx(
242
      pattern, caseInsensitive ? QRegularExpression::CaseInsensitiveOption
243
                               : QRegularExpression::PatternOptions{});
16 ✔
244
  if (!rx.isValid()) {
16 ✔
245
    QMetaObject::invokeMethod(
1 ✔
246
        this,
247
        [this, seq]() {
1 ✔
248
          if (m_seq == seq)
1 ✔
249
            emit finished({});
2 ✔
250
        },
1 ✔
251
        Qt::QueuedConnection);
252
    return;
253
  }
254
  QPointer<NativeGrep> self(this);
255

256
  auto emitResults = [self, seq](QList<QPair<QString, QStringList>> results) {
30 ✔
257
    if (!self)
15 ✔
258
      return;
259
    QMetaObject::invokeMethod(
15 ✔
260
        self,
261
        [self, seq, results = std::move(results)]() {
45 ✔
262
          if (self && self->m_seq == seq)
30 ✔
263
            emit self->finished(results);
15 ✔
264
        },
15 ✔
265
        Qt::QueuedConnection);
266
  };
15 ✔
267

268
  auto cancelFlag = std::make_shared<std::atomic_bool>(false);
15 ✔
269
  QThread *thread = QThread::create([gpgExe, storeDir, env, rx, cancelFlag,
30 ✔
270
                                     emitResults = std::move(emitResults)]() {
271
    std::move(emitResults)(
15 ✔
272
        scanStore(env, gpgExe, storeDir, rx, cancelFlag.get()));
15 ✔
273
  });
15 ✔
274

275
  m_workers.append({thread, cancelFlag});
30 ✔
276
  connect(thread, &QThread::finished, thread, &QObject::deleteLater);
15 ✔
277
  connect(thread, &QThread::finished, this, [this, thread]() {
15 ✔
278
    m_workers.removeIf(
14 ✔
279
        [thread](const Worker &w) { return w.thread == thread; });
14 ✔
280
  });
281
  thread->start();
15 ✔
282
}
31 ✔
283

284
void NativeGrep::cancel() {
622 ✔
285
  for (const Worker &w : std::as_const(m_workers)) {
631 ✔
286
    w.cancel->store(true);
287
    if (w.thread && w.thread->isRunning())
9 ✔
288
      w.thread->requestInterruption();
8 ✔
289
  }
290
}
622 ✔
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