Skip to content
suit Artifact [8d5f4ab476]
Login

Artifact [8d5f4ab476]

Artifact 8d5f4ab47627ce5a33ddbcc55e6d004c29335b99759c8cda8b46c2b7fdd39b60:


#include "stamp.h"

#include "platform.h"

#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/uio.h>
#include <unistd.h>

static char file_buf[STAMP_FILE_MAX + 1];

// Join PARTS (home, "/", name) into OUT without stdio, so the run path pulls
// in no formatting code. False if it does not fit in CAP.
static bool join3(char *out, size_t cap, const char *a, const char *b, const char *c)
{
    size_t la = strlen(a), lb = strlen(b), lc = strlen(c);
    if (la + lb + lc >= cap) return false;
    memcpy(out, a, la);
    memcpy(out + la, b, lb);
    memcpy(out + la + lb, c, lc + 1);
    return true;
}

// Fill OUT with "$SUIT_HOME/NAME" ("~/.suit/NAME" without SUIT_HOME). Returns
// the length of the home folder part (so the caller can mkdir it), or 0 on
// failure after saying why.
static size_t home_path(char *out, size_t cap, const char *name)
{
    const char *home = getenv("SUIT_HOME");
    size_t home_len;
    bool fits;
    if (home != nullptr && home[0] != '\0') {
        fits = join3(out, cap, home, "/", name);
        home_len = strlen(home);
    } else {
        const char *h = getenv("HOME");
        if (h == nullptr || h[0] == '\0') {
            fprintf(stderr, "suit: neither SUIT_HOME nor HOME is set\n");
            return 0;
        }
        fits = join3(out, cap, h, "/.suit/", name);
        home_len = strlen(h) + 6;
    }
    if (!fits) {
        fprintf(stderr, "suit: home path is longer than %zu bytes\n", cap - 1);
        return 0;
    }
    return home_len;
}

// ---- stamp ----------------------------------------------------------------

static int append(size_t *len, const char *path, long long size,
    long long sec, long long nsec, bool missing)
{
    int n;
    if (missing)
        n = snprintf(file_buf + *len, sizeof file_buf - *len, "- - - %s\n", path);
    else
        n = snprintf(file_buf + *len, sizeof file_buf - *len, "%lld %lld %lld %s\n",
            size, sec, nsec, path);
    if (n < 0 || (size_t)n >= sizeof file_buf - *len) return -1;
    *len += (size_t)n;
    return 0;
}

static int write_all(int fd, const char *buf, size_t len)
{
    while (len > 0) {
        ssize_t n = write(fd, buf, len);
        if (n < 0 && errno == EINTR) continue;
        if (n < 0) return -1;
        buf += n;
        len -= (size_t)n;
    }
    return 0;
}

int stamp_write(int npaths, char *const *paths)
{
    char final_path[STAMP_PATH_MAX];
    char temp_path[STAMP_PATH_MAX];
    size_t home_len = home_path(final_path, sizeof final_path, "stamp");
    if (home_len == 0) return 1;
    final_path[home_len] = '\0';
    if (mkdir(final_path, 0755) != 0 && errno != EEXIST) {
        fprintf(stderr, "suit: cannot create %s: %s\n", final_path, strerror(errno));
        return 1;
    }
    final_path[home_len] = '/';
    int n = snprintf(temp_path, sizeof temp_path, "%s.tmp.%d", final_path,
        (int)getpid());
    if (n < 0 || (size_t)n >= sizeof temp_path) {
        fprintf(stderr, "suit: stamp path is too long\n");
        return 1;
    }

    size_t len = 0;
    for (int i = 0; i < npaths; i++) {
        const char *p = paths[i];
        if (p[0] == '\0' || strlen(p) >= STAMP_PATH_MAX || strchr(p, '\n') != nullptr) {
            fprintf(stderr, "suit: stamp: path %d is empty, has a newline, or is "
                "longer than %zu bytes\n", i + 1, STAMP_PATH_MAX - 1);
            return 1;
        }
        struct stat st;
        bool missing = false;
        if (stat(p, &st) != 0) {
            if (errno != ENOENT && errno != ENOTDIR) {
                fprintf(stderr, "suit: stamp: cannot stat %s: %s\n", p, strerror(errno));
                return 1;
            }
            missing = true;
        }
        if (append(&len, p, missing ? 0 : (long long)st.st_size,
                missing ? 0 : platform_mtime_sec(&st),
                missing ? 0 : platform_mtime_nsec(&st), missing) != 0) {
            fprintf(stderr, "suit: stamp is larger than %zu bytes\n", STAMP_FILE_MAX);
            return 1;
        }
    }

    int fd = open(temp_path, O_WRONLY | O_CREAT | O_EXCL, 0644);
    if (fd < 0) {
        fprintf(stderr, "suit: cannot create %s: %s\n", temp_path, strerror(errno));
        return 1;
    }
    if (write_all(fd, file_buf, len) != 0 || fsync(fd) != 0 || close(fd) != 0 ||
        rename(temp_path, final_path) != 0) {
        fprintf(stderr, "suit: cannot write %s: %s\n", final_path, strerror(errno));
        unlink(temp_path);
        return 1;
    }
    return 0;
}

