/* Parallel tool calls: one forked child per call, served over a socket. See
* toolpar.h for why children and not threads.
*
* Frames from a child are a type byte, a 64-bit length and that many bytes:
* S/s started, with the plan (S) or without one (s); pic answers A or N
* F fetch NAME; pic answers D, a 64-bit length (all ones: none), bytes
* P partial output text
* B/E a process started / ended, for `pic ps`
* R the result: is_error, result, full output, image
* C calls the tool makes of other tools (pic_tool_hooks.call): their count, then each
* one's name, JSON input and deadline; pic answers K, a 64-bit length and the outcome (0 or 1
* when lost) and, for each call, is_error, its result and its image type and bytes
* pic sends a child only those answers and 'c' (abort); a child reads EOF
* as pic gone, and aborts too. */
#include "toolpar.h"
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <signal.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
#ifdef __linux__
#include <sys/prctl.h>
#endif
#include "net.h"
#include "toolreg.h"
#define NONE UINT64_MAX
#define FRAME_MAX ((uint64_t)64 << 20)
static int tp_write_all(int fd, const void *p, size_t n) {
const char *c = p;
while (n > 0) {
ssize_t w = write(fd, c, n);
if (w < 0 && errno == EINTR) {
continue;
}
if (w <= 0) {
return -1;
}
c += w;
n -= (size_t)w;
}
return 0;
}
static int read_all(int fd, void *p, size_t n) {
char *c = p;
while (n > 0) {
ssize_t r = read(fd, c, n);
if (r < 0 && errno == EINTR) {
continue;
}
if (r <= 0) {
return -1;
}
c += r;
n -= (size_t)r;
}
return 0;
}
/* A growing frame payload. */
typedef struct {
char *p;
size_t n, cap;
int bad;
} tp_buf;
static void tp_put(tp_buf *b, const void *src, size_t n) {
if (b->bad || n == 0) {
return;
}
if (b->n + n > b->cap) {
size_t cap = b->cap ? b->cap : 256;
char *grown;
while (cap < b->n + n) {
cap *= 2;
}
if (!(grown = realloc(b->p, cap))) {
b->bad = 1;
return;
}
b->p = grown;
b->cap = cap;
}
memcpy(b->p + b->n, src, n);
b->n += n;
}
static void put_u64(tp_buf *b, uint64_t v) { tp_put(b, &v, sizeof v); }
static void put_bytes(tp_buf *b, const void *src, size_t n) {
put_u64(b, src ? (uint64_t)n : NONE);
tp_put(b, src, n);
}
static int send_frame(int fd, char type, const void *payload, size_t n) {
uint64_t len = n;
return tp_write_all(fd, &type, 1) || tp_write_all(fd, &len, sizeof len) || tp_write_all(fd, payload, n) ? -1 : 0;
}
/* Reading a payload back. */
typedef struct {
const char *p;
size_t n, at;
int bad;
} tp_rd;
static uint64_t get_u64(tp_rd *r) {
uint64_t v = 0;
if (r->bad || r->n - r->at < sizeof v) {
r->bad = 1;
return 0;
}
memcpy(&v, r->p + r->at, sizeof v);
r->at += sizeof v;
return v;
}
/* Bytes as a NUL-terminated malloc'd copy, or NULL (none, or bad). */
static char *get_bytes(tp_rd *r, size_t *len) {
uint64_t n = get_u64(r);
char *out;
if (r->bad || n == NONE) {
return NULL;
}
if (n > r->n - r->at || !(out = malloc((size_t)n + 1))) {
r->bad = 1;
return NULL;
}
memcpy(out, r->p + r->at, (size_t)n);
out[n] = '\0';
r->at += (size_t)n;
if (len) {
*len = (size_t)n;
}
return out;
}
/* ---- the child ---------------------------------------------------------------- */
static int child_fd = -1;
static uint64_t child_procs;
static void child_on_signal(int sig) {
(void)sig;
pic_interrupted = 1;
}
/* pic gone (its end of the socket closed): a call dies with it, whatever it
* is doing, so it holds no lock a restarted pic needs; a command it started
* is killed by its supervisor, which sees the call gone. SIGIO comes on
* every arrival; only EOF ends the call. */
static void child_on_io(int sig) {
char c;
int saved = errno;
(void)sig;
if (recv(child_fd, &c, 1, MSG_PEEK | MSG_DONTWAIT) == 0) {
_exit(0);
}
errno = saved;
}
static void child_watch_parent(pid_t parent) {
struct sigaction sa;
memset(&sa, 0, sizeof sa);
sa.sa_handler = child_on_io;
sa.sa_flags = SA_RESTART;
sigemptyset(&sa.sa_mask);
(void)sigaction(SIGIO, &sa, NULL);
#ifdef __linux__
(void)prctl(PR_SET_PDEATHSIG, SIGKILL);
#endif
(void)fcntl(child_fd, F_SETOWN, getpid());
(void)fcntl(child_fd, F_SETFL, fcntl(child_fd, F_GETFL) | O_ASYNC);
if (getppid() != parent) {
_exit(0); /* pic died before the watch was set */
}
}
/* While a command runs, the only thing pic sends is 'c'; EOF is pic gone. */
static void child_side_ready(void) {
char c = 0;
ssize_t r = read(child_fd, &c, 1);
if (r == 1 && c == 'c') {
pic_interrupted = 1;
} else if (r == 0 || (r < 0 && errno != EINTR && errno != EAGAIN)) {
pic_interrupted = 1;
pic_side_fd = -1; /* stop watching a descriptor that stays readable */
}
}
/* pic's answer to a request, skipping an abort sent meanwhile: its type. */
static char child_answer(void) {
for (;;) {
char c = 0;
if (read_all(child_fd, &c, 1) != 0) {
pic_interrupted = 1;
return 0;
}
if (c != 'c') {
return c;
}
pic_interrupted = 1;
}
}
static int child_started(void *ctx, const char *plan, size_t plan_len) {
(void)ctx;
return send_frame(child_fd, plan ? 'S' : 's', plan, plan ? plan_len : 0) == 0 && child_answer() == 'A' ? 0 : -1;
}
static char *child_fetch(void *ctx, const char *name, size_t *len) {
uint64_t n = 0;
char *out;
(void)ctx;
if (send_frame(child_fd, 'F', name, strlen(name)) != 0 || child_answer() != 'D' ||
read_all(child_fd, &n, sizeof n) != 0 || n == NONE || n > FRAME_MAX || !(out = malloc((size_t)n + 1))) {
return NULL;
}
if (read_all(child_fd, out, (size_t)n) != 0) {
free(out);
return NULL;
}
out[n] = '\0';
*len = (size_t)n;
return out;
}
/* The answer to a C frame into CALLS: 0, or -1 (lost, or pic gone). */
static int read_calls(const char *p, size_t len, pic_nested_call *calls, size_t n) {
tp_rd r = {p, len, 0, 0};
int rc;
if (len < 1) {
return -1;
}
rc = p[0] == 0 ? 0 : -1;
r.at = 1;
for (size_t i = 0; rc == 0 && i < n; i++) {
size_t got = 0;
calls[i].is_error = r.at < r.n && r.p[r.at] != 0;
r.at++;
calls[i].result = get_bytes(&r, NULL);
{
char *mime = get_bytes(&r, NULL);
static const char *const mimes[] = {"image/png", "image/jpeg", "image/gif", "image/webp"};
calls[i].mime = NULL;
for (size_t k = 0; mime && k < sizeof mimes / sizeof mimes[0]; k++) {
if (strcmp(mime, mimes[k]) == 0) {
calls[i].mime = mimes[k];
}
}
free(mime);
}
calls[i].image = (unsigned char *)get_bytes(&r, &got);
calls[i].image_len = got;
if (r.bad || !calls[i].result) {
rc = -1;
}
}
if (rc != 0) {
for (size_t i = 0; i < n; i++) {
free(calls[i].result);
free(calls[i].image);
calls[i].result = NULL;
calls[i].image = NULL;
}
}
return rc;
}
static int child_call(void *ctx, pic_nested_call *calls, size_t n) {
tp_buf b = {NULL, 0, 0, 0};
uint64_t len = 0;
char *payload;
int rc;
(void)ctx;
put_u64(&b, (uint64_t)n);
for (size_t i = 0; i < n; i++) {
put_bytes(&b, calls[i].tool, calls[i].tool ? strlen(calls[i].tool) : 0);
put_bytes(&b, calls[i].input, calls[i].input ? strlen(calls[i].input) : 0);
put_u64(&b, (uint64_t)calls[i].deadline_ms);
}
rc = b.bad || send_frame(child_fd, 'C', b.p, b.n) != 0 || child_answer() != 'K' ||
read_all(child_fd, &len, sizeof len) != 0 || len > FRAME_MAX
? -1
: 0;
free(b.p);
if (rc != 0 || !(payload = malloc((size_t)len + 1))) {
return -1;
}
rc = read_all(child_fd, payload, (size_t)len) == 0 ? read_calls(payload, (size_t)len, calls, n) : -1;
free(payload);
return rc;
}
static void child_partial(void *ctx, const char *text) {
(void)ctx;
(void)send_frame(child_fd, 'P', text, strlen(text));
}
static long long child_proc_start(const char *kind, const char *command, long pid, long pgid) {
tp_buf b = {NULL, 0, 0, 0};
uint64_t id = ++child_procs;
put_u64(&b, id);
put_u64(&b, (uint64_t)pid);
put_u64(&b, (uint64_t)pgid);
put_bytes(&b, kind, strlen(kind));
put_bytes(&b, command, strlen(command));
if (b.bad || send_frame(child_fd, 'B', b.p, b.n) != 0) {
id = 0;
}
free(b.p);
return id ? (long long)id : -1;
}
static void child_proc_end(long long id, int exit_code, int sig) {
uint64_t v[3] = {(uint64_t)id, (uint64_t)(int64_t)exit_code, (uint64_t)(int64_t)sig};
(void)send_frame(child_fd, 'E', v, sizeof v);
}
static const pic_proc_sink child_sink = {child_proc_start, child_proc_end};
static void child_main(const char *workspace, const pic_par_call *c, int fd, pid_t parent, const sigset_t *mask) {
struct sigaction sa;
pic_tool_output output = {NULL, 0};
struct pic_tool_image image = {NULL, NULL, 0, 0, 0};
const pic_tool_hooks *h = c->hooks;
pic_tool_hooks mine = {.exec_seconds = h->exec_seconds,
.started = child_started,
.plan = h->plan,
.plan_len = h->plan_len,
.output_name = h->output_name,
.output = h->output ? &output : NULL,
.fetch = h->fetch ? child_fetch : NULL,
.image = h->image ? &image : NULL,
.partial = h->partial ? child_partial : NULL,
.proc_kind = h->proc_kind,
.journal = h->journal,
.effect = h->effect,
.input = h->input,
.call = h->call ? child_call : NULL,
.nested = h->nested};
tp_buf b = {NULL, 0, 0, 0};
int is_error = 0;
char *result, flag;
child_fd = fd;
child_watch_parent(parent);
/* Ctrl-C to the terminal's group, or a TERM or HUP to it, aborts what
* runs here and still reports, as pic's own Ctrl-C does; a second one
* is pic's to act on. */
memset(&sa, 0, sizeof sa);
sa.sa_handler = child_on_signal;
sigemptyset(&sa.sa_mask);
(void)sigaction(SIGINT, &sa, NULL);
(void)sigaction(SIGTERM, &sa, NULL);
(void)sigaction(SIGHUP, &sa, NULL);
(void)signal(SIGPIPE, SIG_IGN);
(void)sigprocmask(SIG_SETMASK, mask, NULL);
pic_side_fd = fd;
pic_side_ready = child_side_ready;
pic_watch_fd = -1; /* the inbox is the parent's */
pic_watch_ready = NULL;
pic_proc_sink_set(&child_sink);
result = pic_toolset_run(workspace, c->tool, c->args, &mine, &is_error);
if (!result) {
_exit(0); /* pic reads EOF: lost, or never started */
}
flag = (char)(is_error != 0);
tp_put(&b, &flag, 1);
put_bytes(&b, result, strlen(result));
put_bytes(&b, output.data, output.len);
flag = image.data != NULL;
tp_put(&b, &flag, 1);
if (image.data) {
put_bytes(&b, image.mime, strlen(image.mime));
put_u64(&b, (uint64_t)image.width);
put_u64(&b, (uint64_t)image.height);
put_bytes(&b, image.data, image.len);
}
if (!b.bad) {
(void)send_frame(fd, 'R', b.p, b.n);
}
_exit(0);
}
/* ---- pic's side --------------------------------------------------------------- */
enum { WAITING, RUNNING, ENDED };
typedef struct {
int state, fd, told, got;
pid_t pid;
long long *procs; /* the sink's ids, by the child's numbers (1-based) */
size_t nprocs;
} par_slot;
static long long tp_now_ms(void) {
struct timespec t;
(void)clock_gettime(CLOCK_MONOTONIC, &t);
return (long long)t.tv_sec * 1000 + t.tv_nsec / 1000000;
}
static int conflicts(const pic_par_call *a, const pic_par_call *b) {
return a->key && b->key && (a->mutates || b->mutates) && strcmp(a->key, b->key) == 0;
}
static void tp_finish(par_slot *sl, pic_par_call *c, char *result, int is_error) {
if (sl->fd >= 0) {
close(sl->fd);
sl->fd = -1;
}
if (sl->pid > 0 && !result) {
(void)kill(sl->pid, SIGKILL); /* gone already, or past saying anything that parses */
}
if (sl->pid > 0) {
while (waitpid(sl->pid, NULL, 0) < 0 && errno == EINTR) {
}
sl->pid = 0;
}
/* A call that ended without reporting its processes' ends (killed, or
* dead): its supervisor kills a command when the call is gone. */
for (size_t k = 0; k < sl->nprocs; k++) {
const pic_proc_sink *sink = pic_proc_sink_get();
if (sink && sl->procs[k] >= 0) {
sink->end(sl->procs[k], -1, SIGKILL);
}
}
free(sl->procs);
sl->procs = NULL;
sl->nprocs = 0;
sl->state = ENDED;
if (!sl->got) {
sl->got = 1;
c->done(c->ctx, result, is_error);
} else {
free(result);
}
}
/* A call pic could not fork for runs here, the way a lone call does. */
static void run_here(const char *workspace, par_slot *sl, pic_par_call *c) {
int is_error = 0;
char *result = pic_toolset_run(workspace, c->tool, c->args, c->hooks, &is_error);
tp_finish(sl, c, result, is_error);
}
static void start(const char *workspace, par_slot *slots, pic_par_call *calls, size_t n, size_t i) {
int sv[2];
pid_t pid, self = getpid();
sigset_t stop, saved;
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) != 0) {
run_here(workspace, &slots[i], &calls[i]);
return;
}
/* Neither end reaches a command the child execs. */
(void)fcntl(sv[0], F_SETFD, FD_CLOEXEC);
(void)fcntl(sv[1], F_SETFD, FD_CLOEXEC);
/* Blocked across fork: an abort cannot kill the child before it has its
* handlers (child_main unblocks them). */
sigemptyset(&stop);
sigaddset(&stop, SIGINT);
sigaddset(&stop, SIGTERM);
sigaddset(&stop, SIGHUP);
(void)sigprocmask(SIG_BLOCK, &stop, &saved);
pid = fork();
if (pid == 0) {
/* pic's ends of the other calls: only pic may hold them, so each
* child sees EOF when pic dies. */
for (size_t k = 0; k < n; k++) {
if (slots[k].fd >= 0) {
close(slots[k].fd);
}
}
close(sv[0]);
child_main(workspace, &calls[i], sv[1], self, &saved);
}
(void)sigprocmask(SIG_SETMASK, &saved, NULL);
close(sv[1]);
if (pid < 0) {
close(sv[0]);
run_here(workspace, &slots[i], &calls[i]);
return;
}
slots[i].pid = pid;
slots[i].fd = sv[0];
slots[i].state = RUNNING;
}
/* One frame from a running call; -1 when it ended (EOF or garbage). */
static int serve(par_slot *sl, pic_par_call *c) {
const pic_tool_hooks *h = c->hooks;
const pic_proc_sink *sink = pic_proc_sink_get();
char type = 0, *payload = NULL;
uint64_t len = 0;
tp_rd r;
if (read_all(sl->fd, &type, 1) != 0 || read_all(sl->fd, &len, sizeof len) != 0 || len > FRAME_MAX ||
!(payload = malloc((size_t)len + 1)) || read_all(sl->fd, payload, (size_t)len) != 0) {
free(payload);
return -1;
}
payload[len] = '\0';
r = (tp_rd){payload, (size_t)len, 0, 0};
switch (type) {
case 'S':
case 's': {
char answer = h->started(h->ctx, type == 'S' ? payload : NULL, (size_t)len) == 0 ? 'A' : 'N';
(void)tp_write_all(sl->fd, &answer, 1);
break;
}
case 'F': {
size_t got = 0;
char *data = h->fetch ? h->fetch(h->ctx, payload, &got) : NULL;
uint64_t n = data ? (uint64_t)got : NONE;
(void)(tp_write_all(sl->fd, "D", 1) || tp_write_all(sl->fd, &n, sizeof n) || (data && tp_write_all(sl->fd, data, got)));
free(data);
break;
}
case 'C': { /* calls the tool makes, run in pic; the answer may take as long as they do */
uint64_t count = get_u64(&r);
pic_nested_call *calls = NULL;
tp_buf out = {NULL, 0, 0, 0};
char ok = 1;
uint64_t n64;
if (!r.bad && count <= 4096 && (calls = calloc(count ? (size_t)count : 1, sizeof *calls))) {
ok = 0;
for (uint64_t i = 0; i < count; i++) {
calls[i].tool = get_bytes(&r, NULL);
calls[i].input = get_bytes(&r, NULL);
calls[i].deadline_ms = (long long)get_u64(&r);
}
ok = r.bad || !h->call || h->call(h->call_ctx, calls, (size_t)count) != 0 ? 1 : 0;
}
tp_put(&out, &ok, 1);
for (uint64_t i = 0; calls && !ok && i < count; i++) {
char e = (char)(calls[i].is_error != 0);
tp_put(&out, &e, 1);
put_bytes(&out, calls[i].result, strlen(calls[i].result));
put_bytes(&out, calls[i].mime, calls[i].mime ? strlen(calls[i].mime) : 0);
put_bytes(&out, calls[i].image, calls[i].image_len);
}
for (uint64_t i = 0; calls && i < count; i++) {
free((char *)(uintptr_t)calls[i].tool);
free((char *)(uintptr_t)calls[i].input);
free(calls[i].result);
free(calls[i].image);
}
free(calls);
n64 = out.bad ? 1 : (uint64_t)out.n;
(void)(tp_write_all(sl->fd, "K", 1) || tp_write_all(sl->fd, &n64, sizeof n64) ||
tp_write_all(sl->fd, out.bad ? "\1" : out.p, (size_t)n64));
free(out.p);
break;
}
case 'P':
if (h->partial) {
h->partial(h->partial_ctx, payload);
}
break;
case 'B': {
uint64_t id = get_u64(&r), pid = get_u64(&r), pgid = get_u64(&r);
char *kind = get_bytes(&r, NULL), *command = get_bytes(&r, NULL);
long long *grown;
if (!r.bad && kind && command && id == sl->nprocs + 1 &&
(grown = realloc(sl->procs, (sl->nprocs + 1) * sizeof *grown))) {
sl->procs = grown;
sl->procs[sl->nprocs++] = sink ? sink->start(kind, command, (long)pid, (long)pgid) : -1;
}
free(kind);
free(command);
break;
}
case 'E': {
uint64_t id = get_u64(&r), code = get_u64(&r), sig = get_u64(&r);
if (!r.bad && sink && id >= 1 && id <= sl->nprocs && sl->procs[id - 1] >= 0) {
sink->end(sl->procs[id - 1], (int)(int64_t)code, (int)(int64_t)sig);
sl->procs[id - 1] = -1;
}
break;
}
case 'R': {
int is_error = len > 0 && payload[0] != 0;
if (len == 0) {
free(payload);
return -1;
}
char *result, *out, *mime = NULL, *data = NULL;
size_t out_len = 0, data_len = 0;
uint64_t width = 0, height = 0;
r.at = 1;
result = get_bytes(&r, NULL);
out = get_bytes(&r, &out_len);
if (!r.bad && r.at < r.n && r.p[r.at++]) {
mime = get_bytes(&r, NULL);
width = get_u64(&r);
height = get_u64(&r);
data = get_bytes(&r, &data_len);
}
if (r.bad || !result) {
free(result);
free(out);
free(mime);
free(data);
free(payload);
return -1;
}
if (out && h->output) {
h->output->data = out;
h->output->len = out_len;
} else {
free(out);
}
/* The image's type is one of the tool's own constant names. */
if (data && h->image) {
static const char *const mimes[] = {"image/png", "image/jpeg", "image/gif", "image/webp"};
for (size_t k = 0; k < sizeof mimes / sizeof mimes[0]; k++) {
if (mime && strcmp(mime, mimes[k]) == 0) {
h->image->mime = mimes[k];
}
}
if (h->image->mime) {
h->image->data = (unsigned char *)data;
h->image->len = data_len;
h->image->width = (long)width;
h->image->height = (long)height;
data = NULL;
}
}
free(mime);
free(data);
free(payload);
tp_finish(sl, c, result, is_error);
return 0;
}
default:
free(payload);
return -1;
}
free(payload);
return 0;
}
void pic_par_run(const char *workspace, pic_par_call *calls, size_t n) {
par_slot *slots = calloc(n ? n : 1, sizeof *slots);
struct pollfd *p = calloc(n + 2, sizeof *p);
if (!slots || !p) {
free(slots);
free(p);
for (size_t i = 0; i < n && !pic_interrupted; i++) {
par_slot one = {WAITING, -1, 0, 0, 0, NULL, 0};
run_here(workspace, &one, &calls[i]);
}
return;
}
for (size_t i = 0; i < n; i++) {
slots[i].fd = -1;
}
for (;;) {
size_t running = 0, np = 0;
for (size_t i = 0; i < n && !pic_interrupted; i++) {
int blocked = 0;
for (size_t j = 0; j < i && !blocked; j++) {
blocked = slots[j].state != ENDED && conflicts(&calls[i], &calls[j]);
}
if (slots[i].state == WAITING && !blocked) {
start(workspace, slots, calls, n, i);
}
}
for (size_t i = 0; i < n; i++) {
if (slots[i].state != RUNNING) {
continue;
}
running++;
if (!slots[i].told && calls[i].deadline_ms && tp_now_ms() > calls[i].deadline_ms) {
slots[i].told = tp_write_all(slots[i].fd, "c", 1) == 0; /* its caller's deadline: aborted */
(void)kill(slots[i].pid, SIGINT);
}
if (pic_interrupted && !slots[i].told) {
/* 'c' for a command's supervisor to kill it and report;
* SIGINT ends a wait a tool is blocked in (EINTR). */
slots[i].told = tp_write_all(slots[i].fd, "c", 1) == 0;
(void)kill(slots[i].pid, SIGINT);
}
p[np++] = (struct pollfd){slots[i].fd, POLLIN, 0};
}
if (!running) {
break;
}
p[np] = (struct pollfd){pic_side_ready ? pic_side_fd : -1, POLLIN, 0};
p[np + 1] = (struct pollfd){pic_watch_ready ? pic_watch_fd : -1, POLLIN, 0};
if (poll(p, (nfds_t)np + 2, 200) <= 0) {
continue;
}
if (p[np].revents && pic_side_ready) {
pic_side_ready();
}
if (p[np + 1].revents && pic_watch_ready) {
pic_watch_ready();
}
for (size_t i = 0, k = 0; i < n && k < np; i++) {
if (slots[i].state != RUNNING || slots[i].fd != p[k].fd) {
continue;
}
if (p[k++].revents && serve(&slots[i], &calls[i]) != 0) {
tp_finish(&slots[i], &calls[i], NULL, 0);
}
}
}
free(slots);
free(p);
}