Files
mcde/lib/McdeSys/backup.c
T
lotherk dcee228451 McdeSys: the backup errors in the catalog, German measured (t0282)
backup.c's 23 mcde_sys_fail calls are messages 22-38 of mcdesys.cat now:
cannot write, the backup disk mounted somewhere else, the six
administrator sentences (set up, change, switch, back up, look into,
restore), BorgBackup missing, password too short, choose a disk, bad numbers,
crontab/dtbackup missing, no disk set up, nothing to restore, cannot go to.
The German copy in programs/localized/de_DE.UTF-8/msg/mcdesys.msg uses the
same numbers; these texts are shown in System Settings (Xft), so they carry
proper umlauts.

Measured with a runner (setlocale + the public calls):
LANG=C: "Only the administrator can set up the backup.", "Only the
administrator can switch the backup.", "Only the administrator can restore
from the backups."; LANG=de_DE.UTF-8: "Nur der Administrator kann die
Sicherung einrichten.", "... die Sicherung umschalten.", "... aus den
Sicherungen wiederherstellen."
make mcde-linux MCDE_DIRS="install lib/McdeSys" and "install
programs/localized/C/msg" exit=0; "check lib/McdeSys": FAIL 0, exit=0;
MCDE_DIRS=plist: ok.
2026-11-16 10:52:58 +00:00

469 lines
15 KiB
C

