Skip to content
suit Documentation
Login

Documentation

#include "project.h"

#include "platform.h"

#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>

static char work[PROJECT_FILE_MAX + 1];  // a file being parsed
static char out_buf[PROJECT_FILE_MAX];   // a file being written

__attribute__((format(printf, 3, 4)))
static bool fail(ProjectError *e, int line, const char *fmt, ...)
{
    va_list ap;
    e->line = line;
    va_start(ap, fmt);
    vsnprintf(e->msg, sizeof e->msg, fmt, ap);
    va_end(ap);
    return false;
}

static bool graphic(char c)
{
    return (unsigned char)c > ' ' && c != 0x7f;
}

static bool printable(char c)
{
    return (unsigned char)c >= ' ' && c != 0x7f;
}

// ---- remote keys ----------------------------------------------------------

bool project_key_ok(const char *key)
{
    size_t len = strlen(key);
    if (len < 3 || len > PROJECT_KEY_MAX) return false;
    for (size_t i = 0; i < len; i++)
        if (!graphic(key[i])) return false;
    const char *slash = strchr(key, '/');
    if (slash == nullptr || slash == key) return false;
    for (const char *h = key; h < slash; h++)
        if (!((*h >= 'a' && *h <= 'z') || (*h >= '0' && *h <= '9') || *h == '.' || *h == '-')) return false;
    const char *path = slash + 1;
    size_t plen = len - (size_t)(path - key);
    if (plen == 0 || path[0] == '/' || path[plen - 1] == '/') return false;
    return !(plen >= 4 && strcmp(path + plen - 4, ".git") == 0);
}

bool project_key_from_url(const char *url, char *key, size_t cap)
{
    char tmp[PROJECT_URL_MAX];
    key[0] = '\0';
    size_t n = strlen(url);
    if (n == 0 || n >= sizeof tmp) return false;
    memcpy(tmp, url, n + 1);
    for (size_t i = 0; i < n; i++)
        if (!graphic(tmp[i])) return false;
    char *cut = strpbrk(tmp, "?#");
    if (cut != nullptr) *cut = '\0';

    char *auth = tmp;
    char *path;
    char *scheme_end = strstr(tmp, "://");
    if (scheme_end != nullptr) {
        // scheme://[user[:password]@]host[:port]/path
        if (scheme_end == tmp || strncasecmp(tmp, "file://", 7) == 0) return false;
        auth = scheme_end + 3;
        path = strchr(auth, '/');
    } else {
        // [user@]host:path, as scp writes it. A colon after a slash is a local path.
        path = strchr(tmp, ':');
        char *slash = strchr(tmp, '/');
        if (path != nullptr && slash != nullptr && slash < path) return false;
    }
    if (path == nullptr) return false;
    *path++ = '\0';

    char *at = strrchr(auth, '@');
    char *host = at != nullptr ? at + 1 : auth;
    char *port = strchr(host, ':');
    if (port != nullptr) *port = '\0';
    for (char *h = host; *h != '\0'; h++)
        if (*h >= 'A' && *h <= 'Z') *h = (char)(*h - 'A' + 'a');

    while (path[0] == '/') path++;
    size_t plen = strlen(path);
    for (;;) {
        if (plen > 0 && path[plen - 1] == '/') plen--;
        else if (plen >= 4 && memcmp(path + plen - 4, ".git", 4) == 0) plen -= 4;
        else break;
    }
    if (plen == 0 || strlen(host) + 1 + plen >= cap) return false;
    [[maybe_unused]] int len = snprintf(key, cap, "%s/%.*s", host, (int)plen, path);
    ensure(len > 0);
    // A host with anything but a-z 0-9 . - in it (an IPv6 literal, say) is no key.
    bool ok = project_key_ok(key);
    if (!ok) key[0] = '\0';
    return ok;
}

bool project_path_ok(const char *path)
{
    size_t len = strlen(path);
    if (path[0] != '/' || len >= PROJECT_PATH_MAX || (len > 1 && path[len - 1] == '/')) return false;
    for (size_t i = 0; i < len; i++)
        if (!printable(path[i])) return false;
    return true;
}

// Whether the line S, ended at its first NUL, starts with WORD, any case.
static bool starts_with_word(const char *s, const char *word)
{
    return strncasecmp(s, word, strlen(word)) == 0;
}

