#include "commands.h"
#include "conf.h"
#include "join.h"
#include "ledger.h"
#include "machine.h"
#include "place.h"
#include "platform.h"
#include "resolve.h"
#include "stamp.h"
#include "store.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
constexpr size_t PATH_CAP = 4096;
constexpr size_t PATH_ROOM = 640;
constexpr size_t ASSET_TEXT_MAX = 262144;
constexpr uint32_t WATCH_MAX = 8192;
constexpr int WATCH_DEPTH = 64;
static Conf conf;
static Assets assets;
static Plan plan;
static Ledger ledger;
static Actions acts;
static char machine[MACHINE_MAX + 1]; // this machine's name, empty if it has none
static char asset_text[ASSET_TEXT_MAX];
static size_t asset_used;
typedef struct {
char home[PATH_CAP]; // $HOME
char suit_home[PATH_CAP]; // $SUIT_HOME
char store[PATH_CAP];
char conf_path[PATH_CAP];
char ledger_path[PATH_CAP];
char lock_path[PATH_CAP];
char machine_path[PATH_CAP];
} Paths;
static int find_paths(Paths *p)
{
const char *home = sys_getenv("HOME");
if (home == nullptr || strlen(home) >= PATH_CAP) {
say(STDERR_FILENO, "suit: HOME is not set, or too long\n");
return 1;
}
snprintf(p->home, sizeof p->home, "%s", home);
size_t len = suit_home_path(p->conf_path, sizeof p->conf_path, "store/" WARDROBE_NAME "/suit.conf");
if (len == 0) return 1;
// Room for a name of any length under the store, which no folder can exceed.
if (len + PATH_ROOM > PATH_CAP) {
say(STDERR_FILENO, "suit: SUIT_HOME is longer than %zu bytes\n", PATH_CAP - PATH_ROOM);
return 1;
}
memcpy(p->suit_home, p->conf_path, len);
p->suit_home[len] = '\0';
// The other paths are shorter than the config's, so they fit if it did.
[[maybe_unused]] size_t a = suit_home_path(p->store, sizeof p->store, "store/" WARDROBE_NAME);
[[maybe_unused]] size_t b = suit_home_path(p->ledger_path, sizeof p->ledger_path, "ledger");
[[maybe_unused]] size_t c = suit_home_path(p->lock_path, sizeof p->lock_path, "lock");
[[maybe_unused]] size_t d = suit_home_path(p->machine_path, sizeof p->machine_path, "machine");
ensure(a != 0 && b != 0 && c != 0 && d != 0);
return 0;
}
// ---- what the store holds -----------------------------------------------------
typedef struct {
NameList *list;
AssetKind kind;
const char *dir;
} Listing;
static int add_asset(void *state, const char *entry)
{
Listing *l = state;
if (entry[0] == '.') return 0;
char path[PATH_CAP];
[[maybe_unused]] int n = snprintf(path, sizeof path, "%s/%s", l->dir, entry);
ensure(n > 0 && (size_t)n < sizeof path); // PATH_ROOM leaves room for an entry's name
struct stat st = {};
(void)sys_stat(path, &st);
bool wanted = l->kind == AK_SKILL ? S_ISDIR(st.st_mode) : S_ISREG(st.st_mode);
if (!wanted) return 0;
size_t len = strlen(entry);
bool md = l->kind != AK_SKILL && len > 3 && strcmp(entry + len - 3, ".md") == 0;
size_t name_len = md ? len - 3 : len;
if (l->list->n == ASSET_MAX || asset_used + len + 1 + name_len + 1 > ASSET_TEXT_MAX) {
say(STDERR_FILENO, "suit: the store has too many %s (limit %u, %zu bytes of names)\n",
asset_kind_name(l->kind), ASSET_MAX, ASSET_TEXT_MAX);
return 1;
}
char *file = asset_text + asset_used;
memcpy(file, entry, len + 1);
char *name = file + len + 1;
memcpy(name, entry, name_len);
name[name_len] = '\0';
asset_used += len + 1 + name_len + 1;
l->list->file[l->list->n] = file;
l->list->name[l->list->n++] = name;
return 0;
}
// Names in order, so the plan does not depend on the order the folder lists.
static void sort_names(NameList *l)
{
for (uint32_t i = 1; i < l->n; i++) {
for (uint32_t j = i; j > 0 && strcmp(l->name[j - 1], l->name[j]) > 0; j--) {
const char *name = l->name[j];
const char *file = l->file[j];
l->name[j] = l->name[j - 1];
l->file[j] = l->file[j - 1];
l->name[j - 1] = name;
l->file[j - 1] = file;
}
}
}
static int load_assets(const Paths *p)
{
static const char *const dirs[AK_COMMAND + 1] = {"skills", "agents", "commands"};
asset_used = 0;
for (int k = AK_SKILL; k <= AK_COMMAND; k++) {
char dir[PATH_CAP];
[[maybe_unused]] int n = snprintf(dir, sizeof dir, "%s/%s", p->store, dirs[k]);
ensure(n > 0 && (size_t)n < sizeof dir);
assets.list[k].n = 0;
Listing l = {&assets.list[k], (AssetKind)k, dir};
int rc = sys_listdir(dir, add_asset, &l);
if (rc > 0) return 1;
if (rc < 0 && errno != ENOENT) {
say(STDERR_FILENO, "suit: cannot read %s: %s\n", dir, strerror(errno));
return 1;
}
sort_names(&assets.list[k]);
}
return 0;
}
// ---- resolve and compare with the disk ----------------------------------------
static int check_source(const char *dest, const char *src)
{
struct stat st;
if (sys_lstat(src, &st) == 0) return 0;
say(STDERR_FILENO, "suit: %s wants %s, which is not in the store\n", dest, src);
return 1;
}
// The placements' sources are in the store, and so are the sources of the files
// to join, which stand in for the placements' own.
static int check_sources(void)
{
for (uint32_t i = 0; i < plan.n; i++) {
bool joined = false;
for (uint32_t j = 0; j < plan.njoins; j++) joined |= strcmp(plan.joins[j].path, plan.p[i].src) == 0;
if (!joined && check_source(plan.p[i].dest, plan.p[i].src) != 0) return 1;
}
for (uint32_t j = 0; j < plan.njoins; j++) {
const Join *join = &plan.joins[j];
if (check_source(join->path, join->first) != 0 || check_source(join->path, join->second) != 0) return 1;
}
return 0;
}
static int load_ledger(const Paths *p)
{
LedgerError err;
if (ledger_load(&ledger, p->ledger_path, &err)) return 0;
say(STDERR_FILENO, "%s:%d: %s\n", p->ledger_path, err.line, err.msg);
return 1;
}
// Everything plan, apply and status start with: the config, the store, the
// ledger, the plan and what to do about the disk.
static int prepare(const Paths *p)
{
ConfError cerr;
if (!conf_load(&conf, p->conf_path, &cerr)) {
say(STDERR_FILENO, "%s:%d: %s\n", p->conf_path, cerr.line, cerr.msg);
return 1;
}
int rc = load_assets(p);
if (rc != 0) return rc;
rc = machine_read(p->machine_path, machine);
if (rc != 0) return rc;
ResolveError rerr;
if (!resolve(&conf, &assets, p->home, p->suit_home, p->store, machine, &plan, &rerr)) {
say(STDERR_FILENO, "suit: %s\n", rerr.msg);
return 1;
}
rc = check_sources();
if (rc != 0) return rc;
rc = load_ledger(p);
if (rc != 0) return rc;
return place_plan(&plan, &ledger, &acts);
}
int cmd_plan(void)
{
Paths p;
int rc = store_check_journal(WARDROBE_NAME);
if (rc != 0) return rc;
rc = find_paths(&p);
rc = rc != 0 ? rc : prepare(&p);
if (rc == 0) place_print(&plan, &acts);
return rc;
}
// ---- the stamp: what the no-change run watches ---------------------------------
typedef struct {
char *paths[WATCH_MAX];
uint32_t n;
char text[2 * 1048576];
size_t used;
char dir[2 * PATH_CAP]; // a path of the store can be longer than any one folder name
int depth;
} Watch;
static Watch watch;
static int watch_add(const char *path)
{
size_t len = strlen(path) + 1;
if (watch.n == WATCH_MAX || watch.used + len > sizeof watch.text) {
say(STDERR_FILENO, "suit: more than %u files and folders in the store to watch\n", WATCH_MAX);
return 1;
}
char *copy = watch.text + watch.used;
memcpy(copy, path, len);
watch.used += len;
watch.paths[watch.n++] = copy;
return 0;
}
static int watch_dir(const char *dir);
static int watch_entry(void *state, const char *entry)
{
(void)state;
bool skip = strcmp(entry, ".fslckout") == 0 || strncmp(entry, SUIT_TMP_PREFIX, strlen(SUIT_TMP_PREFIX)) == 0;
if (skip) return 0;
size_t len = strlen(watch.dir);
[[maybe_unused]] int n = snprintf(watch.dir + len, sizeof watch.dir - len, "/%s", entry);
ensure(n > 0 && (size_t)n < sizeof watch.dir - len); // the system allows no longer path
struct stat st = {};
(void)sys_lstat(watch.dir, &st);
int rc = watch_add(watch.dir);
if (rc == 0 && S_ISDIR(st.st_mode)) rc = watch_dir(watch.dir);
watch.dir[len] = '\0';
return rc;
}
static int watch_dir(const char *dir)
{
if (watch.depth == WATCH_DEPTH) {
say(STDERR_FILENO, "suit: folders in the store are nested more than %d deep at %s\n",
WATCH_DEPTH, dir);
return 1;
}
watch.depth++;
int rc = sys_listdir(dir, watch_entry, nullptr);
watch.depth--;
if (rc < 0) {
say(STDERR_FILENO, "suit: cannot read %s: %s\n", dir, strerror(errno));
return 1;
}
return rc;
}
// Stamp the config, the machine's name, the ledger and everything in the store but the checkout
// database: a change to any of them is a reason to run apply.
static int write_stamp(const Paths *p)
{
watch.n = 0;
watch.used = 0;
watch.depth = 0;
snprintf(watch.dir, sizeof watch.dir, "%s", p->store);
[[maybe_unused]] int conf_rc = watch_add(p->conf_path);
[[maybe_unused]] int ledger_rc = watch_add(p->ledger_path);
[[maybe_unused]] int machine_rc = watch_add(p->machine_path);
ensure(conf_rc == 0 && ledger_rc == 0 && machine_rc == 0); // the list is empty, so three paths always fit
int rc = watch_dir(p->store);
return rc != 0 ? rc : stamp_write((int)watch.n, watch.paths);
}
// ---- apply ---------------------------------------------------------------------
int cmd_apply(void)
{
Paths p;
int rc = store_check_journal(WARDROBE_NAME);
if (rc != 0) return rc;
rc = find_paths(&p);
if (rc != 0) return rc;
rc = place_lock(p.lock_path);
if (rc != 0) return rc;
rc = prepare(&p);
rc = rc != 0 ? rc : place_apply(&ledger, &acts, p.ledger_path);
if (rc == 0) place_print(&plan, &acts);
rc = rc != 0 ? rc : write_stamp(&p);
place_unlock(p.lock_path);
return rc;
}
// ---- status --------------------------------------------------------------------
typedef struct {
const char *harness;
AssetKind kind;
uint32_t count;
} Tally;
static int cmp_tally(const void *pa, const void *pb)
{
const Tally *a = pa;
const Tally *b = pb;
int r = strcmp(a->harness, b->harness);
return r != 0 ? r : (int)a->kind - (int)b->kind;
}
static void print_links(void)
{
static Tally tally[(CONF_HARNESS_MAX + 1) * AK_COUNT];
uint32_t n = 0;
for (uint32_t i = 0; i < acts.n; i++) {
const Action *a = &acts.a[i];
if (a->kind != ACT_KEEP) continue;
uint32_t t = 0;
while (t < n && !(strcmp(tally[t].harness, a->want->harness) == 0 && tally[t].kind == a->want->kind))
t++;
if (t == n) tally[n++] = (Tally){a->want->harness, a->want->kind, 0};
tally[t].count++;
}
qsort(tally, n, sizeof tally[0], cmp_tally);
for (uint32_t i = 0; i < n; i++)
say(STDOUT_FILENO, "links %s %s %u\n", tally[i].harness, asset_kind_name(tally[i].kind),
tally[i].count);
}
// One line for each wear limited to a machine that is not this one.
static void print_ignored_limits(void)
{
for (uint32_t i = 0; i < conf.nsections; i++) {
const Section *s = &conf.sections[i];
if (s->kind != KIND_WEAR || strcmp(s->arg[0], "user") != 0) continue;
if (s->arg[2][0] == '\0' || strcmp(s->arg[2], machine) == 0) continue;
if (machine[0] == '\0')
say(STDOUT_FILENO, "machine %s: not this machine (this machine has no name)\n", s->arg[2]);
else
say(STDOUT_FILENO, "machine %s: not this machine (this is %s)\n", s->arg[2], machine);
}
}
int cmd_status(void)
{
Paths p;
int rc = store_show_version(WARDROBE_NAME);
rc = rc != 0 ? rc : find_paths(&p);
rc = rc != 0 ? rc : prepare(&p);
if (rc != 0) return rc;
print_links();
for (uint32_t i = 0; i < acts.n; i++)
if (acts.a[i].kind == ACT_CLASH)
say(STDOUT_FILENO, "clash %s (%s)\n", acts.a[i].dest, acts.a[i].reason);
(void)place_missing(&ledger, true);
for (uint32_t i = 0; i < plan.nskips; i++) say(STDOUT_FILENO, "%s\n", plan.skips[i]);
print_ignored_limits();
return 0;
}
// ---- machine -------------------------------------------------------------------
int cmd_machine(const char *name)
{
Paths p;
int rc = find_paths(&p);
if (rc != 0) return rc;
if (name != nullptr) {
if (!machine_name_ok(name, strlen(name))) {
say(STDERR_FILENO, "suit: '%s' is not a machine name (1 to %zu letters, digits, - _ .)\n", name,
MACHINE_MAX);
return 2;
}
return machine_write(p.machine_path, name);
}
rc = machine_read(p.machine_path, machine);
if (rc == 0 && machine[0] == '\0') {
say(STDERR_FILENO, "suit: this machine has no name (suit machine NAME sets one)\n");
return 1;
}
if (rc == 0) say(STDOUT_FILENO, "%s\n", machine);
return rc;
}
// ---- off -----------------------------------------------------------------------
int cmd_off(void)
{
Paths p;
int rc = find_paths(&p);
if (rc != 0) return rc;
rc = place_lock(p.lock_path);
if (rc != 0) return rc;
rc = load_ledger(&p);
rc = rc != 0 ? rc : place_off(&ledger, p.ledger_path);
if (rc == 0) {
// Nothing is applied, so there is nothing for the timer to watch.
char stamp[PATH_CAP];
[[maybe_unused]] size_t home = suit_home_path(stamp, sizeof stamp, "stamp");
ensure(home != 0);
(void)sys_unlink(stamp);
}
place_unlock(p.lock_path);
return rc;
}
// ---- run -----------------------------------------------------------------------
int cmd_run(void)
{
int rc = stamp_check(false);
return rc == EXIT_CHANGED ? cmd_apply() : rc;
}