Skip to content
suit Artifact [222fc3f249]
Login

Artifact [222fc3f249]

Artifact 222fc3f249a47cf3f3981ab00022c6e85f21b0c9f8fcbd65a962508adb8d964b:


#include "upstream.h"

#include "attention.h"
#include "platform.h"
#include "stamp.h"
#include "store.h"
#include "wardrobes.h"

#include <errno.h>
#include <fcntl.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>

constexpr size_t PATH_CAP = 4096;
constexpr size_t PATH_ROOM = 640;
constexpr int DEPTH_MAX = 32;

// ---- reading the folder ---------------------------------------------------------------

typedef struct {
    UpstreamFiles *f;
    const char *upstream;
    int depth;
    char rel[UPSTREAM_REL_MAX + 1];  // the folder being read, below the root
} Walk;

static int walk_dir(Walk *w);

static void walk_path(const Walk *w, char *out, size_t cap)
{
    [[maybe_unused]] int n = snprintf(out, cap, "%s%s%s", w->f->root, w->rel[0] != '\0' ? "/" : "", w->rel);
    ensure(n > 0 && (size_t)n < cap);
}

static int add_file(Walk *w, const struct stat *st)
{
    UpstreamFiles *f = w->f;
    uint64_t size = (uint64_t)st->st_size;
    if (f->n == UPSTREAM_FILES_MAX) {
        say(STDERR_FILENO, "suit: upstream %s: more than %u files; nothing is taken\n", w->upstream,
            UPSTREAM_FILES_MAX);
        return 1;
    }
    if (f->bytes + size > UPSTREAM_BYTES_MAX) {
        say(STDERR_FILENO, "suit: upstream %s: more than %llu MiB in all; nothing is taken\n", w->upstream,
            (unsigned long long)(UPSTREAM_BYTES_MAX >> 20));
        return 1;
    }
    char *name = f->pool[f->n];
    [[maybe_unused]] int n = snprintf(name, sizeof f->pool[0], "%s%s", f->prefix, w->rel);
    ensure(n > 0 && (size_t)n < sizeof f->pool[0]);
    f->f[f->n].name = name;
    f->f[f->n].size = size;
    f->f[f->n].exec = (st->st_mode & S_IXUSR) != 0;
    f->n++;
    f->bytes += size;
    return 0;
}

// What the stamp says of one file or folder: its path, size, times, inode and
// whether it is a file and executable, which are what a take could see change
// short of reading the content. The sum does not depend on the order of the
// entries.
constexpr uint64_t FNV_BASIS = 14695981039346656037ULL;

static uint64_t fnv(uint64_t h, const void *data, size_t n)
{
    const unsigned char *b = data;
    for (size_t i = 0; i < n; i++) h = (h ^ b[i]) * 1099511628211ULL;
    return h;
}

static uint64_t fnv_num(uint64_t h, uint64_t v)
{
    for (int shift = 0; shift < 64; shift += 8) h = (h ^ ((v >> shift) & 0xff)) * 1099511628211ULL;
    return h;
}

static void stamp_mix(UpstreamFiles *f, const char *rel, const struct stat *st)
{
    uint64_t h = fnv_num(fnv(FNV_BASIS, rel, strlen(rel)), strlen(rel));
    h = fnv_num(h, (uint64_t)st->st_size);
    h = fnv_num(h, (uint64_t)platform_mtime_sec(st));
    h = fnv_num(h, (uint64_t)platform_mtime_nsec(st));
    h = fnv_num(h, (uint64_t)st->st_ino);
    f->stamp += fnv_num(h, (uint64_t)(st->st_mode & (S_IFMT | S_IXUSR)));
}

