4#include <QCoreApplication>
5#include <QDeadlineTimer>
9#include <QStringDecoder>
25std::atomic_int g_childUmask{-1};
27constexpr int kBlockingCancelPollMs = 100;
30constexpr int kBlockingKillGraceMs = 1000;
38 connect(&
m_process, &QProcess::readyReadStandardError,
this,
40 connect(&
m_process, &QProcess::readyReadStandardOutput,
this, [
this]() {
54auto utf8SequenceLength(
unsigned char lead) ->
int {
58 if ((lead & 0xC0) == 0x80) {
61 if ((lead & 0xE0) == 0xC0) {
64 if ((lead & 0xF0) == 0xE0) {
73 static const QByteArray prefix = QByteArrayLiteral(
"[GNUPG:] ");
74 if (!line.startsWith(prefix)) {
77 QByteArray keyword = line.mid(prefix.size());
78 keyword.truncate(keyword.indexOf(
' ') < 0 ? keyword.size()
79 : keyword.indexOf(
' '));
80 if (keyword.endsWith(
'\r')) {
83 const QString key = QString::fromLatin1(keyword);
92 for (qsizetype end = chunk.indexOf(
'\n'); end >= 0;
93 start = end + 1, end = chunk.indexOf(
'\n', start)) {
96 m_line.append(chunk.constData() + start, end - start);
107 m_line.append(chunk.constData() + start, chunk.size() - start);
113 if (
m_head.size() < half) {
114 from = qMin(half -
m_head.size(), chunk.size());
115 m_head.append(chunk.constData(), from);
117 if (from == chunk.size()) {
120 m_tail.append(chunk.constData() + from, chunk.size() - from);
121 if (
m_tail.size() > half) {
122 const qsizetype excess =
m_tail.size() - half;
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)));
150 while (start <
m_tail.size() &&
151 utf8SequenceLength(
static_cast<unsigned char>(
m_tail.at(start))) ==
155 all = head + QByteArrayLiteral(
"\n[... ") +
156 QByteArray::number(
m_dropped + chopped + start) +
157 QByteArrayLiteral(
" bytes left out ...]\n") +
m_tail.mid(start);
176constexpr int killWaitMs = 5000;
186 if (
m_process.state() != QProcess::NotRunning) {
188 static_cast<void>(
m_process.waitForFinished(killWaitMs));
193#if defined(Q_OS_UNIX) && QT_VERSION >= QT_VERSION_CHECK(6, 7, 0)
215 QProcess::UnixProcessParameters params = process.unixProcessParameters();
216 params.flags |= QProcess::UnixProcessFlag::CreateNewSession;
217 process.setUnixProcessParameters(params);
228 const QStringList &args) {
232 if (
const int mask = g_childUmask.load(); mask >= 0) {
233 process.setChildProcessModifier(
234 [mask] { ::umask(
static_cast<mode_t
>(mask)); });
238 process.start(wsl->launcher, wsl->argv(args));
245 if (app.isEmpty() || QDir::isAbsolutePath(app)) {
248 const QDir appDir(QCoreApplication::applicationDirPath());
249 QStringList candidates{QDir::cleanPath(appDir.absoluteFilePath(app))};
251 candidates << QDir::cleanPath(
252 appDir.absoluteFilePath(app + QStringLiteral(
".exe")));
254 for (
const QString &candidate : std::as_const(candidates)) {
256 const QFileInfo info(candidate);
257 if (info.isFile() && info.isExecutable()) {
265 return options + QStringList{QStringLiteral(
"--exec"),
command} + args;
273 -> std::optional<WslCommand> {
274 const QStringList parts = QProcess::splitCommand(app);
275 if (parts.size() < 2) {
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);
285 launcherName.compare(QLatin1String(
"wsl"), Qt::CaseInsensitive) == 0 ||
286 launcherName.compare(QLatin1String(
"wsl.exe"), Qt::CaseInsensitive) == 0;
294 wsl.
launcher = separator < 0 ? QStringLiteral(
"wsl") : launcher;
302 static const QStringList valued{
303 QStringLiteral(
"-d"), QStringLiteral(
"--distribution"),
304 QStringLiteral(
"-u"), QStringLiteral(
"--user"),
305 QStringLiteral(
"--cd"), QStringLiteral(
"--shell-type")};
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")) {
312 if (valued.contains(option)) {
313 if (i + 1 >= parts.size()) {
316 wsl.
options << option << parts.at(++i);
323 if (i != parts.size() - 1) {
337 QString normalizedPath = QDir::cleanPath(path);
340 return normalizedPath;
343 const auto wslpath = wsl->with(QStringLiteral(
"wslpath"));
345 wslpath.argv({normalizedPath}), &wslPath);
349 QString translated = std::move(wslPath);
350 if (translated.endsWith(QLatin1Char(
'\n'))) {
353 if (translated.endsWith(QLatin1Char(
'\r'))) {
356 return (rc == 0 && !translated.isEmpty()) ? translated : normalizedPath;
378 if (i.
app.isEmpty()) {
379 qCDebug(lcQtPass) <<
"No executable set for:" << i.
id;
380 const int failedId = i.
id;
384 QMetaObject::invokeMethod(
387 emit
error(failedId, -1, QString(),
388 tr(
"No executable configured for this command"));
393 Qt::QueuedConnection);
409 qCDebug(lcQtPass) <<
"Process failed to start:" << i.
id <<
" " << i.
app;
410 const int failedId = i.
id;
411 const QString failedApp = i.
app;
416 QMetaObject::invokeMethod(
418 [
this, failedId, failedApp]() {
419 emit
error(failedId, -1, QString(),
420 tr(
"Failed to start %1").arg(failedApp));
425 Qt::QueuedConnection);
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 <<
" "
440 bool readStdout,
bool readStderr) {
441 execute(
id, QString(), app, args, QString(), readStdout, readStderr);
445 const QStringList &args,
bool readStdout,
447 execute(
id, workDir, app, args, QString(), readStdout, readStderr);
451 QString input,
bool readStdout,
bool readStderr) {
452 execute(
id, QString(), app, args, std::move(input), readStdout, readStderr);
456 const QStringList &args, QString input,
bool readStdout,
461 {id, app, args, std::move(input), readStdout, readStderr, workDir});
472static auto decodeAssumingUtf8(
const QByteArray &in,
bool *lossless =
nullptr)
477 QStringDecoder(QStringDecoder::Utf8, QStringDecoder::Flag::Stateless);
478 QString out = converter(in);
479 if (converter.hasError()) {
481 QStringDecoder(QStringDecoder::System, QStringDecoder::Flag::Stateless);
484 if (lossless !=
nullptr) {
485 *lossless = out.toUtf8() == in;
491 return decodeAssumingUtf8(bytes);
506auto waitForGroup(pid_t group,
int ms) ->
bool {
507 QDeadlineTimer deadline(ms);
510 while (::kill(-group, 0) == 0) {
511 if (deadline.hasExpired()) {
530void stopBlocking(QProcess &process) {
532 const auto group =
static_cast<pid_t
>(process.processId());
533 const auto signalGroup = [group](
int signal) {
535 ::kill(-group, signal);
538 signalGroup(SIGTERM);
541 if (!process.waitForFinished(kBlockingKillGraceMs)) {
543 signalGroup(SIGKILL);
551 if (!process.waitForFinished(kBlockingKillGraceMs)) {
552 qCWarning(lcQtPass) <<
"Process still running after kill():"
553 << process.program();
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()";
571auto msecsLeft(
const QDeadlineTimer &deadline) ->
int {
572 if (deadline.isForever()) {
575 return static_cast<int>(
576 std::clamp<qint64>(deadline.remainingTime(), 0, INT_MAX));
588auto waitOrCancel(QProcess &process,
const std::atomic_bool *cancel,
589 const QDeadlineTimer &deadline) ->
bool {
590 if (cancel ==
nullptr) {
594 if (!process.waitForFinished(msecsLeft(deadline)) &&
595 process.state() != QProcess::NotRunning) {
596 stopBlocking(process);
601 while (!process.waitForFinished(
603 ? kBlockingCancelPollMs
604 : qMin(kBlockingCancelPollMs, msecsLeft(deadline)))) {
605 if (process.state() == QProcess::NotRunning) {
608 if (cancel->load() || deadline.hasExpired()) {
609 stopBlocking(process);
619 const QStringList &args,
const QString &input,
620 QString *process_out, QString *process_err,
621 const std::atomic_bool *cancel,
int timeoutMs)
625 process_out !=
nullptr ? &out :
nullptr,
626 process_err, cancel, timeoutMs);
627 if (process_out !=
nullptr) {
628 *process_out = decodeAssumingUtf8(out);
634 const QStringList &args,
const QByteArray &input,
635 QByteArray *process_out, QString *process_err,
636 const std::atomic_bool *cancel,
int timeoutMs)
638 if (cancel !=
nullptr && cancel->load())
640 const QDeadlineTimer deadline = timeoutMs < 0
641 ? QDeadlineTimer(QDeadlineTimer::Forever)
642 : QDeadlineTimer(timeoutMs);
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);
661 if (!process.waitForStarted(msecsLeft(deadline))) {
662 qCDebug(lcQtPass) <<
"Process failed to start:" << app;
663 if (process.state() != QProcess::NotRunning) {
664 stopBlocking(process);
668 if (!input.isEmpty()) {
669 if (process.write(input) != input.length()) {
670 qCDebug(lcQtPass) <<
"Not all input written:" << app;
674 process.closeWriteChannel();
675 if (!waitOrCancel(process, cancel, deadline)) {
680 if (process_out !=
nullptr) {
681 *process_out = process.readAllStandardOutput();
683 if (process_err !=
nullptr) {
684 err.
append(process.readAllStandardError());
685 *process_err = decodeAssumingUtf8(err.
take());
687 return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
691 const QStringList &args,
692 const QByteArray &input,
693 QByteArray *process_out, QString *process_err,
694 const std::atomic_bool *cancel,
int timeoutMs)
696 return runBlockingRaw(process, app, args, input, process_out, process_err,
701 const QString &input, QString *process_out,
702 QString *process_err) ->
int {
704 return runBlocking(internal, app, args, input, process_out, process_err);
708 const QStringList &args,
const QString &input,
709 QString *process_out, QString *process_err,
710 const std::atomic_bool *cancel,
int timeoutMs)
712 return runBlocking(process, app, args, input, process_out, process_err,
717 QString *process_out, QString *process_err)
719 return executeBlocking(app, args, QString(), process_out, process_err);
723 const QString &app,
const QStringList &args,
724 QString *process_out, QString *process_err)
727 process.setProcessEnvironment(env);
728 return runBlocking(process, app, args, QString(), process_out, process_err);
743 const qint64 pid =
m_process.processId();
752 ::kill(-
static_cast<pid_t
>(pid), SIGTERM);
756 QTimer::singleShot(kBlockingKillGraceMs,
this, [
this, pid, run]() {
757 const bool stillThisRun =
766 const bool pidReused =
768 if (pid > 0 && !pidReused) {
769 ::kill(-
static_cast<pid_t
>(pid), SIGKILL);
797 QProcess::ExitStatus exitStatus) {
805 if (err.trimmed().isEmpty()) {
806 err = tr(
"%1 was stopped").arg(i.
app);
808 emit
error(i.
id, -1, output, err);
811 }
else if (exitStatus == QProcess::NormalExit) {
813 qCDebug(lcQtPass) << i.
app <<
"exited with" << exitCode << err;
821 if (err.trimmed().isEmpty()) {
822 err = tr(
"%1 crashed or was killed").arg(i.
app);
827 emit
error(i.
id, -1, output, err);
843 QMetaObject::invokeMethod(
851 Qt::QueuedConnection);
855 -> std::pair<QString, QString> {
859 if (item.readStdout) {
860 output = decodeAssumingUtf8(
m_process.readAllStandardOutput(),
866 if (item.readStderr || exitCode != 0) {
867 err = decodeAssumingUtf8(errBytes);
869 return {output, err};
A stream of bytes held as its first and last kMaxStderrBytes / 2 bytes, with its gpg status records c...
void clear()
Drop everything, counts included, for the next command.
QByteArray m_head
The first bytes, up to half the cap.
static constexpr qsizetype kMaxStatusLineBytes
Longest line still looked at for a status keyword.
void countStatus(const QByteArray &line)
Count line if it is a status record.
bool m_lineTooLong
The line not ended yet ran past kMaxStatusLineBytes.
static constexpr int kMaxStatusKeywords
Most distinct status keywords counted.
void append(const QByteArray &chunk)
Add what the process wrote next.
qint64 m_dropped
Bytes that fell out between head and tail.
QHash< QString, qint64 > m_status
Status keyword to count, see statusCounts().
auto take() -> QByteArray
Everything kept, and start over.
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...
QByteArray m_line
The line not ended yet; empty once it ran too long.
QByteArray m_tail
The latest bytes, up to half the cap.
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),...
QQueue< ExecQueueItem > m_execQueue
Commands waiting to run, head first. The head stays queued while it runs and is dequeued in onProcess...
auto isIdle() const -> bool
Whether no command is running and nothing is queued.
static auto childUmask() -> int
The umask setChildUmask() set.
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...
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.
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...
static auto translatePathForWsl(const QString &path, const QString &exe) -> QString
Translate a native path for a WSL-routed executable.
auto environment() const -> QProcessEnvironment
Return the environment passed to child processes.
bool m_discardStdout
The running queued command's stdout is not wanted: dropped as it comes.
void onProcessFinished(int exitCode, QProcess::ExitStatus exitStatus)
Finish the running item when its process exits.
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...
CappedOutput m_stderr
stderr of the running queued command, read as it arrives and capped.
bool m_drainCheckPosted
A drained() check is posted and not run yet.
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.
void execute(int id, const QString &app, const QStringList &args, bool readStdout, bool readStderr=true)
Queue a command without stdin input.
static auto resolveExecutable(const QString &app) -> QString
The one rule for turning a configured executable into what runs.
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.
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.
static void setChildUmask(int mask)
The umask every child QtPass starts gets, as pass sets its own.
Executor(QObject *parent=nullptr)
Construct an Executor with an optional parent QObject.
QHash< QString, qint64 > m_lastStatus
lastStatusCounts(): set by collectOutput(), cleared after the emit.
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...
bool running
Whether the head of the queue has been started (or is being dequeued, see dequeuing()) and has not fi...
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-...
void setEnvironment(const QProcessEnvironment &env)
Set the environment passed to all child processes.
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....
static void detachFromTerminal(QProcess &process)
Make process start its child without a controlling terminal.
void executeNext()
Start the head of the queue unless something runs or the queue is empty.
static auto parseWslCommand(const QString &app) -> std::optional< WslCommand >
Parse a configured executable as a WSL command.
auto cancelNext() -> int
Cancel the next queued command without executing it.
QProcess m_process
The one process object; every queued command reuses it.
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.
bool readStdout
Whether stdout is captured for finished().
QString workingDir
Working directory to start in; empty for the current one.
QString input
Data written to the process's stdin, then closed.
int id
Identifier the caller gave; echoed in finished()/error().
QStringList args
Arguments for the executable.
QString app
Executable as configured; resolved when started.
A configured executable that runs a Linux program through WSL.
auto argv(const QStringList &args) const -> QStringList
Arguments for launcher that run command with args.
QString command
The Linux program to run, looked up on the WSL PATH.
QString launcher
What to start.
QStringList options
wsl.exe options that go before the program (-d Debian, -u me), without any -e/--exec: argv() always a...
auto with(const QString &program) const -> WslCommand
The same launcher and options running another program.