dtchat: add the atomic state store (T1.3)

store.c keeps accounts.json, secrets.json and identity.json in a 0700 directory with 0600 files, writes through a temporary file with fsync/rename/dir-fsync, repairs a wrong file mode on load, moves invalid JSON to NAME.bad and rejects path names. test_store covers accounts/secrets/identity, overwrite, corrupt/missing files, stale tmp, read-only directory, default HOME path and permissions. make mcde-host exit=0; test_json, test_frame, test_loop and test_store all ok; ASan/UBSan clean.
This commit is contained in:
lotherk committed 2026-11-16 17:09:27 +00:00
1 parent 4e97d5930d
commit 82ab2cb4b5
4 files changed
+761 -3

No files matched your search

+6 -3
View File
@@ -10,13 +10,13 @@ libDtChatIpc_la_SOURCES = json.c
libDtChatIpc_la_LDFLAGS = -version-info 1:0:0
libDtChat_la_CPPFLAGS = -I$(top_srcdir)/include
libDtChat_la_SOURCES = core.c loop.c dc_internal.h
libDtChat_la_SOURCES = core.c loop.c store.c dc_internal.h
libDtChat_la_LIBADD = libDtChatIpc.la
libDtChat_la_LDFLAGS = -version-info 1:0:0
# Built by make mcde-host as well, so tools/mcde-tests.sh finds them in
# build/mcde-host; make check still builds and runs them.
noinst_PROGRAMS = test_json test_frame test_loop
noinst_PROGRAMS = test_json test_frame test_loop test_store
test_json_SOURCES = test_json.c
test_json_CPPFLAGS = -I$(top_srcdir)/include
test_json_LDADD = libDtChatIpc.la
@@ -26,4 +26,7 @@ test_frame_LDADD = libDtChatIpc.la
test_loop_SOURCES = test_loop.c
test_loop_CPPFLAGS = -I$(top_srcdir)/include -I$(srcdir)
test_loop_LDADD = libDtChat.la
TESTS = test_json test_frame test_loop
test_store_SOURCES = test_store.c
test_store_CPPFLAGS = -I$(top_srcdir)/include -I$(srcdir)
test_store_LDADD = libDtChat.la libDtChatIpc.la
TESTS = test_json test_frame test_loop test_store
+31
View File
@@ -60,4 +60,35 @@ int dc_loop_wakeup_fd(const DcLoop *loop);
*/
int dc_loop_run(DcLoop *loop, int timeout_ms);
/*
* The store: ~/.dt/dtchat with accounts.json, secrets.json, identity.json.
* The directory is 0700, every file 0600. Writes are atomic (write a
* temporary file, fsync, rename, fsync the directory). A file that is not
* valid JSON is renamed to NAME.bad and reported as missing/corrupt; it is
* never silently parsed or overwritten.
*/
typedef struct DcStore DcStore;
DcStore *dc_store_open(const char *dir); /* NULL: $HOME/.dt/dtchat */
void dc_store_close(DcStore *store);
const char *dc_store_dir(const DcStore *store);
/*
* Load/save one named file. NAME is a base name (no '/', no ".."). On a
* missing file dc_store_load() returns NULL and sets *MISSING to 1; on a
* corrupt file it sets *MISSING to 0, writes a message to ERR and moves the
* file to NAME.bad. ERR may be NULL.
*/
DcJson *dc_store_load(DcStore *store, const char *name, int *missing,
char *err, size_t errlen);
int dc_store_save(DcStore *store, const char *name, const DcJson *json);
/* Typed wrappers with their empty defaults. */
DcJson *dc_store_load_accounts(DcStore *store); /* {"accounts":[]} */
int dc_store_save_accounts(DcStore *store, const DcJson *json);
DcJson *dc_store_load_secrets(DcStore *store); /* {} */
int dc_store_save_secrets(DcStore *store, const DcJson *json);
DcJson *dc_store_load_identity(DcStore *store); /* no default: NULL */
int dc_store_save_identity(DcStore *store, const DcJson *json);
#endif /* _DtChat_dc_internal_h */
+407
View File
@@ -0,0 +1,407 @@
/*
* store.c -- dtchat's on-disk state
*
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* ~/.dt/dtchat is 0700, every file 0600. Writes go to a temporary file,
* are fsynced, renamed over the target and the directory is fsynced. A
* file that is not valid JSON is moved aside as NAME.bad; it is never
* silently parsed and never overwritten by a default.
*/
#include "dc_internal.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#ifndef PATH_MAX
#define PATH_MAX 4096
#endif
struct DcStore {
char *dir;
};
static const char *
errtext(int err)
{
return strerror(err);
}
static int
valid_name(const char *name)
{
const unsigned char *p;
size_t len;
if (name == NULL || *name == '\0' || *name == '.' ||
(len = strlen(name)) > 200)
return 0;
for (p = (const unsigned char *)name; *p != '\0'; p++) {
if ((*p >= 'a' && *p <= 'z') || (*p >= 'A' && *p <= 'Z') ||
(*p >= '0' && *p <= '9') || *p == '.' || *p == '_' ||
*p == '-')
continue;
return 0;
}
return strstr(name, "..") == NULL;
}
static int
join_path(char *out, size_t cap, const char *dir, const char *name)
{
int n;
if (dir == NULL || name == NULL)
return -1;
n = snprintf(out, cap, "%s/%s", dir, name);
return (n > 0 && (size_t)n < cap) ? 0 : -1;
}
static int
make_dir_p(const char *path)
{
char tmp[PATH_MAX];
struct stat st;
char *p;
size_t len;
if (path == NULL || *path == '\0' || strcmp(path, "/") == 0)
return -1;
len = strlen(path);
if (len >= sizeof(tmp))
return -1;
memcpy(tmp, path, len + 1);
for (p = tmp + 1; *p != '\0'; p++) {
if (*p != '/')
continue;
*p = '\0';
if (mkdir(tmp, 0700) != 0 && errno != EEXIST)
return -1;
*p = '/';
}
if (mkdir(tmp, 0700) != 0 && errno != EEXIST)
return -1;
if (stat(tmp, &st) != 0 || !S_ISDIR(st.st_mode))
return -1;
if (chmod(tmp, 0700) != 0)
return -1;
return 0;
}
DcStore *
dc_store_open(const char *dir)
{
char home_path[PATH_MAX];
const char *home;
DcStore *store;
if (dir == NULL) {
home = getenv("HOME");
if (home == NULL || *home == '\0')
return NULL;
if (snprintf(home_path, sizeof(home_path), "%s/.dt/dtchat",
home) >= (int)sizeof(home_path))
return NULL;
dir = home_path;
}
if (make_dir_p(dir) != 0)
return NULL;
store = calloc(1, sizeof(*store));
if (store == NULL)
return NULL;
store->dir = strdup(dir);
if (store->dir == NULL) {
free(store);
return NULL;
}
return store;
}
void
dc_store_close(DcStore *store)
{
if (store == NULL)
return;
free(store->dir);
free(store);
}
const char *
dc_store_dir(const DcStore *store)
{
return store ? store->dir : NULL;
}
static char *
read_file(const char *path, size_t *len, int *missing, char *err,
size_t errlen)
{
struct stat st;
char *buf;
size_t used = 0;
int fd;
*missing = 0;
fd = open(path, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
if (errno == ENOENT) {
*missing = 1;
return NULL;
}
if (err != NULL && errlen > 0)
snprintf(err, errlen, "open %s: %s", path,
errtext(errno));
return NULL;
}
if (fstat(fd, &st) != 0) {
if (err != NULL && errlen > 0)
snprintf(err, errlen, "stat %s: %s", path,
errtext(errno));
close(fd);
return NULL;
}
if (st.st_size < 0 || (unsigned long long)st.st_size >
DC_IPC_MAX_LINE) {
if (err != NULL && errlen > 0)
snprintf(err, errlen, "%s: file too large", path);
close(fd);
return NULL;
}
buf = malloc((size_t)st.st_size + 1);
if (buf == NULL) {
if (err != NULL && errlen > 0)
snprintf(err, errlen, "out of memory");
close(fd);
return NULL;
}
while (used < (size_t)st.st_size) {
ssize_t n = read(fd, buf + used, (size_t)st.st_size - used);
if (n < 0) {
if (errno == EINTR)
continue;
if (err != NULL && errlen > 0)
snprintf(err, errlen, "read %s: %s", path,
errtext(errno));
free(buf);
close(fd);
return NULL;
}
if (n == 0)
break;
used += (size_t)n;
}
close(fd);
buf[used] = '\0';
*len = used;
return buf;
}
static void
move_bad(DcStore *store, const char *name)
{
char path[PATH_MAX];
char bad[PATH_MAX];
if (join_path(path, sizeof(path), store->dir, name) != 0)
return;
if (snprintf(bad, sizeof(bad), "%s/%s.bad", store->dir, name) >=
(int)sizeof(bad))
return;
unlink(bad);
(void)rename(path, bad);
}
DcJson *
dc_store_load(DcStore *store, const char *name, int *missing, char *err,
size_t errlen)
{
char path[PATH_MAX];
char *text;
size_t len = 0;
int miss = 0;
DcJson *json;
if (missing != NULL)
*missing = 0;
if (err != NULL && errlen > 0)
err[0] = '\0';
if (store == NULL || !valid_name(name)) {
if (err != NULL && errlen > 0)
snprintf(err, errlen, "invalid store name");
return NULL;
}
if (join_path(path, sizeof(path), store->dir, name) != 0) {
if (err != NULL && errlen > 0)
snprintf(err, errlen, "store path too long");
return NULL;
}
text = read_file(path, &len, &miss, err, errlen);
if (text == NULL) {
if (miss && missing != NULL)
*missing = 1;
return NULL;
}
json = dc_json_parse(text, len, err, errlen);
free(text);
if (json == NULL) {
move_bad(store, name);
if (err != NULL && errlen > 0 && err[0] == '\0')
snprintf(err, errlen, "invalid JSON in %s", name);
return NULL;
}
(void)chmod(path, 0600);
return json;
}
static void
sync_dir(const char *dir)
{
int fd = open(dir, O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if (fd < 0)
return;
(void)fsync(fd);
close(fd);
}
int
dc_store_save(DcStore *store, const char *name, const DcJson *json)
{
char path[PATH_MAX];
char tmp[PATH_MAX];
char *text;
size_t len = 0;
size_t off = 0;
static unsigned counter;
int fd;
if (store == NULL || !valid_name(name) || json == NULL)
return -1;
text = dc_json_write(json, &len);
if (text == NULL || len > DC_IPC_MAX_LINE) {
free(text);
return -1;
}
if (join_path(path, sizeof(path), store->dir, name) != 0) {
free(text);
return -1;
}
if (snprintf(tmp, sizeof(tmp), "%s/.%s.tmp.%ld.%u", store->dir,
name, (long)getpid(), counter++) >= (int)sizeof(tmp)) {
free(text);
return -1;
}
fd = open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
if (fd < 0 && errno == EEXIST) {
unlink(tmp);
fd = open(tmp, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, 0600);
}
if (fd < 0) {
free(text);
return -1;
}
(void)fchmod(fd, 0600);
while (off < len) {
ssize_t n = write(fd, text + off, len - off);
if (n < 0) {
if (errno == EINTR)
continue;
close(fd);
unlink(tmp);
free(text);
return -1;
}
if (n == 0)
break;
off += (size_t)n;
}
{
int failed = 0;
if (off != len)
failed = 1;
if (!failed && fsync(fd) != 0)
failed = 1;
if (close(fd) != 0)
failed = 1;
fd = -1;
if (failed) {
unlink(tmp);
free(text);
return -1;
}
}
if (rename(tmp, path) != 0) {
unlink(tmp);
free(text);
return -1;
}
sync_dir(store->dir);
free(text);
return 0;
}
static DcJson *
empty_object(void)
{
return dc_json_new_object();
}
DcJson *
dc_store_load_accounts(DcStore *store)
{
int missing = 0;
DcJson *json = dc_store_load(store, "accounts.json", &missing, NULL, 0);
DcJson *empty;
if (json != NULL)
return json;
empty = empty_object();
if (empty != NULL)
(void)dc_json_object_set(empty, "accounts",
dc_json_new_array());
return empty;
}
int
dc_store_save_accounts(DcStore *store, const DcJson *json)
{
return dc_store_save(store, "accounts.json", json);
}
DcJson *
dc_store_load_secrets(DcStore *store)
{
DcJson *json = dc_store_load(store, "secrets.json", NULL, NULL, 0);
if (json != NULL)
return json;
return empty_object();
}
int
dc_store_save_secrets(DcStore *store, const DcJson *json)
{
return dc_store_save(store, "secrets.json", json);
}
DcJson *
dc_store_load_identity(DcStore *store)
{
return dc_store_load(store, "identity.json", NULL, NULL, 0);
}
int
dc_store_save_identity(DcStore *store, const DcJson *json)
{
return dc_store_save(store, "identity.json", json);
}
+317
View File
@@ -0,0 +1,317 @@
/*
* test_store.c -- unit tests for dtchat's atomic store
*
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*/
#include "dc_internal.h"
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
static int fails;
#define CHECK(cond) do { \
if (!(cond)) { \
fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, \
#cond); \
fails++; \
} \
} while (0)
static void
path_join(char *out, size_t cap, const char *dir, const char *name)
{
if (snprintf(out, cap, "%s/%s", dir, name) >= (int)cap) {
fprintf(stderr, "path too long: %s/%s\n", dir, name);
exit(1);
}
}
static void
check_mode(const char *path, mode_t want)
{
struct stat st;
CHECK(stat(path, &st) == 0);
if (stat(path, &st) == 0)
CHECK((st.st_mode & 0777) == want);
}
static void
write_file(const char *path, const char *text)
{
int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC, 0600);
size_t len = strlen(text);
CHECK(fd >= 0);
if (fd < 0)
return;
CHECK(write(fd, text, len) == (ssize_t)len);
close(fd);
}
static int
count_tmp(const char *dir)
{
DIR *d = opendir(dir);
struct dirent *e;
int n = 0;
if (d == NULL)
return -1;
while ((e = readdir(d)) != NULL) {
if (strstr(e->d_name, ".tmp") != NULL)
n++;
}
closedir(d);
return n;
}
static DcJson *
accounts_json(const char *id)
{
DcJson *root = dc_json_new_object();
DcJson *array = dc_json_new_array();
DcJson *account = dc_json_new_object();
CHECK(root != NULL && array != NULL && account != NULL);
if (root == NULL || array == NULL || account == NULL) {
dc_json_free(root);
dc_json_free(array);
dc_json_free(account);
return NULL;
}
CHECK(dc_json_object_set(account, "id", dc_json_new_string(id)) == 0);
CHECK(dc_json_array_append(array, account) == 0);
CHECK(dc_json_object_set(root, "accounts", array) == 0);
return root;
}
static const char *
accounts_id(const DcJson *json)
{
const DcJson *accounts = dc_json_get(json, "accounts");
const DcJson *account = dc_json_array_get(accounts, 0);
return dc_json_string(dc_json_get(account, "id"));
}
static void
test_store(DcStore *store, const char *dir)
{
char path[512];
char err[256];
DcJson *json;
int missing = -1;
CHECK(dc_store_dir(store) != NULL);
check_mode(dir, 0700);
json = accounts_json("libera");
CHECK(json != NULL);
CHECK(dc_store_save_accounts(store, json) == 0);
dc_json_free(json);
path_join(path, sizeof(path), dir, "accounts.json");
check_mode(path, 0600);
CHECK(count_tmp(dir) == 0);
json = dc_store_load(store, "accounts.json", &missing, err, sizeof(err));
CHECK(json != NULL);
CHECK(missing == 0);
if (json != NULL) {
CHECK(strcmp(accounts_id(json), "libera") == 0);
dc_json_free(json);
}
/* overwrite */
json = accounts_json("oftc");
CHECK(json != NULL);
CHECK(dc_store_save_accounts(store, json) == 0);
dc_json_free(json);
json = dc_store_load_accounts(store);
CHECK(json != NULL);
if (json != NULL) {
CHECK(strcmp(accounts_id(json), "oftc") == 0);
dc_json_free(json);
}
/* secrets */
json = dc_json_new_object();
{
DcJson *secret = dc_json_new_object();
CHECK(dc_json_object_set(secret, "password",
dc_json_new_string("s3cret")) == 0);
CHECK(dc_json_object_set(json, "libera", secret) == 0);
}
CHECK(dc_store_save_secrets(store, json) == 0);
dc_json_free(json);
path_join(path, sizeof(path), dir, "secrets.json");
check_mode(path, 0600);
json = dc_store_load_secrets(store);
CHECK(json != NULL);
if (json != NULL) {
CHECK(strcmp(dc_json_string(dc_json_get(
dc_json_get(json, "libera"), "password")), "s3cret") == 0);
dc_json_free(json);
}
/* identity, and no default before it exists */
CHECK(dc_store_load_identity(store) == NULL);
json = dc_json_new_object();
CHECK(dc_json_object_set(json, "id",
dc_json_new_string("0123456789abcdef")) == 0);
CHECK(dc_json_object_set(json, "name",
dc_json_new_string("Test")) == 0);
CHECK(dc_store_save_identity(store, json) == 0);
dc_json_free(json);
path_join(path, sizeof(path), dir, "identity.json");
check_mode(path, 0600);
json = dc_store_load_identity(store);
CHECK(json != NULL);
if (json != NULL) {
CHECK(strcmp(dc_json_string(dc_json_get(json, "name")),
"Test") == 0);
dc_json_free(json);
}
/* a wrong mode is repaired on load */
path_join(path, sizeof(path), dir, "accounts.json");
CHECK(chmod(path, 0644) == 0);
json = dc_store_load_accounts(store);
CHECK(json != NULL);
dc_json_free(json);
check_mode(path, 0600);
/* a corrupt file is moved to .bad, not parsed */
write_file(path, "{not json");
json = dc_store_load(store, "accounts.json", &missing, err, sizeof(err));
CHECK(json == NULL);
CHECK(missing == 0);
CHECK(err[0] != '\0');
{
char bad[512];
path_join(bad, sizeof(bad), dir, "accounts.json.bad");
CHECK(access(bad, F_OK) == 0);
}
json = dc_store_load_accounts(store);
CHECK(json != NULL);
if (json != NULL) {
CHECK(dc_json_array_size(dc_json_get(json, "accounts")) == 0);
dc_json_free(json);
}
/* missing file */
json = dc_store_load(store, "nope.json", &missing, err, sizeof(err));
CHECK(json == NULL);
CHECK(missing == 1);
/* invalid names */
CHECK(dc_store_load(store, "../x", NULL, NULL, 0) == NULL);
CHECK(dc_store_load(store, "a/b", NULL, NULL, 0) == NULL);
CHECK(dc_store_load(store, "", NULL, NULL, 0) == NULL);
json = accounts_json("x");
CHECK(dc_store_save(store, "../x", json) == -1);
CHECK(dc_store_save(store, "a/b", json) == -1);
dc_json_free(json);
/* a stale temporary file is ignored */
path_join(path, sizeof(path), dir, "accounts.json.tmp");
write_file(path, "stale");
json = dc_store_load_accounts(store);
CHECK(json != NULL);
dc_json_free(json);
CHECK(count_tmp(dir) >= 1);
unlink(path);
CHECK(count_tmp(dir) == 0);
/* a read-only directory refuses the write and leaves nothing */
CHECK(chmod(dir, 0500) == 0);
json = accounts_json("y");
CHECK(dc_store_save_accounts(store, json) == -1);
dc_json_free(json);
CHECK(chmod(dir, 0700) == 0);
CHECK(count_tmp(dir) == 0);
/* the save path is writable again */
json = accounts_json("z");
CHECK(dc_store_save_accounts(store, json) == 0);
dc_json_free(json);
json = dc_store_load_accounts(store);
CHECK(json != NULL);
if (json != NULL) {
CHECK(strcmp(accounts_id(json), "z") == 0);
dc_json_free(json);
}
}
static void
test_default_dir(const char *tmpdir)
{
char want[512];
DcStore *store;
CHECK(setenv("HOME", tmpdir, 1) == 0);
store = dc_store_open(NULL);
CHECK(store != NULL);
if (store != NULL) {
snprintf(want, sizeof(want), "%s/.dt/dtchat", tmpdir);
CHECK(strcmp(dc_store_dir(store), want) == 0);
dc_store_close(store);
}
}
int
main(void)
{
char tmpdir[] = "/tmp/opencode/dtchat-store-XXXXXX";
char dir[512];
char path[512];
DcStore *store;
if (mkdtemp(tmpdir) == NULL) {
perror("mkdtemp");
return 1;
}
snprintf(dir, sizeof(dir), "%s/state", tmpdir);
store = dc_store_open(dir);
if (store == NULL) {
perror("dc_store_open");
return 1;
}
test_store(store, dir);
dc_store_close(store);
test_default_dir(tmpdir);
/* clean up */
path_join(path, sizeof(path), dir, "accounts.json");
unlink(path);
path_join(path, sizeof(path), dir, "accounts.json.bad");
unlink(path);
path_join(path, sizeof(path), dir, "secrets.json");
unlink(path);
path_join(path, sizeof(path), dir, "identity.json");
unlink(path);
rmdir(dir);
snprintf(path, sizeof(path), "%s/.dt/dtchat", tmpdir);
rmdir(path);
snprintf(path, sizeof(path), "%s/.dt", tmpdir);
rmdir(path);
rmdir(tmpdir);
if (fails != 0) {
fprintf(stderr, "%d test(s) failed\n", fails);
return 1;
}
printf("test_store: all ok\n");
return 0;
}