// An entry of the folder: skip a name that starts with a dot, refuse a symlink,
// read into a folder, take a regular file.
static int walk_entry(void *state, const char *entry)
{
    Walk *w = state;
    if (entry[0] == '.') return 0;
    size_t len = strlen(w->rel);
    if (len + strlen(entry) + 1 > UPSTREAM_REL_MAX) {
        say(STDERR_FILENO, "suit: upstream %s: a path is longer than %zu bytes: %s/%s\n", w->upstream,
            UPSTREAM_REL_MAX, w->rel, entry);
        return 1;
    }
    snprintf(w->rel + len, sizeof w->rel - len, "%s%s", len > 0 ? "/" : "", entry);
    char path[sizeof w->f->root + UPSTREAM_REL_MAX + 2];
    walk_path(w, path, sizeof path);
    struct stat st = {};
    int rc = 0;
    if (sys_lstat(path, &st) != 0) {
        say(STDERR_FILENO, "suit: upstream %s: cannot look at %s: %s\n", w->upstream, path, strerror(errno));
        rc = 1;
    } else if (S_ISLNK(st.st_mode)) {
        say(STDERR_FILENO, "suit: upstream %s: %s is a symlink; symlinks are not taken\n", w->upstream, path);
        rc = 1;
    } else if (S_ISDIR(st.st_mode)) {
        stamp_mix(w->f, w->rel, &st);
        rc = walk_dir(w);
    } else if (S_ISREG(st.st_mode)) {
        stamp_mix(w->f, w->rel, &st);
        rc = add_file(w, &st);
    } else {
        say(STDERR_FILENO, "suit: upstream %s: %s is neither a file nor a folder\n", w->upstream, path);
        rc = 1;
    }
    w->rel[len] = '\0';
    return rc;
}

static int walk_dir(Walk *w)
{
    char path[sizeof w->f->root + UPSTREAM_REL_MAX + 2];
    walk_path(w, path, sizeof path);
    if (w->depth == DEPTH_MAX) {
        say(STDERR_FILENO, "suit: upstream %s: folders are nested more than %d deep at %s\n", w->upstream,
            DEPTH_MAX, path);
        return 1;
    }
    w->depth++;
    int rc = sys_listdir(path, walk_entry, w);
    w->depth--;
    if (rc < 0) {
        say(STDERR_FILENO, "suit: upstream %s: cannot read %s: %s\n", w->upstream, path, strerror(errno));
        return 1;
    }
    return rc;
}

static int compare_files(const void *a, const void *b)
{
    const UpstreamFile *fa = a;
    const UpstreamFile *fb = b;
    return strcmp(fa->name, fb->name);
}

int upstream_scan(UpstreamFiles *f, const char *name, const char *folder, const char *path, const char *into)
{
    f->n = 0;
    f->bytes = 0;
    f->stamp = 0;
    int n = snprintf(f->root, sizeof f->root, "%s%s%s", folder, path != nullptr ? "/" : "",
        path != nullptr ? path : "");
    if ((size_t)n >= sizeof f->root) {
        say(STDERR_FILENO, "suit: upstream %s: the folder's path is longer than %zu bytes\n", name,
            sizeof f->root - 1);
        return 1;
    }
    struct stat st = {};
    if (sys_stat(f->root, &st) != 0) {
        say(STDERR_FILENO, "suit: upstream %s: cannot read %s: %s\n", name, f->root, strerror(errno));
        return 1;
    }
    if (!S_ISDIR(st.st_mode)) {
        say(STDERR_FILENO, "suit: upstream %s: %s is not a folder\n", name, f->root);
        return 1;
    }
    f->into_len = (size_t)snprintf(f->prefix, sizeof f->prefix, "%s/", into);
    const char *below = path != nullptr ? path : "";
    uint64_t h = fnv_num(fnv(FNV_BASIS, folder, strlen(folder)), strlen(folder));
    h = fnv_num(fnv(h, below, strlen(below)), strlen(below));
    f->stamp = fnv_num(fnv(h, into, strlen(into)), strlen(into));
    stamp_mix(f, "", &st);
    Walk w = {.f = f, .upstream = name};
    if (walk_dir(&w) != 0) return 1;
    qsort(f->f, f->n, sizeof f->f[0], compare_files);
    return 0;
}

// ---- the config -------------------------------------------------------------------------

