Skip to content
suit Documentation
Login

Documentation

#include "upstream.h"

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

#include <errno.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;
}

// 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)) {
        rc = walk_dir(w);
    } else if (S_ISREG(st.st_mode)) {
        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;
    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);
    Walk w = {.f = f, .upstream = name};
    if (walk_dir(&w) != 0) return 1;
    if (f->n == 0) {
        say(STDERR_FILENO, "suit: upstream %s: %s holds no files to take\n", name, f->root);
        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 *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->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;
}

// Every wardrobe's config. 0, or the exit code after a message.
static int load_config(void)
{
    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_find(&wards, dir);
    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 upstreams\n");
    return 2;
}

static int do_take(const Up *u, const char *folder)
{
    if (u->pin == nullptr) {
        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 (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;
    }
    int rc = upstream_scan(&files, u->name, folder, u->path, u->into);
    if (rc != 0) return rc;
    UpstreamSpec spec = {.name = u->name, .pin = u->pin, .into = u->into, .auto_accept = u->auto_trust};
    bool taken;
    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);
}

// --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;
    if (!(take || accept || diff) || (take && argc != 5) || (diff && 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();
    Up u;
    rc = rc != 0 ? rc : find_upstream(argv[2], &u);
    if (rc != 0) return rc;
    if (take) return do_take(&u, argv[4]);
    if (accept) return store_upstream_accept(u.ward, u.name, &settle);
    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();
    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;
}