Skip to content
suit Artifact [77a9bc075c]
Login

Artifact [77a9bc075c]

Artifact 77a9bc075c0ec57d0e8f8f3637a6572e727eefd1bf1057996d85b4e97ac7cf55:


#include "hook.h"

#include "platform.h"
#include "stamp.h"

#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

constexpr size_t COPY_CHUNK = 65536;
constexpr int EXIT_FAIL = 1;
constexpr int SIGNAL_BASE = 128;

bool hook_event_ok(const char *event)
{
    static const char allowed[] =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-";
    size_t n = strlen(event);
    if (n < 1 || n > HOOK_EVENT_MAX || event[0] == '.') return false;
    for (size_t i = 0; i < n; i++)
        if (strchr(allowed, event[i]) == nullptr) return false;
    return true;
}

// A, B and C joined into OUT, which is large enough (callers bound each part).
static void cat3(char *out, const char *a, const char *b, const char *c)
{
    size_t la = strlen(a), lb = strlen(b);
    memcpy(out, a, la);
    memcpy(out + la, b, lb);
    memcpy(out + la + lb, c, strlen(c) + 1);
}

HookForm hook_probe(const char *event, char *slot, size_t cap)
{
    char name[HOOK_EVENT_MAX + 16];
    cat3(name, "slots/hook/", event, "");
    if (suit_home_path(slot, cap, name) == 0) return HOOK_FAILED;
    struct stat st;
    if (sys_lstat(slot, &st) < 0) {
        if (errno == ENOENT || errno == ENOTDIR) return HOOK_ABSENT;
        say(STDERR_FILENO, "suit: hook %s: cannot look at %s: %s\n", event, slot, strerror(errno));
        return HOOK_FAILED;
    }
    // A link to a folder is a folder; a link that leads nowhere is one program
    // that will not run.
    return sys_stat(slot, &st) == 0 && S_ISDIR(st.st_mode) ? HOOK_FOLDER : HOOK_SINGLE;
}

typedef struct {
    char (*names)[HOOK_NAME_MAX + 1];
    int cap;
    int count;
    bool over;
} Collect;

static int collect_one(void *state, const char *name)
{
    Collect *c = state;
    if (name[0] == '.') return 0;
    if (c->count == c->cap) {
        c->over = true;
        return 1;
    }
    ensure(strlen(name) <= HOOK_NAME_MAX);
    memcpy(c->names[c->count++], name, strlen(name) + 1);
    return 0;
}

int hook_collect(const char *dir, char (*names)[HOOK_NAME_MAX + 1], int cap, int *count)
{
    Collect c = {.names = names, .cap = cap};
    if (sys_listdir(dir, collect_one, &c) < 0) return -1;
    // Insertion sort by byte order: at most 64 names.
    for (int i = 1; i < c.count; i++) {
        char tmp[HOOK_NAME_MAX + 1];
        memcpy(tmp, names[i], sizeof tmp);
        int j = i;
        for (; j > 0 && strcmp(names[j - 1], tmp) > 0; j--)
            memcpy(names[j], names[j - 1], sizeof tmp);
        memcpy(names[j], tmp, sizeof tmp);
    }
    *count = c.count;
    return c.over ? 1 : 0;
}

int hook_programs(const char *event, const char *slot, HookForm form, HookSet *set)
{
    if (form == HOOK_SINGLE) {
        set->count = 1;
        set->names[0][0] = '\0';
        return 0;
    }
    int rc = hook_collect(slot, set->names, HOOK_PROGRAMS_MAX, &set->count);
    if (rc < 0) {
        say(STDERR_FILENO, "suit: hook %s: cannot read %s: %s\n", event, slot, strerror(errno));
        return EXIT_FAIL;
    }
    if (rc > 0) {
        say(STDERR_FILENO, "suit: hook %s: more than %d programs\n", event, HOOK_PROGRAMS_MAX);
        return EXIT_FAIL;
    }
    return 0;
}

