#include "place.h"
#include "join.h"
#include "platform.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
constexpr size_t PATH_CAP = 4096;
constexpr unsigned LOCK_WAIT_MS = 2000;
constexpr unsigned LOCK_POLL_MS = 50;
static const char REASON_FILE[] = "a real file";
static const char REASON_DIR[] = "a real folder";
static const char REASON_LINK[] = "someone else's link";
static const char REASON_BLOCKED[] = "something in the way";
typedef enum { D_NONE, D_LINK, D_DIR, D_FILE } DestKind;
// What is at DEST, without following a link. For a link, its target too.
static int inspect(const char *dest, DestKind *kind, char *target, size_t cap)
{
struct stat st;
if (sys_lstat(dest, &st) != 0) {
if (errno == ENOENT || errno == ENOTDIR) {
*kind = D_NONE;
return 0;
}
say(STDERR_FILENO, "suit: cannot look at %s: %s\n", dest, strerror(errno));
return 1;
}
*kind = S_ISDIR(st.st_mode) ? D_DIR : D_FILE;
if (!S_ISLNK(st.st_mode)) return 0;
ssize_t n = sys_readlink(dest, target, cap - 1);
if (n < 0) {
say(STDERR_FILENO, "suit: cannot read the link %s: %s\n", dest, strerror(errno));
return 1;
}
target[n] = '\0';
*kind = D_LINK;
return 0;
}
static const char *reason_for(DestKind kind)
{
if (kind == D_LINK) return REASON_LINK;
return kind == D_DIR ? REASON_DIR : REASON_FILE;
}
// ---- folders ----------------------------------------------------------------
static bool have_dir(const Actions *out, const char *path)
{
for (uint32_t i = 0; i < out->ndirs; i++)
if (strcmp(out->dirs[i], path) == 0) return true;
return false;
}
static int add_dir(Actions *out, const char *path)
{
if (have_dir(out, path)) return 0;
size_t len = strlen(path) + 1;
if (out->ndirs == DIR_MAX || out->used + len > sizeof out->text) {
say(STDERR_FILENO, "suit: too many folders to make (limit %u folders, %zu bytes of names)\n",
DIR_MAX, DIR_TEXT_MAX);
return 1;
}
char *copy = out->text + out->used;
memcpy(copy, path, len);
out->used += len;
out->dirs[out->ndirs++] = copy;
return 0;
}
// The folders above DEST that do not exist yet go in OUT, parents first. If one
// of them exists and is not a folder, DEST is BLOCKED.
static int parents(Actions *out, const char *dest, bool *blocked)
{
*blocked = false;
bool missing = false;
for (const char *s = strchr(dest + 1, '/'); s != nullptr; s = strchr(s + 1, '/')) {
size_t len = (size_t)(s - dest);
char prefix[PATH_CAP];
ensure(len < sizeof prefix);
memcpy(prefix, dest, len);
prefix[len] = '\0';
struct stat st;
if (!missing && sys_stat(prefix, &st) != 0) {
if (errno != ENOENT) {
say(STDERR_FILENO, "suit: cannot look at %s: %s\n", prefix, strerror(errno));
return 1;
}
missing = true;
} else if (!missing && !S_ISDIR(st.st_mode)) {
*blocked = true;
return 0;
}
if (missing && add_dir(out, prefix) != 0) return 1;
}
return 0;
}
// ---- plan -------------------------------------------------------------------
static int cmp_action(const void *pa, const void *pb)
{
const Action *a = pa;
const Action *b = pb;
return strcmp(a->dest, b->dest);
}
static int cmp_dest(const void *key, const void *elem)
{
const Placement *p = elem;
return strcmp(key, p->dest);
}
// One wanted placement against what is on disk and what the ledger says.
static int decide_want(const Placement *w, const Ledger *ledger, Actions *out)
{
const LedgerEntry *mine = ledger_find_link(ledger, w->dest);
Action act = {ACT_CLASH, w->dest, w->src, nullptr, nullptr, w, nullptr};
DestKind kind;
char target[PATH_CAP];
int rc = inspect(w->dest, &kind, target, sizeof target);
if (rc != 0) return rc;
if (kind == D_NONE) {
bool blocked;
rc = parents(out, w->dest, &blocked);
if (rc != 0) return rc;
act.kind = blocked ? ACT_CLASH : ACT_CREATE;
act.reason = blocked ? REASON_BLOCKED : nullptr;
} else if (kind == D_LINK) {
// Ours if the ledger has it and it points where we put it, or where we
// would put it now (a crash between making a link and writing the ledger).
bool at_want = strcmp(target, w->src) == 0;
bool ours = mine != nullptr && (at_want || strcmp(target, mine->src) == 0);
act.kind = !ours ? ACT_CLASH : (at_want ? ACT_KEEP : ACT_REPLACE);
act.reason = ours ? nullptr : REASON_LINK;
act.old = mine != nullptr ? mine->src : nullptr;
} else {
act.reason = reason_for(kind);
}
out->a[out->n++] = act;
return 0;
}
// A link the ledger has and nothing wants any more.
static int decide_stale(const LedgerEntry *le, Actions *out)
{
Action act = {ACT_DROP, le->dest, le->src, nullptr, nullptr, nullptr, nullptr};
DestKind kind;
char target[PATH_CAP];
int rc = inspect(le->dest, &kind, target, sizeof target);
if (rc != 0) return rc;
bool ours = kind == D_LINK && strcmp(target, le->src) == 0;
if (kind != D_NONE) {
act.kind = ours ? ACT_REMOVE : ACT_CLASH;
act.reason = ours ? nullptr : reason_for(kind);
}
out->a[out->n++] = act;
return 0;
}
static bool ledger_has_file(const Ledger *l, const char *path)
{
for (uint32_t i = 0; i < l->n; i++)
if (l->e[i].kind == ENTRY_FILE && strcmp(l->e[i].dest, path) == 0) return true;
return false;
}
// A joined file against what the ledger and the disk say: write it if it is
// missing or out of date.
static int decide_join(const Join *j, const Ledger *ledger, Actions *out)
{
int current = join_current(j);
if (current < 0) return 1;
bool blocked; // a folder in the way shows when the file is written
int rc = current == 1 ? 0 : parents(out, j->path, &blocked);
if (rc != 0) return rc;
Action act = {current == 1 ? ACT_FILE : ACT_WRITE, j->path, nullptr, nullptr, nullptr, nullptr, j};
act.old = ledger_has_file(ledger, j->path) ? j->path : nullptr;
out->a[out->n++] = act;
return 0;
}
// A joined file the ledger has and no join wants any more.
static int decide_stale_file(const LedgerEntry *le, Actions *out)
{
DestKind kind;
char target[PATH_CAP];
int rc = inspect(le->dest, &kind, target, sizeof target);
if (rc == 0 && kind != D_NONE)
out->a[out->n++] = (Action){ACT_UNWRITE, le->dest, nullptr, nullptr, nullptr, nullptr, nullptr};
return rc;
}
static bool is_join_path(const Plan *plan, const char *path)
{
for (uint32_t i = 0; i < plan->njoins; i++)
if (strcmp(plan->joins[i].path, path) == 0) return true;
return false;
}
int place_plan(const Plan *plan, const Ledger *ledger, Actions *out)
{
out->n = 0;
out->ndirs = 0;
out->used = 0;
for (uint32_t i = 0; i < plan->n; i++) {
int rc = decide_want(&plan->p[i], ledger, out);
if (rc != 0) return rc;
}
for (uint32_t i = 0; i < plan->njoins; i++) {
int rc = decide_join(&plan->joins[i], ledger, out);
if (rc != 0) return rc;
}
for (uint32_t i = 0; i < ledger->n; i++) {
const LedgerEntry *le = &ledger->e[i];
int rc = 0;
if (le->kind == ENTRY_LINK && bsearch(le->dest, plan->p, plan->n, sizeof plan->p[0], cmp_dest) == nullptr)
rc = decide_stale(le, out);
if (le->kind == ENTRY_FILE && !is_join_path(plan, le->dest)) rc = decide_stale_file(le, out);
if (rc != 0) return rc;
}
qsort(out->a, out->n, sizeof out->a[0], cmp_action);
return 0;
}
void place_print(const Plan *plan, const Actions *acts)
{
for (uint32_t i = 0; i < plan->nskips; i++) say(STDOUT_FILENO, "~ %s\n", plan->skips[i]);
for (uint32_t i = 0; i < acts->n; i++) {
const Action *a = &acts->a[i];
if (a->kind == ACT_CREATE || a->kind == ACT_REPLACE)
say(STDOUT_FILENO, "+ link %s -> %s\n", a->dest, a->src);
if (a->kind == ACT_REMOVE) say(STDOUT_FILENO, "- link %s\n", a->dest);
if (a->kind == ACT_WRITE) say(STDOUT_FILENO, "+ file %s\n", a->dest);
if (a->kind == ACT_UNWRITE) say(STDOUT_FILENO, "- file %s\n", a->dest);
if (a->kind == ACT_CLASH) say(STDOUT_FILENO, "! clash %s (%s)\n", a->dest, a->reason);
}
}
uint32_t place_missing(const Ledger *ledger, bool print)
{
uint32_t count = 0;
for (uint32_t i = 0; i < ledger->n; i++) {
struct stat st;
const LedgerEntry *le = &ledger->e[i];
if (le->kind != ENTRY_LINK || sys_lstat(le->dest, &st) == 0 || errno != ENOENT) continue;
count++;
if (print) say(STDOUT_FILENO, "missing %s\n", le->dest);
}
return count;
}
// ---- lock -------------------------------------------------------------------
// The pid in the lock file, or 0 if it cannot be told.
static pid_t lock_owner(const char *path)
{
char text[32] = {};
int fd = sys_open(path, O_RDONLY, 0);
if (fd < 0) return 0;
ssize_t n = sys_read(fd, text, sizeof text - 1);
(void)sys_close(fd);
return n > 0 ? (pid_t)atol(text) : 0;
}
// A lock whose process is gone is taken over. (Two processes that both find it
// stale both remove it and race for O_EXCL; one wins.)
static bool lock_is_stale(const char *path)
{
pid_t owner = lock_owner(path);
return owner > 0 && sys_kill0(owner) != 0 && errno == ESRCH;
}
int place_lock(const char *path)
{
for (unsigned waited = 0;; waited += LOCK_POLL_MS) {
int fd = sys_open(path, O_WRONLY | O_CREAT | O_EXCL, 0644);
if (fd >= 0) {
char text[32];
int n = snprintf(text, sizeof text, "%d\n", (int)getpid());
ensure(n > 0);
bool ok = sys_write_all(fd, text, (size_t)n);
(void)sys_close(fd);
if (ok) return 0;
(void)sys_unlink(path);
say(STDERR_FILENO, "suit: cannot write the lock %s: %s\n", path, strerror(errno));
return 1;
}
if (errno != EEXIST) {
say(STDERR_FILENO, "suit: cannot take the lock %s: %s\n", path, strerror(errno));
return 1;
}
if (lock_is_stale(path)) {
(void)sys_unlink(path);
continue;
}
if (waited >= LOCK_WAIT_MS) {
say(STDERR_FILENO, "suit: another suit holds the lock %s; try again in a moment\n", path);
return EXIT_BUSY;
}
platform_pause_ms(LOCK_POLL_MS);
}
}
void place_unlock(const char *path)
{
(void)sys_unlink(path);
}
// ---- apply ------------------------------------------------------------------
constexpr size_t OP_MAX = PLACE_MAX + LEDGER_ENTRY_MAX + CONF_HARNESS_MAX;
static Ledger next_ledger;
static bool op_done[OP_MAX];
static bool dir_done[DIR_MAX];
static bool add_entry(Ledger *l, EntryKind kind, const char *dest, const char *src)
{
if (l->n == LEDGER_ENTRY_MAX) return false;
l->e[l->n++] = (LedgerEntry){kind, dest, src};
return true;
}
// The ledger for this moment. INTENT, before anything is done: everything that
// is about to exist and everything about to go, so that a crash leaves the
// ledger a superset of the disk. Final, after: only what was done.
static bool build_ledger(Ledger *l, const Ledger *old, const Actions *acts, bool final)
{
l->n = 0;
bool ok = true;
for (uint32_t i = 0; i < old->n; i++)
if (old->e[i].kind == ENTRY_DIR) ok &= add_entry(l, ENTRY_DIR, old->e[i].dest, nullptr);
for (uint32_t i = 0; i < acts->ndirs; i++)
if (!final || dir_done[i]) ok &= add_entry(l, ENTRY_DIR, acts->dirs[i], nullptr);
for (uint32_t i = 0; i < acts->n; i++) {
const Action *a = &acts->a[i];
bool done = final && op_done[i];
if (a->kind == ACT_KEEP || (a->kind == ACT_CREATE && !(final && !done)))
ok &= add_entry(l, ENTRY_LINK, a->dest, a->src);
if (a->kind == ACT_REPLACE) ok &= add_entry(l, ENTRY_LINK, a->dest, done ? a->src : a->old);
if (a->kind == ACT_REMOVE && !done) ok &= add_entry(l, ENTRY_LINK, a->dest, a->src);
// A file is listed before it is written, and while it may still be there.
if (a->kind == ACT_FILE || (a->kind == ACT_WRITE && !(final && !done && a->old == nullptr)))
ok &= add_entry(l, ENTRY_FILE, a->dest, nullptr);
if (a->kind == ACT_UNWRITE && !done) ok &= add_entry(l, ENTRY_FILE, a->dest, nullptr);
}
return ok;
}
static int make_link(const char *dest, const char *src)
{
static unsigned counter;
const char *slash = strrchr(dest, '/');
ensure(slash != nullptr);
char tmp[PATH_CAP + 64];
[[maybe_unused]] int n = snprintf(tmp, sizeof tmp, "%.*s/" SUIT_TMP_PREFIX "link.%d.%u",
(int)(slash - dest), dest, (int)getpid(), counter++);
ensure(n > 0 && (size_t)n < sizeof tmp);
if (sys_symlink(src, tmp) != 0 || sys_rename(tmp, dest) != 0) {
int err = errno;
(void)sys_unlink(tmp);
return err;
}
return 0;
}
static bool in_phase(ActKind kind, int phase)
{
if (phase == 0) return kind == ACT_WRITE;
if (phase == 1) return kind == ACT_CREATE || kind == ACT_REPLACE || kind == ACT_REMOVE;
return kind == ACT_UNWRITE;
}
// Run the actions of one phase, in order: the joined files are written before
// any link can point at them and removed after every link has left them.
static int run_phase(const Actions *acts, int phase)
{
for (uint32_t i = 0; i < acts->n; i++) {
const Action *a = &acts->a[i];
if (!in_phase(a->kind, phase)) continue;
if (a->kind == ACT_WRITE) {
if (join_write(a->join) != 0) return 1;
} else {
bool removing = a->kind == ACT_REMOVE || a->kind == ACT_UNWRITE;
int err = removing ? (sys_unlink(a->dest) == 0 ? 0 : errno) : make_link(a->dest, a->src);
if (err != 0) {
say(STDERR_FILENO, "suit: cannot %s %s: %s\n", removing ? "remove" : "link", a->dest,
strerror(err));
return 1;
}
}
op_done[i] = true;
}
return 0;
}
static int run_actions(const Actions *acts)
{
for (uint32_t i = 0; i < acts->ndirs; i++) {
if (sys_mkdir(acts->dirs[i], 0755) != 0 && errno != EEXIST) {
say(STDERR_FILENO, "suit: cannot make the folder %s: %s\n", acts->dirs[i], strerror(errno));
return 1;
}
dir_done[i] = true;
}
for (int phase = 0; phase < 3; phase++) {
int rc = run_phase(acts, phase);
if (rc != 0) return rc;
}
return 0;
}
static int write_ledger(const Ledger *l, const char *path)
{
int err = ledger_write(l, path);
if (err != 0) say(STDERR_FILENO, "suit: cannot write the ledger %s: %s\n", path, strerror(err));
return err == 0 ? 0 : 1;
}
int place_apply(const Ledger *old, const Actions *acts, const char *ledger_path)
{
memset(op_done, 0, sizeof op_done);
memset(dir_done, 0, sizeof dir_done);
if (!build_ledger(&next_ledger, old, acts, false)) {
say(STDERR_FILENO, "suit: the ledger would hold more than %u entries\n", LEDGER_ENTRY_MAX);
return 1;
}
int rc = write_ledger(&next_ledger, ledger_path);
if (rc != 0) return rc;
int failed = run_actions(acts);
// The limit was checked for the first ledger; the final one is never larger.
[[maybe_unused]] bool fits = build_ledger(&next_ledger, old, acts, true);
ensure(fits);
rc = write_ledger(&next_ledger, ledger_path);
return failed != 0 ? failed : rc;
}
// ---- off --------------------------------------------------------------------
static bool off_gone[LEDGER_ENTRY_MAX];
// Remove one link if it is still ours. -1 left alone, 0 removed or already gone,
// 1 error.
static int off_link(const LedgerEntry *le)
{
DestKind kind;
char target[PATH_CAP];
int rc = inspect(le->dest, &kind, target, sizeof target);
if (rc != 0) return rc;
if (kind == D_NONE) return 0;
if (kind != D_LINK || strcmp(target, le->src) != 0) {
say(STDOUT_FILENO, "left %s (%s)\n", le->dest, reason_for(kind));
return 0;
}
if (sys_unlink(le->dest) != 0) {
say(STDERR_FILENO, "suit: cannot remove %s: %s\n", le->dest, strerror(errno));
return 1;
}
say(STDOUT_FILENO, "- link %s\n", le->dest);
return 0;
}
// Remove one joined file. It is suit's own, so it goes whatever it holds.
static int off_file(const LedgerEntry *le)
{
if (sys_unlink(le->dest) == 0) {
say(STDOUT_FILENO, "- file %s\n", le->dest);
return 0;
}
if (errno == ENOENT) return 0;
say(STDERR_FILENO, "suit: cannot remove %s: %s\n", le->dest, strerror(errno));
return 1;
}
static int off_dir(const LedgerEntry *le)
{
if (sys_rmdir(le->dest) == 0) {
say(STDOUT_FILENO, "- dir %s\n", le->dest);
return 0;
}
if (errno == ENOENT) return 0;
if (errno == ENOTEMPTY || errno == EEXIST) {
say(STDOUT_FILENO, "left %s (not empty)\n", le->dest);
return 0;
}
say(STDERR_FILENO, "suit: cannot remove the folder %s: %s\n", le->dest, strerror(errno));
return 1;
}
int place_off(const Ledger *old, const char *ledger_path)
{
memset(off_gone, 0, sizeof off_gone);
int failed = 0;
for (uint32_t i = 0; i < old->n && failed == 0; i++) {
if (old->e[i].kind != ENTRY_LINK) continue;
failed = off_link(&old->e[i]);
off_gone[i] = failed == 0;
}
for (uint32_t i = 0; i < old->n && failed == 0; i++) {
if (old->e[i].kind != ENTRY_FILE) continue;
failed = off_file(&old->e[i]);
off_gone[i] = failed == 0;
}
// Folders go deepest first, so a folder goes before the one that holds it.
static uint32_t dirs[LEDGER_ENTRY_MAX];
uint32_t ndirs = 0;
for (uint32_t i = 0; i < old->n; i++)
if (old->e[i].kind == ENTRY_DIR) dirs[ndirs++] = i;
for (uint32_t i = 1; i < ndirs; i++) { // insertion sort, longest path first
uint32_t cur = dirs[i];
uint32_t j = i;
while (j > 0 && strcmp(old->e[dirs[j - 1]].dest, old->e[cur].dest) < 0) {
dirs[j] = dirs[j - 1];
j--;
}
dirs[j] = cur;
}
for (uint32_t i = 0; i < ndirs && failed == 0; i++) {
failed = off_dir(&old->e[dirs[i]]);
off_gone[dirs[i]] = failed == 0;
}
next_ledger.n = 0;
for (uint32_t i = 0; i < old->n; i++)
if (!off_gone[i]) next_ledger.e[next_ledger.n++] = old->e[i];
int rc = write_ledger(&next_ledger, ledger_path);
return failed != 0 ? failed : rc;
}