static Conf conf;  // every wardrobe's config, as one set
static Wards wards;
static UpstreamFiles files;

typedef struct {
    const char *name;
    const char *ward;  // the wardrobe whose config defines it
    const char *url;   // nullptr when the config has none
    const char *pin;   // nullptr when the config has none
    const char *path;  // nullptr: the folder's top
    const char *into;
    bool auto_trust;
} Up;

static const char *entry_value(const Section *s, const char *key)
{
    for (uint32_t i = 0; i < s->count; i++) {
        const Entry *e = &conf.entries[s->first + i];
        if (strcmp(e->key, key) == 0) return e->val;
    }
    return nullptr;
}

static void describe(const Section *s, Up *u)
{
    const char *into = entry_value(s, "into");
    const char *trust = entry_value(s, "trust");
    u->name = s->arg[0];
    u->ward = wards.w[s->ward].name;
    u->url = entry_value(s, "url");
    u->pin = entry_value(s, "pin");
    u->path = entry_value(s, "path");
    u->into = into != nullptr ? into : "skills";
    u->auto_trust = trust != nullptr && strcmp(trust, "auto") == 0;
}

constexpr int LOAD_NONE = -1;  // QUIET only: there is no wardrobe

// Every wardrobe's config. 0, or the exit code after a message; with QUIET, no
// wardrobe at all is LOAD_NONE and says nothing.
static int load_config(bool quiet)
{
    char dir[PATH_CAP];
    size_t len = suit_home_path(dir, sizeof dir, "store");
    if (len == 0) return 1;
    // Room for a name of any length under the store, which no folder can exceed.
    if (len + PATH_ROOM > PATH_CAP) {
        say(STDERR_FILENO, "suit: SUIT_HOME is longer than %zu bytes\n", PATH_CAP - PATH_ROOM);
        return 1;
    }
    dir[len] = '\0';
    int rc = wardrobes_look(&wards, dir, !quiet);
    if (rc == 2 && wards.n == 0 && quiet) return LOAD_NONE;
    if (rc != 0) return rc;
    return wardrobes_load(&wards, &conf) == 0 ? 0 : 2;
}

static int find_upstream(const char *name, Up *u)
{
    for (uint32_t i = 0; i < conf.nsections; i++) {
        if (conf.sections[i].kind != KIND_UPSTREAM || strcmp(conf.sections[i].arg[0], name) != 0) continue;
        describe(&conf.sections[i], u);
        return 0;
    }
    say(STDERR_FILENO, "suit: no upstream %.60s in the config of any wardrobe\n", name);
    return 2;
}

// True if PATH is relative and none of its parts is "..".
static bool relative_path(const char *path)
{
    if (path[0] == '/' || path[0] == '~') return false;
    for (const char *s = path; *s != '\0';) {
        size_t len = strcspn(s, "/");
        if (len == 2 && s[0] == '.' && s[1] == '.') return false;
        s += len + (s[len] == '/' ? 1 : 0);
    }
    return true;
}

// ---- the commands -------------------------------------------------------------------------

static int usage(void)
{
    say(STDERR_FILENO, "usage: suit upstream NAME take [FOLDER]\n"
        "       suit upstream NAME accept [--theirs PATH] [--mine PATH]...\n"
        "       suit upstream NAME diff\n"
        "       suit upstream NAME undo\n"
        "       suit upstreams\n");
    return 2;
}

// A local upstream's url is file:// and an absolute path ("Local upstreams").
// Returns 1 with that path in *FOLDER, 0 for any other url, 2 after a message
// for file:// and something else.
static int local_folder(const Up *u, const char **folder)
{
    if (u->url == nullptr || strncmp(u->url, "file://", 7) != 0) return 0;
    if (u->url[7] != '/') {
        say(STDERR_FILENO, "suit: upstream %s: a file:// url needs an absolute path (file:///FOLDER), not %.60s\n",
            u->name, u->url);
        return 2;
    }
    *folder = u->url + 7;
    return 1;
}

