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

IJHack / QtPass / 46322307370

29 Nov 2026 11:15PM UTC coverage: 94.493% (+0.02%) from 94.474%
46322307370

push

github

web-flow
A gpg, Git or pass run that will not end can be stopped (#2407)

Executor ran the queued commands one at a time and waited for each with
no deadline and no way to stop it. A store entry crafted to keep gpg
busy held up every later show, save and Git step for as long as its
author chose; MainWindow's 30 s watchdog re-enabled the window but
nothing queued completed.

- Executor::stopRunning() terminates the running command and its
  process group (each runs in a session of its own) and kills the group
  a grace period later, also once the leader has exited, so a child
  that ignored SIGTERM does not go on. It does not block; the run is
  reported through error() whatever it exits with, and the queue moves
  on. Pass::stopRunning() forwards it.
- When the watchdog fires while a run still goes, a Stop button in the
  status bar names it ("git pull", "pass init", "a decrypt"; the
  tooltip follows the queue). For anything but a decrypt or a search it
  asks first, as stopping a write can leave it half done, and stops
  only the run it asked about (Executor::runningSerial()).

No timer stops a run by itself: a decrypt may be waiting for a
passphrase or a smartcard. On Windows only the command QtPass started is
ended, not what it started in turn (CHANGELOG).

Tests: a long run and a child that ignores SIGTERM are stopped and the
next command runs; a run that exits 0 on SIGTERM is an error; the
button appears with the watchdog, names the run, asks for a pull (No
keeps it, Yes stops it), stops a decrypt without asking, follows the
queue, and Yes on a pull that ended while asked leaves the next one
running. Each guard was reverted once and its test failed.

Scan finding ANT-2026-5ZCF42YU.

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

74 of 77 new or added lines in 4 files covered. (96.1%)

3 existing lines in 1 file now uncovered.

11205 of 11858 relevant lines covered (94.49%)

23582.51 hits per line

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

96.09
/src/executor.cpp
1
// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
#include "executor.h"
4
#include <QCoreApplication>
5
#include <QDeadlineTimer>
6
#include <QDir>
7
#include <QFileInfo>
8
#include <QScopeGuard>
9
#include <QStringDecoder>
10
#include <QThread>
11
#include <QTimer>
12
#include <algorithm>
13
#include <climits>
14
#include <utility>
15

16
#include "qtpasslogging.h"
17

18
#ifdef Q_OS_UNIX
19
#include <csignal>
20
#include <sys/stat.h>
21
#endif
22

23
namespace {
24
/// Executor::setChildUmask(); negative for none.
25
std::atomic_int g_childUmask{-1};
26
/// How often a cancellable blocking run re-checks its cancel flag.
27
constexpr int kBlockingCancelPollMs = 100;
28
/// Grace between terminate() and kill() once a blocking run is cancelled;
29
/// gpg and git exit on SIGTERM well within this.
30
constexpr int kBlockingKillGraceMs = 1000;
31
} // namespace
32

33
Executor::Executor(QObject *parent) : QObject(parent) {
526 ✔
34
  connect(&m_process, &QProcess::finished, this, &Executor::onProcessFinished);
526 ✔
35
  connect(&m_process, &QProcess::started, this, &Executor::starting);
526 ✔
36
  // Read as it arrives, so what QProcess buffers stays small: stderr into
37
  // the cap, stdout nobody asked for into nothing.
38
  connect(&m_process, &QProcess::readyReadStandardError, this,
526 ✔
39
          [this]() { m_stderr.append(m_process.readAllStandardError()); });
3,046 ✔
40
  connect(&m_process, &QProcess::readyReadStandardOutput, this, [this]() {
526 ✔
41
    if (m_discardStdout) {
162 ✔
42
      m_process.readAllStandardOutput();
4 ✔
43
    }
44
  });
162 ✔
45
}
526 ✔
46

47
namespace {
48

49
/**
50
 * @brief Length of a UTF-8 sequence from its lead byte.
51
 * @param lead The first byte.
52
 * @return 1 to 4, or 0 for a continuation byte.
53
 */
54
auto utf8SequenceLength(unsigned char lead) -> int {
16 ✔
55
  if (lead < 0x80) {
16 ✔
56
    return 1;
57
  }
58
  if ((lead & 0xC0) == 0x80) {
2 ✔
59
    return 0;
60
  }
61
  if ((lead & 0xE0) == 0xC0) {
2 ✔
62
    return 2;
63
  }
64
  if ((lead & 0xF0) == 0xE0) {
×
65
    return 3;
×
66
  }
67
  return 4;
68
}
69

70
} // namespace
71

72
void Executor::CappedOutput::countStatus(const QByteArray &line) {
268,733 ✔
73
  static const QByteArray prefix = QByteArrayLiteral("[GNUPG:] ");
268,735 ✔
74
  if (!line.startsWith(prefix)) {
268,733 ✔
75
    return;
249,380 ✔
76
  }
77
  QByteArray keyword = line.mid(prefix.size());
19,353 ✔
78
  keyword.truncate(keyword.indexOf(' ') < 0 ? keyword.size()
23,536 ✔
79
                                            : keyword.indexOf(' '));
80
  if (keyword.endsWith('\r')) {
81
    keyword.chop(1);
6,001 ✔
82
  }
83
  const QString key = QString::fromLatin1(keyword);
84
  if (m_status.contains(key) || m_status.size() < kMaxStatusKeywords) {
19,589 ✔
85
    ++m_status[key];
19,348 ✔
86
  }
87
}
88

89
void Executor::CappedOutput::append(const QByteArray &chunk) {
5,078 ✔
90
  // Status records, whole lines at a time, before the text is cut.
91
  qsizetype start = 0;
92
  for (qsizetype end = chunk.indexOf('\n'); end >= 0;
273,811 ✔
93
       start = end + 1, end = chunk.indexOf('\n', start)) {
268,733 ✔
94
    if (!m_lineTooLong &&
268,733 ✔
95
        m_line.size() + (end - start) <= kMaxStatusLineBytes) {
268,732 ✔
96
      m_line.append(chunk.constData() + start, end - start);
537,462 ✔
97
      countStatus(m_line);
268,731 ✔
98
    }
99
    m_line.clear();
268,733 ✔
100
    m_lineTooLong = false;
268,733 ✔
101
  }
102
  if (!m_lineTooLong) {
5,078 ✔
103
    if (m_line.size() + (chunk.size() - start) > kMaxStatusLineBytes) {
4,999 ✔
104
      m_line.clear();
2 ✔
105
      m_lineTooLong = true;
2 ✔
106
    } else {
107
      m_line.append(chunk.constData() + start, chunk.size() - start);
8,782 ✔
108
    }
109
  }
110

111
  constexpr qsizetype half = kMaxStderrBytes / 2;
112
  qsizetype from = 0;
113
  if (m_head.size() < half) {
5,078 ✔
114
    from = qMin(half - m_head.size(), chunk.size());
2,245 ✔
115
    m_head.append(chunk.constData(), from);
3,284 ✔
116
  }
117
  if (from == chunk.size()) {
5,078 ✔
118
    return;
119
  }
120
  m_tail.append(chunk.constData() + from, chunk.size() - from);
8,502 ✔
121
  if (m_tail.size() > half) {
2,834 ✔
122
    const qsizetype excess = m_tail.size() - half;
2,385 ✔
123
    m_dropped += excess;
2,385 ✔
124
    m_tail.remove(0, excess);
2,385 ✔
125
  }
126
}
127

128
// When bytes were left out, the head may end and the tail begin in the
129
// middle of a character: both are cut back to whole ones, so the text
130
// still decodes as UTF-8 rather than falling back to another encoding.
131
auto Executor::CappedOutput::take() -> QByteArray {
1,705 ✔
132
  QByteArray all;
1,705 ✔
133
  if (m_dropped == 0) {
1,705 ✔
134
    all = m_head + m_tail;
3,394 ✔
135
  } else {
136
    QByteArray head = m_head;
137
    qsizetype chopped = 0;
138
    for (qsizetype back = 1; back <= qMin<qsizetype>(4, head.size()); ++back) {
8 ✔
139
      const int length = utf8SequenceLength(
8 ✔
140
          static_cast<unsigned char>(head.at(head.size() - back)));
8 ✔
141
      if (length != 0) {
8 ✔
142
        if (length > back) {
8 ✔
143
          chopped = back;
144
          head.chop(back);
1 ✔
145
        }
146
        break;
147
      }
148
    }
149
    qsizetype start = 0;
150
    while (start < m_tail.size() &&
8 ✔
151
           utf8SequenceLength(static_cast<unsigned char>(m_tail.at(start))) ==
8 ✔
152
               0) {
153
      ++start;
×
154
    }
155
    all = head + QByteArrayLiteral("\n[... ") +
16 ✔
156
          QByteArray::number(m_dropped + chopped + start) +
24 ✔
157
          QByteArrayLiteral(" bytes left out ...]\n") + m_tail.mid(start);
24 ✔
158
  }
159
  m_head.clear();
1,705 ✔
160
  m_tail.clear();
1,705 ✔
161
  m_dropped = 0;
1,705 ✔
162
  // A last line without a line end is a record too.
163
  if (!m_lineTooLong && !m_line.isEmpty()) {
1,705 ✔
164
    countStatus(m_line);
2 ✔
165
  }
166
  m_line.clear();
1,705 ✔
167
  m_lineTooLong = false;
1,705 ✔
168
  return all;
1,705 ✔
169
}
170

171
Executor::~Executor() { m_process.blockSignals(true); }
1,053 ✔
172

173
void Executor::detachFromTerminal(QProcess &process) {
3,154 ✔
174
#if defined(Q_OS_UNIX) && QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
175
  // A child inherits QtPass's controlling terminal when QtPass was started
176
  // from one. git (HTTPS credentials) and ssh (key passphrase, host key) then
177
  // prompt on that /dev/tty, and as the queue runs one command at a time,
178
  // every decrypt and save waits behind a prompt nobody sees: QtPass looks
179
  // frozen. In a session of its own the child has no terminal, so git and
180
  // ssh use SSH_ASKPASS/GIT_ASKPASS when set and otherwise fail with an
181
  // error QtPass shows. GIT_TERMINAL_PROMPT=0 is not set on top: without a
182
  // tty git has nothing to prompt on, and some credential helpers read it as
183
  // "no interaction at all" and would skip their own dialogs.
184
  //
185
  // gpg is unaffected: pinentry is started by gpg-agent, which finds the
186
  // terminal through GPG_TTY (set by the user's shell) or the tty on gpg's
187
  // stdin, here always a pipe. pass is a shell script running that gpg and
188
  // git, so the same holds for it.
189
  //
190
  // Signal dispositions are left alone (no ResetSignalHandlers): exec()
191
  // already resets caught signals, and QtPass sets no SIG_IGN of its own, so
192
  // that flag would only undo what QtPass's own parent chose (nohup, say).
193
  // Terminal signals (Ctrl+C, the SIGHUP of a closed terminal) now reach
194
  // QtPass but not the child; the children are short-lived and, with no
195
  // terminal, cannot sit waiting for input.
196
  QProcess::UnixProcessParameters params = process.unixProcessParameters();
3,154 ✔
197
  params.flags |= QProcess::UnixProcessFlag::CreateNewSession;
198
  process.setUnixProcessParameters(params);
3,154 ✔
199
#else
200
  Q_UNUSED(process);
201
#endif
202
}
3,154 ✔
203

204
void Executor::setChildUmask(int mask) { g_childUmask.store(mask); }
5 ✔
205

206
auto Executor::childUmask() -> int { return g_childUmask.load(); }
31 ✔
207

208
void Executor::startProcess(QProcess &process, const QString &app,
3,148 ✔
209
                            const QStringList &args) {
210
  detachFromTerminal(process);
3,148 ✔
211
#ifdef Q_OS_UNIX
212
  // In the child, between fork and exec: umask() is async-signal-safe.
213
  if (const int mask = g_childUmask.load(); mask >= 0) {
3,148 ✔
214
    process.setChildProcessModifier(
1 ✔
215
        [mask] { ::umask(static_cast<mode_t>(mask)); });
1 ✔
216
  }
217
#endif
218
  if (const auto wsl = parseWslCommand(app)) {
3,148 ✔
219
    process.start(wsl->launcher, wsl->argv(args));
18 ✔
220
  } else {
221
    process.start(resolveExecutable(app), args);
6,278 ✔
222
  }
223
}
3,148 ✔
224

225
auto Executor::resolveExecutable(const QString &app) -> QString {
3,145 ✔
226
  if (app.isEmpty() || QDir::isAbsolutePath(app)) {
6,289 ✔
227
    return app;
228
  }
229
  const QDir appDir(QCoreApplication::applicationDirPath());
76 ✔
230
  QStringList candidates{QDir::cleanPath(appDir.absoluteFilePath(app))};
304 ✔
231
#ifdef Q_OS_WIN
232
  candidates << QDir::cleanPath(
233
      appDir.absoluteFilePath(app + QStringLiteral(".exe")));
234
#endif
235
  for (const QString &candidate : std::as_const(candidates)) {
149 ✔
236
    // A stray non-executable file of that name must not mask PATH.
237
    const QFileInfo info(candidate);
76 ✔
238
    if (info.isFile() && info.isExecutable()) {
76 ✔
239
      return candidate;
240
    }
241
  }
76 ✔
242
  return app;
243
}
152 ✔
244

245
auto Executor::WslCommand::argv(const QStringList &args) const -> QStringList {
35 ✔
246
  return options + QStringList{QStringLiteral("--exec"), command} + args;
140 ✔
247
}
248

249
auto Executor::WslCommand::with(const QString &program) const -> WslCommand {
12 ✔
250
  return {launcher, options, program};
12 ✔
251
}
252

253
auto Executor::parseWslCommand(const QString &app)
5,125 ✔
254
    -> std::optional<WslCommand> {
255
  const QStringList parts = QProcess::splitCommand(app);
5,125 ✔
256
  if (parts.size() < 2) {
5,125 ✔
257
    return std::nullopt;
5,080 ✔
258
  }
259
  // The file name after the last separator of either kind: a Windows path
260
  // has to be recognised as such wherever the parser runs.
261
  const QString &launcher = parts.first();
262
  const qsizetype separator = std::max(launcher.lastIndexOf(QLatin1Char('/')),
45 ✔
263
                                       launcher.lastIndexOf(QLatin1Char('\\')));
45 ✔
264
  const QString launcherName = launcher.mid(separator + 1);
45 ✔
265
  const bool isWsl =
266
      launcherName.compare(QLatin1String("wsl"), Qt::CaseInsensitive) == 0 ||
58 ✔
267
      launcherName.compare(QLatin1String("wsl.exe"), Qt::CaseInsensitive) == 0;
13 ✔
268
  if (!isWsl) {
269
    return std::nullopt;
3 ✔
270
  }
271
  WslCommand wsl;
42 ✔
272
#ifdef Q_OS_WIN
273
  // A bare wsl or wsl.exe in any case is looked up on PATH as `wsl`; a path
274
  // stays as is.
275
  wsl.launcher = separator < 0 ? QStringLiteral("wsl") : launcher;
276
#else
277
  // QtPass running inside WSL reaches wsl.exe through interop under exactly
278
  // that name; nothing says `wsl` resolves too, so start what was written.
279
  wsl.launcher = launcher;
42 ✔
280
#endif
281
  // wsl.exe options that take a value; anything else starting with `-` is a
282
  // flag. A user-written -e/--exec is dropped, argv() always adds one.
283
  static const QStringList valued{
284
      QStringLiteral("-d"),   QStringLiteral("--distribution"),
2 ✔
285
      QStringLiteral("-u"),   QStringLiteral("--user"),
2 ✔
286
      QStringLiteral("--cd"), QStringLiteral("--shell-type")};
58 ✔
287
  qsizetype i = 1;
288
  for (; i < parts.size() && parts.at(i).startsWith(QLatin1Char('-')); ++i) {
59 ✔
289
    const QString &option = parts.at(i);
290
    if (option == QLatin1String("-e") || option == QLatin1String("--exec")) {
18 ✔
291
      continue;
7 ✔
292
    }
293
    if (valued.contains(option)) {
11 ✔
294
      if (i + 1 >= parts.size()) {
11 ✔
295
        return std::nullopt;
1 ✔
296
      }
297
      wsl.options << option << parts.at(++i);
298
    } else {
299
      wsl.options << option;
300
    }
301
  }
302
  // Exactly one program. More is a shell command line (`sh -c "..."`),
303
  // which is what --exec exists to keep out.
304
  if (i != parts.size() - 1) {
41 ✔
305
    return std::nullopt;
6 ✔
306
  }
307
  wsl.command = parts.at(i);
35 ✔
308
  return wsl;
309
}
42 ✔
310

311
auto Executor::wslExecArgs(const QString &command, const QStringList &args)
2 ✔
312
    -> QStringList {
313
  return WslCommand{QStringLiteral("wsl"), {}, command}.argv(args);
2 ✔
314
}
315

316
auto Executor::translatePathForWsl(const QString &path, const QString &exe)
1,436 ✔
317
    -> QString {
318
  QString normalizedPath = QDir::cleanPath(path);
1,436 ✔
319
  const auto wsl = parseWslCommand(exe);
1,436 ✔
320
  if (!wsl) {
1,436 ✔
321
    return normalizedPath;
1,432 ✔
322
  }
323
  QString wslPath;
4 ✔
324
  const auto wslpath = wsl->with(QStringLiteral("wslpath"));
8 ✔
325
  const int rc = executeBlocking(wslpath.launcher,
4 ✔
326
                                 wslpath.argv({normalizedPath}), &wslPath);
12 ✔
327
  // Only the line end wslpath prints: white space at the end of the path is
328
  // the name's own ("team " beside "team", a folder named " "), and trimmed
329
  // it made git remove or move the neighbour, or the whole store.
330
  QString translated = wslPath;
331
  if (translated.endsWith(QLatin1Char('\n'))) {
4 ✔
332
    translated.chop(1);
4 ✔
333
  }
334
  if (translated.endsWith(QLatin1Char('\r'))) {
4 ✔
335
    translated.chop(1);
×
336
  }
337
  return (rc == 0 && !translated.isEmpty()) ? translated : normalizedPath;
4 ✔
338
}
4 ✔
339

340
void Executor::executeNext() {
946 ✔
341
  // Nothing starts while a failed start's error() is still on its way: every
342
  // other failure is emitted before the next item starts (onProcessFinished),
343
  // and a caller that drops the rest of its work on a failure (ImitatePass's
344
  // insert-then-commit) relies on that order. The posted error continues the
345
  // queue once it is out.
346
  if (running || m_pendingErrors > 0 || m_execQueue.isEmpty()) {
946 ✔
347
    return;
489 ✔
348
  }
349
  // A copy, and marked running, before anyone hears of it: a slot on
350
  // dequeuing() that queues more cannot invalidate it or start it a second
351
  // time, and one that calls cancelNext() cannot drop it.
352
  const ExecQueueItem i = m_execQueue.head();
469 ✔
353
  running = true;
469 ✔
354
  ++m_runSerial;
469 ✔
355
  emit dequeuing(i.id, true);
469 ✔
356

357
  // An empty executable never emits finished(); dropping it wedged the queue
358
  // (#1682). Fail it like a failed-to-start process so the queue drains.
359
  if (i.app.isEmpty()) {
469 ✔
360
    qCDebug(lcQtPass) << "No executable set for:" << i.id;
6 ✔
361
    const int failedId = i.id;
6 ✔
362
    running = false;
6 ✔
363
    m_execQueue.dequeue();
6 ✔
364
    ++m_pendingErrors;
6 ✔
365
    QMetaObject::invokeMethod(
6 ✔
366
        this,
367
        [this, failedId]() {
6 ✔
368
          emit error(failedId, -1, QString(),
12 ✔
369
                     tr("No executable configured for this command"));
6 ✔
370
          --m_pendingErrors;
6 ✔
371
          executeNext();
6 ✔
372
          postDrainedIfIdle();
6 ✔
373
        },
6 ✔
374
        Qt::QueuedConnection);
375
    return;
6 ✔
376
  }
377

378
  // Always set it: an item without a directory runs in the application's
379
  // cwd, not wherever the previous item happened to run.
380
  m_process.setWorkingDirectory(i.workingDir);
463 ✔
381
  m_stderr.clear();
463 ✔
382
  m_discardStdout = !i.readStdout;
463 ✔
383
  startProcess(m_process, i.app, i.args);
463 ✔
384

385
  // A failed start never emits finished(), so `running` would stall the queue
386
  // and waiters (the keygen dialog) would hang. The emit is queued so it does
387
  // not re-enter KeygenDialog::done(), still on the stack; -1 goes through
388
  // Pass::finished's non-zero error gate.
389
  if (!m_process.waitForStarted(-1)) {
463 ✔
390
    qCDebug(lcQtPass) << "Process failed to start:" << i.id << " " << i.app;
6 ✔
391
    const int failedId = i.id;
6 ✔
392
    const QString failedApp = i.app;
393
    m_process.closeWriteChannel();
6 ✔
394
    running = false;
6 ✔
395
    m_execQueue.dequeue();
6 ✔
396
    ++m_pendingErrors;
6 ✔
397
    QMetaObject::invokeMethod(
6 ✔
398
        this,
399
        [this, failedId, failedApp]() {
18 ✔
400
          emit error(failedId, -1, QString(),
18 ✔
401
                     tr("Failed to start %1").arg(failedApp));
12 ✔
402
          --m_pendingErrors;
6 ✔
403
          executeNext();
6 ✔
404
          postDrainedIfIdle();
6 ✔
405
        },
6 ✔
406
        Qt::QueuedConnection);
407
    return;
408
  }
409

410
  if (!i.input.isEmpty()) {
457 ✔
411
    QByteArray data = i.input.toUtf8();
412
    if (m_process.write(data) != data.length()) {
125 ✔
413
      qCDebug(lcQtPass) << "Not all data written to process:" << i.id << " "
×
414
                        << i.app;
×
415
    }
416
  }
417
  m_process.closeWriteChannel();
457 ✔
418
}
469 ✔
419

420
void Executor::execute(int id, const QString &app, const QStringList &args,
95 ✔
421
                       bool readStdout, bool readStderr) {
422
  execute(id, QString(), app, args, QString(), readStdout, readStderr);
190 ✔
423
}
95 ✔
424

425
void Executor::execute(int id, const QString &workDir, const QString &app,
2 ✔
426
                       const QStringList &args, bool readStdout,
427
                       bool readStderr) {
428
  execute(id, workDir, app, args, QString(), readStdout, readStderr);
2 ✔
429
}
2 ✔
430

431
void Executor::execute(int id, const QString &app, const QStringList &args,
3 ✔
432
                       QString input, bool readStdout, bool readStderr) {
433
  execute(id, QString(), app, args, std::move(input), readStdout, readStderr);
6 ✔
434
}
3 ✔
435

436
void Executor::execute(int id, const QString &workDir, const QString &app,
484 ✔
437
                       const QStringList &args, QString input, bool readStdout,
438
                       bool readStderr) {
439
  // Queue even an empty executable: executeNext() reports it (#1682).
440
  // startProcess resolves the executable, as on the blocking path.
441
  m_execQueue.push_back(
484 ✔
442
      {id, app, args, std::move(input), readStdout, readStderr, workDir});
443
  executeNext();
484 ✔
444
}
1,452 ✔
445

446
// UTF-8 first; on a decoding error fall back to the system encoding.
447
// lossless, when given, says whether the text encodes back to exactly these
448
// bytes: what writing it to gpg or pass (toUtf8(), as every writer here
449
// does) would store. Not for bytes that are not UTF-8 (each became U+FFFD,
450
// or on Windows a code-page character), nor for a leading byte order mark,
451
// which the decoder drops without an error. A literal U+FFFD, as older
452
// QtPass versions left in such entries, does encode back.
453
static auto decodeAssumingUtf8(const QByteArray &in, bool *lossless = nullptr)
3,651 ✔
454
    -> QString {
455
  // Stateless: a truncated trailing byte becomes a replacement character
456
  // instead of being held back for a continuation that never comes.
457
  auto converter =
3,651 ✔
458
      QStringDecoder(QStringDecoder::Utf8, QStringDecoder::Flag::Stateless);
459
  QString out = converter(in);
3,651 ✔
460
  if (converter.hasError()) {
3,651 ✔
461
    auto fallback =
4 ✔
462
        QStringDecoder(QStringDecoder::System, QStringDecoder::Flag::Stateless);
463
    out = fallback(in);
8 ✔
464
  }
465
  if (lossless != nullptr) {
3,651 ✔
466
    *lossless = out.toUtf8() == in;
398 ✔
467
  }
468
  return out;
3,651 ✔
469
}
470

471
auto Executor::decodeText(const QByteArray &bytes) -> QString {
432 ✔
472
  return decodeAssumingUtf8(bytes);
432 ✔
473
}
474

475
// Returns an error code rather than throwing, matching QtPass's error
476
// handling elsewhere.
477
namespace {
478

479
#ifdef Q_OS_UNIX
480
/**
481
 * @brief Wait up to @p ms for every process in group @p group to exit.
482
 * @param group A process group id; the child's own pid, as it leads a
483
 *        session of its own (Executor::detachFromTerminal()).
484
 * @param ms Most milliseconds to wait.
485
 * @return true once the group is empty.
486
 */
487
auto waitForGroup(pid_t group, int ms) -> bool {
18 ✔
488
  QDeadlineTimer deadline(ms);
18 ✔
489
  // kill(-group, 0) fails with ESRCH once no process is left in it; while
490
  // one is, no new process can be given that id.
491
  while (::kill(-group, 0) == 0) {
25 ✔
492
    if (deadline.hasExpired()) {
7 ✔
493
      return false;
494
    }
495
    QThread::msleep(10);
7 ✔
496
  }
497
  return true;
498
}
499
#endif
500

501
/**
502
 * @brief Stop a running @p process from the thread that owns it:
503
 * terminate(), then kill() if it is still running after a grace period,
504
 * then at most one more grace period for it to exit.
505
 * A console gpg ignores terminate() on Windows (WM_CLOSE), hence the kill.
506
 *
507
 * On Unix the whole process group gets the signals and is waited for: pass
508
 * is a shell script, and the git it runs would otherwise go on pulling into
509
 * the store after the run was reported stopped.
510
 */
511
void stopBlocking(QProcess &process) {
18 ✔
512
#ifdef Q_OS_UNIX
513
  const auto group = static_cast<pid_t>(process.processId());
18 ✔
514
  const auto signalGroup = [group](int signal) {
21 ✔
515
    if (group > 0) {
21 ✔
516
      ::kill(-group, signal);
21 ✔
517
    }
518
  };
39 ✔
519
  signalGroup(SIGTERM);
18 ✔
520
#endif
521
  process.terminate();
18 ✔
522
  if (!process.waitForFinished(kBlockingKillGraceMs)) {
18 ✔
523
#ifdef Q_OS_UNIX
524
    signalGroup(SIGKILL);
3 ✔
525
#endif
526
    process.kill();
3 ✔
527
    // SIGKILL cannot be ignored, but a child in uninterruptible sleep (a
528
    // hung NFS or FUSE mount) dies only when the kernel lets it. Wait one
529
    // more grace period, not forever: the run is reported as failed either
530
    // way, and a blocking run then lasts at most its timeout plus twice the
531
    // grace.
532
    if (!process.waitForFinished(kBlockingKillGraceMs)) {
3 ✔
533
      qCWarning(lcQtPass) << "Process still running after kill():"
×
534
                          << process.program();
×
535
    }
536
  }
537
#ifdef Q_OS_UNIX
538
  if (group > 0 && !waitForGroup(group, kBlockingKillGraceMs)) {
18 ✔
539
    signalGroup(SIGKILL);
×
540
    if (!waitForGroup(group, kBlockingKillGraceMs)) {
×
541
      qCWarning(lcQtPass) << "Processes started by" << process.program()
×
542
                          << "still running after kill()";
×
543
    }
544
  }
545
#endif
546
}
18 ✔
547

548
/**
549
 * @brief What is left of @p deadline, as QProcess's wait functions take it:
550
 * -1 for none.
551
 */
552
auto msecsLeft(const QDeadlineTimer &deadline) -> int {
4,450 ✔
553
  if (deadline.isForever()) {
4,450 ✔
554
    return -1;
555
  }
556
  return static_cast<int>(
557
      std::clamp<qint64>(deadline.remainingTime(), 0, INT_MAX));
148 ✔
558
}
559

560
/**
561
 * @brief Wait for @p process to finish, stopping it when @p cancel is set
562
 * or @p deadline passes.
563
 *
564
 * Polls the flag; every QProcess call, terminate()/kill() included, stays on
565
 * this thread, so another thread can never act on an exited process (or a
566
 * pid the OS has since reused).
567
 * @return false when it was cancelled or ran out of time.
568
 */
569
auto waitOrCancel(QProcess &process, const std::atomic_bool *cancel,
2,625 ✔
570
                  const QDeadlineTimer &deadline) -> bool {
571
  if (cancel == nullptr) {
2,625 ✔
572
    // waitForFinished() can also fail (a poll error) with the child still
573
    // running; that is not completion either. Stop it rather than report
574
    // it done.
575
    if (!process.waitForFinished(msecsLeft(deadline)) &&
1,768 ✔
576
        process.state() != QProcess::NotRunning) {
6 ✔
577
      stopBlocking(process);
6 ✔
578
      return false;
6 ✔
579
    }
580
    return true;
1,756 ✔
581
  }
582
  while (!process.waitForFinished(
1,794 ✔
583
      deadline.isForever()
584
          ? kBlockingCancelPollMs
585
          : qMin(kBlockingCancelPollMs, msecsLeft(deadline)))) {
3 ✔
586
    if (process.state() == QProcess::NotRunning) {
46 ✔
587
      return true;
588
    }
589
    if (cancel->load() || deadline.hasExpired()) {
58 ✔
590
      stopBlocking(process);
12 ✔
591
      return false;
12 ✔
592
    }
593
  }
594
  return true;
595
}
596

597
} // namespace
598

599
auto Executor::runBlocking(QProcess &process, const QString &app,
1,928 ✔
600
                           const QStringList &args, const QString &input,
601
                           QString *process_out, QString *process_err,
602
                           const std::atomic_bool *cancel, int timeoutMs)
603
    -> int {
604
  QByteArray out;
1,928 ✔
605
  const int rc = runBlockingRaw(process, app, args, input.toUtf8(),
3,856 ✔
606
                                process_out != nullptr ? &out : nullptr,
607
                                process_err, cancel, timeoutMs);
608
  if (process_out != nullptr) {
1,928 ✔
609
    *process_out = decodeAssumingUtf8(out);
3,366 ✔
610
  }
611
  return rc;
1,928 ✔
612
}
613

614
auto Executor::runBlockingRaw(QProcess &process, const QString &app,
2,694 ✔
615
                              const QStringList &args, const QByteArray &input,
616
                              QByteArray *process_out, QString *process_err,
617
                              const std::atomic_bool *cancel, int timeoutMs)
618
    -> int {
619
  if (cancel != nullptr && cancel->load())
2,694 ✔
620
    return -1;
621
  const QDeadlineTimer deadline = timeoutMs < 0
622
                                      ? QDeadlineTimer(QDeadlineTimer::Forever)
2,685 ✔
623
                                      : QDeadlineTimer(timeoutMs);
2,685 ✔
624
  // Read as it arrives (QProcess emits these from inside its waitFor*()
625
  // calls too), so neither channel piles up in QProcess's buffers: stderr
626
  // into the cap, stdout nobody asked for into nothing. Wanted stdout is
627
  // kept whole, as a decrypt must be lossless; gpg's --max-output bounds it.
628
  CappedOutput err;
2,685 ✔
629
  const QMetaObject::Connection errReader = QObject::connect(
630
      &process, &QProcess::readyReadStandardError,
631
      [&process, &err]() { err.append(process.readAllStandardError()); });
6,827 ✔
632
  const QMetaObject::Connection outDropper =
633
      process_out != nullptr
634
          ? QMetaObject::Connection()
2,685 ✔
635
          : QObject::connect(&process, &QProcess::readyReadStandardOutput,
636
                             [&process]() { process.readAllStandardOutput(); });
2,932 ✔
637
  const auto disconnectReaders = qScopeGuard([&errReader, &outDropper]() {
2,685 ✔
638
    QObject::disconnect(errReader);
2,685 ✔
639
    QObject::disconnect(outDropper);
2,685 ✔
640
  });
2,685 ✔
641
  startProcess(process, app, args);
2,685 ✔
642
  if (!process.waitForStarted(msecsLeft(deadline))) {
2,685 ✔
643
    qCDebug(lcQtPass) << "Process failed to start:" << app;
60 ✔
644
    if (process.state() != QProcess::NotRunning) {
60 ✔
645
      stopBlocking(process);
×
646
    }
647
    return -1;
60 ✔
648
  }
649
  if (!input.isEmpty()) {
2,625 ✔
650
    if (process.write(input) != input.length()) {
937 ✔
651
      qCDebug(lcQtPass) << "Not all input written:" << app;
×
652
    }
653
  }
654
  // Always close stdin so a child blocking on EOF doesn't hang.
655
  process.closeWriteChannel();
2,625 ✔
656
  if (!waitOrCancel(process, cancel, deadline)) {
2,625 ✔
657
    return -1;
658
  }
659
  // Read before judging the exit: a process that crashed may have said why,
660
  // as the queued path (onProcessFinished) keeps it too.
661
  if (process_out != nullptr) {
2,607 ✔
662
    *process_out = process.readAllStandardOutput();
4,468 ✔
663
  }
664
  if (process_err != nullptr) {
2,607 ✔
665
    err.append(process.readAllStandardError());
761 ✔
666
    *process_err = decodeAssumingUtf8(err.take());
1,522 ✔
667
  }
668
  return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
2,607 ✔
669
}
2,685 ✔
670

671
auto Executor::executeBlockingRaw(QProcess &process, const QString &app,
766 ✔
672
                                  const QStringList &args,
673
                                  const QByteArray &input,
674
                                  QByteArray *process_out, QString *process_err,
675
                                  const std::atomic_bool *cancel, int timeoutMs)
676
    -> int {
677
  return runBlockingRaw(process, app, args, input, process_out, process_err,
766 ✔
678
                        cancel, timeoutMs);
766 ✔
679
}
680

681
auto Executor::executeBlocking(const QString &app, const QStringList &args,
476 ✔
682
                               const QString &input, QString *process_out,
683
                               QString *process_err) -> int {
684
  QProcess internal;
476 ✔
685
  return runBlocking(internal, app, args, input, process_out, process_err);
952 ✔
686
}
476 ✔
687

688
auto Executor::executeBlocking(QProcess &process, const QString &app,
1,416 ✔
689
                               const QStringList &args, const QString &input,
690
                               QString *process_out, QString *process_err,
691
                               const std::atomic_bool *cancel, int timeoutMs)
692
    -> int {
693
  return runBlocking(process, app, args, input, process_out, process_err,
1,416 ✔
694
                     cancel, timeoutMs);
1,416 ✔
695
}
696

697
auto Executor::executeBlocking(const QString &app, const QStringList &args,
284 ✔
698
                               QString *process_out, QString *process_err)
699
    -> int {
700
  return executeBlocking(app, args, QString(), process_out, process_err);
568 ✔
701
}
702

703
auto Executor::executeBlocking(const QProcessEnvironment &env,
36 ✔
704
                               const QString &app, const QStringList &args,
705
                               QString *process_out, QString *process_err)
706
    -> int {
707
  QProcess process;
36 ✔
708
  process.setProcessEnvironment(env);
36 ✔
709
  return runBlocking(process, app, args, QString(), process_out, process_err);
72 ✔
710
}
36 ✔
711

712
void Executor::setEnvironment(const QProcessEnvironment &env) {
922 ✔
713
  m_process.setProcessEnvironment(env);
922 ✔
714
}
922 ✔
715

716
auto Executor::environment() const -> QProcessEnvironment {
154 ✔
717
  return m_process.processEnvironment();
154 ✔
718
}
719

720
auto Executor::stopRunning() -> bool {
8 ✔
721
  if (!running || m_process.state() == QProcess::NotRunning) {
8 ✔
722
    return false;
2 ✔
723
  }
724
  const qint64 pid = m_process.processId();
6 ✔
725
  const quint64 run = m_runSerial;
6 ✔
726
  // Reported as stopped whatever it exits with (onProcessFinished()): a
727
  // command that exits 0 on SIGTERM did not do its work.
728
  m_stoppedRun = run;
6 ✔
729
  // Not blocking: finished() comes through the event loop as for any run,
730
  // and the queue moves on from there.
731
#ifdef Q_OS_UNIX
732
  if (pid > 0) {
6 ✔
733
    ::kill(-static_cast<pid_t>(pid), SIGTERM);
6 ✔
734
  }
735
#endif
736
  m_process.terminate();
6 ✔
737
  QTimer::singleShot(kBlockingKillGraceMs, this, [this, pid, run]() {
6 ✔
738
    const bool stillThisRun =
739
        running && m_runSerial == run && m_process.processId() == pid;
5 ✔
740
#ifdef Q_OS_UNIX
741
    // Also once the leader is gone: a child that ignored SIGTERM goes on in
742
    // the old process group while the queue has moved on. Not when the pid
743
    // came back as the next run's own (and so its group's) id.
744
    const bool pidReused =
745
        !stillThisRun && running && m_process.processId() == pid;
5 ✔
746
    if (pid > 0 && !pidReused) {
5 ✔
747
      ::kill(-static_cast<pid_t>(pid), SIGKILL);
5 ✔
748
    }
749
#endif
750
    if (stillThisRun) {
5 ✔
NEW
751
      m_process.kill();
×
752
    }
753
  });
5 ✔
754
  return true;
6 ✔
755
}
756

757
// Also -1 while the head is already running: that one is not cancelled.
758
auto Executor::cancelNext() -> int {
17 ✔
759
  if (running || m_execQueue.isEmpty()) {
17 ✔
760
    return -1;
761
  }
762
  const int id = m_execQueue.dequeue().id;
13 ✔
763
  // As in executeNext(): while the signal is out, a slot's cancelNext()
764
  // drops nothing and its execute() only queues. Nothing is started here
765
  // afterwards: the caller (ImitatePass dropping the rest of a failed
766
  // transaction from its completion handler) may cancel again, and the
767
  // queue moves on when that handler returns (onProcessFinished()).
768
  running = true;
13 ✔
769
  emit dequeuing(id, false);
13 ✔
770
  running = false;
13 ✔
771
  return id;
13 ✔
772
}
773

774
void Executor::onProcessFinished(int exitCode,
450 ✔
775
                                 QProcess::ExitStatus exitStatus) {
776
  ExecQueueItem i = m_execQueue.dequeue();
777
  running = false;
450 ✔
778
  const bool stopped = m_stoppedRun != 0 && m_stoppedRun == m_runSerial;
450 ✔
779
  m_stoppedRun = 0;
450 ✔
780
  auto [output, err] = collectOutput(i, exitCode);
450 ✔
781
  if (stopped) {
450 ✔
782
    // A stopped run failed, also when it exited 0 on SIGTERM.
783
    if (err.trimmed().isEmpty()) {
6 ✔
784
      err = tr("%1 was stopped").arg(i.app);
10 ✔
785
    }
786
    emit error(i.id, -1, output, err);
6 ✔
787
    m_outputLossless = true;
6 ✔
788
    m_lastStatus.clear();
6 ✔
789
  } else if (exitStatus == QProcess::NormalExit) {
444 ✔
790
    if (exitCode != 0) {
443 ✔
791
      qCDebug(lcQtPass) << i.app << "exited with" << exitCode << err;
50 ✔
792
    }
793
    emit finished(i.id, exitCode, output, err);
443 ✔
794
    m_outputLossless = true;
443 ✔
795
    m_lastStatus.clear();
443 ✔
796
  } else {
797
    // A signal-killed process usually leaves stderr empty; without this the
798
    // password pane would show nothing at all for the failure.
799
    if (err.trimmed().isEmpty()) {
1 ✔
800
      err = tr("%1 crashed or was killed").arg(i.app);
2 ✔
801
    }
802
    // Qt leaves exitCode undefined after a CrashExit (the signal number on
803
    // Unix), and Pass::finished gates on it: 0 would pass as success and 1
804
    // as grep's "no matches". Report -1, like the failed-to-start path.
805
    emit error(i.id, -1, output, err);
1 ✔
806
    m_outputLossless = true;
1 ✔
807
    m_lastStatus.clear();
1 ✔
808
  }
809
  executeNext();
450 ✔
810
  postDrainedIfIdle();
450 ✔
811
}
450 ✔
812

813
void Executor::postDrainedIfIdle() {
462 ✔
814
  // One check at a time, run after what is emitted now; it fires only once
815
  // nothing runs or waits and every posted error() of a failed start is
816
  // out (the last of those posts the check again).
817
  if (m_drainCheckPosted) {
462 ✔
818
    return;
819
  }
820
  m_drainCheckPosted = true;
459 ✔
821
  QMetaObject::invokeMethod(
459 ✔
822
      this,
823
      [this]() {
459 ✔
824
        m_drainCheckPosted = false;
396 ✔
825
        if (isIdle() && m_pendingErrors == 0) {
174 ✔
826
          emit drained();
174 ✔
827
        }
828
      },
396 ✔
829
      Qt::QueuedConnection);
830
}
831

832
auto Executor::collectOutput(const ExecQueueItem &item, int exitCode)
450 ✔
833
    -> std::pair<QString, QString> {
834
  QString output;
450 ✔
835
  QString err;
450 ✔
836
  m_outputLossless = true;
450 ✔
837
  if (item.readStdout) {
450 ✔
838
    output = decodeAssumingUtf8(m_process.readAllStandardOutput(),
796 ✔
839
                                &m_outputLossless);
840
  }
841
  m_stderr.append(m_process.readAllStandardError());
450 ✔
842
  const QByteArray errBytes = m_stderr.take();
450 ✔
843
  m_lastStatus = m_stderr.statusCounts();
450 ✔
844
  if (item.readStderr || exitCode != 0) {
450 ✔
845
    err = decodeAssumingUtf8(errBytes);
754 ✔
846
  }
847
  return {output, err};
450 ✔
848
}
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