static char *skip_blanks(char *s)
{
    while (*s == ' ' || *s == '\t') s++;
    return s;
}

static void trim_end(char *s)
{
    size_t len = strlen(s);
    while (len > 0 && (s[len - 1] == ' ' || s[len - 1] == '\t' || s[len - 1] == '\r')) len--;
    s[len] = '\0';
}

bool project_git_remote(char *text, size_t len, char *url, size_t cap)
{
    text[len] = '\0';
    bool in_remote = false;
    bool is_origin = false;
    bool have_url = false;  // this remote has had its url
    bool have_first = false;
    char *p = text;
    char *end = text + len;
    while (p < end) {
        char *nl = memchr(p, '\n', (size_t)(end - p));
        char *s = p;
        if (nl != nullptr) *nl = '\0';
        p = nl != nullptr ? nl + 1 : end;
        s = skip_blanks(s);
        if (s[0] == '[') {
            // [remote "NAME"]; every other section ends the remote.
            in_remote = false;
            have_url = false;
            char *close = strchr(s, ']');
            if (close != nullptr && starts_with_word(s + 1, "remote ")) {
                char *open = strchr(s, '"');
                char *shut = open != nullptr ? strchr(open + 1, '"') : nullptr;
                if (shut != nullptr && shut < close) {
                    in_remote = true;
                    is_origin = shut - open - 1 == 6 && strncmp(open + 1, "origin", 6) == 0;
                }
            }
        } else if (in_remote && !have_url && starts_with_word(s, "url")) {
            char *eq = skip_blanks(s + 3);
            if (eq[0] != '=') continue;
            char *value = skip_blanks(eq + 1);
            trim_end(value);
            if (value[0] == '\0' || strlen(value) >= cap) continue;
            have_url = true;
            if (is_origin) {
                memcpy(url, value, strlen(value) + 1);
                return true;
            }
            if (!have_first) {
                memcpy(url, value, strlen(value) + 1);
                have_first = true;
            }
        }
    }
    return have_first;
}

// ---- reading a file -------------------------------------------------------

ReadResult project_read_file(const char *path, char *buf, size_t cap, size_t *len, int *err)
{
    *len = 0;
    int fd = sys_open(path, O_RDONLY, 0);
    if (fd < 0 && errno == ENOENT) return READ_MISSING;
    if (fd < 0) {
        *err = errno;
        return READ_FAILED;
    }
    ssize_t n = 1;
    while (*len <= cap && n > 0) {
        n = sys_read(fd, buf + *len, cap + 1 - *len);
        if (n < 0 && errno == EINTR) {
            n = 1;
            continue;
        }
        *len += n > 0 ? (size_t)n : 0;
    }
    *err = errno;
    (void)sys_close(fd);
    if (n < 0) return READ_FAILED;
    if (*len > cap) return READ_BIG;
    buf[*len] = '\0';
    return READ_OK;
}

// Read PATH into WORK as a file of at most LIMIT bytes, and hand the text to
// PARSE. A file that is not there is parsed as no text at all.
static bool load(const char *path, size_t limit, bool (*parse)(void *, const char *, size_t, ProjectError *),
    void *target, ProjectError *e)
{
    size_t len;
    int err = 0;
    ReadResult r = project_read_file(path, work, limit, &len, &err);
    if (r == READ_MISSING) return parse(target, "", 0, e);
    if (r == READ_FAILED) return fail(e, 0, "cannot read: %s", strerror(err));
    if (r == READ_BIG) return fail(e, 0, "file is over the limit of %zu bytes", limit);
    return parse(target, work, len, e);
}

// Split BUF (LEN bytes, changed in place) into lines and call FN on each.
typedef bool (*LineFn)(void *ctx, int line, char *s, ProjectError *e);

static bool each_line(char *buf, size_t len, ProjectError *e, LineFn fn, void *ctx)
{
    buf[len] = '\0';
    char *p = buf;
    char *end = buf + len;
    int line = 0;
    while (p < end) {
        char *nl = memchr(p, '\n', (size_t)(end - p));
        line++;
        if (nl == nullptr) return fail(e, line, "line has no newline");
        size_t n = (size_t)(nl - p);
        if (n > PROJECT_LINE_MAX) return fail(e, line, "line is %zu bytes, limit is %zu", n, PROJECT_LINE_MAX);
        if (memchr(p, '\0', n) != nullptr) return fail(e, line, "NUL byte in line");
        *nl = '\0';
        char *s = p;
        p = nl + 1;
        if (!fn(ctx, line, s, e)) return false;
    }
    return true;
}