static void utoa(char *out, unsigned v)
{
    char rev[12];
    size_t n = 0;
    do rev[n++] = (char)('0' + v % 10);
    while ((v /= 10) > 0);
    while (n > 0) *out++ = rev[--n];
    *out = '\0';
}

// Standard input copied into a new file that is already unlinked, left in FD
// as a read-only descriptor at offset 0, so no program can change what the next
// one reads. 0, or an exit status after a message.
static int fill_spool(const char *event, int *fdp)
{
    char name[HOOK_EVENT_MAX];
    cat3(name, SUIT_TMP_PREFIX, "hook.", "");
    utoa(name + strlen(name), platform_pid());
    char path[HOOK_PATH_MAX + HOOK_EVENT_MAX];
    if (suit_home_path(path, HOOK_PATH_MAX, name) == 0) return EXIT_FAIL;
    int fd = sys_open(path, O_RDWR | O_CREAT | O_EXCL, 0600);
    if (fd < 0) {
        // The home folder will not take it: the temporary folder.
        const char *tmp = sys_getenv("TMPDIR");
        if (tmp == nullptr || strlen(tmp) >= HOOK_PATH_MAX) tmp = "/tmp";
        cat3(path, tmp, "/", name);
        fd = sys_open(path, O_RDWR | O_CREAT | O_EXCL, 0600);
        if (fd < 0) {
            say(STDERR_FILENO, "suit: hook %s: cannot make a temporary file: %s\n", event,
                strerror(errno));
            return EXIT_FAIL;
        }
    }
    // The read-only descriptor the programs get, opened before the unlink.
    int rfd = sys_open(path, O_RDONLY, 0);
    if (rfd < 0) {
        say(STDERR_FILENO, "suit: hook %s: cannot reopen the temporary file: %s\n", event,
            strerror(errno));
        (void)sys_unlink(path);
        (void)sys_close(fd);
        return EXIT_FAIL;
    }
    // Unlinked at once, so nothing is left behind whatever happens next.
    if (sys_unlink(path) < 0) {
        say(STDERR_FILENO, "suit: hook %s: cannot remove %s: %s\n", event, path, strerror(errno));
        (void)sys_close(rfd);
        (void)sys_close(fd);
        return EXIT_FAIL;
    }
    char buf[COPY_CHUNK];
    size_t total = 0;
    for (;;) {
        ssize_t n = sys_read(STDIN_FILENO, buf, sizeof buf);
        if (n < 0 && errno == EINTR) continue;
        if (n < 0) {
            say(STDERR_FILENO, "suit: hook %s: cannot read standard input: %s\n", event,
                strerror(errno));
            (void)sys_close(fd);
            (void)sys_close(rfd);
            return EXIT_FAIL;
        }
        if (n == 0) break;
        total += (size_t)n;
        if (total > HOOK_INPUT_MAX) {
            say(STDERR_FILENO, "suit: hook %s: standard input is over %zu MiB\n", event,
                HOOK_INPUT_MAX >> 20);
            (void)sys_close(fd);
            (void)sys_close(rfd);
            return HOOK_EXIT_INPUT;
        }
        if (!sys_write_all(fd, buf, (size_t)n)) {
            say(STDERR_FILENO, "suit: hook %s: cannot write the input: %s\n", event,
                strerror(errno));
            (void)sys_close(fd);
            (void)sys_close(rfd);
            return EXIT_FAIL;
        }
    }
    (void)sys_close(fd);
    *fdp = rfd;
    return 0;
}

