Files
mcde/lib/libDtChat/instance.c
T
lotherk 581735f013 dtchat: add the single-instance lock and control socket (T1.6)
instance.c: DIR/run 0700, dtchat.lock 0600 with flock(LOCK_EX|LOCK_NB), primary Unix listener at dtchat.sock 0600, one open request per client with a 2 s timeout, non-primary instance plus dc_instance_notify with connect retries, and socket/lock cleanup on close. test_instance covers primary/secondary, modes, open callback, malformed client, notify after close and re-acquisition. make mcde-host exit=0; all eight dtchat tests 'all ok'; ASan/UBSan clean. SIGPIPE is ignored so a dead local client cannot kill the core.
2026-11-16 17:45:58 +00:00

449 lines
9.6 KiB
C

/*
* instance.c -- one dtchat per user: flock and the control socket
*
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* The first process holds DIR/run/dtchat.lock and listens on
* DIR/run/dtchat.sock. A second start fails the non-blocking flock, gets a
* non-primary instance, sends {"cmd":"open","conv":...} to the socket and
* exits. The primary answers one open request per connection.
*/
#include "dc_internal.h"
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/un.h>
#include <time.h>
#include <unistd.h>
typedef struct DcClient DcClient;
struct DcClient {
DcInstance *instance;
int fd;
int fd_id;
int timer_id;
DcFrameBuf frame;
};
struct DcInstance {
DcLoop *loop;
char *dir;
char *run_dir;
char *sock_path;
char *lock_path;
int lock_fd;
int listen_fd;
int listen_id;
int primary;
DcInstanceOpenFn fn;
void *arg;
DcClient **clients;
size_t nclients;
size_t capclients;
};
static int
set_nonblock_cloexec(int fd)
{
int fl = fcntl(fd, F_GETFL, 0);
if (fl < 0 || fcntl(fd, F_SETFL, fl | O_NONBLOCK) < 0)
return -1;
if (fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
return -1;
return 0;
}
static int
ensure_dir(const char *path)
{
struct stat st;
if (path == NULL || *path == '\0')
return -1;
if (mkdir(path, 0700) != 0 && errno != EEXIST)
return -1;
if (stat(path, &st) != 0 || !S_ISDIR(st.st_mode))
return -1;
return chmod(path, 0700);
}
static int
make_path(char **out, const char *dir, const char *name)
{
size_t len = strlen(dir) + strlen(name) + 2;
*out = malloc(len);
if (*out == NULL)
return -1;
snprintf(*out, len, "%s/%s", dir, name);
return 0;
}
static void
client_close(DcClient *client)
{
DcInstance *instance;
size_t i;
if (client == NULL)
return;
instance = client->instance;
if (client->fd_id != 0)
(void)dc_loop_del_fd(instance->loop, client->fd_id);
if (client->timer_id != 0)
(void)dc_loop_del_timer(instance->loop, client->timer_id);
if (client->fd >= 0)
close(client->fd);
dc_frame_free(&client->frame);
for (i = 0; i < instance->nclients; i++) {
if (instance->clients[i] == client) {
memmove(&instance->clients[i], &instance->clients[i + 1],
(instance->nclients - i - 1) *
sizeof(*instance->clients));
instance->nclients--;
break;
}
}
free(client);
}
static void
client_timeout_cb(void *arg)
{
DcClient *client = arg;
client->timer_id = 0;
client_close(client);
}
static void
client_reply(DcClient *client, int ok)
{
DcJson *json = dc_json_new_object();
size_t len = 0;
char *text;
if (json == NULL)
return;
(void)dc_json_object_set(json, "ok", dc_json_new_bool(ok));
text = dc_json_write(json, &len);
if (text != NULL) {
(void)dc_frame_send(client->fd, text, len);
free(text);
}
dc_json_free(json);
}
static void
client_cb(int fd, short revents, void *arg)
{
DcClient *client = arg;
char buf[512];
(void)revents;
for (;;) {
ssize_t n = read(fd, buf, sizeof(buf));
if (n < 0) {
if (errno == EINTR)
continue;
if (errno == EAGAIN || errno == EWOULDBLOCK)
return;
client_close(client);
return;
}
if (n == 0) {
client_close(client);
return;
}
if (dc_frame_feed(&client->frame, buf, (size_t)n) != 0) {
client_close(client);
return;
}
for (;;) {
size_t len = 0;
char *line = dc_frame_next(&client->frame, &len);
DcJson *cmd;
const char *type;
const char *conv;
if (line == NULL)
return;
cmd = dc_json_parse(line, len, NULL, 0);
free(line);
if (cmd == NULL) {
client_close(client);
return;
}
type = dc_json_string(dc_json_get(cmd, "cmd"));
conv = dc_json_string(dc_json_get(cmd, "conv"));
if (type != NULL && strcmp(type, "open") == 0) {
if (client->instance->fn != NULL)
client->instance->fn(
conv != NULL ? conv : "",
client->instance->arg);
client_reply(client, 1);
} else {
client_reply(client, 0);
}
dc_json_free(cmd);
client_close(client);
return;
}
}
}
static void
accept_cb(int fd, short revents, void *arg)
{
DcInstance *instance = arg;
int cfd;
DcClient *client;
(void)revents;
for (;;) {
cfd = accept(fd, NULL, NULL);
if (cfd < 0) {
if (errno == EINTR)
continue;
if (errno == EAGAIN || errno == EWOULDBLOCK)
return;
return;
}
if (set_nonblock_cloexec(cfd) != 0) {
close(cfd);
continue;
}
client = calloc(1, sizeof(*client));
if (client == NULL) {
close(cfd);
return;
}
client->instance = instance;
client->fd = cfd;
dc_frame_init(&client->frame);
client->fd_id = dc_loop_add_fd(instance->loop, cfd, POLLIN,
client_cb, client);
client->timer_id = dc_loop_add_timer(instance->loop, 2000,
client_timeout_cb, client);
if (client->fd_id <= 0 || client->timer_id <= 0) {
client_close(client);
return;
}
if (instance->nclients == instance->capclients) {
size_t cap = instance->capclients != 0 ?
instance->capclients * 2 : 4;
DcClient **next = realloc(instance->clients,
cap * sizeof(*next));
if (next == NULL) {
client_close(client);
return;
}
instance->clients = next;
instance->capclients = cap;
}
instance->clients[instance->nclients++] = client;
}
}
DcInstance *
dc_instance_acquire(DcLoop *loop, const char *dir, DcInstanceOpenFn open_cb,
void *arg)
{
DcInstance *instance;
struct sockaddr_un addr;
int lock_fd;
int sock;
if (loop == NULL || dir == NULL || *dir == '\0')
return NULL;
(void)signal(SIGPIPE, SIG_IGN);
instance = calloc(1, sizeof(*instance));
if (instance == NULL)
return NULL;
instance->loop = loop;
instance->fn = open_cb;
instance->arg = arg;
instance->lock_fd = -1;
instance->listen_fd = -1;
instance->dir = strdup(dir);
if (instance->dir == NULL ||
make_path(&instance->run_dir, dir, "run") != 0 ||
make_path(&instance->sock_path, instance->run_dir,
"dtchat.sock") != 0 ||
make_path(&instance->lock_path, instance->run_dir,
"dtchat.lock") != 0)
goto fail;
if (strlen(instance->sock_path) >= sizeof(addr.sun_path))
goto fail;
if (ensure_dir(instance->dir) != 0 ||
ensure_dir(instance->run_dir) != 0)
goto fail;
lock_fd = open(instance->lock_path,
O_RDWR | O_CREAT | O_CLOEXEC, 0600);
if (lock_fd < 0)
goto fail;
if (flock(lock_fd, LOCK_EX | LOCK_NB) != 0) {
if (errno == EWOULDBLOCK || errno == EAGAIN) {
close(lock_fd);
instance->primary = 0;
return instance;
}
close(lock_fd);
goto fail;
}
instance->lock_fd = lock_fd;
instance->primary = 1;
(void)unlink(instance->sock_path);
sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock < 0)
goto fail;
if (set_nonblock_cloexec(sock) != 0) {
close(sock);
goto fail;
}
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s",
instance->sock_path);
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) != 0) {
close(sock);
goto fail;
}
(void)chmod(instance->sock_path, 0600);
if (listen(sock, 8) != 0) {
close(sock);
(void)unlink(instance->sock_path);
goto fail;
}
instance->listen_fd = sock;
instance->listen_id = dc_loop_add_fd(loop, sock, POLLIN, accept_cb,
instance);
if (instance->listen_id <= 0) {
close(sock);
instance->listen_fd = -1;
(void)unlink(instance->sock_path);
goto fail;
}
return instance;
fail:
dc_instance_close(instance);
return NULL;
}
int
dc_instance_is_primary(const DcInstance *instance)
{
return instance ? instance->primary : 0;
}
const char *
dc_instance_socket(const DcInstance *instance)
{
return instance ? instance->sock_path : NULL;
}
void
dc_instance_close(DcInstance *instance)
{
if (instance == NULL)
return;
if (instance->listen_id != 0)
(void)dc_loop_del_fd(instance->loop, instance->listen_id);
if (instance->listen_fd >= 0)
close(instance->listen_fd);
while (instance->nclients > 0)
client_close(instance->clients[0]);
if (instance->lock_fd >= 0)
close(instance->lock_fd);
if (instance->primary && instance->sock_path != NULL)
(void)unlink(instance->sock_path);
free(instance->clients);
free(instance->dir);
free(instance->run_dir);
free(instance->sock_path);
free(instance->lock_path);
free(instance);
}
int
dc_instance_notify(const char *dir, const char *conv)
{
char *run_dir = NULL;
char *sock_path = NULL;
struct sockaddr_un addr;
DcJson *json;
size_t len = 0;
char *text = NULL;
int fd = -1;
int i;
if (dir == NULL)
return -1;
if (make_path(&run_dir, dir, "run") != 0 ||
make_path(&sock_path, run_dir, "dtchat.sock") != 0)
goto fail;
if (strlen(sock_path) >= sizeof(addr.sun_path))
goto fail;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", sock_path);
for (i = 0; i < 10; i++) {
struct timespec ts = { 0, 50 * 1000 * 1000 };
fd = socket(AF_UNIX, SOCK_STREAM, 0);
if (fd < 0)
goto fail;
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == 0)
break;
close(fd);
fd = -1;
if (errno != ENOENT && errno != ECONNREFUSED)
break;
(void)nanosleep(&ts, NULL);
}
if (fd < 0)
goto fail;
json = dc_json_new_object();
if (json == NULL)
goto fail;
(void)dc_json_object_set(json, "cmd", dc_json_new_string("open"));
(void)dc_json_object_set(json, "conv",
dc_json_new_string(conv != NULL ? conv : ""));
text = dc_json_write(json, &len);
dc_json_free(json);
if (text == NULL)
goto fail;
if (dc_frame_send(fd, text, len) != 0)
goto fail;
(void)shutdown(fd, SHUT_WR);
close(fd);
free(text);
free(run_dir);
free(sock_path);
return 0;
fail:
if (fd >= 0)
close(fd);
free(text);
free(run_dir);
free(sock_path);
return -1;
}