// ---- roots ----------------------------------------------------------------

static bool root_line(void *ctx, int line, char *s, ProjectError *e)
{
    Roots *r = ctx;
    if (!project_path_ok(s)) return fail(e, line, "a root is one absolute path with no control character and no trailing /");
    if (strlen(s) > PROJECT_ROOT_MAX) return fail(e, line, "root is over %zu bytes", PROJECT_ROOT_MAX);
    AddResult a = roots_add(r, s);
    if (a == ADD_DUPLICATE) return fail(e, line, "duplicate root %.80s", s);
    if (a == ADD_FULL) return fail(e, line, "too many roots (limit %zu)", ROOTS_MAX);
    return true;
}

static bool roots_parse_text(void *target, const char *data, size_t len, ProjectError *e)
{
    Roots *r = target;
    r->n = 0;
    if (len > ROOTS_FILE_MAX) return fail(e, 0, "file is %zu bytes, limit is %zu", len, ROOTS_FILE_MAX);
    if (data != work) memcpy(work, data, len);
    bool ok = each_line(work, len, e, root_line, r);
    r->n = ok ? r->n : 0;
    return ok;
}

bool roots_parse(Roots *r, const char *data, size_t len, ProjectError *e)
{
    return roots_parse_text(r, data, len, e);
}

bool roots_load(Roots *r, const char *path, ProjectError *e)
{
    r->n = 0;
    bool ok = load(path, ROOTS_FILE_MAX, roots_parse_text, r, e);
    r->n = ok ? r->n : 0;
    return ok;
}

int roots_write(const Roots *r, const char *path)
{
    size_t len = 0;
    for (uint32_t i = 0; i < r->n; i++) {
        size_t room = sizeof out_buf - len;
        int n = snprintf(out_buf + len, room, "%s\n", r->path[i]);
        ensure(n > 0 && (size_t)n < room);  // 64 roots of under 4096 bytes fit
        len += (size_t)n;
    }
    return sys_write_atomic(path, out_buf, len);
}

AddResult roots_add(Roots *r, const char *path)
{
    for (uint32_t i = 0; i < r->n; i++)
        if (strcmp(r->path[i], path) == 0) return ADD_DUPLICATE;
    if (r->n == ROOTS_MAX) return ADD_FULL;
    ensure(strlen(path) < PROJECT_PATH_MAX);
    memcpy(r->path[r->n++], path, strlen(path) + 1);
    return ADD_OK;
}

bool roots_remove(Roots *r, const char *path)
{
    for (uint32_t i = 0; i < r->n; i++) {
        if (strcmp(r->path[i], path) != 0) continue;
        memmove(r->path[i], r->path[i + 1], (r->n - i - 1) * sizeof r->path[0]);
        r->n--;
        return true;
    }
    return false;
}

// ---- projects -------------------------------------------------------------

const char *project_kind_name(ProjectKind kind)
{
    return kind == KIND_GIT ? "git" : (kind == KIND_FOSSIL ? "fossil" : "zit");
}

static ProjectKind kind_from_name(const char *s)
{
    if (strcmp(s, "git") == 0) return KIND_GIT;
    if (strcmp(s, "fossil") == 0) return KIND_FOSSIL;
    return strcmp(s, "zit") == 0 ? KIND_ZIT : KIND_NONE;
}

typedef struct {
    Projects *p;
    bool with_kind;
} ProjectsParse;

static bool project_line(void *ctx, int line, char *s, ProjectError *e)
{
    ProjectsParse *pp = ctx;
    char *key = s;
    char *path = strchr(s, ' ');
    if (path == nullptr)
        return fail(e, line, pp->with_kind ? "expected 'KEY PATH KIND'" : "expected 'KEY PATH'");
    *path++ = '\0';
    ProjectKind kind = KIND_NONE;
    if (pp->with_kind) {
        char *word = strrchr(path, ' ');
        if (word == nullptr) return fail(e, line, "expected 'KEY PATH KIND'");
        *word++ = '\0';
        kind = kind_from_name(word);
        if (kind == KIND_NONE) return fail(e, line, "unknown kind '%.40s' (git, fossil or zit)", word);
    }
    bool no_key = pp->with_kind && strcmp(key, "-") == 0;
    if (!no_key && !project_key_ok(key))
        return fail(e, line, "'%.80s' is not a remote key (host/path, lower-case host)", key);
    if (!project_path_ok(path)) return fail(e, line, "a path is absolute, with no control character and no trailing /");
    AddResult a = projects_add(pp->p, no_key ? "" : key, path, kind);
    if (a == ADD_DUPLICATE) return fail(e, line, "duplicate path %.80s", path);
    if (a == ADD_FULL)
        return fail(e, line, "too many entries (limit %u, or %zu bytes of text)", PROJECT_ENTRY_MAX, sizeof pp->p->buf);
    return true;
}