// Standard input, made into a file every program can read from the start, as
// descriptor 0. Standard input that is closed or a terminal gives an empty one.
// 0, or an exit status after a message.
static int spool_input(const char *event)
{
    struct stat st;
    int fd;
    if (sys_fstat(STDIN_FILENO, &st) < 0 || platform_isatty(STDIN_FILENO)) {
        fd = sys_open("/dev/null", O_RDONLY, 0);
        if (fd < 0) {
            say(STDERR_FILENO, "suit: hook %s: cannot open /dev/null: %s\n", event, strerror(errno));
            return EXIT_FAIL;
        }
    } else {
        int rc = fill_spool(event, &fd);
        if (rc != 0) return rc;
    }
    if (fd == STDIN_FILENO) return 0;
    int rc = sys_dup2(fd, STDIN_FILENO);
    if (rc < 0) say(STDERR_FILENO, "suit: hook %s: cannot set up input: %s\n", event, strerror(errno));
    (void)sys_close(fd);
    return rc < 0 ? EXIT_FAIL : 0;
}

// The status a wait result stands for.
static int status_of(int status)
{
    if (WIFEXITED(status)) return WEXITSTATUS(status);
    ensure(WIFSIGNALED(status));
    return SIGNAL_BASE + WTERMSIG(status);
}

static int run_programs(const char *event, const char *slot, const HookSet *set)
{
    if (sys_setenv("SUIT_HOOK_EVENT", event) < 0) {
        say(STDERR_FILENO, "suit: hook %s: cannot set the environment: %s\n", event, strerror(errno));
        return EXIT_FAIL;
    }
    char ev[HOOK_EVENT_MAX + 1];
    memcpy(ev, event, strlen(event) + 1);
    int first = 0;
    for (int i = 0; i < set->count; i++) {
        const char *name = set->names[i];
        char path[HOOK_PATH_MAX + HOOK_NAME_MAX + 2];
        char label[HOOK_EVENT_MAX + HOOK_NAME_MAX + 2];
        if (name[0] == '\0') {
            cat3(path, slot, "", "");
            cat3(label, event, "", "");
        } else {
            cat3(path, slot, "/", name);
            cat3(label, event, "/", name);
        }
        // Programs share one open file, so each starts from the beginning.
        if (sys_lseek(STDIN_FILENO, 0, SEEK_SET) < 0) {
            say(STDERR_FILENO, "suit: hook %s: cannot rewind the input: %s\n", label, strerror(errno));
            return EXIT_FAIL;
        }
        char *argv[] = {path, ev, nullptr};
        pid_t pid;
        int rc = sys_spawn(&pid, path, argv);
        int status;
        if (rc != 0) {
            say(STDERR_FILENO, "suit: hook %s: cannot run: %s\n", label, strerror(rc));
            status = HOOK_EXIT_CANNOT;
        } else {
            int w;
            while ((w = (int)sys_wait4(pid, &status, nullptr)) < 0 && errno == EINTR) {}
            if (w < 0) {
                say(STDERR_FILENO, "suit: hook %s: cannot wait: %s\n", label, strerror(errno));
                return EXIT_FAIL;
            }
            status = status_of(status);
        }
        if (status == HOOK_EXIT_BLOCK) return HOOK_EXIT_BLOCK;
        if (first == 0) first = status;
    }
    return first;
}

// Apart from hook_dispatch so the absent case has a small frame.
[[gnu::noinline]] static int dispatch_present(const char *event, const char *slot, HookForm form)
{
    HookSet set;
    int rc = hook_programs(event, slot, form, &set);
    if (rc != 0 || set.count == 0) return rc;
    rc = spool_input(event);
    if (rc != 0) return rc;
    return run_programs(event, slot, &set);
}

int hook_dispatch(const char *event)
{
    if (!hook_event_ok(event)) {
        say(STDERR_FILENO, "suit: hook: the event is 1 to %zu letters, digits and . _ - "
            "and does not start with a dot\n", HOOK_EVENT_MAX);
        return HOOK_EXIT_USAGE;
    }
    char slot[HOOK_PATH_MAX];
    HookForm form = hook_probe(event, slot, sizeof slot);
    if (form == HOOK_ABSENT) return 0;
    if (form == HOOK_FAILED) return EXIT_FAIL;
    return dispatch_present(event, slot, form);
}