// The config's pin and path are fit to take from. A local upstream needs no pin.
static int check_up(const Up *u, bool local)
{
    if (u->pin == nullptr && !local) {
        say(STDERR_FILENO, "suit: upstream %s: the config has no pin; add pin = WORD to [upstream %s]\n", u->name,
            u->name);
        return 2;
    }
    if (u->pin != nullptr && strlen(u->pin) > UPSTREAM_PIN_MAX) {
        say(STDERR_FILENO, "suit: upstream %s: the pin is longer than %zu bytes\n", u->name, UPSTREAM_PIN_MAX);
        return 2;
    }
    if (u->path != nullptr && !relative_path(u->path)) {
        say(STDERR_FILENO, "suit: upstream %s: path must be relative with no .. part, not %.60s\n", u->name,
            u->path);
        return 2;
    }
    return 0;
}

// Check in what upstream_scan read into FILES, and accept it with trust = auto.
// A local upstream's pin is "from FOLDER", and ends with " at PIN" if the config has one.
static int take_files(const Up *u, const char *folder, bool local)
{
    char label[UPSTREAM_PIN_MAX + 1];
    const char *pin = u->pin;
    if (local) {
        snprintf(label, sizeof label, "from %s%s%s", folder, u->pin != nullptr ? " at " : "",
            u->pin != nullptr ? u->pin : "");
        pin = label;
    }
    UpstreamSpec spec = {.name = u->name, .pin = pin, .into = u->into, .auto_accept = u->auto_trust};
    bool taken;
    int rc = store_upstream_take(u->ward, &spec, &files, &taken);
    if (rc != 0 || !taken || !spec.auto_accept) return rc;
    static const UpstreamSettle none;
    return store_upstream_accept(u->ward, u->name, &none);
}

static int do_take(const Up *u, const char *folder, bool local)
{
    int rc = check_up(u, local);
    if (rc != 0) return rc;
    rc = upstream_scan(&files, u->name, folder, u->path, u->into);
    if (rc == 0 && files.n == 0) {
        say(STDERR_FILENO, "suit: upstream %s: %s holds no files to take\n", u->name, files.root);
        return 1;
    }
    return rc != 0 ? rc : take_files(u, folder, local);
}

// --theirs PATH and --mine PATH, each as often as wanted, no PATH in both. ARGC - 4 is even.
static int parse_settle(int argc, char **argv, UpstreamSettle *s)
{
    for (int i = 4; i < argc; i += 2) {
        bool theirs = strcmp(argv[i], "--theirs") == 0;
        bool mine = strcmp(argv[i], "--mine") == 0;
        if (!(theirs || mine)) return usage();
        uint32_t *n = theirs ? &s->ntheirs : &s->nmine;
        if (*n == UPSTREAM_SETTLE_MAX) {
            say(STDERR_FILENO, "suit: more than %u paths for %s\n", UPSTREAM_SETTLE_MAX, argv[i]);
            return 2;
        }
        (theirs ? s->theirs : s->mine)[(*n)++] = argv[i + 1];
    }
    for (uint32_t i = 0; i < s->ntheirs; i++) {
        for (uint32_t j = 0; j < s->nmine; j++) {
            if (strcmp(s->theirs[i], s->mine[j]) != 0) continue;
            say(STDERR_FILENO, "suit: %.200s is named by both --theirs and --mine\n", s->theirs[i]);
            return 2;
        }
    }
    return 0;
}

