#include "install.h"
#include "attention.h"
#include "platform.h"
#include "stamp.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
// ---- the text of the files ----------------------------------------------------
typedef struct {
char *p;
size_t len;
size_t cap;
} Buf;
// Every caller's text fits: the paths are limited, and OUT holds INSTALL_TEXT_MAX.
static void put(Buf *b, const char *s)
{
size_t n = strlen(s);
ensure(n <= b->cap - b->len);
memcpy(b->p + b->len, s, n);
b->len += n;
}
static void put_char(Buf *b, char c)
{
ensure(b->len < b->cap);
b->p[b->len++] = c;
}
// S as XML text.
static void put_xml(Buf *b, const char *s)
{
for (; *s != '\0'; s++) {
switch (*s) {
case '&': put(b, "&"); break;
case '<': put(b, "<"); break;
case '>': put(b, ">"); break;
case '"': put(b, """); break;
case '\'': put(b, "'"); break;
default: put_char(b, *s);
}
}
}
// S inside a double-quoted systemd word: the backslash and the quote are
// escaped, and % and $ are doubled because systemd expands them.
static void put_sd(Buf *b, const char *s)
{
for (; *s != '\0'; s++) {
if (*s == '\\' || *s == '"') put_char(b, '\\');
if (*s == '%' || *s == '$') put_char(b, *s);
put_char(b, *s);
}
}
static bool path_ok(const char *p)
{
if (p == nullptr || p[0] != '/' || strlen(p) > INSTALL_PATH_MAX) return false;
for (; *p != '\0'; p++)
if ((unsigned char)*p < 0x20 || *p == 0x7f) return false;
return true;
}
bool install_spec_ok(const InstallSpec *s)
{
return path_ok(s->suit) && path_ok(s->run) && path_ok(s->home);
}
const char *install_label(Timer t)
{
return t == TIMER_RUN ? "app.zeitforge.suit.run" : "app.zeitforge.suit.tend";
}
static unsigned seconds(Timer t)
{
return t == TIMER_RUN ? INSTALL_RUN_SECONDS : INSTALL_TEND_SECONDS;
}
static const char *word(Timer t)
{
return t == TIMER_RUN ? "run" : "tend";
}
// ---- launchd
ssize_t install_plist(char *out, size_t cap, const InstallSpec *s, Timer t)
{
ensure(cap >= INSTALL_TEXT_MAX);
if (!install_spec_ok(s)) return -1;
Buf b = {out, 0, cap};
char num[16];
[[maybe_unused]] int n = snprintf(num, sizeof num, "%u", seconds(t));
ensure(n > 0);
put(&b, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
"<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" "
"\"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n"
"<plist version=\"1.0\">\n<dict>\n\t<key>Label</key>\n\t<string>");
put(&b, install_label(t));
put(&b, "</string>\n\t<key>ProgramArguments</key>\n\t<array>\n\t\t<string>");
put_xml(&b, t == TIMER_RUN ? s->run : s->suit);
put(&b, "</string>\n");
if (t == TIMER_TEND) put(&b, "\t\t<string>tend</string>\n");
put(&b, "\t</array>\n\t<key>StartInterval</key>\n\t<integer>");
put(&b, num);
put(&b, "</integer>\n\t<key>RunAtLoad</key>\n\t<false/>\n"
"\t<key>ProcessType</key>\n\t<string>Background</string>\n"
"\t<key>LowPriorityIO</key>\n\t<true/>\n");
if (s->home_set) {
put(&b, "\t<key>EnvironmentVariables</key>\n\t<dict>\n\t\t<key>SUIT_HOME</key>\n\t\t<string>");
put_xml(&b, s->home);
put(&b, "</string>\n\t</dict>\n");
}
put(&b, "\t<key>StandardErrorPath</key>\n\t<string>");
put_xml(&b, s->home);
put(&b, "/log/");
put(&b, word(t));
put(&b, ".err</string>\n</dict>\n</plist>\n");
return (ssize_t)b.len;
}
// ---- systemd
ssize_t install_service(char *out, size_t cap, const InstallSpec *s, Timer t)
{
ensure(cap >= INSTALL_TEXT_MAX);
if (!install_spec_ok(s)) return -1;
Buf b = {out, 0, cap};
put(&b, t == TIMER_RUN ? "[Unit]\nDescription=suit: look for changes and apply them\n"
: "[Unit]\nDescription=suit: tend every wardrobe\n");
put(&b, "\n[Service]\nType=oneshot\nExecStart=\"");
put_sd(&b, t == TIMER_RUN ? s->run : s->suit);
put(&b, t == TIMER_RUN ? "\"\n" : "\" tend\n");
if (s->home_set) {
put(&b, "Environment=\"SUIT_HOME=");
put_sd(&b, s->home);
put(&b, "\"\n");
}
return (ssize_t)b.len;
}
ssize_t install_timer(char *out, size_t cap, const InstallSpec *s, Timer t)
{
ensure(cap >= INSTALL_TEXT_MAX);
if (!install_spec_ok(s)) return -1;
Buf b = {out, 0, cap};
char num[16];
[[maybe_unused]] int n = snprintf(num, sizeof num, "%u", seconds(t));
ensure(n > 0);
put(&b, t == TIMER_RUN ? "[Unit]\nDescription=suit: every minute\n"
: "[Unit]\nDescription=suit: every hour\n");
put(&b, "\n[Timer]\nOnBootSec=");
put(&b, num);
put(&b, "s\nOnUnitActiveSec=");
put(&b, num);
put(&b, t == TIMER_RUN ? "s\nAccuracySec=1s\n" : "s\nPersistent=true\n");
put(&b, "\n[Install]\nWantedBy=timers.target\n");
return (ssize_t)b.len;
}
// ---- where the files go -------------------------------------------------------
typedef enum { FORM_PLIST, FORM_SERVICE, FORM_TIMER } Form;
typedef struct {
const char *name;
Timer timer;
Form form;
} FileDef;
static const FileDef launchd_files[] = {
{"app.zeitforge.suit.run.plist", TIMER_RUN, FORM_PLIST},
{"app.zeitforge.suit.tend.plist", TIMER_TEND, FORM_PLIST},
};
static const FileDef systemd_files[] = {
{"suit-run.service", TIMER_RUN, FORM_SERVICE},
{"suit-run.timer", TIMER_RUN, FORM_TIMER},
{"suit-tend.service", TIMER_TEND, FORM_SERVICE},
{"suit-tend.timer", TIMER_TEND, FORM_TIMER},
};
constexpr size_t MAX_FILES = 4;
constexpr size_t BUF = INSTALL_PATH_MAX + 128;
static size_t file_defs(Manager m, const FileDef **defs)
{
if (m == MANAGER_LAUNCHD) {
*defs = launchd_files;
return sizeof launchd_files / sizeof launchd_files[0];
}
*defs = systemd_files;
return sizeof systemd_files / sizeof systemd_files[0];
}
static const char *env_nonempty(const char *name)
{
const char *v = sys_getenv(name);
return v != nullptr && v[0] != '\0' ? v : nullptr;
}
// The folder that holds the files of manager M, into OUT (BUF bytes).
static bool find_dir(Manager m, char *out)
{
const char *home = env_nonempty("HOME");
const char *xdg = m == MANAGER_SYSTEMD ? env_nonempty("XDG_CONFIG_HOME") : nullptr;
const char *base = xdg != nullptr ? xdg : home;
if (base == nullptr) {
say(STDERR_FILENO, "suit: HOME is not set\n");
return false;
}
if (strlen(base) > INSTALL_PATH_MAX) {
say(STDERR_FILENO, "suit: %s is longer than %zu bytes\n", xdg != nullptr ? "XDG_CONFIG_HOME" : "HOME", INSTALL_PATH_MAX);
return false;
}
const char *tail = m == MANAGER_LAUNCHD ? "/Library/LaunchAgents" : xdg != nullptr ? "/systemd/user" : "/.config/systemd/user";
[[maybe_unused]] int n = snprintf(out, BUF, "%s%s", base, tail);
ensure(n > 0 && (size_t)n < BUF);
return true;
}
// The folder suit keeps its files in, into OUT, and whether SUIT_HOME names it.
static bool find_home(char *out, bool *set)
{
const char *given = env_nonempty("SUIT_HOME");
const char *home = env_nonempty("HOME");
if (given == nullptr && home == nullptr) {
say(STDERR_FILENO, "suit: neither SUIT_HOME nor HOME is set\n");
return false;
}
const char *base = given != nullptr ? given : home;
if (strlen(base) > INSTALL_PATH_MAX) {
say(STDERR_FILENO, "suit: %s is longer than %zu bytes\n", given != nullptr ? "SUIT_HOME" : "HOME", INSTALL_PATH_MAX);
return false;
}
[[maybe_unused]] int n = snprintf(out, BUF, "%s%s", base, given != nullptr ? "" : "/.suit");
ensure(n > 0 && (size_t)n < BUF);
char def[BUF];
n = snprintf(def, sizeof def, "%s/.suit", home != nullptr ? home : "");
ensure(n > 0 && (size_t)n < sizeof def);
*set = given != nullptr && strcmp(given, def) != 0;
return true;
}
// An absolute, existing, executable regular file.
static bool exe_ok(const char *path, const char *what)
{
struct stat st;
if (sys_stat(path, &st) != 0) {
say(STDERR_FILENO, "suit: cannot use %s (%s): %s\n", what, path, strerror(errno));
return false;
}
if (!S_ISREG(st.st_mode) || (st.st_mode & 0111) == 0) {
say(STDERR_FILENO, "suit: %s (%s) is not an executable file\n", what, path);
return false;
}
return true;
}
typedef struct {
Manager mgr;
const FileDef *defs;
size_t n;
char dir[BUF];
char home[BUF];
char suit[BUF];
char run[BUF + 16];
InstallSpec spec;
char path[MAX_FILES][BUF * 2];
char text[MAX_FILES][INSTALL_TEXT_MAX];
size_t len[MAX_FILES];
} Plan;
static Plan plan;
// Fill `plan` as far as where the files go. 0, or 1 after saying why.
static int locate(void)
{
plan.mgr = platform_manager();
plan.n = file_defs(plan.mgr, &plan.defs);
if (!find_dir(plan.mgr, plan.dir)) return 1;
for (size_t i = 0; i < plan.n; i++) {
[[maybe_unused]] int n = snprintf(plan.path[i], sizeof plan.path[i], "%s/%s", plan.dir, plan.defs[i].name);
ensure(n > 0 && (size_t)n < sizeof plan.path[i]);
}
return 0;
}
// Fill `plan`: where the files go and what each says. 0, or 1 after saying why.
static int build_plan(void)
{
if (locate() != 0 || !find_home(plan.home, &plan.spec.home_set)) return 1;
if (!platform_self_path(plan.suit, BUF)) {
say(STDERR_FILENO, "suit: cannot find the path of this program\n");
return 1;
}
ensure(plan.suit[0] == '/'); // the platform gives the absolute path
char *slash = strrchr(plan.suit, '/');
[[maybe_unused]] int n = snprintf(plan.run, sizeof plan.run, "%.*s/suit-run", (int)(slash - plan.suit), plan.suit);
ensure(n > 0 && (size_t)n < sizeof plan.run);
if (!exe_ok(plan.suit, "suit") || !exe_ok(plan.run, "suit-run, which sits beside suit,")) return 1;
plan.spec.suit = plan.suit;
plan.spec.run = plan.run;
plan.spec.home = plan.home;
if (!install_spec_ok(&plan.spec)) {
say(STDERR_FILENO, "suit: a path is too long, not absolute or holds a control character\n");
return 1;
}
for (size_t i = 0; i < plan.n; i++) {
const FileDef *d = &plan.defs[i];
ssize_t len = d->form == FORM_PLIST ? install_plist(plan.text[i], INSTALL_TEXT_MAX, &plan.spec, d->timer)
: d->form == FORM_SERVICE ? install_service(plan.text[i], INSTALL_TEXT_MAX, &plan.spec, d->timer)
: install_timer(plan.text[i], INSTALL_TEXT_MAX, &plan.spec, d->timer);
ensure(len > 0);
plan.len[i] = (size_t)len;
ensure(plan.len[i] < INSTALL_TEXT_MAX);
plan.text[i][plan.len[i]] = '\0';
}
return 0;
}
// ---- reading and writing the files -------------------------------------------
typedef enum { UNIT_ABSENT, UNIT_SAME, UNIT_DIFFERENT } UnitState;
static char current[INSTALL_TEXT_MAX + 1];
// How file I of the plan stands: absent, the same text or other text. 0, or 1
// after saying why it cannot be read.
static int unit_state(size_t i, UnitState *st)
{
int fd = sys_open(plan.path[i], O_RDONLY, 0);
if (fd < 0 && errno == ENOENT) {
*st = UNIT_ABSENT;
return 0;
}
if (fd < 0) {
say(STDERR_FILENO, "suit: cannot open %s: %s\n", plan.path[i], strerror(errno));
return 1;
}
size_t len = 0;
ssize_t got = 1;
while (got != 0 && len <= INSTALL_TEXT_MAX) {
got = sys_read(fd, current + len, INSTALL_TEXT_MAX + 1 - len);
if (got < 0 && errno == EINTR) continue;
if (got < 0) break;
len += (size_t)got;
}
int err = errno;
(void)sys_close(fd);
if (got < 0) {
say(STDERR_FILENO, "suit: cannot read %s: %s\n", plan.path[i], strerror(err));
return 1;
}
*st = len == plan.len[i] && memcmp(current, plan.text[i], len) == 0 ? UNIT_SAME : UNIT_DIFFERENT;
return 0;
}
// mkdir -p. 0 or an errno value.
static int make_folder(const char *path)
{
char tmp[BUF * 2];
[[maybe_unused]] int n = snprintf(tmp, sizeof tmp, "%s", path);
ensure(n > 0 && (size_t)n < sizeof tmp);
for (char *p = tmp + 1;; p++) {
char c = *p;
if (c == '/' || c == '\0') {
*p = '\0';
if (sys_mkdir(tmp, 0755) != 0 && errno != EEXIST) return errno;
*p = c;
}
if (c == '\0') return 0;
}
}
// ---- the loader --------------------------------------------------------------
// The text of the last loader command, for messages.
static char last_cmd[4 * BUF];
static char *unconst(const char *s)
{
char *p;
memcpy(&p, &s, sizeof p);
return p;
}
// Run the loader with up to four arguments (the first null ends them) and
// wait. Its exit status, or -1 after saying why it did not run to the end.
static int run_loader(const char *a, const char *b, const char *c, const char *d)
{
const char *loader = platform_loader();
char *argv[] = {unconst(loader), unconst(a), unconst(b), unconst(c), unconst(d), nullptr};
last_cmd[0] = '\0';
size_t used = 0;
for (size_t i = 0; argv[i] != nullptr; i++) {
[[maybe_unused]] int n = snprintf(last_cmd + used, sizeof last_cmd - used, "%s%s", i > 0 ? " " : "", argv[i]);
ensure(n > 0 && (size_t)n < sizeof last_cmd - used);
used += (size_t)n;
}
pid_t pid;
int rc = sys_spawn(&pid, loader, argv);
if (rc != 0) {
say(STDERR_FILENO, "suit: cannot run %s: %s\n", loader, strerror(rc));
return -1;
}
int status;
while (sys_wait4(pid, &status, nullptr) < 0) {
if (errno == EINTR) continue;
say(STDERR_FILENO, "suit: cannot wait for %s: %s\n", loader, strerror(errno));
return -1;
}
if (!WIFEXITED(status)) {
say(STDERR_FILENO, "suit: %s was killed by signal %d\n", last_cmd, WTERMSIG(status));
return -1;
}
return WEXITSTATUS(status);
}
// What the loader is asked to call a timer: its label on macOS, its unit on Linux.
static const char *timer_unit(Timer t)
{
return t == TIMER_RUN ? "suit-run.timer" : "suit-tend.timer";
}
// The plist of timer T (macOS).
static const char *plist_of(Timer t)
{
return plan.path[t == TIMER_RUN ? 0 : 1];
}
// Unload timer T. A loader that says no is reported; it is normal when the
// timer was not loaded.
static void unload_timer(Timer t)
{
char target[BUF];
int status;
if (plan.mgr == MANAGER_LAUNCHD) {
[[maybe_unused]] int n = snprintf(target, sizeof target, "gui/%u/%s", platform_uid(), install_label(t));
ensure(n > 0 && (size_t)n < sizeof target);
status = run_loader("bootout", target, nullptr, nullptr);
} else {
status = run_loader("--user", "disable", "--now", timer_unit(t));
}
if (status > 0)
say(STDERR_FILENO, "suit: %s exited with status %d (already unloaded is normal)\n", last_cmd, status);
}
// Load timer T, which is `replace` if an older one may be loaded. 0, or the
// loader's failure after saying so.
static int load_timer(Timer t, bool replace)
{
int status;
if (plan.mgr == MANAGER_LAUNCHD) {
if (replace) unload_timer(t);
char domain[BUF];
[[maybe_unused]] int n = snprintf(domain, sizeof domain, "gui/%u", platform_uid());
ensure(n > 0 && (size_t)n < sizeof domain);
status = run_loader("bootstrap", domain, plist_of(t), nullptr);
} else {
status = run_loader("--user", "enable", "--now", timer_unit(t));
}
if (status > 0) say(STDERR_FILENO, "suit: %s exited with status %d\n", last_cmd, status);
return status == 0 ? 0 : EXIT_LOADER_FAILED;
}
// ---- install -----------------------------------------------------------------
static int print_files(void)
{
Out o;
out_init(&o, STDOUT_FILENO);
for (size_t i = 0; i < plan.n; i++) {
out_str(&o, "# ");
out_str(&o, plan.path[i]);
out_str(&o, "\n");
out_str(&o, plan.text[i]);
out_str(&o, "\n");
}
if (!out_finish(&o)) {
say(STDERR_FILENO, "suit: cannot write the files: %s\n", strerror(errno));
return 1;
}
return 0;
}
// Ask the loader to take up both timers, those in REPLACE having had older
// files. Both, not only those whose files changed, so that a run that stopped
// half way is finished by the next. 0, or EXIT_LOADER_FAILED after saying so.
static int load_all(const bool replace[2])
{
if (plan.mgr == MANAGER_SYSTEMD) {
int status = run_loader("--user", "daemon-reload", nullptr, nullptr);
if (status > 0) say(STDERR_FILENO, "suit: %s exited with status %d\n", last_cmd, status);
if (status != 0) return EXIT_LOADER_FAILED;
}
for (Timer t = TIMER_RUN; t <= TIMER_TEND; t++)
if (load_timer(t, replace[t]) != 0) return EXIT_LOADER_FAILED;
return 0;
}
int cmd_install(bool print)
{
if (build_plan() != 0) return 1;
if (print) return print_files();
UnitState st[MAX_FILES] = {UNIT_ABSENT};
bool changed[2] = {false, false};
bool replace[2] = {false, false}; // a file of the timer was there already
for (size_t i = 0; i < plan.n; i++) {
if (unit_state(i, &st[i]) != 0) return 1;
Timer t = plan.defs[i].timer;
changed[t] = changed[t] || st[i] != UNIT_SAME;
replace[t] = replace[t] || st[i] != UNIT_ABSENT;
}
if (changed[TIMER_RUN] || changed[TIMER_TEND]) {
char logs[BUF + 8];
[[maybe_unused]] int n = snprintf(logs, sizeof logs, "%s/log", plan.home);
ensure(n > 0 && (size_t)n < sizeof logs);
int err = make_folder(plan.dir);
if (err == 0 && plan.mgr == MANAGER_LAUNCHD) err = make_folder(logs);
if (err != 0) {
say(STDERR_FILENO, "suit: cannot create the folder: %s\n", strerror(err));
return 1;
}
for (size_t i = 0; i < plan.n; i++) {
if (st[i] == UNIT_SAME) continue;
err = sys_write_atomic_exact(plan.path[i], plan.text[i], plan.len[i], 0644);
if (err != 0) {
say(STDERR_FILENO, "suit: cannot write %s: %s (nothing was loaded; run suit install again)\n",
plan.path[i], strerror(err));
return 1;
}
}
int rc = load_all(replace);
if (rc != 0) {
say(STDERR_FILENO, "suit: the files are in place in %s; load them by hand (docs/install.md)\n", plan.dir);
return rc;
}
}
for (Timer t = TIMER_RUN; t <= TIMER_TEND; t++)
say(STDOUT_FILENO, "%s: %s\n", word(t), !changed[t] ? "already installed" : replace[t] ? "updated" : "installed");
return 0;
}
// ---- uninstall and state -----------------------------------------------------
// Whether file I of the plan is there: 1, 0, or -1 after saying why not.
static int present(size_t i)
{
struct stat st;
if (sys_lstat(plan.path[i], &st) == 0) return 1;
if (errno == ENOENT) return 0;
say(STDERR_FILENO, "suit: cannot look at %s: %s\n", plan.path[i], strerror(errno));
return -1;
}
int cmd_uninstall(void)
{
if (locate() != 0) return 1;
bool there[MAX_FILES] = {false};
bool any = false;
for (size_t i = 0; i < plan.n; i++) {
int p = present(i);
if (p < 0) return 1;
there[i] = p == 1;
any = any || there[i];
}
if (!any) {
say(STDOUT_FILENO, "not installed\n");
return 0;
}
unload_timer(TIMER_RUN);
unload_timer(TIMER_TEND);
int rc = 0;
for (size_t i = 0; i < plan.n; i++) {
if (!there[i]) continue;
if (sys_unlink(plan.path[i]) != 0) {
say(STDERR_FILENO, "suit: cannot remove %s: %s\n", plan.path[i], strerror(errno));
rc = 1;
} else {
say(STDOUT_FILENO, "removed %s\n", plan.path[i]);
}
}
return rc;
}
int install_print_state(void)
{
if (locate() != 0) return 1;
size_t there = 0;
for (size_t i = 0; i < plan.n; i++) {
int p = present(i);
if (p < 0) return 1;
there += (size_t)p;
}
const char *state = "not installed";
if (there > 0) {
state = "differ from this suit (run suit install)";
if (build_plan() == 0) {
size_t same = 0;
for (size_t i = 0; i < plan.n; i++) {
UnitState st;
if (unit_state(i, &st) != 0) return 1;
same += st == UNIT_SAME;
}
if (same == plan.n) state = "installed";
}
}
say(STDOUT_FILENO, "timers: %s\n", state);
return 0;
}
int cmd_status_line(void)
{
char path[STAMP_PATH_MAX];
unsigned count;
if (suit_home_path(path, sizeof path, "attention") == 0) return 1;
if (attention_count(path, &count) != 0) return 1;
if (count > 0) {
say(STDOUT_FILENO, "suit: %u need you\n", count);
return 0;
}
if (locate() != 0) return 1;
for (size_t i = 0; i < plan.n; i++) {
int p = present(i);
if (p < 0) return 1;
if (p == 0) {
say(STDOUT_FILENO, "suit: not installed\n");
return 0;
}
}
say(STDOUT_FILENO, "suit ok\n");
return 0;
}