// ---- run ------------------------------------------------------------------

static void report_changed(const char *path)
{
    struct iovec iov[3] = {
        {.iov_base = (void *)"changed: ", .iov_len = 9},
        {.iov_base = (void *)path, .iov_len = strlen(path)},
        {.iov_base = (void *)"\n", .iov_len = 1},
    };
    ssize_t n = writev(STDOUT_FILENO, iov, 3);
    (void)n;
}

// Parse a decimal field ending at a space. Returns the position after the
// space, or nullptr.
static char *read_number(char *s, int64_t *out)
{
    if (*s < '0' || *s > '9') return nullptr;
    int64_t v = 0;
    for (; *s >= '0' && *s <= '9'; s++) {
        if (v > (INT64_MAX - 9) / 10) return nullptr;
        v = v * 10 + (*s - '0');
    }
    if (*s != ' ') return nullptr;
    *out = v;
    return s + 1;
}

static int bad_stamp(int line, const char *why)
{
    fprintf(stderr, "suit: stamp:%d: %s\n", line, why);
    return EXIT_BAD_STAMP;
}

static ssize_t read_stamp(const char *path)
{
    int fd = open(path, O_RDONLY);
    if (fd < 0) return errno == ENOENT ? -2 : -1;
    size_t len = 0;
    while (len <= STAMP_FILE_MAX) {
        ssize_t n = read(fd, file_buf + len, STAMP_FILE_MAX + 1 - len);
        if (n < 0 && errno == EINTR) continue;
        if (n <= 0) {
            close(fd);
            return n < 0 ? -1 : (ssize_t)len;
        }
        len += (size_t)n;
    }
    close(fd);
    return -3;
}

// Stat paths that share a folder through one open handle on it, so the
// kernel walks the folder's path once instead of once per file.
typedef struct {
    char dir[STAMP_PATH_MAX];
    size_t len;  // 0: no folder remembered yet
    int fd;      // -1: not opened; opened on the second path in a folder
} DirCache;

static int stat_path(DirCache *dc, const char *path, struct stat *st)
{
    const char *slash = strrchr(path, '/');
    if (slash == nullptr || slash == path || slash[1] == '\0') return stat(path, st);
    size_t len = (size_t)(slash - path);
    if (dc->len != len || memcmp(dc->dir, path, len) != 0) {
        if (dc->fd >= 0) close(dc->fd);
        dc->fd = -1;
        dc->len = len;
        memcpy(dc->dir, path, len);
        return stat(path, st);
    }
    if (dc->fd < 0) {
        dc->dir[len] = '\0';
        dc->fd = open(dc->dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
        if (dc->fd < 0) return stat(path, st);
    }
    return fstatat(dc->fd, slash + 1, st, 0);
}

int stamp_run(void)
{
    static DirCache dir_cache = {.fd = -1};
    char path[STAMP_PATH_MAX];
    if (home_path(path, sizeof path, "stamp") == 0) return 1;
    ssize_t got = read_stamp(path);
    if (got == -2) {
        fprintf(stderr, "suit: no stamp at %s; run `suit stamp PATH...` first\n", path);
        return EXIT_NO_STAMP;
    }
    if (got == -3) return bad_stamp(1, "stamp is larger than the limit");
    if (got < 0) {
        fprintf(stderr, "suit: cannot read %s: %s\n", path, strerror(errno));
        return 1;
    }

    size_t len = (size_t)got;
    char *p = file_buf;
    char *end = file_buf + len;
    int line = 0;
    int changed = 0;
    while (p < end) {
        char *nl = memchr(p, '\n', (size_t)(end - p));
        line++;
        if (nl == nullptr) return bad_stamp(line, "line has no newline");
        *nl = '\0';
        char *s = p;
        p = nl + 1;

        bool recorded_missing = strncmp(s, "- - - ", 6) == 0;
        int64_t size = 0, sec = 0, nsec = 0;
        if (recorded_missing) {
            s += 6;
        } else {
            s = read_number(s, &size);
            if (s != nullptr) s = read_number(s, &sec);
            if (s != nullptr) s = read_number(s, &nsec);
            if (s == nullptr) return bad_stamp(line, "expected SIZE MTIME_SEC MTIME_NSEC PATH");
        }
        if (s[0] == '\0') return bad_stamp(line, "path is empty");

        struct stat st;
        bool same;
        if (stat_path(&dir_cache, s, &st) != 0)
            same = recorded_missing && (errno == ENOENT || errno == ENOTDIR);
        else
            same = !recorded_missing && st.st_size == size &&
                platform_mtime_sec(&st) == sec && platform_mtime_nsec(&st) == nsec;
        if (!same) {
            report_changed(s);
            changed++;
        }
    }
    if (dir_cache.fd >= 0) close(dir_cache.fd);
    return changed > 0 ? EXIT_CHANGED : EXIT_UNCHANGED;
}