int cmd_upstream(int argc, char **argv)
{
    const char *verb = argv[3];
    bool take = strcmp(verb, "take") == 0;
    bool accept = strcmp(verb, "accept") == 0;
    bool diff = strcmp(verb, "diff") == 0;
    bool undo = strcmp(verb, "undo") == 0;
    if (!(take || accept || diff || undo) || (take && argc > 5) || ((diff || undo) && argc != 4)) return usage();
    UpstreamSettle settle = {};
    if (accept && (argc - 4) % 2 != 0) return usage();
    int rc = accept ? parse_settle(argc, argv, &settle) : 0;
    rc = rc != 0 ? rc : load_config(false);
    Up u;
    rc = rc != 0 ? rc : find_upstream(argv[2], &u);
    if (rc != 0) return rc;
    if (take) {
        const char *folder = nullptr;
        rc = local_folder(&u, &folder);
        if (rc == 2) return rc;
        if (argc == 5) folder = argv[4];
        if (folder == nullptr) {
            say(STDERR_FILENO, "suit: upstream %s: no FOLDER to take from; its url is not file:///FOLDER\n", u.name);
            return 2;
        }
        return do_take(&u, folder, rc == 1);
    }
    if (accept) return store_upstream_accept(u.ward, u.name, &settle);
    if (undo) return store_upstream_undo(u.ward, u.name);
    return store_upstream_diff(u.ward, u.name);
}

static int compare_sections(const void *a, const void *b)
{
    return strcmp(conf.sections[*(const uint32_t *)a].arg[0], conf.sections[*(const uint32_t *)b].arg[0]);
}

int cmd_upstreams(void)
{
    static const char *const words[] = {"never taken", "current", "waiting for review", "conflict"};
    int rc = load_config(false);
    if (rc != 0) return rc;
    uint32_t order[CONF_UPSTREAM_MAX];
    uint32_t n = 0;
    for (uint32_t i = 0; i < conf.nsections; i++)
        if (conf.sections[i].kind == KIND_UPSTREAM) order[n++] = i;
    qsort(order, n, sizeof order[0], compare_sections);
    int worst = 0;
    for (uint32_t i = 0; i < n; i++) {
        Up u;
        describe(&conf.sections[order[i]], &u);
        UpstreamState state;
        char taken[UPSTREAM_PIN_MAX + 1];
        rc = store_upstream_state(u.ward, u.name, &state, taken, sizeof taken);
        worst = rc > worst ? rc : worst;
        if (rc != 0) continue;
        const char *pin = u.pin != nullptr ? u.pin : "none";
        if (state == UPSTREAM_NEVER_TAKEN) say(STDOUT_FILENO, "%s: never taken (config %s)\n", u.name, pin);
        else say(STDOUT_FILENO, "%s: %s (taken %s, config %s)\n", u.name, words[state], taken, pin);
    }
    return worst;
}

// ---- local upstreams, taken by `suit tend` ----------------------------------------------------

// The file that holds what an upstream's folder looked like at its last take.
static void stamp_path(const char *name, char *out, size_t cap)
{
    char leaf[CONF_NAME_MAX + 32];
    snprintf(leaf, sizeof leaf, "upstream-%s.stamp", name);
    [[maybe_unused]] size_t home = suit_home_path(out, cap, leaf);
    ensure(home != 0);  // load_config found the home folder
}

constexpr size_t STAMP_TEXT_MAX = 96;

static size_t stamp_text(const UpstreamFiles *f, char *out)
{
    int n = snprintf(out, STAMP_TEXT_MAX, "suit upstream stamp 1 %016" PRIx64 " %u\n", f->stamp, f->n);
    ensure(n > 0 && (size_t)n < STAMP_TEXT_MAX);
    return (size_t)n;
}

// Whether the stamp file at PATH holds the N bytes of WANT. One that cannot be
// read is not the stamp: the folder is taken, which finds no change if there is none.
static bool stamp_current(const char *path, const char *want, size_t n)
{
    char have[STAMP_TEXT_MAX + 1];
    ssize_t got = -1;
    int fd = sys_open(path, O_RDONLY, 0);
    if (fd >= 0) {
        got = sys_read(fd, have, sizeof have);
        (void)sys_close(fd);
    }
    return got == (ssize_t)n && memcmp(have, want, n) == 0;
}

static int stamp_save(const char *path, const char *text, size_t n)
{
    int err = sys_write_atomic(path, text, n);
    if (err != 0) say(STDERR_FILENO, "suit: cannot write %s: %s\n", path, strerror(err));
    return err == 0 ? 0 : 1;
}

