Branch data Line data Source code
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 : 574 : Executor::Executor(QObject *parent) : QObject(parent) {
34 : 574 : connect(&m_process, &QProcess::finished, this, &Executor::onProcessFinished);
35 : 574 : 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 : 574 : connect(&m_process, &QProcess::readyReadStandardError, this,
39 [ + + ]: 3278 : [this]() { m_stderr.append(m_process.readAllStandardError()); });
40 : 574 : connect(&m_process, &QProcess::readyReadStandardOutput, this, [this]() {
41 [ + + ]: 167 : if (m_discardStdout) {
42 : 4 : m_process.readAllStandardOutput();
43 : : }
44 : 167 : });
45 : 574 : }
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 : 16 : auto utf8SequenceLength(unsigned char lead) -> int {
55 [ + + ]: 16 : if (lead < 0x80) {
56 : : return 1;
57 : : }
58 [ + - ]: 2 : if ((lead & 0xC0) == 0x80) {
59 : : return 0;
60 : : }
61 [ - + ]: 2 : if ((lead & 0xE0) == 0xC0) {
62 : : return 2;
63 : : }
64 [ # # ]: 0 : if ((lead & 0xF0) == 0xE0) {
65 : 0 : return 3;
66 : : }
67 : : return 4;
68 : : }
69 : :
70 : : } // namespace
71 : :
72 : 268730 : void Executor::CappedOutput::countStatus(const QByteArray &line) {
73 : 268732 : static const QByteArray prefix = QByteArrayLiteral("[GNUPG:] ");
74 [ + + ]: 268730 : if (!line.startsWith(prefix)) {
75 : 249377 : return;
76 : : }
77 : 19353 : QByteArray keyword = line.mid(prefix.size());
78 [ + + + ]: 23536 : keyword.truncate(keyword.indexOf(' ') < 0 ? keyword.size()
79 : : : keyword.indexOf(' '));
80 : : if (keyword.endsWith('\r')) {
81 : 6001 : keyword.chop(1);
82 : : }
83 : : const QString key = QString::fromLatin1(keyword);
84 [ + + + + ]: 19589 : if (m_status.contains(key) || m_status.size() < kMaxStatusKeywords) {
85 : 19348 : ++m_status[key];
86 : : }
87 : : }
88 : :
89 : 5581 : void Executor::CappedOutput::append(const QByteArray &chunk) {
90 : : // Status records, whole lines at a time, before the text is cut.
91 : : qsizetype start = 0;
92 [ + + ]: 274311 : for (qsizetype end = chunk.indexOf('\n'); end >= 0;
93 : 268730 : start = end + 1, end = chunk.indexOf('\n', start)) {
94 [ + + ]: 268730 : if (!m_lineTooLong &&
95 [ + + ]: 268729 : m_line.size() + (end - start) <= kMaxStatusLineBytes) {
96 : 537456 : m_line.append(chunk.constData() + start, end - start);
97 : 268728 : countStatus(m_line);
98 : : }
99 : 268730 : m_line.clear();
100 : 268730 : m_lineTooLong = false;
101 : : }
102 [ + + ]: 5581 : if (!m_lineTooLong) {
103 [ + + ]: 5502 : if (m_line.size() + (chunk.size() - start) > kMaxStatusLineBytes) {
104 : 2 : m_line.clear();
105 : 2 : m_lineTooLong = true;
106 : : } else {
107 : 9606 : m_line.append(chunk.constData() + start, chunk.size() - start);
108 : : }
109 : : }
110 : :
111 : : constexpr qsizetype half = kMaxStderrBytes / 2;
112 : : qsizetype from = 0;
113 [ + + ]: 5581 : if (m_head.size() < half) {
114 : 2484 : from = qMin(half - m_head.size(), chunk.size());
115 : 3580 : m_head.append(chunk.constData(), from);
116 : : }
117 [ + + ]: 5581 : if (from == chunk.size()) {
118 : : return;
119 : : }
120 : 9294 : m_tail.append(chunk.constData() + from, chunk.size() - from);
121 [ + + ]: 3098 : if (m_tail.size() > half) {
122 : 2591 : const qsizetype excess = m_tail.size() - half;
123 : 2591 : m_dropped += excess;
124 : 2591 : 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.
131 : 1918 : auto Executor::CappedOutput::take() -> QByteArray {
132 : 1918 : QByteArray all;
133 [ + + ]: 1918 : if (m_dropped == 0) {
134 : 3820 : all = m_head + m_tail;
135 : : } else {
136 : : QByteArray head = m_head;
137 : : qsizetype chopped = 0;
138 [ + - ]: 8 : for (qsizetype back = 1; back <= qMin<qsizetype>(4, head.size()); ++back) {
139 : 8 : const int length = utf8SequenceLength(
140 [ + - ]: 8 : static_cast<unsigned char>(head.at(head.size() - back)));
141 [ + - ]: 8 : if (length != 0) {
142 [ + + ]: 8 : if (length > back) {
143 : : chopped = back;
144 : 1 : head.chop(back);
145 : : }
146 : : break;
147 : : }
148 : : }
149 : : qsizetype start = 0;
150 [ + - ]: 8 : while (start < m_tail.size() &&
151 [ - + ]: 8 : utf8SequenceLength(static_cast<unsigned char>(m_tail.at(start))) ==
152 : : 0) {
153 : 0 : ++start;
154 : : }
155 : 16 : all = head + QByteArrayLiteral("\n[... ") +
156 : 24 : QByteArray::number(m_dropped + chopped + start) +
157 : 24 : QByteArrayLiteral(" bytes left out ...]\n") + m_tail.mid(start);
158 : : }
159 : 1918 : m_head.clear();
160 : 1918 : m_tail.clear();
161 : 1918 : m_dropped = 0;
162 : : // A last line without a line end is a record too.
163 [ + + + + ]: 1918 : if (!m_lineTooLong && !m_line.isEmpty()) {
164 : 2 : countStatus(m_line);
165 : : }
166 : 1918 : m_line.clear();
167 : 1918 : m_lineTooLong = false;
168 : 1918 : return all;
169 : : }
170 : :
171 : : namespace {
172 : : /**
173 : : * @brief How long ~Executor waits for a killed command to be gone, in
174 : : * milliseconds.
175 : : */
176 : : constexpr int killWaitMs = 5000;
177 : : } // namespace
178 : :
179 : 575 : Executor::~Executor() {
180 : 574 : 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 [ + + ]: 574 : if (m_process.state() != QProcess::NotRunning) {
187 : 7 : m_process.kill();
188 : 7 : static_cast<void>(m_process.waitForFinished(killWaitMs));
189 : : }
190 : 1149 : }
191 : :
192 : 3572 : void 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 : 3572 : QProcess::UnixProcessParameters params = process.unixProcessParameters();
216 : : params.flags |= QProcess::UnixProcessFlag::CreateNewSession;
217 : 3572 : process.setUnixProcessParameters(params);
218 : : #else
219 : : Q_UNUSED(process);
220 : : #endif
221 : 3572 : }
222 : :
223 : 5 : void Executor::setChildUmask(int mask) { g_childUmask.store(mask); }
224 : :
225 : 31 : auto Executor::childUmask() -> int { return g_childUmask.load(); }
226 : :
227 : 3566 : void Executor::startProcess(QProcess &process, const QString &app,
228 : : const QStringList &args) {
229 : 3566 : detachFromTerminal(process);
230 : : #ifdef Q_OS_UNIX
231 : : // In the child, between fork and exec: umask() is async-signal-safe.
232 [ + + ]: 3566 : if (const int mask = g_childUmask.load(); mask >= 0) {
233 : 1 : process.setChildProcessModifier(
234 : 1 : [mask] { ::umask(static_cast<mode_t>(mask)); });
235 : : }
236 : : #endif
237 [ + + ]: 3566 : if (const auto wsl = parseWslCommand(app)) {
238 : 18 : process.start(wsl->launcher, wsl->argv(args));
239 : : } else {
240 : 7114 : process.start(resolveExecutable(app), args);
241 : : }
242 : 3566 : }
243 : :
244 : 3563 : auto Executor::resolveExecutable(const QString &app) -> QString {
245 [ + + + + ]: 7125 : if (app.isEmpty() || QDir::isAbsolutePath(app)) {
246 : : return app;
247 : : }
248 : 76 : const QDir appDir(QCoreApplication::applicationDirPath());
249 : 304 : 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 [ + + ]: 149 : for (const QString &candidate : std::as_const(candidates)) {
255 : : // A stray non-executable file of that name must not mask PATH.
256 : 76 : const QFileInfo info(candidate);
257 [ + + + + : 76 : if (info.isFile() && info.isExecutable()) {
+ + ]
258 : : return candidate;
259 : : }
260 : 76 : }
261 : : return app;
262 : 152 : }
263 : :
264 : 35 : auto Executor::WslCommand::argv(const QStringList &args) const -> QStringList {
265 : 140 : return options + QStringList{QStringLiteral("--exec"), command} + args;
266 : : }
267 : :
268 : 12 : auto Executor::WslCommand::with(const QString &program) const -> WslCommand {
269 : 12 : return {launcher, options, program};
270 : : }
271 : :
272 : 5822 : auto Executor::parseWslCommand(const QString &app)
273 : : -> std::optional<WslCommand> {
274 : 5822 : const QStringList parts = QProcess::splitCommand(app);
275 [ + + ]: 5822 : if (parts.size() < 2) {
276 : 5777 : 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 : 45 : const qsizetype separator = std::max(launcher.lastIndexOf(QLatin1Char('/')),
282 : 45 : launcher.lastIndexOf(QLatin1Char('\\')));
283 : 45 : const QString launcherName = launcher.mid(separator + 1);
284 : : const bool isWsl =
285 [ + + + + ]: 58 : launcherName.compare(QLatin1String("wsl"), Qt::CaseInsensitive) == 0 ||
286 : 13 : launcherName.compare(QLatin1String("wsl.exe"), Qt::CaseInsensitive) == 0;
287 : : if (!isWsl) {
288 : 3 : return std::nullopt;
289 : : }
290 : 42 : 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 : 42 : 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 : 2 : QStringLiteral("-d"), QStringLiteral("--distribution"),
304 : 2 : QStringLiteral("-u"), QStringLiteral("--user"),
305 : 58 : QStringLiteral("--cd"), QStringLiteral("--shell-type")};
306 : : qsizetype i = 1;
307 [ + + + + : 59 : for (; i < parts.size() && parts.at(i).startsWith(QLatin1Char('-')); ++i) {
+ + + +
+ ]
308 : : const QString &option = parts.at(i);
309 [ + + + + ]: 18 : if (option == QLatin1String("-e") || option == QLatin1String("--exec")) {
310 : 7 : continue;
311 : : }
312 [ + - ]: 11 : if (valued.contains(option)) {
313 [ + + ]: 11 : if (i + 1 >= parts.size()) {
314 : 1 : 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 [ + + ]: 41 : if (i != parts.size() - 1) {
324 : 6 : return std::nullopt;
325 : : }
326 : 35 : wsl.command = parts.at(i);
327 : : return wsl;
328 : 42 : }
329 : :
330 : 2 : auto Executor::wslExecArgs(const QString &command, const QStringList &args)
331 : : -> QStringList {
332 : 2 : return WslCommand{QStringLiteral("wsl"), {}, command}.argv(args);
333 : : }
334 : :
335 : 1708 : auto Executor::translatePathForWsl(const QString &path, const QString &exe)
336 : : -> QString {
337 : 1708 : QString normalizedPath = QDir::cleanPath(path);
338 : 1708 : const auto wsl = parseWslCommand(exe);
339 [ + + ]: 1708 : if (!wsl) {
340 : 1704 : return normalizedPath;
341 : : }
342 : 4 : QString wslPath;
343 : 8 : const auto wslpath = wsl->with(QStringLiteral("wslpath"));
344 : 4 : const int rc = executeBlocking(wslpath.launcher,
345 [ + + + + : 12 : 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 [ + + - ]: 4 : if (translated.endsWith(QLatin1Char('\n'))) {
351 : 4 : translated.chop(1);
352 : : }
353 [ + - + ]: 4 : if (translated.endsWith(QLatin1Char('\r'))) {
354 : 0 : translated.chop(1);
355 : : }
356 [ + - - + ]: 4 : return (rc == 0 && !translated.isEmpty()) ? translated : normalizedPath;
357 : 4 : }
358 : :
359 : 1000 : void Executor::executeNext() {
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 [ + + + + : 1000 : if (running || m_pendingErrors > 0 || m_execQueue.isEmpty()) {
+ + ]
366 : 516 : 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 : 496 : const ExecQueueItem i = m_execQueue.head();
372 : 496 : running = true;
373 : 496 : ++m_runSerial;
374 : 496 : 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 [ + + ]: 496 : if (i.app.isEmpty()) {
379 : 6 : qCDebug(lcQtPass) << "No executable set for:" << i.id;
380 : 6 : const int failedId = i.id;
381 : 6 : running = false;
382 : 6 : m_execQueue.dequeue();
383 : 6 : ++m_pendingErrors;
384 : 6 : QMetaObject::invokeMethod(
385 : : this,
386 : 6 : [this, failedId]() {
387 : 12 : emit error(failedId, -1, QString(),
388 : 6 : tr("No executable configured for this command"));
389 : 6 : --m_pendingErrors;
390 : 6 : executeNext();
391 : 6 : postDrainedIfIdle();
392 : 6 : },
393 : : Qt::QueuedConnection);
394 : 6 : 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 : 490 : m_process.setWorkingDirectory(i.workingDir);
400 : 490 : m_stderr.clear();
401 : 490 : m_discardStdout = !i.readStdout;
402 : 490 : startProcess(m_process, i.app, i.args);
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 [ + + + ]: 490 : if (!m_process.waitForStarted(-1)) {
409 : 6 : qCDebug(lcQtPass) << "Process failed to start:" << i.id << " " << i.app;
410 : 6 : const int failedId = i.id;
411 : : const QString failedApp = i.app;
412 : 6 : m_process.closeWriteChannel();
413 : 6 : running = false;
414 : 6 : m_execQueue.dequeue();
415 : 6 : ++m_pendingErrors;
416 : 6 : QMetaObject::invokeMethod(
417 : : this,
418 : 18 : [this, failedId, failedApp]() {
419 : 18 : emit error(failedId, -1, QString(),
420 : 12 : tr("Failed to start %1").arg(failedApp));
421 : 6 : --m_pendingErrors;
422 : 6 : executeNext();
423 : 6 : postDrainedIfIdle();
424 : 6 : },
425 : : Qt::QueuedConnection);
426 : : return;
427 : : }
428 : :
429 [ + + ]: 484 : if (!i.input.isEmpty()) {
430 : : QByteArray data = i.input.toUtf8();
431 [ + - + ]: 128 : if (m_process.write(data) != data.length()) {
432 : 0 : qCDebug(lcQtPass) << "Not all data written to process:" << i.id << " "
433 : 0 : << i.app;
434 : : }
435 : : }
436 : 484 : m_process.closeWriteChannel();
437 : 496 : }
438 : :
439 : 95 : void Executor::execute(int id, const QString &app, const QStringList &args,
440 : : bool readStdout, bool readStderr) {
441 : 190 : execute(id, QString(), app, args, QString(), readStdout, readStderr);
442 : 95 : }
443 : :
444 : 2 : void Executor::execute(int id, const QString &workDir, const QString &app,
445 : : const QStringList &args, bool readStdout,
446 : : bool readStderr) {
447 : 2 : execute(id, workDir, app, args, QString(), readStdout, readStderr);
448 : 2 : }
449 : :
450 : 3 : void Executor::execute(int id, const QString &app, const QStringList &args,
451 : : QString input, bool readStdout, bool readStderr) {
452 : 6 : execute(id, QString(), app, args, std::move(input), readStdout, readStderr);
453 : 3 : }
454 : :
455 : 511 : void 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 : 511 : m_execQueue.push_back(
461 : : {id, app, args, std::move(input), readStdout, readStderr, workDir});
462 : 511 : executeNext();
463 : 1533 : }
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.
472 : 4112 : static 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 : 4112 : auto converter =
477 : : QStringDecoder(QStringDecoder::Utf8, QStringDecoder::Flag::Stateless);
478 : 4112 : QString out = converter(in);
479 [ + + ]: 4112 : if (converter.hasError()) {
480 : 4 : auto fallback =
481 : : QStringDecoder(QStringDecoder::System, QStringDecoder::Flag::Stateless);
482 : 8 : out = fallback(in);
483 : : }
484 [ + + ]: 4112 : if (lossless != nullptr) {
485 : 425 : *lossless = out.toUtf8() == in;
486 : : }
487 : 4112 : return out;
488 : : }
489 : :
490 : 387 : auto Executor::decodeText(const QByteArray &bytes) -> QString {
491 : 387 : return decodeAssumingUtf8(bytes);
492 : : }
493 : :
494 : : // Returns an error code rather than throwing, matching QtPass's error
495 : : // handling elsewhere.
496 : : namespace {
497 : :
498 : : #ifdef Q_OS_UNIX
499 : : /**
500 : : * @brief Wait up to @p ms for every process in group @p group to exit.
501 : : * @param group A process group id; the child's own pid, as it leads a
502 : : * session of its own (Executor::detachFromTerminal()).
503 : : * @param ms Most milliseconds to wait.
504 : : * @return true once the group is empty.
505 : : */
506 : 20 : auto waitForGroup(pid_t group, int ms) -> bool {
507 : 20 : 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 [ + + ]: 27 : while (::kill(-group, 0) == 0) {
511 [ + - ]: 7 : if (deadline.hasExpired()) {
512 : : return false;
513 : : }
514 : 7 : QThread::msleep(10);
515 : : }
516 : : return true;
517 : : }
518 : : #endif
519 : :
520 : : /**
521 : : * @brief Stop a running @p process from the thread that owns it:
522 : : * terminate(), then kill() if it is still running after a grace period,
523 : : * then at most one more grace period for it to exit.
524 : : * A console gpg ignores terminate() on Windows (WM_CLOSE), hence the kill.
525 : : *
526 : : * On Unix the whole process group gets the signals and is waited for: pass
527 : : * is a shell script, and the git it runs would otherwise go on pulling into
528 : : * the store after the run was reported stopped.
529 : : */
530 : 20 : void stopBlocking(QProcess &process) {
531 : : #ifdef Q_OS_UNIX
532 : 20 : const auto group = static_cast<pid_t>(process.processId());
533 : 23 : const auto signalGroup = [group](int signal) {
534 [ + - ]: 23 : if (group > 0) {
535 : 23 : ::kill(-group, signal);
536 : : }
537 : 43 : };
538 : 20 : signalGroup(SIGTERM);
539 : : #endif
540 : 20 : process.terminate();
541 [ + + ]: 20 : if (!process.waitForFinished(kBlockingKillGraceMs)) {
542 : : #ifdef Q_OS_UNIX
543 : 3 : signalGroup(SIGKILL);
544 : : #endif
545 : 3 : 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 [ - + ]: 3 : if (!process.waitForFinished(kBlockingKillGraceMs)) {
552 : 0 : qCWarning(lcQtPass) << "Process still running after kill():"
553 : 0 : << process.program();
554 : : }
555 : : }
556 : : #ifdef Q_OS_UNIX
557 [ + - - + ]: 20 : if (group > 0 && !waitForGroup(group, kBlockingKillGraceMs)) {
558 : 0 : signalGroup(SIGKILL);
559 [ # # ]: 0 : if (!waitForGroup(group, kBlockingKillGraceMs)) {
560 : 0 : qCWarning(lcQtPass) << "Processes started by" << process.program()
561 : 0 : << "still running after kill()";
562 : : }
563 : : }
564 : : #endif
565 : 20 : }
566 : :
567 : : /**
568 : : * @brief What is left of @p deadline, as QProcess's wait functions take it:
569 : : * -1 for none.
570 : : */
571 : 5027 : auto msecsLeft(const QDeadlineTimer &deadline) -> int {
572 [ + + ]: 5027 : if (deadline.isForever()) {
573 : : return -1;
574 : : }
575 : : return static_cast<int>(
576 : 148 : std::clamp<qint64>(deadline.remainingTime(), 0, INT_MAX));
577 : : }
578 : :
579 : : /**
580 : : * @brief Wait for @p process to finish, stopping it when @p cancel is set
581 : : * or @p deadline passes.
582 : : *
583 : : * Polls the flag; every QProcess call, terminate()/kill() included, stays on
584 : : * this thread, so another thread can never act on an exited process (or a
585 : : * pid the OS has since reused).
586 : : * @return false when it was cancelled or ran out of time.
587 : : */
588 : 3013 : auto waitOrCancel(QProcess &process, const std::atomic_bool *cancel,
589 : : const QDeadlineTimer &deadline) -> bool {
590 [ + + ]: 3013 : 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 [ + + + - ]: 1954 : if (!process.waitForFinished(msecsLeft(deadline)) &&
595 : 6 : process.state() != QProcess::NotRunning) {
596 : 6 : stopBlocking(process);
597 : 6 : return false;
598 : : }
599 : 1942 : return true;
600 : : }
601 [ + + + + ]: 2198 : while (!process.waitForFinished(
602 : : deadline.isForever()
603 : : ? kBlockingCancelPollMs
604 : 3 : : qMin(kBlockingCancelPollMs, msecsLeft(deadline)))) {
605 [ - + ]: 48 : if (process.state() == QProcess::NotRunning) {
606 : : return true;
607 : : }
608 [ + + + + : 62 : if (cancel->load() || deadline.hasExpired()) {
+ + ]
609 : 14 : stopBlocking(process);
610 : 14 : return false;
611 : : }
612 : : }
613 : : return true;
614 : : }
615 : :
616 : : } // namespace
617 : :
618 : 2251 : auto 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 : 2251 : QByteArray out;
624 [ + + + ]: 4502 : const int rc = runBlockingRaw(process, app, args, input.toUtf8(),
625 : : process_out != nullptr ? &out : nullptr,
626 : : process_err, cancel, timeoutMs);
627 [ + + ]: 2251 : if (process_out != nullptr) {
628 : 3960 : *process_out = decodeAssumingUtf8(out);
629 : : }
630 : 2251 : return rc;
631 : : }
632 : :
633 : 3087 : auto 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 [ + + + + ]: 3087 : if (cancel != nullptr && cancel->load())
639 : : return -1;
640 : : const QDeadlineTimer deadline = timeoutMs < 0
641 [ + + ]: 3076 : ? QDeadlineTimer(QDeadlineTimer::Forever)
642 : 3076 : : 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 : 3076 : CappedOutput err;
648 : : const QMetaObject::Connection errReader = QObject::connect(
649 : : &process, &QProcess::readyReadStandardError,
650 [ + + ]: 7668 : [&process, &err]() { err.append(process.readAllStandardError()); });
651 : : const QMetaObject::Connection outDropper =
652 : : process_out != nullptr
653 [ + + ]: 3076 : ? QMetaObject::Connection()
654 : : : QObject::connect(&process, &QProcess::readyReadStandardOutput,
655 [ + + + ]: 3323 : [&process]() { process.readAllStandardOutput(); });
656 : 3076 : const auto disconnectReaders = qScopeGuard([&errReader, &outDropper]() {
657 : 3076 : QObject::disconnect(errReader);
658 : 3076 : QObject::disconnect(outDropper);
659 : 3076 : });
660 : 3076 : startProcess(process, app, args);
661 [ + + + ]: 3076 : if (!process.waitForStarted(msecsLeft(deadline))) {
662 : 63 : qCDebug(lcQtPass) << "Process failed to start:" << app;
663 [ + - + ]: 63 : if (process.state() != QProcess::NotRunning) {
664 : 0 : stopBlocking(process);
665 : : }
666 : 63 : return -1;
667 : : }
668 [ + + ]: 3013 : if (!input.isEmpty()) {
669 [ + - + ]: 993 : if (process.write(input) != input.length()) {
670 : 0 : qCDebug(lcQtPass) << "Not all input written:" << app;
671 : : }
672 : : }
673 : : // Always close stdin so a child blocking on EOF doesn't hang.
674 : 3013 : process.closeWriteChannel();
675 [ + + + ]: 3013 : 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 [ + + ]: 2993 : if (process_out != nullptr) {
681 : 5128 : *process_out = process.readAllStandardOutput();
682 : : }
683 [ + + ]: 2993 : if (process_err != nullptr) {
684 : 916 : err.append(process.readAllStandardError());
685 : 1832 : *process_err = decodeAssumingUtf8(err.take());
686 : : }
687 [ + - + + ]: 2993 : return process.exitStatus() == QProcess::NormalExit ? process.exitCode() : -1;
688 : 3076 : }
689 : :
690 : 836 : auto 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 : 836 : return runBlockingRaw(process, app, args, input, process_out, process_err,
697 : 836 : cancel, timeoutMs);
698 : : }
699 : :
700 : 476 : auto Executor::executeBlocking(const QString &app, const QStringList &args,
701 : : const QString &input, QString *process_out,
702 : : QString *process_err) -> int {
703 : 476 : QProcess internal;
704 : 952 : return runBlocking(internal, app, args, input, process_out, process_err);
705 : 476 : }
706 : :
707 : 1674 : auto 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 : 1674 : return runBlocking(process, app, args, input, process_out, process_err,
713 : 1674 : cancel, timeoutMs);
714 : : }
715 : :
716 : 284 : auto Executor::executeBlocking(const QString &app, const QStringList &args,
717 : : QString *process_out, QString *process_err)
718 : : -> int {
719 : 568 : return executeBlocking(app, args, QString(), process_out, process_err);
720 : : }
721 : :
722 : 101 : auto Executor::executeBlocking(const QProcessEnvironment &env,
723 : : const QString &app, const QStringList &args,
724 : : QString *process_out, QString *process_err)
725 : : -> int {
726 : 101 : QProcess process;
727 : 101 : process.setProcessEnvironment(env);
728 : 202 : return runBlocking(process, app, args, QString(), process_out, process_err);
729 : 101 : }
730 : :
731 : 998 : void Executor::setEnvironment(const QProcessEnvironment &env) {
732 : 998 : m_process.setProcessEnvironment(env);
733 : 998 : }
734 : :
735 : 223 : auto Executor::environment() const -> QProcessEnvironment {
736 : 223 : return m_process.processEnvironment();
737 : : }
738 : :
739 : 8 : auto Executor::stopRunning() -> bool {
740 [ + + - + ]: 8 : if (!running || m_process.state() == QProcess::NotRunning) {
741 : 2 : return false;
742 : : }
743 : 6 : const qint64 pid = m_process.processId();
744 : 6 : 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 : 6 : 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 [ + - ]: 6 : if (pid > 0) {
752 : 6 : ::kill(-static_cast<pid_t>(pid), SIGTERM);
753 : : }
754 : : #endif
755 : 6 : m_process.terminate();
756 : 6 : QTimer::singleShot(kBlockingKillGraceMs, this, [this, pid, run]() {
757 : : const bool stillThisRun =
758 [ + + - + : 5 : 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 [ + + + - ]: 5 : !stillThisRun && running && m_process.processId() == pid;
768 [ + - ]: 5 : if (pid > 0 && !pidReused) {
769 : 5 : ::kill(-static_cast<pid_t>(pid), SIGKILL);
770 : : }
771 : : #endif
772 [ - + ]: 5 : if (stillThisRun) {
773 : 0 : m_process.kill();
774 : : }
775 : 5 : });
776 : 6 : return true;
777 : : }
778 : :
779 : : // Also -1 while the head is already running: that one is not cancelled.
780 : 17 : auto Executor::cancelNext() -> int {
781 [ + + + + ]: 17 : if (running || m_execQueue.isEmpty()) {
782 : : return -1;
783 : : }
784 : 13 : 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 : 13 : running = true;
791 : 13 : emit dequeuing(id, false);
792 : 13 : running = false;
793 : 13 : return id;
794 : : }
795 : :
796 : 477 : void Executor::onProcessFinished(int exitCode,
797 : : QProcess::ExitStatus exitStatus) {
798 : : ExecQueueItem i = m_execQueue.dequeue();
799 : 477 : running = false;
800 [ + + - + ]: 477 : const bool stopped = m_stoppedRun != 0 && m_stoppedRun == m_runSerial;
801 : 477 : m_stoppedRun = 0;
802 : 477 : auto [output, err] = collectOutput(i, exitCode);
803 [ + + ]: 477 : if (stopped) {
804 : : // A stopped run failed, also when it exited 0 on SIGTERM.
805 [ + + ]: 6 : if (err.trimmed().isEmpty()) {
806 : 10 : err = tr("%1 was stopped").arg(i.app);
807 : : }
808 : 6 : emit error(i.id, -1, output, err);
809 : 6 : m_outputLossless = true;
810 : 6 : m_lastStatus.clear();
811 [ + + ]: 471 : } else if (exitStatus == QProcess::NormalExit) {
812 [ + + ]: 470 : if (exitCode != 0) {
813 : 48 : qCDebug(lcQtPass) << i.app << "exited with" << exitCode << err;
814 : : }
815 : 470 : emit finished(i.id, exitCode, output, err);
816 : 470 : m_outputLossless = true;
817 : 470 : 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 [ + - ]: 1 : if (err.trimmed().isEmpty()) {
822 : 2 : 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 : 1 : emit error(i.id, -1, output, err);
828 : 1 : m_outputLossless = true;
829 : 1 : m_lastStatus.clear();
830 : : }
831 : 477 : executeNext();
832 : 477 : postDrainedIfIdle();
833 : 477 : }
834 : :
835 : 489 : void Executor::postDrainedIfIdle() {
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 [ + + ]: 489 : if (m_drainCheckPosted) {
840 : : return;
841 : : }
842 : 486 : m_drainCheckPosted = true;
843 : 486 : QMetaObject::invokeMethod(
844 : : this,
845 : 486 : [this]() {
846 : 421 : m_drainCheckPosted = false;
847 [ + - ]: 191 : if (isIdle() && m_pendingErrors == 0) {
848 : 191 : emit drained();
849 : : }
850 : 421 : },
851 : : Qt::QueuedConnection);
852 : : }
853 : :
854 : 477 : auto Executor::collectOutput(const ExecQueueItem &item, int exitCode)
855 : : -> std::pair<QString, QString> {
856 : 477 : QString output;
857 : 477 : QString err;
858 : 477 : m_outputLossless = true;
859 [ + + ]: 477 : if (item.readStdout) {
860 : 850 : output = decodeAssumingUtf8(m_process.readAllStandardOutput(),
861 : : &m_outputLossless);
862 : : }
863 : 477 : m_stderr.append(m_process.readAllStandardError());
864 : 477 : const QByteArray errBytes = m_stderr.take();
865 : 477 : m_lastStatus = m_stderr.statusCounts();
866 [ + + + + ]: 477 : if (item.readStderr || exitCode != 0) {
867 : 808 : err = decodeAssumingUtf8(errBytes);
868 : : }
869 : 477 : return {output, err};
870 : : }
|