QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
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
23namespace {
25std::atomic_int g_childUmask{-1};
27constexpr int kBlockingCancelPollMs = 100;
30constexpr int kBlockingKillGraceMs = 1000;
31} // namespace
32
33Executor::Executor(QObject *parent) : QObject(parent) {
34 connect(&m_process, &QProcess::finished, this, &Executor::onProcessFinished);
35 connect(&m_process, &QProcess::started, this, &Executor::starting);
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,
39 [this]() { m_stderr.append(m_process.readAllStandardError()); });
40 connect(&m_process, &QProcess::readyReadStandardOutput, this, [this]() {
41 if (m_discardStdout) {
42 m_process.readAllStandardOutput();
43 }
44 });
45}
46
47namespace {
48
54auto utf8SequenceLength(unsigned char lead) -> int {
55 if (lead < 0x80) {
56 return 1;
57 }
58 if ((lead & 0xC0) == 0x80) {
59 return 0;
60 }
61 if ((lead & 0xE0) == 0xC0) {
62 return 2;
63 }
64 if ((lead & 0xF0) == 0xE0) {
65 return 3;
66 }
67 return 4;
68}
69
70} // namespace
71
72void Executor::CappedOutput::countStatus(const QByteArray &line) {
73 static const QByteArray prefix = QByteArrayLiteral("[GNUPG:] ");
74 if (!line.startsWith(prefix)) {
75 return;
76 }
77 QByteArray keyword = line.mid(prefix.size());
78 keyword.truncate(keyword.indexOf(' ') < 0 ? keyword.size()
79 : keyword.indexOf(' '));
80 if (keyword.endsWith('\r')) {
81 keyword.chop(1);
82 }
83 const QString key = QString::fromLatin1(keyword);
84 if (m_status.contains(key) || m_status.size() < kMaxStatusKeywords) {
85 ++m_status[key];
86 }
87}
88
89void Executor::CappedOutput::append(const QByteArray &chunk) {
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;
93 start = end + 1, end = chunk.indexOf('\n', start)) {
94 if (!m_lineTooLong &&
95 m_line.size() + (end - start) <= kMaxStatusLineBytes) {
96 m_line.append(chunk.constData() + start, end - start);
98 }
99 m_line.clear();
100 m_lineTooLong = false;
101 }
102 if (!m_lineTooLong) {
103 if (m_line.size() + (chunk.size() - start) > kMaxStatusLineBytes) {
104 m_line.clear();
105 m_lineTooLong = true;
106 } else {
107 m_line.append(chunk.constData() + start, chunk.size() - start);
108 }
109 }
110
111 constexpr qsizetype half = kMaxStderrBytes / 2;
112 qsizetype from = 0;
113 if (m_head.size() < half) {
114 from = qMin(half - m_head.size(), chunk.size());
115 m_head.append(chunk.constData(), from);
116 }
117 if (from == chunk.size()) {
118 return;
119 }
120 m_tail.append(chunk.constData() + from, chunk.size() - from);
121 if (m_tail.size() > half) {
122 const qsizetype excess = m_tail.size() - half;
123 m_dropped += excess;
124 m_tail.remove(0, excess);
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.
131auto Executor::CappedOutput::take() -> QByteArray {
132 QByteArray all;
133 if (m_dropped == 0) {
134 all = m_head + m_tail;
135 } else {
136 QByteArray head = m_head;
137 qsizetype chopped = 0;
138 for (qsizetype back = 1; back <= qMin<qsizetype>(4, head.size()); ++back) {
139 const int length = utf8SequenceLength(
140 static_cast<unsigned char>(head.at(head.size() - back)));
141 if (length != 0) {
142 if (length > back) {
143 chopped = back;
144 head.chop(back);
145 }
146 break;
147 }
148 }
149 qsizetype start = 0;
150 while (start < m_tail.size() &&
151 utf8SequenceLength(static_cast<unsigned char>(m_tail.at(start))) ==
152 0) {
153 ++start;
154 }
155 all = head + QByteArrayLiteral("\n[... ") +
156 QByteArray::number(m_dropped + chopped + start) +
157 QByteArrayLiteral(" bytes left out ...]\n") + m_tail.mid(start);
158 }
159 m_head.clear();
160 m_tail.clear();
161 m_dropped = 0;
162 // A last line without a line end is a record too.
163 if (!m_lineTooLong && !m_line.isEmpty()) {
165 }
166 m_line.clear();
167 m_lineTooLong = false;
168 return all;
169}
170
171namespace {
176constexpr int killWaitMs = 5000;
177} // namespace
178
180 m_process.blockSignals(true);
181 // What ~QProcess does for a command still running, without its warning
182 // that nobody ended the process: ending it here is meant. The wait is
183 // short: a process that outlives its kill is left to ~QProcess, which
184 // waits its own 30 seconds and then does warn. So the result of the wait
185 // changes nothing here.
186 if (m_process.state() != QProcess::NotRunning) {
187 m_process.kill();
188 static_cast<void>(m_process.waitForFinished(killWaitMs));
189 }
190}
191
192void Executor::detachFromTerminal(QProcess &process) {
193#if defined(Q_OS_UNIX) && QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
194 // A child inherits QtPass's controlling terminal when QtPass was started
195 // from one. git (HTTPS credentials) and ssh (key passphrase, host key) then
196 // prompt on that /dev/tty, and as the queue runs one command at a time,
197 // every decrypt and save waits behind a prompt nobody sees: QtPass looks
198 // frozen. In a session of its own the child has no terminal, so git and
199 // ssh use SSH_ASKPASS/GIT_ASKPASS when set and otherwise fail with an
200 // error QtPass shows. GIT_TERMINAL_PROMPT=0 is not set on top: without a
201 // tty git has nothing to prompt on, and some credential helpers read it as
202 // "no interaction at all" and would skip their own dialogs.
203 //
204 // gpg is unaffected: pinentry is started by gpg-agent, which finds the
205 // terminal through GPG_TTY (set by the user's shell) or the tty on gpg's
206 // stdin, here always a pipe. pass is a shell script running that gpg and
207 // git, so the same holds for it.
208 //
209 // Signal dispositions are left alone (no ResetSignalHandlers): exec()
210 // already resets caught signals, and QtPass sets no SIG_IGN of its own, so
211 // that flag would only undo what QtPass's own parent chose (nohup, say).
212 // Terminal signals (Ctrl+C, the SIGHUP of a closed terminal) now reach
213 // QtPass but not the child; the children are short-lived and, with no
214 // terminal, cannot sit waiting for input.
215 QProcess::UnixProcessParameters params = process.unixProcessParameters();
216 params.flags |= QProcess::UnixProcessFlag::CreateNewSession;
217 process.setUnixProcessParameters(params);
218#else
219 Q_UNUSED(process);
220#endif
221}
222
223void Executor::setChildUmask(int mask) { g_childUmask.store(mask); }
224
225auto Executor::childUmask() -> int { return g_childUmask.load(); }
226
227void Executor::startProcess(QProcess &process, const QString &app,
228 const QStringList &args) {
229 detachFromTerminal(process);
230#ifdef Q_OS_UNIX
231 // In the child, between fork and exec: umask() is async-signal-safe.
232 if (const int mask = g_childUmask.load(); mask >= 0) {
233 process.setChildProcessModifier(
234 [mask] { ::umask(static_cast<mode_t>(mask)); });
235 }
236#endif
237 if (const auto wsl = parseWslCommand(app)) {
238 process.start(wsl->launcher, wsl->argv(args));
239 } else {
240 process.start(resolveExecutable(app), args);
241 }
242}
243
244auto Executor::resolveExecutable(const QString &app) -> QString {
245 if (app.isEmpty() || QDir::isAbsolutePath(app)) {
246 return app;
247 }
248 const QDir appDir(QCoreApplication::applicationDirPath());
249 QStringList candidates{QDir::cleanPath(appDir.absoluteFilePath(app))};
250#ifdef Q_OS_WIN
251 candidates << QDir::cleanPath(
252 appDir.absoluteFilePath(app + QStringLiteral(".exe")));
253#endif
254 for (const QString &candidate : std::as_const(candidates)) {
255 // A stray non-executable file of that name must not mask PATH.
256 const QFileInfo info(candidate);
257 if (info.isFile() && info.isExecutable()) {
258 return candidate;
259 }
260 }
261 return app;
262}
263
264auto Executor::WslCommand::argv(const QStringList &args) const -> QStringList {
265 return options + QStringList{QStringLiteral("--exec"), command} + args;
266}
267
268auto Executor::WslCommand::with(const QString &program) const -> WslCommand {
269 return {launcher, options, program};
270}
271
272auto Executor::parseWslCommand(const QString &app)
273 -> std::optional<WslCommand> {
274 const QStringList parts = QProcess::splitCommand(app);
275 if (parts.size() < 2) {
276 return std::nullopt;
277 }
278 // The file name after the last separator of either kind: a Windows path
279 // has to be recognised as such wherever the parser runs.
280 const QString &launcher = parts.first();
281 const qsizetype separator = std::max(launcher.lastIndexOf(QLatin1Char('/')),
282 launcher.lastIndexOf(QLatin1Char('\\')));
283 const QString launcherName = launcher.mid(separator + 1);
284 const bool isWsl =
285 launcherName.compare(QLatin1String("wsl"), Qt::CaseInsensitive) == 0 ||
286 launcherName.compare(QLatin1String("wsl.exe"), Qt::CaseInsensitive) == 0;
287 if (!isWsl) {
288 return std::nullopt;
289 }
290 WslCommand wsl;
291#ifdef Q_OS_WIN
292 // A bare wsl or wsl.exe in any case is looked up on PATH as `wsl`; a path
293 // stays as is.
294 wsl.launcher = separator < 0 ? QStringLiteral("wsl") : launcher;
295#else
296 // QtPass running inside WSL reaches wsl.exe through interop under exactly
297 // that name; nothing says `wsl` resolves too, so start what was written.
298 wsl.launcher = launcher;
299#endif
300 // wsl.exe options that take a value; anything else starting with `-` is a
301 // flag. A user-written -e/--exec is dropped, argv() always adds one.
302 static const QStringList valued{
303 QStringLiteral("-d"), QStringLiteral("--distribution"),
304 QStringLiteral("-u"), QStringLiteral("--user"),
305 QStringLiteral("--cd"), QStringLiteral("--shell-type")};
306 qsizetype i = 1;
307 for (; i < parts.size() && parts.at(i).startsWith(QLatin1Char('-')); ++i) {
308 const QString &option = parts.at(i);
309 if (option == QLatin1String("-e") || option == QLatin1String("--exec")) {
310 continue;
311 }
312 if (valued.contains(option)) {
313 if (i + 1 >= parts.size()) {
314 return std::nullopt;
315 }
316 wsl.options << option << parts.at(++i);
317 } else {
318 wsl.options << option;
319 }
320 }
321 // Exactly one program. More is a shell command line (`sh -c "..."`),
322 // which is what --exec exists to keep out.
323 if (i != parts.size() - 1) {
324 return std::nullopt;
325 }
326 wsl.command = parts.at(i);
327 return wsl;
328}
329
330auto Executor::wslExecArgs(const QString &command, const QStringList &args)
331 -> QStringList {
332 return WslCommand{QStringLiteral("wsl"), {}, command}.argv(args);
333}
334
335auto Executor::translatePathForWsl(const QString &path, const QString &exe)
336 -> QString {
337 QString normalizedPath = QDir::cleanPath(path);
338 const auto wsl = parseWslCommand(exe);
339 if (!wsl) {
340 return normalizedPath;
341 }
342 QString wslPath;
343 const auto wslpath = wsl->with(QStringLiteral("wslpath"));
344 const int rc = executeBlocking(wslpath.launcher,
345 wslpath.argv({normalizedPath}), &wslPath);
346 // Only the line end wslpath prints: white space at the end of the path is
347 // the name's own ("team " beside "team", a folder named " "), and trimmed
348 // it made git remove or move the neighbour, or the whole store.
349 QString translated = std::move(wslPath);
350 if (translated.endsWith(QLatin1Char('\n'))) {
351 translated.chop(1);
352 }
353 if (translated.endsWith(QLatin1Char('\r'))) {
354 translated.chop(1);
355 }
356 return (rc == 0 && !translated.isEmpty()) ? translated : normalizedPath;
357}
358
360 // Nothing starts while a failed start's error() is still on its way: every
361 // other failure is emitted before the next item starts (onProcessFinished),
362 // and a caller that drops the rest of its work on a failure (ImitatePass's
363 // insert-then-commit) relies on that order. The posted error continues the
364 // queue once it is out.
365 if (running || m_pendingErrors > 0 || m_execQueue.isEmpty()) {
366 return;
367 }
368 // A copy, and marked running, before anyone hears of it: a slot on
369 // dequeuing() that queues more cannot invalidate it or start it a second
370 // time, and one that calls cancelNext() cannot drop it.
371 const ExecQueueItem i = m_execQueue.head();
372 running = true;
373 ++m_runSerial;
374 emit dequeuing(i.id, true);
375
376 // An empty executable never emits finished(); dropping it wedged the queue
377 // (#1682). Fail it like a failed-to-start process so the queue drains.
378 if (i.app.isEmpty()) {
379 qCDebug(lcQtPass) << "No executable set for:" << i.id;
380 const int failedId = i.id;
381 running = false;
382 m_execQueue.dequeue();
384 QMetaObject::invokeMethod(
385 this,
386 [this, failedId]() {
387 emit error(failedId, -1, QString(),
388 tr("No executable configured for this command"));
390 executeNext();
392 },
393 Qt::QueuedConnection);
394 return;
395 }
396
397 // Always set it: an item without a directory runs in the application's
398 // cwd, not wherever the previous item happened to run.
399 m_process.setWorkingDirectory(i.workingDir);
400 m_stderr.clear();
403
404 // A failed start never emits finished(), so `running` would stall the queue
405 // and waiters (the keygen dialog) would hang. The emit is queued so it does
406 // not re-enter KeygenDialog::done(), still on the stack; -1 goes through
407 // Pass::finished's non-zero error gate.
408 if (!m_process.waitForStarted(-1)) {
409 qCDebug(lcQtPass) << "Process failed to start:" << i.id << " " << i.app;
410 const int failedId = i.id;
411 const QString failedApp = i.app;
412 m_process.closeWriteChannel();
413 running = false;
414 m_execQueue.dequeue();
416 QMetaObject::invokeMethod(
417 this,
418 [this, failedId, failedApp]() {
419 emit error(failedId, -1, QString(),
420 tr("Failed to start %1").arg(failedApp));
422 executeNext();
424 },
425 Qt::QueuedConnection);
426 return;
427 }
428
429 if (!i.input.isEmpty()) {
430 QByteArray data = i.input.toUtf8();
431 if (m_process.write(data) != data.length()) {
432 qCDebug(lcQtPass) << "Not all data written to process:" << i.id << " "
433 << i.app;
434 }
435 }
436 m_process.closeWriteChannel();
437}
438
439void Executor::execute(int id, const QString &app, const QStringList &args,
440 bool readStdout, bool readStderr) {
441 execute(id, QString(), app, args, QString(), readStdout, readStderr);
442}
443
444void Executor::execute(int id, const QString &workDir, const QString &app,
445 const QStringList &args, bool readStdout,
446 bool readStderr) {
447 execute(id, workDir, app, args, QString(), readStdout, readStderr);
448}
449
450void Executor::execute(int id, const QString &app, const QStringList &args,
451 QString input, bool readStdout, bool readStderr) {
452 execute(id, QString(), app, args, std::move(input), readStdout, readStderr);
453}
454
455void Executor::execute(int id, const QString &workDir, const QString &app,
456 const QStringList &args, QString input, bool readStdout,
457 bool readStderr) {
458 // Queue even an empty executable: executeNext() reports it (#1682).
459 // startProcess resolves the executable, as on the blocking path.
460 m_execQueue.push_back(
461 {id, app, args, std::move(input), readStdout, readStderr, workDir});
462 executeNext();
463}
464
465// UTF-8 first; on a decoding error fall back to the system encoding.
466// lossless, when given, says whether the text encodes back to exactly these
467// bytes: what writing it to gpg or pass (toUtf8(), as every writer here
468// does) would store. Not for bytes that are not UTF-8 (each became U+FFFD,
469// or on Windows a code-page character), nor for a leading byte order mark,
470// which the decoder drops without an error. A literal U+FFFD, as older
471// QtPass versions left in such entries, does encode back.
472static auto decodeAssumingUtf8(const QByteArray &in, bool *lossless = nullptr)
473 -> QString {
474 // Stateless: a truncated trailing byte becomes a replacement character
475 // instead of being held back for a continuation that never comes.
476 auto converter =
477 QStringDecoder(QStringDecoder::Utf8, QStringDecoder::Flag::Stateless);
478 QString out = converter(in);
479 if (converter.hasError()) {
480 auto fallback =
481 QStringDecoder(QStringDecoder::System, QStringDecoder::Flag::Stateless);
482 out = fallback(in);
483 }
484 if (lossless != nullptr) {
485 *lossless = out.toUtf8() == in;
486 }
487 return out;
488}
489
490auto Executor::decodeText(const QByteArray &bytes) -> QString {
491 return decodeAssumingUtf8(bytes);
492}
493
494// Returns an error code rather than throwing, matching QtPass's error
495// handling elsewhere.
496namespace {
497
498#ifdef Q_OS_UNIX
506auto waitForGroup(pid_t group, int ms) -> bool {
507 QDeadlineTimer deadline(ms);
508 // kill(-group, 0) fails with ESRCH once no process is left in it; while
509 // one is, no new process can be given that id.
510 while (::kill(-group, 0) == 0) {
511 if (deadline.hasExpired()) {
512 return false;
513 }
514 QThread::msleep(10);
515 }
516 return true;
517}
518#endif
519
530void stopBlocking(QProcess &process) {
531#ifdef Q_OS_UNIX
532 const auto group = static_cast<pid_t>(process.processId());
533 const auto signalGroup = [group](int signal) {
534 if (group > 0) {
535 ::kill(-group, signal);
536 }
537 };
538 signalGroup(SIGTERM);
539#endif
540 process.terminate();
541 if (!process.waitForFinished(kBlockingKillGraceMs)) {
542#ifdef Q_OS_UNIX
543 signalGroup(SIGKILL);
544#endif
545 process.kill();
546 // SIGKILL cannot be ignored, but a child in uninterruptible sleep (a
547 // hung NFS or FUSE mount) dies only when the kernel lets it. Wait one
548 // more grace period, not forever: the run is reported as failed either
549 // way, and a blocking run then lasts at most its timeout plus twice the
550 // grace.
551 if (!process.waitForFinished(kBlockingKillGraceMs)) {
552 qCWarning(lcQtPass) << "Process still running after kill():"
553 << process.program();
554 }
555 }
556#ifdef Q_OS_UNIX
557 if (group > 0 && !waitForGroup(group, kBlockingKillGraceMs)) {
558 signalGroup(SIGKILL);
559 if (!waitForGroup(group, kBlockingKillGraceMs)) {
560 qCWarning(lcQtPass) << "Processes started by" << process.program()
561 << "still running after kill()";
562 }
563 }
564#endif
565}
566
571auto msecsLeft(const QDeadlineTimer &deadline) -> int {
572 if (deadline.isForever()) {
573 return -1;
574 }
575 return static_cast<int>(
576 std::clamp<qint64>(deadline.remainingTime(), 0, INT_MAX));
577}
578
588auto waitOrCancel(QProcess &process, const std::atomic_bool *cancel,
589 const QDeadlineTimer &deadline) -> bool {
590 if (cancel == nullptr) {
591 // waitForFinished() can also fail (a poll error) with the child still
592 // running; that is not completion either. Stop it rather than report
593 // it done.
594 if (!process.waitForFinished(msecsLeft(deadline)) &&
595 process.state() != QProcess::NotRunning) {
596 stopBlocking(process);
597 return false;
598 }
599 return true;
600 }
601 while (!process.waitForFinished(
602 deadline.isForever()
603 ? kBlockingCancelPollMs
604 : qMin(kBlockingCancelPollMs, msecsLeft(deadline)))) {
605 if (process.state() == QProcess::NotRunning) {
606 return true;
607 }
608 if (cancel->load() || deadline.hasExpired()) {
609 stopBlocking(process);
610 return false;
611 }
612 }
613 return true;
614}
615
616} // namespace
617
618auto Executor::runBlocking(QProcess &process, const QString &app,
619 const QStringList &args, const QString &input,
620 QString *process_out, QString *process_err,
621 const std::atomic_bool *cancel, int timeoutMs)
622 -> int {
623 QByteArray out;
624 const int rc = runBlockingRaw(process, app, args, input.toUtf8(),
625 process_out != nullptr ? &out : nullptr,
626 process_err, cancel, timeoutMs);
627 if (process_out != nullptr) {
628 *process_out = decodeAssumingUtf8(out);
629 }
630 return rc;
631}
632
633auto Executor::runBlockingRaw(QProcess &process, const QString &app,
634 const QStringList &args, const QByteArray &input,
635 QByteArray *process_out, QString *process_err,
636 const std::atomic_bool *cancel, int timeoutMs)
637 -> int {
638 if (cancel != nullptr && cancel->load())
639 return -1;
640 const QDeadlineTimer deadline = timeoutMs < 0
641 ? QDeadlineTimer(QDeadlineTimer::Forever)
642 : QDeadlineTimer(timeoutMs);
643 // Read as it arrives (QProcess emits these from inside its waitFor*()
644 // calls too), so neither channel piles up in QProcess's buffers: stderr
645 // into the cap, stdout nobody asked for into nothing. Wanted stdout is
646 // kept whole, as a decrypt must be lossless; gpg's --max-output bounds it.
647 CappedOutput err;
648 const QMetaObject::Connection errReader = QObject::connect(
649 &process, &QProcess::readyReadStandardError,
650 [&process, &err]() { err.append(process.readAllStandardError()); });
651 const QMetaObject::Connection outDropper =
652 process_out != nullptr
653 ? QMetaObject::Connection()
654 : QObject::connect(&process, &QProcess::readyReadStandardOutput,
655 [&process]() { process.readAllStandardOutput(); });
656 const auto disconnectReaders = qScopeGuard([&errReader, &outDropper]() {
657 QObject::disconnect(errReader);
658 QObject::disconnect(outDropper);
659 });
660 startProcess(process, app, args);
661 if (!process.waitForStarted(msecsLeft(deadline))) {
662 qCDebug(lcQtPass) << "Process failed to start:" << app;
663 if (process.state() != QProcess::NotRunning) {
664 stopBlocking(process);
665 }
666 return -1;
667 }
668 if (!input.isEmpty()) {
669 if (process.write(input) != input.length()) {
670 qCDebug(lcQtPass) << "Not all input written:" << app;
671 }
672 }
673 // Always close stdin so a child blocking on EOF doesn't hang.
674 process.closeWriteChannel();
675 if (!waitOrCancel(process, cancel, deadline)) {
676 return -1;
677 }
678 // Read before judging the exit: a process that crashed may have said why,
679 // as the queued path (onProcessFinished) keeps it too.
680 if (process_out != nullptr) {
681 *process_out = process.readAllStandardOutput();
682 }
683 if (process_err != nullptr) {
684 err.append(process.readAllStandardError());
685 *process_err = decodeAssumingUtf8(err.take());
686 }
687 return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
688}
689
690auto Executor::executeBlockingRaw(QProcess &process, const QString &app,
691 const QStringList &args,
692 const QByteArray &input,
693 QByteArray *process_out, QString *process_err,
694 const std::atomic_bool *cancel, int timeoutMs)
695 -> int {
696 return runBlockingRaw(process, app, args, input, process_out, process_err,
697 cancel, timeoutMs);
698}
699
700auto Executor::executeBlocking(const QString &app, const QStringList &args,
701 const QString &input, QString *process_out,
702 QString *process_err) -> int {
703 QProcess internal;
704 return runBlocking(internal, app, args, input, process_out, process_err);
705}
706
707auto Executor::executeBlocking(QProcess &process, const QString &app,
708 const QStringList &args, const QString &input,
709 QString *process_out, QString *process_err,
710 const std::atomic_bool *cancel, int timeoutMs)
711 -> int {
712 return runBlocking(process, app, args, input, process_out, process_err,
713 cancel, timeoutMs);
714}
715
716auto Executor::executeBlocking(const QString &app, const QStringList &args,
717 QString *process_out, QString *process_err)
718 -> int {
719 return executeBlocking(app, args, QString(), process_out, process_err);
720}
721
722auto Executor::executeBlocking(const QProcessEnvironment &env,
723 const QString &app, const QStringList &args,
724 QString *process_out, QString *process_err)
725 -> int {
726 QProcess process;
727 process.setProcessEnvironment(env);
728 return runBlocking(process, app, args, QString(), process_out, process_err);
729}
730
731void Executor::setEnvironment(const QProcessEnvironment &env) {
732 m_process.setProcessEnvironment(env);
733}
734
735auto Executor::environment() const -> QProcessEnvironment {
736 return m_process.processEnvironment();
737}
738
739auto Executor::stopRunning() -> bool {
740 if (!running || m_process.state() == QProcess::NotRunning) {
741 return false;
742 }
743 const qint64 pid = m_process.processId();
744 const quint64 run = m_runSerial;
745 // Reported as stopped whatever it exits with (onProcessFinished()): a
746 // command that exits 0 on SIGTERM did not do its work.
747 m_stoppedRun = run;
748 // Not blocking: finished() comes through the event loop as for any run,
749 // and the queue moves on from there.
750#ifdef Q_OS_UNIX
751 if (pid > 0) {
752 ::kill(-static_cast<pid_t>(pid), SIGTERM);
753 }
754#endif
755 m_process.terminate();
756 QTimer::singleShot(kBlockingKillGraceMs, this, [this, pid, run]() {
757 const bool stillThisRun =
758 running && m_runSerial == run && m_process.processId() == pid;
759#ifdef Q_OS_UNIX
760 // Also once the leader is gone: a child that ignored SIGTERM goes on in
761 // the old process group while the queue has moved on. Not when the pid
762 // came back as the next run's own (and so its group's) id. That a pid
763 // is taken within the grace by some other process that leads a group of
764 // its own is not ruled out: unlikely, and the price of reaching the
765 // child.
766 const bool pidReused =
767 !stillThisRun && running && m_process.processId() == pid;
768 if (pid > 0 && !pidReused) {
769 ::kill(-static_cast<pid_t>(pid), SIGKILL);
770 }
771#endif
772 if (stillThisRun) {
773 m_process.kill();
774 }
775 });
776 return true;
777}
778
779// Also -1 while the head is already running: that one is not cancelled.
780auto Executor::cancelNext() -> int {
781 if (running || m_execQueue.isEmpty()) {
782 return -1;
783 }
784 const int id = m_execQueue.dequeue().id;
785 // As in executeNext(): while the signal is out, a slot's cancelNext()
786 // drops nothing and its execute() only queues. Nothing is started here
787 // afterwards: the caller (ImitatePass dropping the rest of a failed
788 // transaction from its completion handler) may cancel again, and the
789 // queue moves on when that handler returns (onProcessFinished()).
790 running = true;
791 emit dequeuing(id, false);
792 running = false;
793 return id;
794}
795
797 QProcess::ExitStatus exitStatus) {
798 ExecQueueItem i = m_execQueue.dequeue();
799 running = false;
800 const bool stopped = m_stoppedRun != 0 && m_stoppedRun == m_runSerial;
801 m_stoppedRun = 0;
802 auto [output, err] = collectOutput(i, exitCode);
803 if (stopped) {
804 // A stopped run failed, also when it exited 0 on SIGTERM.
805 if (err.trimmed().isEmpty()) {
806 err = tr("%1 was stopped").arg(i.app);
807 }
808 emit error(i.id, -1, output, err);
809 m_outputLossless = true;
810 m_lastStatus.clear();
811 } else if (exitStatus == QProcess::NormalExit) {
812 if (exitCode != 0) {
813 qCDebug(lcQtPass) << i.app << "exited with" << exitCode << err;
814 }
815 emit finished(i.id, exitCode, output, err);
816 m_outputLossless = true;
817 m_lastStatus.clear();
818 } else {
819 // A signal-killed process usually leaves stderr empty; without this the
820 // password pane would show nothing at all for the failure.
821 if (err.trimmed().isEmpty()) {
822 err = tr("%1 crashed or was killed").arg(i.app);
823 }
824 // Qt leaves exitCode undefined after a CrashExit (the signal number on
825 // Unix), and Pass::finished gates on it: 0 would pass as success and 1
826 // as grep's "no matches". Report -1, like the failed-to-start path.
827 emit error(i.id, -1, output, err);
828 m_outputLossless = true;
829 m_lastStatus.clear();
830 }
831 executeNext();
833}
834
836 // One check at a time, run after what is emitted now; it fires only once
837 // nothing runs or waits and every posted error() of a failed start is
838 // out (the last of those posts the check again).
839 if (m_drainCheckPosted) {
840 return;
841 }
842 m_drainCheckPosted = true;
843 QMetaObject::invokeMethod(
844 this,
845 [this]() {
846 m_drainCheckPosted = false;
847 if (isIdle() && m_pendingErrors == 0) {
848 emit drained();
849 }
850 },
851 Qt::QueuedConnection);
852}
853
854auto Executor::collectOutput(const ExecQueueItem &item, int exitCode)
855 -> std::pair<QString, QString> {
856 QString output;
857 QString err;
858 m_outputLossless = true;
859 if (item.readStdout) {
860 output = decodeAssumingUtf8(m_process.readAllStandardOutput(),
862 }
863 m_stderr.append(m_process.readAllStandardError());
864 const QByteArray errBytes = m_stderr.take();
866 if (item.readStderr || exitCode != 0) {
867 err = decodeAssumingUtf8(errBytes);
868 }
869 return {output, err};
870}
A stream of bytes held as its first and last kMaxStderrBytes / 2 bytes, with its gpg status records c...
Definition executor.h:193
void clear()
Drop everything, counts included, for the next command.
Definition executor.h:221
QByteArray m_head
The first bytes, up to half the cap.
Definition executor.h:243
static constexpr qsizetype kMaxStatusLineBytes
Longest line still looked at for a status keyword.
Definition executor.h:226
void countStatus(const QByteArray &line)
Count line if it is a status record.
Definition executor.cpp:72
bool m_lineTooLong
The line not ended yet ran past kMaxStatusLineBytes.
Definition executor.h:239
static constexpr int kMaxStatusKeywords
Most distinct status keywords counted.
Definition executor.h:228
void append(const QByteArray &chunk)
Add what the process wrote next.
Definition executor.cpp:89
qint64 m_dropped
Bytes that fell out between head and tail.
Definition executor.h:247
QHash< QString, qint64 > m_status
Status keyword to count, see statusCounts().
Definition executor.h:241
auto take() -> QByteArray
Everything kept, and start over.
Definition executor.cpp:131
auto statusCounts() const -> QHash< QString, qint64 >
How many complete lines of each gpg status keyword came by since the last take(), the left-out ones i...
Definition executor.h:217
QByteArray m_line
The line not ended yet; empty once it ran too long.
Definition executor.h:237
QByteArray m_tail
The latest bytes, up to half the cap.
Definition executor.h:245
void postDrainedIfIdle()
Definition executor.cpp:835
void dequeuing(int id, bool completes)
Emitted, synchronously, when the queue's head leaves it: just before it is started,...
auto stopRunning() -> bool
Stop the command that is running, if any: terminate it (its whole process group on Unix),...
Definition executor.cpp:739
QQueue< ExecQueueItem > m_execQueue
Commands waiting to run, head first. The head stays queued while it runs and is dequeued in onProcess...
Definition executor.h:63
auto isIdle() const -> bool
Whether no command is running and nothing is queued.
Definition executor.h:620
static auto childUmask() -> int
The umask setChildUmask() set.
Definition executor.cpp:225
static constexpr qsizetype kMaxStderrBytes
Most bytes of a command's stderr kept: the first and the last half of this, with a note of how much w...
Definition executor.h:181
quint64 m_stoppedRun
Definition executor.h:96
static auto executeBlocking(const QString &app, const QStringList &args, const QString &input=QString(), QString *process_out=nullptr, QString *process_err=nullptr) -> int
Run a command synchronously and return its exit code.
Definition executor.cpp:700
static auto runBlockingRaw(QProcess &process, const QString &app, const QStringList &args, const QByteArray &input, QByteArray *process_out, QString *process_err, const std::atomic_bool *cancel=nullptr, int timeoutMs=-1) -> int
runBlocking() on bytes: input is written and stdout returned as they are, with no text decoding or en...
Definition executor.cpp:633
static auto translatePathForWsl(const QString &path, const QString &exe) -> QString
Translate a native path for a WSL-routed executable.
Definition executor.cpp:335
auto environment() const -> QProcessEnvironment
Return the environment passed to child processes.
Definition executor.cpp:735
bool m_discardStdout
The running queued command's stdout is not wanted: dropped as it comes.
Definition executor.h:259
void onProcessFinished(int exitCode, QProcess::ExitStatus exitStatus)
Finish the running item when its process exits.
Definition executor.cpp:796
int m_pendingErrors
Definition executor.h:88
auto collectOutput(const ExecQueueItem &item, int exitCode) -> std::pair< QString, QString >
Read what a finished process produced, according to the queue item's readStdout/readStderr flags; std...
Definition executor.cpp:854
CappedOutput m_stderr
stderr of the running queued command, read as it arrives and capped.
Definition executor.h:255
bool m_drainCheckPosted
A drained() check is posted and not run yet.
Definition executor.h:90
static void startProcess(QProcess &process, const QString &app, const QStringList &args)
Start process running app, handling the "wsl " prefix once for both the queued and the blocking path.
Definition executor.cpp:227
void execute(int id, const QString &app, const QStringList &args, bool readStdout, bool readStderr=true)
Queue a command without stdin input.
Definition executor.cpp:439
bool m_outputLossless
Definition executor.h:99
static auto resolveExecutable(const QString &app) -> QString
The one rule for turning a configured executable into what runs.
Definition executor.cpp:244
void drained()
Emitted once the last queued item is done and nothing runs or waits any more (isIdle()),...
~Executor() override
Stop listening to the running process, then end it.
Definition executor.cpp:179
void error(int id, int exitCode, const QString &output, const QString &errout)
Emitted instead of finished() when a queued process could not be started, had no executable configure...
static auto wslExecArgs(const QString &command, const QStringList &args) -> QStringList
Build the wsl.exe argument list that runs command directly.
Definition executor.cpp:330
static void setChildUmask(int mask)
The umask every child QtPass starts gets, as pass sets its own.
Definition executor.cpp:223
Executor(QObject *parent=nullptr)
Construct an Executor with an optional parent QObject.
Definition executor.cpp:33
QHash< QString, qint64 > m_lastStatus
lastStatusCounts(): set by collectOutput(), cleared after the emit.
Definition executor.h:257
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
bool running
Whether the head of the queue has been started (or is being dequeued, see dequeuing()) and has not fi...
Definition executor.h:70
void finished(int id, int exitCode, const QString &output, const QString &errout)
Emitted when a queued process exits normally, whatever its exit code; a non-zero code is the receiver...
void starting()
Emitted just before a queued process is started; the main window shows the busy indicator on it.
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
quint64 m_runSerial
Definition executor.h:93
void setEnvironment(const QProcessEnvironment &env)
Set the environment passed to all child processes.
Definition executor.cpp:731
static auto runBlocking(QProcess &process, const QString &app, const QStringList &args, const QString &input, QString *process_out, QString *process_err, const std::atomic_bool *cancel=nullptr, int timeoutMs=-1) -> int
Shared blocking run: start process, optionally feed input on stdin, wait, and capture stdout/stderr....
Definition executor.cpp:618
static void detachFromTerminal(QProcess &process)
Make process start its child without a controlling terminal.
Definition executor.cpp:192
void executeNext()
Start the head of the queue unless something runs or the queue is empty.
Definition executor.cpp:359
static auto parseWslCommand(const QString &app) -> std::optional< WslCommand >
Parse a configured executable as a WSL command.
Definition executor.cpp:272
auto cancelNext() -> int
Cancel the next queued command without executing it.
Definition executor.cpp:780
QProcess m_process
The one process object; every queued command reuses it.
Definition executor.h:65
Executor, the FIFO queue every gpg, git and pass child process of QtPass goes through,...
The "qtpass" logging category.
Execution queue item for non-interactive ordered execution.
Definition executor.h:39
bool readStdout
Whether stdout is captured for finished().
Definition executor.h:49
QString workingDir
Working directory to start in; empty for the current one.
Definition executor.h:56
QString input
Data written to the process's stdin, then closed.
Definition executor.h:47
int id
Identifier the caller gave; echoed in finished()/error().
Definition executor.h:41
QStringList args
Arguments for the executable.
Definition executor.h:45
QString app
Executable as configured; resolved when started.
Definition executor.h:43
A configured executable that runs a Linux program through WSL.
Definition executor.h:484
auto argv(const QStringList &args) const -> QStringList
Arguments for launcher that run command with args.
Definition executor.cpp:264
QString command
The Linux program to run, looked up on the WSL PATH.
Definition executor.h:500
QString launcher
What to start.
Definition executor.h:493
QStringList options
wsl.exe options that go before the program (-d Debian, -u me), without any -e/--exec: argv() always a...
Definition executor.h:498
auto with(const QString &program) const -> WslCommand
The same launcher and options running another program.
Definition executor.cpp:268