Branch data Line data Source code
1 : : // SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2 : : // SPDX-License-Identifier: GPL-3.0-or-later
3 : : /**
4 : : * @file
5 : : * @brief Executor, the FIFO queue every gpg, git and pass child process of
6 : : * QtPass goes through, and the WSL command parsing it shares with the
7 : : * settings code.
8 : : */
9 : : #ifndef SRC_EXECUTOR_H_
10 : : #define SRC_EXECUTOR_H_
11 : :
12 : : #include <QHash>
13 : : #include <QObject>
14 : : #include <QProcess>
15 : : #include <QProcessEnvironment>
16 : : #include <QQueue>
17 : : #include <atomic>
18 : : #include <optional>
19 : : #include <utility>
20 : :
21 : : /**
22 : : * @class Executor
23 : : * @ingroup process
24 : : * @brief Runs non-interactive external commands in FIFO order using a single
25 : : * QProcess.
26 : : *
27 : : * Queues execution requests and emits per-request completion or error signals;
28 : : * supports optional stdin, configurable stdout/stderr capture, and per-request
29 : : * working directory and environment.
30 : : */
31 : :
32 : : class Executor : public QObject {
33 : 18 : Q_OBJECT
34 : :
35 : : /**
36 : : * @struct ExecQueueItem
37 : : * @brief Execution queue item for non-interactive ordered execution.
38 : : */
39 : : struct ExecQueueItem {
40 : : /** @brief Identifier the caller gave; echoed in finished()/error(). */
41 : : int id;
42 : : /** @brief Executable as configured; resolved when started. */
43 : : QString app;
44 : : /** @brief Arguments for the executable. */
45 : : QStringList args;
46 : : /** @brief Data written to the process's stdin, then closed. */
47 : : QString input;
48 : : /** @brief Whether stdout is captured for finished(). */
49 : : bool readStdout;
50 : : /**
51 : : * @brief Whether stderr is captured; it is read regardless when the
52 : : * process exits non-zero.
53 : : */
54 : : bool readStderr;
55 : : /** @brief Working directory to start in; empty for the current one. */
56 : : QString workingDir;
57 : : };
58 : :
59 : : /**
60 : : * @brief Commands waiting to run, head first. The head stays queued while
61 : : * it runs and is dequeued in onProcessFinished().
62 : : */
63 : : QQueue<ExecQueueItem> m_execQueue;
64 : : /** @brief The one process object; every queued command reuses it. */
65 : : QProcess m_process;
66 : : /**
67 : : * @brief Whether the head of the queue has been started (or is being
68 : : * dequeued, see dequeuing()) and has not finished yet.
69 : : */
70 : : bool running{false};
71 : : /**
72 : : * @brief Start the head of the queue unless something runs or the queue
73 : : * is empty.
74 : : *
75 : : * Marks the executor running and emits dequeuing() before touching the
76 : : * item, so a slot there cannot invalidate it. An item with no executable
77 : : * is failed with a queued error() (an empty command used to wedge the
78 : : * queue, #1682) and the next one is tried at once. Called after each
79 : : * execute() and from onProcessFinished().
80 : : */
81 : : void executeNext();
82 : : /// Post one check for drained(), coalesced: it comes after what is
83 : : /// being emitted now, and fires only when the executor is idle and no
84 : : /// error() of a failed start is still on its way.
85 : : void postDrainedIfIdle();
86 : : /// error()s of failed starts posted but not delivered yet; nothing new
87 : : /// starts while there is one (executeNext()).
88 : : int m_pendingErrors = 0;
89 : : /// A drained() check is posted and not run yet.
90 : : bool m_drainCheckPosted = false;
91 : : /// Counts the commands started, so a run can be told from the next one of
92 : : /// the same kind (runningSerial()).
93 : : quint64 m_runSerial = 0;
94 : : /// The run stopRunning() was called for, 0 for none: it ends as a failure
95 : : /// whatever it exits with.
96 : : quint64 m_stoppedRun = 0;
97 : : /// lastOutputLossless(): set by collectOutput(), true again after the
98 : : /// emit, so a receiver that runs later never reads a stale value.
99 : : bool m_outputLossless = true;
100 : : /**
101 : : * @brief Start @p process running @p app, handling the "wsl " prefix once
102 : : * for both the queued and the blocking path.
103 : : *
104 : : * Also applies detachFromTerminal() and the umask from setChildUmask(),
105 : : * so every child QtPass starts gets both.
106 : : * @param process Process object to start; configured by the caller.
107 : : * @param app Executable as configured (see resolveExecutable() and
108 : : * parseWslCommand()).
109 : : * @param args Command arguments.
110 : : */
111 : : static void startProcess(QProcess &process, const QString &app,
112 : : const QStringList &args);
113 : : /**
114 : : * @brief Read what a finished process produced, according to the queue
115 : : * item's readStdout/readStderr flags; stderr is always read on a non-zero
116 : : * exit so the caller can report it.
117 : : * @param item The queue item the process ran for.
118 : : * @param exitCode Its exit code.
119 : : * @return stdout and stderr, each empty when not read.
120 : : */
121 : : auto collectOutput(const ExecQueueItem &item, int exitCode)
122 : : -> std::pair<QString, QString>;
123 : : /**
124 : : * @brief Shared blocking run: start @p process, optionally feed @p input on
125 : : * stdin, wait, and capture stdout/stderr. Backs the executeBlocking
126 : : * overloads. The caller configures @p process (e.g. environment) first.
127 : : *
128 : : * With a null @p cancel the wait is a plain waitForFinished(-1). With a
129 : : * non-null one the wait polls the flag; once it is set this thread
130 : : * terminate()s the child, gives it a short grace period, kill()s it if it
131 : : * is still running, waits one more grace period at most, and returns -1.
132 : : * A flag that is already set skips the start altogether.
133 : : * @param process Pre-configured QProcess to run.
134 : : * @param app Executable path.
135 : : * @param args Command arguments.
136 : : * @param input Data to write to stdin (empty = none).
137 : : * @param process_out If non-null, receives stdout.
138 : : * @param process_err If non-null, receives stderr.
139 : : * @param cancel Optional flag another thread may set to end the run.
140 : : * @param timeoutMs Time for the whole run, start included; negative for
141 : : * none.
142 : : * @return Process exit code, or -1 on start/crash failure, cancel or
143 : : * timeout.
144 : : */
145 : : static auto runBlocking(QProcess &process, const QString &app,
146 : : const QStringList &args, const QString &input,
147 : : QString *process_out, QString *process_err,
148 : : const std::atomic_bool *cancel = nullptr,
149 : : int timeoutMs = -1) -> int;
150 : : /**
151 : : * @brief runBlocking() on bytes: @p input is written and stdout returned
152 : : * as they are, with no text decoding or encoding. stderr is still decoded.
153 : : * @param process Pre-configured QProcess to run.
154 : : * @param app Executable path.
155 : : * @param args Command arguments.
156 : : * @param input Bytes to write to stdin (empty = none).
157 : : * @param process_out If non-null, receives stdout.
158 : : * @param process_err If non-null, receives stderr.
159 : : * @param cancel Optional flag another thread may set to end the run.
160 : : * @param timeoutMs Time for the whole run, start included; negative for
161 : : * none.
162 : : * @return Process exit code, or -1 on start/crash failure, cancel or
163 : : * timeout.
164 : : */
165 : : static auto runBlockingRaw(QProcess &process, const QString &app,
166 : : const QStringList &args, const QByteArray &input,
167 : : QByteArray *process_out, QString *process_err,
168 : : const std::atomic_bool *cancel = nullptr,
169 : : int timeoutMs = -1) -> int;
170 : :
171 : : public:
172 : : /**
173 : : * @brief Most bytes of a command's stderr kept: the first and the last
174 : : * half of this, with a note of how much was left out between.
175 : : *
176 : : * gpg writes a line per packet it rejects and git one per ref, so an
177 : : * entry or a repository someone else made could fill gigabytes, all of
178 : : * it held in memory and then shown (scan ANT-2026-VQGRD45V). The end is
179 : : * kept because that is where the error is.
180 : : */
181 : : static constexpr qsizetype kMaxStderrBytes = qsizetype{64} * 1024;
182 : :
183 : : /**
184 : : * @class CappedOutput
185 : : * @brief A stream of bytes held as its first and last
186 : : * kMaxStderrBytes / 2 bytes, with its gpg status records counted
187 : : * whole.
188 : : *
189 : : * What is left out of the text is still counted: a caller that judges a
190 : : * run by its status records (RealPass counting END_ENCRYPTION against the
191 : : * entries pass re-encrypted) reads statusCounts(), not the capped text.
192 : : */
193 : 574 : class CappedOutput {
194 : : public:
195 : : /**
196 : : * @brief Add what the process wrote next.
197 : : * @param chunk The bytes, in order.
198 : : */
199 : : void append(const QByteArray &chunk);
200 : : /**
201 : : * @brief Everything kept, and start over.
202 : : * @return The bytes as written when nothing was left out; otherwise the
203 : : * head, a line saying how many bytes were left out, and the
204 : : * tail, each cut at a UTF-8 character boundary.
205 : : */
206 : : auto take() -> QByteArray;
207 : : /**
208 : : * @brief How many complete lines of each gpg status keyword came by
209 : : * since the last take(), the left-out ones included.
210 : : *
211 : : * A line counts when it starts with "[GNUPG:] "; its keyword is the
212 : : * word after that. Lines longer than kMaxStatusLineBytes, and keywords
213 : : * past the first kMaxStatusKeywords, are not counted: gpg's own status
214 : : * lines are short and few in kind.
215 : : * @return Keyword to count.
216 : : */
217 : : [[nodiscard]] auto statusCounts() const -> QHash<QString, qint64> {
218 : : return m_status;
219 : : }
220 : : /** @brief Drop everything, counts included, for the next command. */
221 : 490 : void clear() {
222 : 490 : take();
223 : 490 : m_status.clear();
224 : 490 : }
225 : : /** @brief Longest line still looked at for a status keyword. */
226 : : static constexpr qsizetype kMaxStatusLineBytes = 1024;
227 : : /** @brief Most distinct status keywords counted. */
228 : : static constexpr int kMaxStatusKeywords = 64;
229 : :
230 : : private:
231 : : /**
232 : : * @brief Count @p line if it is a status record.
233 : : * @param line One line, without its line end.
234 : : */
235 : : void countStatus(const QByteArray &line);
236 : : /** @brief The line not ended yet; empty once it ran too long. */
237 : : QByteArray m_line;
238 : : /** @brief The line not ended yet ran past kMaxStatusLineBytes. */
239 : : bool m_lineTooLong = false;
240 : : /** @brief Status keyword to count, see statusCounts(). */
241 : : QHash<QString, qint64> m_status;
242 : : /** @brief The first bytes, up to half the cap. */
243 : : QByteArray m_head;
244 : : /** @brief The latest bytes, up to half the cap. */
245 : : QByteArray m_tail;
246 : : /** @brief Bytes that fell out between head and tail. */
247 : : qint64 m_dropped = 0;
248 : : };
249 : :
250 : : private:
251 : : /**
252 : : * @brief stderr of the running queued command, read as it arrives and
253 : : * capped.
254 : : */
255 : : CappedOutput m_stderr;
256 : : /// lastStatusCounts(): set by collectOutput(), cleared after the emit.
257 : : QHash<QString, qint64> m_lastStatus;
258 : : /// The running queued command's stdout is not wanted: dropped as it comes.
259 : : bool m_discardStdout = false;
260 : :
261 : : public:
262 : : /**
263 : : * @brief Construct an Executor with an optional parent QObject.
264 : : * @param parent Parent QObject, or nullptr for no parent.
265 : : */
266 : : explicit Executor(QObject *parent = nullptr);
267 : : /**
268 : : * @brief Stop listening to the running process, then end it.
269 : : *
270 : : * Ending a command still running (a gpg decrypting at quit) emits
271 : : * finished(). Delivered, that ran onProcessFinished() and the owner's
272 : : * slots on an object half destroyed: Pass::finished() read members that
273 : : * were already gone. The command is killed here and not left to
274 : : * ~QProcess, which does the same but warns that it had to.
275 : : */
276 : : ~Executor() override;
277 : :
278 : : /**
279 : : * @brief Queue a command without stdin input.
280 : : * @param id Caller-assigned process identifier.
281 : : * @param app Executable path.
282 : : * @param args Command arguments.
283 : : * @param readStdout Whether to capture stdout.
284 : : * @param readStderr Whether to capture stderr.
285 : : */
286 : : void execute(int id, const QString &app, const QStringList &args,
287 : : bool readStdout, bool readStderr = true);
288 : :
289 : : /**
290 : : * @brief Queue a command with an explicit working directory.
291 : : * @param id Caller-assigned process identifier.
292 : : * @param workDir Working directory for the process.
293 : : * @param app Executable path.
294 : : * @param args Command arguments.
295 : : * @param readStdout Whether to capture stdout.
296 : : * @param readStderr Whether to capture stderr.
297 : : */
298 : : void execute(int id, const QString &workDir, const QString &app,
299 : : const QStringList &args, bool readStdout,
300 : : bool readStderr = true);
301 : :
302 : : /**
303 : : * @brief Queue a command with optional stdin input.
304 : : * @param id Caller-assigned process identifier.
305 : : * @param app Executable path.
306 : : * @param args Command arguments.
307 : : * @param input Data to write to stdin.
308 : : * @param readStdout Whether to capture stdout.
309 : : * @param readStderr Whether to capture stderr.
310 : : */
311 : : void execute(int id, const QString &app, const QStringList &args,
312 : : QString input = QString(), bool readStdout = false,
313 : : bool readStderr = true);
314 : :
315 : : /**
316 : : * @brief Queue a command with working directory and optional stdin input.
317 : : * @param id Caller-assigned process identifier.
318 : : * @param workDir Working directory for the process.
319 : : * @param app Executable path.
320 : : * @param args Command arguments.
321 : : * @param input Data to write to stdin.
322 : : * @param readStdout Whether to capture stdout.
323 : : * @param readStderr Whether to capture stderr.
324 : : */
325 : : void execute(int id, const QString &workDir, const QString &app,
326 : : const QStringList &args, QString input = QString(),
327 : : bool readStdout = false, bool readStderr = true);
328 : :
329 : : /**
330 : : * @brief Run a command synchronously and return its exit code.
331 : : * @param app Executable path.
332 : : * @param args Command arguments.
333 : : * @param input Data to write to stdin.
334 : : * @param process_out If non-null, receives stdout output.
335 : : * @param process_err If non-null, receives stderr output.
336 : : * @return Process exit code.
337 : : */
338 : : [[nodiscard]] static auto executeBlocking(const QString &app,
339 : : const QStringList &args,
340 : : const QString &input = QString(),
341 : : QString *process_out = nullptr,
342 : : QString *process_err = nullptr)
343 : : -> int;
344 : :
345 : : /**
346 : : * @brief Run a command synchronously on a caller-supplied QProcess, with
347 : : * optional cancellation.
348 : : *
349 : : * The caller configures @p process (environment, say) before the call;
350 : : * it must be a fresh, not yet started object. QProcess is not thread-safe,
351 : : * so @p process belongs to the calling thread for the whole run: no other
352 : : * thread may call terminate(), kill() or anything else on it. To let a run
353 : : * be cancelled, pass @p cancel: the wait then polls the flag, and once it
354 : : * is set the calling thread itself terminate()s the child, waits a short
355 : : * grace period, kill()s it if it is still running, waits one more grace
356 : : * period at most, and returns -1. Setting the flag is the only thing
357 : : * another thread does; it may do so at any time, before or during the run.
358 : : * A run given @p timeoutMs ends the same way once that time has passed,
359 : : * start included, so it returns within the timeout plus twice the grace
360 : : * even when a kill()ed child cannot exit yet (uninterruptible sleep on a
361 : : * hung mount). Not timed: QProcess::start() itself, which can block, for
362 : : * example opening a FIFO named by a redirected channel (no caller
363 : : * redirects one), and QProcess's destructor, which still waits for such a
364 : : * child, for up to 30 s.
365 : : * @param process Process object to run the command on.
366 : : * @param app Executable path.
367 : : * @param args Command arguments.
368 : : * @param input Data to write to stdin.
369 : : * @param process_out If non-null, receives stdout output.
370 : : * @param process_err If non-null, receives stderr output.
371 : : * @param cancel If non-null, a flag that ends the run when set.
372 : : * @param timeoutMs Time for the whole run, start included; negative (the
373 : : * default) for none.
374 : : * @return Process exit code, or -1 if it failed to start, crashed, was
375 : : * cancelled or ran out of time.
376 : : */
377 : : [[nodiscard]] static auto executeBlocking(
378 : : QProcess &process, const QString &app, const QStringList &args,
379 : : const QString &input = QString(), QString *process_out = nullptr,
380 : : QString *process_err = nullptr, const std::atomic_bool *cancel = nullptr,
381 : : int timeoutMs = -1) -> int;
382 : :
383 : : /**
384 : : * @brief executeBlocking() on bytes, for an entry's plaintext: @p input is
385 : : * written to stdin and stdout returned exactly as they are, so content
386 : : * that is not UTF-8 (a Latin-1 password, a binary key) passes through
387 : : * unchanged. stderr is decoded as in executeBlocking(). A name of its own,
388 : : * not an overload: a string literal or nullptr would be ambiguous.
389 : : * @param process Process object to run the command on.
390 : : * @param app Executable path.
391 : : * @param args Command arguments.
392 : : * @param input Bytes to write to stdin (empty = none).
393 : : * @param process_out If non-null, receives stdout.
394 : : * @param process_err If non-null, receives stderr.
395 : : * @param cancel If non-null, a flag that ends the run when set.
396 : : * @param timeoutMs Time for the whole run, start included; negative (the
397 : : * default) for none.
398 : : * @return Process exit code, or -1 if it failed to start, crashed, was
399 : : * cancelled or ran out of time.
400 : : */
401 : : [[nodiscard]] static auto
402 : : executeBlockingRaw(QProcess &process, const QString &app,
403 : : const QStringList &args, const QByteArray &input,
404 : : QByteArray *process_out, QString *process_err = nullptr,
405 : : const std::atomic_bool *cancel = nullptr,
406 : : int timeoutMs = -1) -> int;
407 : :
408 : : /**
409 : : * @brief Run a command synchronously capturing stdout and stderr.
410 : : * @param app Executable path.
411 : : * @param args Command arguments.
412 : : * @param process_out Receives stdout output.
413 : : * @param process_err If non-null, receives stderr output.
414 : : * @return Process exit code.
415 : : */
416 : : [[nodiscard]] static auto
417 : : executeBlocking(const QString &app, const QStringList &args,
418 : : QString *process_out, QString *process_err = nullptr) -> int;
419 : :
420 : : /**
421 : : * @brief Run a command synchronously with a custom environment.
422 : : * @param env Process environment for the child process.
423 : : * @param app Executable path.
424 : : * @param args Command arguments.
425 : : * @param process_out If non-null, receives stdout output.
426 : : * @param process_err If non-null, receives stderr output.
427 : : * @return Process exit code.
428 : : */
429 : : [[nodiscard]] static auto
430 : : executeBlocking(const QProcessEnvironment &env, const QString &app,
431 : : const QStringList &args, QString *process_out = nullptr,
432 : : QString *process_err = nullptr) -> int;
433 : :
434 : : /**
435 : : * @brief The one rule for turning a configured executable into what runs.
436 : : *
437 : : * Absolute paths and "wsl ..." commands are used as given. A bare or
438 : : * relative name is looked up next to the application first (the Windows
439 : : * and macOS bundles ship gpg/git/pass there) and otherwise left for
440 : : * QProcess's PATH lookup. Both the queued and the blocking path go through
441 : : * this, so the same setting can no longer run two different binaries.
442 : : * @param app Executable as configured.
443 : : * @return What to hand to QProcess::start().
444 : : */
445 : : static auto resolveExecutable(const QString &app) -> QString;
446 : :
447 : : /**
448 : : * @brief Make @p process start its child without a controlling terminal.
449 : : *
450 : : * On Unix the child starts in a new session (setsid), so it has no
451 : : * /dev/tty. git and ssh then use an askpass helper when there is one and
452 : : * fail at once otherwise, instead of prompting in the terminal QtPass was
453 : : * started from while the queue waits behind them. Other Unix process
454 : : * flags set on @p process are kept. Does nothing on Windows. Every child
455 : : * QtPass starts goes through this; startProcess() calls it for the queued
456 : : * and the blocking path.
457 : : * @param process Process to configure; call it before start().
458 : : */
459 : : static void detachFromTerminal(QProcess &process);
460 : :
461 : : /**
462 : : * @brief The umask every child QtPass starts gets, as pass sets its own.
463 : : *
464 : : * pass runs git and gpg under umask 077 (or PASSWORD_STORE_UMASK), so the
465 : : * folders and files they create in the store, .git included, are the
466 : : * user's alone. QtPass gives that umask to the processes it starts
467 : : * (startProcess(), the queue and the blocking calls) and not to itself:
468 : : * a browser or file manager it opens keeps the session's. Unix only.
469 : : * @param mask The umask, or a negative value for none (the default).
470 : : */
471 : : static void setChildUmask(int mask);
472 : :
473 : : /**
474 : : * @brief The umask setChildUmask() set.
475 : : * @return The umask, or a negative value when none was set.
476 : : */
477 : : [[nodiscard]] static auto childUmask() -> int;
478 : :
479 : : /**
480 : : * @brief A configured executable that runs a Linux program through WSL.
481 : : *
482 : : * The one definition of "a WSL command" in QtPass; see parseWslCommand().
483 : : */
484 : : struct WslCommand {
485 : : /**
486 : : * @brief What to start.
487 : : *
488 : : * On Windows a bare `wsl`/`wsl.exe` in any case becomes `wsl`, which the
489 : : * PATH lookup resolves; elsewhere (QtPass itself running inside WSL,
490 : : * where `wsl.exe` is reachable through interop but `wsl` need not be)
491 : : * and for a launcher given as a path it stays as configured.
492 : : */
493 : : QString launcher;
494 : : /**
495 : : * @brief wsl.exe options that go before the program (`-d Debian`,
496 : : * `-u me`), without any `-e`/`--exec`: argv() always adds that.
497 : : */
498 : : QStringList options;
499 : : /** @brief The Linux program to run, looked up on the WSL PATH. */
500 : : QString command;
501 : : /**
502 : : * @brief Arguments for @ref launcher that run @ref command with @p args.
503 : : *
504 : : * Always through `--exec`, so WSL starts the program itself instead of
505 : : * handing the joined command line to the distribution's default shell.
506 : : * Without it every argument (entry paths, .gpg-id recipients, commit
507 : : * messages) is word-split and `$()`-expanded by that shell, and a
508 : : * hostile password store gets code execution.
509 : : * @param args Arguments for @ref command, passed through verbatim.
510 : : * @return @ref options, `--exec`, @ref command, then @p args.
511 : : */
512 : : auto argv(const QStringList &args) const -> QStringList;
513 : : /**
514 : : * @brief The same launcher and options running another program.
515 : : * @param program Linux program to run instead of @ref command.
516 : : * @return A copy with @ref command replaced by @p program.
517 : : */
518 : : auto with(const QString &program) const -> WslCommand;
519 : : };
520 : :
521 : : /**
522 : : * @brief Parse a configured executable as a WSL command.
523 : : *
524 : : * Accepts `wsl` or `wsl.exe` in any case, bare or as a path, followed by
525 : : * wsl.exe options and exactly one program: `wsl gpg`, `WSL.EXE -d Debian
526 : : * /usr/bin/gpg`, `C:\Windows\System32\wsl.exe -u me gpg`. A `-e`/`--exec`
527 : : * the user wrote is dropped (argv() adds it), anything after the program
528 : : * (`wsl sh -c "gpg"`) or a `wsl` with no program is not a WSL command.
529 : : *
530 : : * Every place that starts, probes or translates paths for a configured
531 : : * executable goes through this, so a form one of them accepts cannot be
532 : : * started differently by another.
533 : : * @param app Executable as configured.
534 : : * @return The parsed command, or nothing when @p app is not one.
535 : : */
536 : : static auto parseWslCommand(const QString &app) -> std::optional<WslCommand>;
537 : :
538 : : /**
539 : : * @brief Build the wsl.exe argument list that runs @p command directly.
540 : : * @param command Linux command to run (looked up on the WSL PATH).
541 : : * @param args Arguments for @p command, passed through verbatim.
542 : : * @return Arguments for `wsl`: `--exec`, @p command, then @p args.
543 : : * @see WslCommand::argv
544 : : */
545 : : static auto wslExecArgs(const QString &command, const QStringList &args)
546 : : -> QStringList;
547 : :
548 : : /**
549 : : * @brief Decode process output as executeBlocking() does: UTF-8 first, the
550 : : * system encoding when it is not UTF-8 (a Windows code page). For callers
551 : : * that run a process on bytes (executeBlockingRaw()) and then read its
552 : : * output as text.
553 : : * @param bytes What the process wrote.
554 : : * @return The text.
555 : : */
556 : : [[nodiscard]] static auto decodeText(const QByteArray &bytes) -> QString;
557 : :
558 : : /**
559 : : * @brief Translate a native path for a WSL-routed executable.
560 : : *
561 : : * When @p exe is a WSL command (parseWslCommand()) the path is converted
562 : : * with `wslpath` in the same distribution (the Linux binary cannot open
563 : : * `C:\...`); otherwise it is only cleaned.
564 : : * @param path Native filesystem path.
565 : : * @param exe Executable the path is meant for.
566 : : * @return Path suitable for @p exe.
567 : : */
568 : : static auto translatePathForWsl(const QString &path, const QString &exe)
569 : : -> QString;
570 : :
571 : : /**
572 : : * @brief Set the environment passed to all child processes.
573 : : * @param env Process environment for child processes.
574 : : */
575 : : void setEnvironment(const QProcessEnvironment &env);
576 : : /**
577 : : * @brief Return the environment passed to child processes.
578 : : * @return Process environment.
579 : : */
580 : : auto environment() const -> QProcessEnvironment;
581 : :
582 : : /**
583 : : * @brief Cancel the next queued command without executing it.
584 : : * @return The id of the cancelled command, or -1 if the queue was empty.
585 : : */
586 : : auto cancelNext() -> int;
587 : :
588 : : /**
589 : : * @brief Stop the command that is running, if any: terminate it (its
590 : : * whole process group on Unix), and kill it if it is still running
591 : : * a grace period later. It then ends as a failed run, through
592 : : * error() as any other, and the queue moves on.
593 : : *
594 : : * Nothing else limits a queued command: a store entry crafted to keep gpg
595 : : * busy for minutes held up every later show, save and Git step, while a
596 : : * decrypt that waits for a passphrase must not be cut off by a timer.
597 : : * @return Whether a command was running.
598 : : */
599 : : auto stopRunning() -> bool;
600 : :
601 : : /**
602 : : * @brief Which run is going: a number no other run of this executor had.
603 : : * @return It, or 0 when nothing runs.
604 : : */
605 : : [[nodiscard]] auto runningSerial() const -> quint64 {
606 [ + - + - ]: 9 : return running ? m_runSerial : 0;
607 : : }
608 : :
609 : : /**
610 : : * @brief The id of the command that is running.
611 : : * @return The id given to execute(), or -1 when nothing runs.
612 : : */
613 : : [[nodiscard]] auto runningId() const -> int {
614 [ + - + - : 14 : return running && !m_execQueue.isEmpty() ? m_execQueue.head().id : -1;
- + + - +
- - + + -
+ - - + ]
615 : : }
616 : : /**
617 : : * @brief Whether no command is running and nothing is queued.
618 : : * @return true when the executor has nothing in flight.
619 : : */
620 [ + + + + ]: 1190 : auto isIdle() const -> bool { return !running && m_execQueue.isEmpty(); }
[ + + + -
+ + + - ]
[ - + - -
+ - + + -
+ - - ]
621 : : /**
622 : : * @brief Whether the stdout of the item whose finished() or error() is
623 : : * being emitted encodes back (toUtf8(), as every writer here does) to
624 : : * exactly the bytes the process wrote. When false, writing that text back
625 : : * changes the bytes whatever else happens to it.
626 : : *
627 : : * Valid only in a slot directly connected to those signals, while the
628 : : * emission runs; at any other time, and when stdout was not read, true.
629 : : * @return false when the output was not UTF-8 or began with a byte order
630 : : * mark.
631 : : */
632 : : [[nodiscard]] auto lastOutputLossless() const -> bool {
633 : 52 : return m_outputLossless;
634 : : }
635 : :
636 : : /**
637 : : * @brief The gpg status records on the stderr of the command whose
638 : : * finished() or error() is being emitted, counted by keyword over
639 : : * the whole stream (CappedOutput::statusCounts()).
640 : : *
641 : : * Valid only in a slot directly connected to those signals, while the
642 : : * emission runs; empty at any other time.
643 : : * @return Keyword to count.
644 : : */
645 : : [[nodiscard]] auto lastStatusCounts() const -> QHash<QString, qint64> {
646 : : return m_lastStatus;
647 : : }
648 : :
649 : : /**
650 : : * @brief Whether a command with process id @p id is queued or running.
651 : : *
652 : : * The running command stays at the head of the queue until it finishes, so
653 : : * one scan covers both the queued and the running one. Used to refuse a
654 : : * store change while a Git pull is still in flight, whose conflict a
655 : : * call-time check could not yet see.
656 : : * @param id The process id to look for (an Enums::PROCESS value).
657 : : * @return true when the queue holds a command with that id.
658 : : */
659 : : auto hasQueued(int id) const -> bool {
660 [ + + ]: 104 : for (const ExecQueueItem &item : m_execQueue) {
[ + + + + ]
661 [ + + ]: 31 : if (item.id == id) {
[ + + - + ]
662 : : return true;
663 : : }
664 : : }
665 : : return false;
666 : : }
667 : :
668 : : private slots:
669 : : /**
670 : : * @brief Finish the running item when its process exits.
671 : : *
672 : : * Dequeues the head, collects its output and emits finished() for a
673 : : * normal exit or error() with exit code -1 for a crash (Qt leaves the
674 : : * code undefined then, and 0 or 1 would be mistaken for success or
675 : : * "no matches"), then starts the next item and posts a drained() check.
676 : : * @param exitCode Exit code reported by QProcess.
677 : : * @param exitStatus Whether the process exited normally or crashed.
678 : : */
679 : : void onProcessFinished(int exitCode, QProcess::ExitStatus exitStatus);
680 : : signals:
681 : : /**
682 : : * @brief Emitted once the last queued item is done and nothing runs or
683 : : * waits any more (isIdle()), after that item's finished() or error().
684 : : */
685 : : void drained();
686 : : /**
687 : : * @brief Emitted when a queued process exits normally, whatever its exit
688 : : * code; a non-zero code is the receiver's to interpret (Pass does).
689 : : * @param id Caller-assigned id the item was queued with.
690 : : * @param exitCode Exit code of the process.
691 : : * @param output stdout, when the item asked for it; empty otherwise.
692 : : * @param errout stderr, when the item asked for it or the exit code is
693 : : * non-zero.
694 : : */
695 : : void finished(int id, int exitCode, const QString &output,
696 : : const QString &errout);
697 : : /**
698 : : * @brief Emitted just before a queued process is started; the main
699 : : * window shows the busy indicator on it.
700 : : */
701 : : void starting();
702 : : /**
703 : : * @brief Emitted, synchronously, when the queue's head leaves it: just
704 : : * before it is started, when it cannot be (no executable, a failed
705 : : * start), or when cancelNext() drops it. Lets a caller do per-item work
706 : : * at the moment the item actually runs, not when it was queued.
707 : : * @param id The item's id.
708 : : * @param completes Whether finished() or error() follows for it: for
709 : : * every item but one cancelNext() dropped. Those that complete
710 : : * do so in the order they left the queue.
711 : : *
712 : : * A slot may queue more with execute(): that waits behind this item. The
713 : : * executor counts as running while the signal is out, also for an item
714 : : * cancelNext() drops, so cancelNext() drops nothing then (-1) and
715 : : * nothing starts until the signal has returned.
716 : : */
717 : : void dequeuing(int id, bool completes);
718 : : /**
719 : : * @brief Emitted instead of finished() when a queued process could not be
720 : : * started, had no executable configured, or crashed.
721 : : * @param id Caller-assigned id the item was queued with.
722 : : * @param exitCode Always -1; the real code is unknown in these cases.
723 : : * @param output stdout read so far, when the item asked for it.
724 : : * @param errout stderr, or a message saying what went wrong when the
725 : : * process left none.
726 : : */
727 : : void error(int id, int exitCode, const QString &output,
728 : : const QString &errout);
729 : : };
730 : :
731 : : #endif // SRC_EXECUTOR_H_
|