static void missing_item(const Up *u, const char *folder, char *out, size_t cap)
{
    snprintf(out, cap, "upstream %s: folder %s is missing", u->name, folder);
}

// The item "folder FOLDER is missing" of any folder, which the upstream's own item replaced.
static bool is_missing_item(const Up *u, const char *header)
{
    char start[CONF_NAME_MAX + 32];
    snprintf(start, sizeof start, "upstream %s: folder ", u->name);
    size_t len = strlen(header);
    static const char end[] = " is missing";
    // The start is longer than the end, so the end is inside the header when the start is.
    return strncmp(header, start, strlen(start)) == 0 && strcmp(header + len - (sizeof end - 1), end) == 0;
}

// The folder is back: the item that said it was missing goes, and is replaced
// by the one it replaced, "waiting for review", if the upstream is waiting.
static int folder_is_back(const Up *u, const char *attention)
{
    char header[PATH_CAP + 128];
    if (attention_header(attention, ATTENTION_UPSTREAM, u->name, header, sizeof header) != 0) return 1;
    if (!is_missing_item(u, header)) return 0;
    UpstreamState state;
    char taken[UPSTREAM_PIN_MAX + 1];
    int rc = store_upstream_state(u->ward, u->name, &state, taken, sizeof taken);
    if (rc != 0) return rc;
    if (state != UPSTREAM_WAITING) return attention_remove(attention, ATTENTION_UPSTREAM, u->name);
    snprintf(header, sizeof header, "upstream %s: update waiting for review", u->name);
    return attention_add(attention, ATTENTION_UPSTREAM, u->name, header, nullptr);
}

// One local upstream: a missing folder is an item; an empty one is left alone; a folder whose stamp is the
// saved one is left alone; any other is taken, and the stamp saved if that went through
// (a conflict on accept is an item already).
static int tend_one(const Up *u, const char *folder, const char *attention)
{
    struct stat st = {};
    if (sys_stat(folder, &st) != 0 && errno == ENOENT) {
        char header[PATH_CAP + 128];
        missing_item(u, folder, header, sizeof header);
        return attention_add(attention, ATTENTION_UPSTREAM, u->name, header, nullptr);
    }
    int rc = folder_is_back(u, attention);
    rc = rc != 0 ? rc : check_up(u, true);
    rc = rc != 0 ? rc : upstream_scan(&files, u->name, folder, u->path, u->into);
    // An empty folder is nothing to take yet (an inbox with nothing in it), not an error.
    if ((rc != 0) | (files.n == 0)) return rc;
    char path[PATH_CAP];
    char text[STAMP_TEXT_MAX];
    stamp_path(u->name, path, sizeof path);
    size_t n = stamp_text(&files, text);
    if (stamp_current(path, text, n)) return 0;
    rc = take_files(u, folder, true);
    if (rc != 0 && rc != EXIT_CONFLICT) return rc;
    return stamp_save(path, text, n);
}

int upstream_tend_local(void)
{
    // A config that cannot be read has said so; it does not change tend's exit, as for the usage scan.
    int rc = load_config(true);
    if (rc != 0) return 0;
    char attention[PATH_CAP];
    [[maybe_unused]] size_t home = suit_home_path(attention, sizeof attention, "attention");
    ensure(home != 0);  // load_config found the home folder
    uint32_t order[CONF_UPSTREAM_MAX];
    uint32_t n = 0;
    for (uint32_t i = 0; i < conf.nsections; i++)
        if (conf.sections[i].kind == KIND_UPSTREAM) order[n++] = i;
    qsort(order, n, sizeof order[0], compare_sections);
    int worst = 0;
    for (uint32_t i = 0; i < n; i++) {
        Up u;
        describe(&conf.sections[order[i]], &u);
        const char *folder = nullptr;
        rc = local_folder(&u, &folder);
        if (rc == 1) rc = tend_one(&u, folder, attention);
        worst = rc > worst ? rc : worst;
    }
    return worst;
}