#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;
}
// Write N bytes to ZNAME by way of a temporary file beside it. An executable
// file stays executable.
static int fs_write(void *state, char const *zName, void const *src, fsl_size_t n)
{
static unsigned counter;
const char *slash = strrchr(zName, '/');
ensure(slash != nullptr);
char tmp[TMP_PATH_MAX];
[[maybe_unused]] int len = snprintf(tmp, sizeof tmp, "%.*s/" STORE_TMP_PREFIX "%d.%u",
(int)(slash - zName), zName, (int)getpid(), counter++);
ensure(len > 0 && (size_t)len < sizeof tmp);
struct stat st;
bool executable = sys_stat(zName, &st) == 0 && (st.st_mode & 0100) != 0;
if (!write_temp(tmp, executable ? 0755 : 0644, src, n) || sys_rename(tmp, zName) != 0) {
int err = errno;
(void)sys_unlink(tmp);
return fsl_cx_err_set((fsl_cx *)state, FSL_RC_IO, "cannot write %s: %s", zName,
strerror(err));
}
return 0;
}
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);
}