/*
* backup.c -- MCDE: the whole system, every hour, to a disk of its own
*
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* BorgBackup does the work (docs/reference/borg.txt in the Makronix tree):
*
* borg init -e repokey-blake2 REPO encrypted; the key lives in the
* repository, behind the passphrase
* borg create -x --exclude-caches --compression lz4
* REPO::{hostname}-{now:%Y-%m-%dT%H:%M} / [/home]
* -x: no other file systems, so not
* /proc, /dev, /tmp nor the backup
* disk itself
* borg prune -H 24 -d 30 -w 52 -m -1 24 hourly, 30 daily, 52 weekly,
* every monthly (negative: no limit);
* the numbers are settings
* borg compact gives the space back
* borg delete REPO::OLDEST when the disk's free space is
* below min_free percent, before and
* after a backup -- the oldest first,
* never the newest
* borg list --json, borg extract
*
* The passphrase is kept in /etc/mcde-backup.pass (root, 0600) and handed
* to borg by BORG_PASSCOMMAND, so the hourly run needs nobody; the disk is
* encrypted against whoever takes it away, not against root of this
* computer. /etc/mcde-backup.conf names the partition and the repository;
* /var/db/mcde-backup.state the last run. The hourly run is a line in
* root's crontab(5), between "# MCDE backup" markers: dtbackup run.
*
* POSIX; the system's part (mounting the disk) is the backend's
* (mcde_sys_disk_mount).
*/
#define _POSIX_C_SOURCE 200809L
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/statvfs.h>
#include <Mcde/McdeSys.h>
#include "private.h"
#define CONF "/etc/mcde-backup.conf"
#define PASS "/etc/mcde-backup.pass"
#define STATE "/var/db/mcde-backup.state"
#define PASSCMD "BORG_PASSCOMMAND=cat " PASS
static const char *const borgPaths[] = { MCDE_PKG_PREFIX "/bin/borg",
"/usr/bin/borg", "/usr/local/bin/borg", NULL };
static const char *const crontabPaths[] = { "/usr/bin/crontab", NULL };
static const char *const dtbackupPaths[] = { MCDE_PKG_PREFIX "/dt/bin/dtbackup",
"/usr/dt/bin/dtbackup", NULL };
static void
Value(const char *file, const char *key, char *buf, size_t len)
{
buf[0] = '\0';
(void) mcde_sys_file_value(file, key, buf, len);
}
int
mcde_sys_backup_get(McdeSysBackup *b)
{
char v[64];
memset(b, 0, sizeof *b);
Value(CONF, "disk=", b->disk, sizeof b->disk);
Value(CONF, "repo=", b->repo, sizeof b->repo);
Value(CONF, "enabled=", v, sizeof v);
b->configured = b->disk[0] != '\0' && b->repo[0] != '\0';
b->enabled = b->configured && strcmp(v, "1") == 0;
Value(STATE, "last=", v, sizeof v);
b->last = atoll(v);
Value(STATE, "result=", b->result, sizeof b->result);
/* the settings, or their defaults */
b->keepHourly = 24;
b->keepDaily = 30;
b->keepWeekly = 52;
b->keepMonthly = -1;
b->minFree = 10;
Value(CONF, "keep_hourly=", v, sizeof v);
if (v[0] != '\0')
b->keepHourly = atoi(v);
Value(CONF, "keep_daily=", v, sizeof v);
if (v[0] != '\0')
b->keepDaily = atoi(v);
Value(CONF, "keep_weekly=", v, sizeof v);
if (v[0] != '\0')
b->keepWeekly = atoi(v);
Value(CONF, "keep_monthly=", v, sizeof v);
if (v[0] != '\0')
b->keepMonthly = atoi(v);
Value(CONF, "min_free=", v, sizeof v);
if (v[0] != '\0')
b->minFree = atoi(v);
return MCDE_SYS_OK;
}
static int
WriteConf(const McdeSysBackup *b)
{
FILE *fp = fopen(CONF ".new", "w");
if (fp == NULL)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_BAK_WRITE, "Cannot write %s."), CONF);
fprintf(fp, "# MCDE backup (System Settings, Backup)\ndisk=%s\nrepo=%s\n"
"enabled=%d\n# kept: a number, -1 for every one\nkeep_hourly=%d\n"
"keep_daily=%d\nkeep_weekly=%d\nkeep_monthly=%d\n"
"# below this many percent free the oldest backups go\n"
"min_free=%d\n", b->disk, b->repo, b->enabled, b->keepHourly,
b->keepDaily, b->keepWeekly, b->keepMonthly, b->minFree);
if (fclose(fp) != 0 || rename(CONF ".new", CONF) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_BAK_WRITE, "Cannot write %s."), CONF);
return MCDE_SYS_OK;
}
static void
WriteState(const char *result)
{
FILE *fp = fopen(STATE, "w");
if (fp == NULL)
return;
fprintf(fp, "last=%lld\nresult=%s\n", (long long) time(NULL), result);
fclose(fp);
}
/* the backup disk mounted; the repository's folder made */
static int
Ready(McdeSysBackup *b)
{
char where[300];
if (mcde_sys_disk_mount(b->disk, where, sizeof where) != MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
if (strncmp(b->repo, where, strlen(where)) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_BAK_WRONG_DISK, "The backup disk is mounted on %s, not where the backups are (%s)."), where, b->repo);
return MCDE_SYS_OK;
}
int
mcde_sys_backup_setup(const char *partition, const char *passphrase)
{
McdeSysBackup b;
const char *borg = mcde_sys_which(borgPaths);
char where[300], host[128];
FILE *fp;
int fd;
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_BAK_EPERM_SETUP, "Only the administrator can set up the backup."));
if (borg == NULL)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, mcde_sys_msg(MSG_BAK_NO_BORG, "BorgBackup is not installed."));
if (passphrase == NULL || strlen(passphrase) < 8 ||
strchr(passphrase, '\n') != NULL)
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_BAK_PASSWORD, "The password needs 8 characters or more."));
if (mcde_sys_disk_mount(partition, where, sizeof where) != MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
if (mcde_sys_hostname_get(host, sizeof host) != MCDE_SYS_OK)
snprintf(host, sizeof host, "computer");
host[strcspn(host, ".")] = '\0';
memset(&b, 0, sizeof b);
snprintf(b.disk, sizeof b.disk, "%s", partition);
snprintf(b.repo, sizeof b.repo, "%s/Backups.%s", where, host);
/* the passphrase for the hourly runs: root alone reads it */
if ((fd = open(PASS ".new", O_WRONLY | O_CREAT | O_TRUNC, 0600)) < 0 ||
(fp = fdopen(fd, "w")) == NULL)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_BAK_WRITE, "Cannot write %s."), PASS);
fprintf(fp, "%s\n", passphrase);
if (fclose(fp) != 0 || rename(PASS ".new", PASS) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_BAK_WRITE, "Cannot write %s."), PASS);
{
char *argv[] = { "/usr/bin/env", PASSCMD, (char *) borg,
"init", "--encryption", "repokey-blake2", b.repo, NULL };
struct stat st;
/* a repository there already (the same disk, set up again)
* is taken as it is */
if (stat(b.repo, &st) != 0 && mcde_sys_run(argv) != MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
}
b.enabled = 0;
b.keepHourly = 24;
b.keepDaily = 30;
b.keepWeekly = 52;
b.keepMonthly = -1;
b.minFree = 10;
return WriteConf(&b);
}
int
mcde_sys_backup_policy(const McdeSysBackup *p)
{
McdeSysBackup b;
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_BAK_EPERM_CHANGE, "Only the administrator can change the backup."));
(void) mcde_sys_backup_get(&b);
if (!b.configured)
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_BAK_NO_DISK_CHOOSE, "Choose a backup disk first."));
if (p->minFree < 1 || p->minFree > 90 || p->keepHourly < -1 ||
p->keepDaily < -1 || p->keepWeekly < -1 || p->keepMonthly < -1)
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_BAK_BAD_NUMBERS, "Those numbers cannot be used."));
b.keepHourly = p->keepHourly;
b.keepDaily = p->keepDaily;
b.keepWeekly = p->keepWeekly;
b.keepMonthly = p->keepMonthly;
b.minFree = p->minFree;
return WriteConf(&b);
}
/* the free share of the disk REPO is on, in percent; -1 when unknown */
static int
FreePercent(const char *repo)
{
struct statvfs sv;
if (statvfs(repo, &sv) != 0 || sv.f_blocks == 0)
return -1;
return (int) ((double) sv.f_bavail * 100.0 / (double) sv.f_blocks);
}
/* the watcher: while the disk has less than MINFREE percent free, the
* oldest backup is deleted and the space given back -- the newest stays.
* How many went into *GONE. */
static void
Thin(const char *borg, const char *repo, int minFree, int *gone)
{
static McdeSysBackupArchive a[4096];
char what[800];
int n, i = 0;
*gone = 0;
if (FreePercent(repo) < 0 || FreePercent(repo) >= minFree)
return;
n = mcde_sys_backup_archives(a, sizeof a / sizeof a[0]);
/* borg list gives them oldest first */
while (n - i > 1 && FreePercent(repo) < minFree) {
char *del[] = { "/usr/bin/env", PASSCMD, (char *) borg,
"delete", what, NULL };
char *compact[] = { "/usr/bin/env", PASSCMD, (char *) borg,
"compact", (char *) repo, NULL };
snprintf(what, sizeof what, "%s::%s", repo, a[i].name);
if (mcde_sys_run(del) != MCDE_SYS_OK)
break;
(void) mcde_sys_run(compact);
(*gone)++;
i++;
}
}
int
mcde_sys_backup_enable(int on)
{
McdeSysBackup b;
const char *ct = mcde_sys_which(crontabPaths);
const char *db = mcde_sys_which(dtbackupPaths);
static char out[16384], in[17000];
char *line, *last = NULL;
size_t n = 0;
int skip = 0;
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_BAK_EPERM_SWITCH, "Only the administrator can switch the backup."));
(void) mcde_sys_backup_get(&b);
if (on && !b.configured)
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_BAK_NO_DISK_CHOOSE, "Choose a backup disk first."));
if (ct == NULL)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, mcde_sys_msg(MSG_BAK_NO_CRONTAB, "crontab is not there."));
if (on && db == NULL)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, mcde_sys_msg(MSG_BAK_NO_DTBACKUP, "dtbackup is not there."));
/* root's crontab with the MCDE lines replaced (crontab(1) -l, -) */
{
char *argv[] = { (char *) ct, "-l", NULL };
if (mcde_sys_capture(argv, out, sizeof out) != MCDE_SYS_OK)
out[0] = '\0'; /* no crontab yet */
}
in[0] = '\0';
for (line = strtok_r(out, "\n", &last); line != NULL;
line = strtok_r(NULL, "\n", &last)) {
if (strcmp(line, "# MCDE backup begin") == 0) {
skip = 1;
continue;
}
if (strcmp(line, "# MCDE backup end") == 0) {
skip = 0;
continue;
}
if (!skip && n + strlen(line) + 2 < sizeof in)
n += (size_t) snprintf(in + n, sizeof in - n, "%s\n",
line);
}
if (on)
n += (size_t) snprintf(in + n, sizeof in - n,
"# MCDE backup begin\n17 * * * * %s run >/dev/null 2>&1\n"
"# MCDE backup end\n", db);
{
char *argv[] = { (char *) ct, "-", NULL };
if (mcde_sys_run_input(argv, in) != MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
}
b.enabled = on;
return WriteConf(&b);
}
int
mcde_sys_backup_run(char *log, size_t len)
{
McdeSysBackup b;
const char *borg = mcde_sys_which(borgPaths);
char archive[700];
int r;
log[0] = '\0';
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_BAK_EPERM_RUN, "Only the administrator can back up the system."));
(void) mcde_sys_backup_get(&b);
if (!b.configured)
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_BAK_NO_DISK, "No backup disk is set up."));
if (borg == NULL)
return mcde_sys_fail(MCDE_SYS_ENOTSUP, mcde_sys_msg(MSG_BAK_NO_BORG, "BorgBackup is not installed."));
if (Ready(&b) != MCDE_SYS_OK) {
WriteState(mcde_sys_error());
return MCDE_SYS_EFAIL;
}
/* room first: a full disk would stop the backup halfway */
{
int gone;
Thin(borg, b.repo, b.minFree, &gone);
}
snprintf(archive, sizeof archive, "%s::{hostname}-{now:%%Y-%%m-%%dT%%H:%%M}",
b.repo);
{
struct stat st;
char *argv[] = { "/usr/bin/env", PASSCMD, (char *) borg,
"create", "--one-file-system", "--exclude-caches",
"--compression", "lz4", "--stats", archive, "/",
stat("/home", &st) == 0 ? "/home" : NULL, NULL };
r = mcde_sys_capture(argv, log, len);
}
if (r != MCDE_SYS_OK) {
WriteState("the backup did not succeed");
return r;
}
{
char h[16], d[16], w[16], m[16];
char *prune[] = { "/usr/bin/env", PASSCMD, (char *) borg,
"prune", "--keep-hourly", h, "--keep-daily", d,
"--keep-weekly", w, "--keep-monthly", m, b.repo, NULL };
char *compact[] = { "/usr/bin/env", PASSCMD, (char *) borg,
"compact", b.repo, NULL };
snprintf(h, sizeof h, "%d", b.keepHourly);
snprintf(d, sizeof d, "%d", b.keepDaily);
snprintf(w, sizeof w, "%d", b.keepWeekly);
snprintf(m, sizeof m, "%d", b.keepMonthly);
(void) mcde_sys_run(prune);
(void) mcde_sys_run(compact);
}
{
int gone;
char text[128];
Thin(borg, b.repo, b.minFree, &gone);
if (gone > 0) {
snprintf(text, sizeof text, "ok; %d of the oldest "
"backups deleted for space", gone);
WriteState(text);
return MCDE_SYS_OK;
}
}
WriteState("ok");
return MCDE_SYS_OK;
}
int
mcde_sys_backup_archives(McdeSysBackupArchive *a, size_t max)
{
McdeSysBackup b;
const char *borg = mcde_sys_which(borgPaths);
static char out[262144];
const char *p;
size_t n = 0;
(void) mcde_sys_backup_get(&b);
if (!b.configured || borg == NULL)
return 0;
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_BAK_EPERM_LOOK, "Only the administrator can look into the backups."));
if (Ready(&b) != MCDE_SYS_OK)
return -1;
{
char *argv[] = { "/usr/bin/env", PASSCMD, (char *) borg, "list",
"--json", b.repo, NULL };
if (mcde_sys_capture(argv, out, sizeof out) != MCDE_SYS_OK)
return -1;
}
/* {"archives": [{"name": "...", ..., "time": "..."}, ...]} -- the
* keys borg always gives; read in order, without a JSON library */
for (p = strstr(out, "\"name\": \""); p != NULL && n < max;
p = strstr(p, "\"name\": \"")) {
const char *e, *t;
p += 9;
if ((e = strchr(p, '"')) == NULL)
break;
snprintf(a[n].name, sizeof a[n].name, "%.*s", (int) (e - p), p);
a[n].time[0] = '\0';
if ((t = strstr(e, "\"time\": \"")) != NULL &&
(t = t + 9) != NULL)
snprintf(a[n].time, sizeof a[n].time, "%.19s", t);
n++;
p = e;
}
return (int) n;
}
int
mcde_sys_backup_restore(const char *archive, const char *path,
const char *dest)
{
McdeSysBackup b;
const char *borg = mcde_sys_which(borgPaths);
char what[800], where[1100], cwd[1100];
int r;
if (geteuid() != 0)
return mcde_sys_fail(MCDE_SYS_EPERM, mcde_sys_msg(MSG_BAK_EPERM_RESTORE, "Only the administrator can restore from the backups."));
if (archive == NULL || path == NULL || path[0] != '/' ||
dest == NULL || dest[0] != '/' || strstr(archive, "::") != NULL)
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_BAK_NOTHING, "Nothing to restore."));
(void) mcde_sys_backup_get(&b);
if (!b.configured || borg == NULL)
return mcde_sys_fail(MCDE_SYS_EINVAL, mcde_sys_msg(MSG_BAK_NO_DISK, "No backup disk is set up."));
if (Ready(&b) != MCDE_SYS_OK)
return MCDE_SYS_EFAIL;
snprintf(what, sizeof what, "%s::%s", b.repo, archive);
/* borg extract writes below the current folder, the path without its
* leading slash */
snprintf(where, sizeof where, "%s", dest);
(void) mkdir(where, 0700);
if (getcwd(cwd, sizeof cwd) == NULL || chdir(where) != 0)
return mcde_sys_fail(MCDE_SYS_EFAIL, mcde_sys_msg(MSG_BAK_CD, "Cannot go to %s: %s."),
where, strerror(errno));
{
char *argv[] = { "/usr/bin/env", PASSCMD, (char *) borg,
"extract", what, (char *) path + 1, NULL };
r = mcde_sys_run(argv);
}
(void) chdir(cwd);
return r;
}