static bool projects_parse_text(ProjectsParse *pp, const char *data, size_t len, ProjectError *e)
{
    Projects *p = pp->p;
    p->n = 0;
    p->used = 0;
    if (len > PROJECT_FILE_MAX) return fail(e, 0, "file is %zu bytes, limit is %zu", len, PROJECT_FILE_MAX);
    if (data != work) memcpy(work, data, len);
    bool ok = each_line(work, len, e, project_line, pp);
    p->n = ok ? p->n : 0;
    return ok;
}

bool projects_parse(Projects *p, const char *data, size_t len, bool with_kind, ProjectError *e)
{
    ProjectsParse pp = {p, with_kind};
    return projects_parse_text(&pp, data, len, e);
}

static bool projects_parse_cb(void *target, const char *data, size_t len, ProjectError *e)
{
    return projects_parse_text(target, data, len, e);
}

bool projects_load(Projects *p, const char *path, bool with_kind, ProjectError *e)
{
    ProjectsParse pp = {p, with_kind};
    p->n = 0;
    return load(path, PROJECT_FILE_MAX, projects_parse_cb, &pp, e);
}

static int cmp_entry(const void *pa, const void *pb)
{
    const ProjectEntry *a = pa;
    const ProjectEntry *b = pb;
    return strcmp(a->path, b->path);
}

int projects_write(const Projects *p, const char *path, bool with_kind)
{
    static ProjectEntry sorted[PROJECT_ENTRY_MAX];
    ensure(p->n <= PROJECT_ENTRY_MAX);
    memcpy(sorted, p->e, p->n * sizeof sorted[0]);
    qsort(sorted, p->n, sizeof sorted[0], cmp_entry);
    size_t len = 0;
    for (uint32_t i = 0; i < p->n; i++) {
        const ProjectEntry *en = &sorted[i];
        size_t room = sizeof out_buf - len;
        ensure(with_kind || en->key[0] != '\0');
        const char *key = en->key[0] != '\0' ? en->key : "-";
        int n = with_kind ? snprintf(out_buf + len, room, "%s %s %s\n", key, en->path, project_kind_name(en->kind))
                          : snprintf(out_buf + len, room, "%s %s\n", key, en->path);
        ensure(n > 0);
        if ((size_t)n >= room) return EFBIG;
        len += (size_t)n;
    }
    return sys_write_atomic(path, out_buf, len);
}

const ProjectEntry *projects_find(const Projects *p, const char *path)
{
    for (uint32_t i = 0; i < p->n; i++)
        if (strcmp(p->e[i].path, path) == 0) return &p->e[i];
    return nullptr;
}

AddResult projects_add(Projects *p, const char *key, const char *path, ProjectKind kind)
{
    if (projects_find(p, path) != nullptr) return ADD_DUPLICATE;
    size_t klen = strlen(key) + 1;
    size_t plen = strlen(path) + 1;
    if (p->n == PROJECT_ENTRY_MAX || klen + plen > sizeof p->buf - p->used) return ADD_FULL;
    char *k = p->buf + p->used;
    memcpy(k, key, klen);
    char *s = k + klen;
    memcpy(s, path, plen);
    p->used += klen + plen;
    p->e[p->n++] = (ProjectEntry){k, s, kind};
    return ADD_OK;
}

bool projects_remove(Projects *p, const char *path)
{
    for (uint32_t i = 0; i < p->n; i++) {
        if (strcmp(p->e[i].path, path) != 0) continue;
        memmove(&p->e[i], &p->e[i + 1], (p->n - i - 1) * sizeof p->e[0]);
        p->n--;
        return true;
    }
    return false;
}