Skip to content
suit Artifact [37df04943f]
Login

Artifact [37df04943f]

Artifact 37df04943fba0d66763ec4f472522c5d8dc66bbd03cf1a845d446e5ed1394767:


#include "store_fs.h"

#include "platform.h"

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

constexpr size_t TMP_PATH_MAX = 4096 + 64;

static bool write_temp(const char *tmp, mode_t mode, const void *src, size_t n)
{
    int fd = sys_open(tmp, O_WRONLY | O_CREAT | O_EXCL, mode);
    if (fd < 0) return false;
    bool written = sys_write_all(fd, src, n) && sys_fsync(fd) == 0;
    bool closed = sys_close(fd) == 0;
    return written && closed;
}

int store_atomic_write(const char *path, const void *src, size_t n)
{
    static unsigned counter;
    const char *slash = strrchr(path, '/');
    ensure(slash != nullptr);
    char tmp[TMP_PATH_MAX];
    [[maybe_unused]] int len = snprintf(tmp, sizeof tmp, "%.*s/" STORE_TMP_PREFIX "%d.%u",
        (int)(slash - path), path, (int)getpid(), counter++);
    ensure(len > 0 && (size_t)len < sizeof tmp);

    struct stat st;
    bool executable = sys_stat(path, &st) == 0 && (st.st_mode & 0100) != 0;
    if (!write_temp(tmp, executable ? 0755 : 0644, src, n) || sys_rename(tmp, path) != 0) {
        int err = errno;
        (void)sys_unlink(tmp);
        return err;
    }
    return 0;
}

// libfossil writes every file through this.
static int fs_write(void *state, char const *zName, void const *src, fsl_size_t n)
{
    int err = store_atomic_write(zName, src, n);
    return err == 0 ? 0 : fsl_cx_err_set((fsl_cx *)state, FSL_RC_IO, "cannot write %s: %s", zName,
        strerror(err));
}

typedef struct {
    fsl_ckout_fs_dir_f cb;
    void *state;
} DirFilter;

static int dir_filter(void *p, char const *entry)
{
    const DirFilter *d = p;
    bool ours = strncmp(entry, STORE_TMP_PREFIX, strlen(STORE_TMP_PREFIX)) == 0;
    return ours ? 0 : d->cb(d->state, entry);
}

static int fs_dirlist(void *state, char const *zDir, fsl_ckout_fs_dir_f cb, void *cbState)
{
    DirFilter d = {cb, cbState};
    return fsl_ckout_fs_os.xDirList(state, zDir, dir_filter, &d);
}

int store_fs_install(fsl_cx *f)
{
    fsl_ckout_fs fs = fsl_ckout_fs_os;
    fs.xWrite = fs_write;
    fs.xDirList = fs_dirlist;
    fs.state = f;
    return fsl_cx_ckout_fs(f, &fs, nullptr);
}