Files
lotherk 4774c2c7d8 dtchat: verify adapter files whose hash arrives at the end (T4.5)
Telegram and WhatsApp learn a document's SHA-256 only when the transfer is
finished, so their file-offer carries none and the digest comes with
file-end.  The UI used to verify only the offer hash, which meant those two
paths wrote the bytes unchecked.  accounts_run now takes the offer's hash
when there is one and the file-end's otherwise, hashes the .part file after
the last chunk and renames only on a match; a mismatch still removes the
part file and reports it in the status line and the transcript.

The fake adapter gained the matching modes: latehash offers without a hash
and sends the right one in file-end, badendhash sends a wrong one there.
tests/file_ui.sh drives all four shapes through the real UI under its own
Xvfb with DTCHAT_TEST_FILE_ACCEPT: files and latehash write the verified
hello world, badhash and badendhash are rejected and leave neither the file
nor a .part.  Measured with the built binaries: four ok, exit 0.

Harness entry DtChat/file_ui added; the full run is 53 ok/0 bad
(make mcde-host exit=0, build/logs/mcde-host-2026-11-17-endhash.log).
2026-11-17 13:08:55 +00:00

1103 lines
30 KiB
C

/*
* accounts_run.c -- one adapter process per configured account
*
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* accounts.json names the accounts:
*
* {"accounts":[{"id":"libera","protocol":"irc","label":"Libera",
* "adapter":"/usr/mdt/bin/dtchat-irc","enabled":true,
* "settings":{"host":"irc.libera.chat","port":6697}}]}
*
* secrets.json keeps the secrets apart, under the account's id:
*
* {"accounts":{"libera":{"password":"..."}}}
*
* Every enabled account gets a DcAdapter (a child process speaking the v1
* protocol); its state, conversations, messages, roster, presence, typing,
* requests and errors become model and panel entries. The DcLoop is pumped
* from an Xt timeout every 40 ms, as in the demo.
*/
#define _POSIX_C_SOURCE 200809L
#include "accounts_run.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <unistd.h>
#include "ui_file.h"
#include "ui_request.h"
#define MAX_ACCOUNTS 16
typedef struct AccountRun AccountRun;
struct AccountRun {
DtAccounts *accounts;
char id[64];
char protocol[32];
char label[128];
char path[512];
DcAdapter *adapter;
int online;
};
/* one incoming file: the offer dialog, the .part file and its bytes */
typedef struct Incoming Incoming;
struct Incoming {
DtAccounts *accounts;
AccountRun *run;
Incoming *next;
char id[64];
char conv[256];
char final[600];
char part[620];
char sha256[65];
FILE *fp;
long long size;
long long got;
int answered;
};
struct DtAccounts {
Widget shell;
DtChatUi *ui;
DcModel *model;
DcStore *store;
DcLoop *loop;
XtIntervalId timer;
AccountRun run[MAX_ACCOUNTS];
size_t count;
int client_seq;
int file_seq;
int test_sent;
Incoming *incoming;
DcJson *accounts_json;
DcJson *secrets_json;
char *adapter_dir;
};
static void poll_cb(XtPointer client, XtIntervalId *id);
static int
debug_on(void)
{
return getenv("DTCHAT_ACCOUNTS_DEBUG") != NULL;
}
static void
schedule_poll(DtAccounts *accounts)
{
accounts->timer = XtAppAddTimeOut(
XtWidgetToApplicationContext(accounts->shell), 40, poll_cb,
accounts);
}
static DcConvKind
conv_kind(const char *kind)
{
if (kind == NULL)
return DC_CONV_DIRECT;
if (strcmp(kind, "channel") == 0)
return DC_CONV_CHANNEL;
if (strcmp(kind, "group") == 0 || strcmp(kind, "muc") == 0)
return DC_CONV_GROUP;
if (strcmp(kind, "nearby") == 0)
return DC_CONV_NEARBY;
return DC_CONV_DIRECT;
}
static AccountRun *
run_find(DtAccounts *accounts, const char *id)
{
size_t i;
if (id == NULL)
return NULL;
for (i = 0; i < accounts->count; i++)
if (strcmp(accounts->run[i].id, id) == 0)
return &accounts->run[i];
return NULL;
}
/* the account the UI is showing; falls back to the one that owns CONV */
static AccountRun *
run_current(DtAccounts *accounts, const char *conv)
{
const char *id = dtchat_ui_current_account(accounts->ui);
AccountRun *run = run_find(accounts, id);
size_t i;
if (run != NULL)
return run;
if (conv != NULL)
for (i = 0; i < accounts->count; i++)
if (dc_model_find_conv(accounts->model,
accounts->run[i].id, conv) != NULL)
return &accounts->run[i];
return accounts->count > 0 ? &accounts->run[0] : NULL;
}
static void
set_account_status(DtAccounts *accounts, AccountRun *run, const char *state)
{
char line[256];
snprintf(line, sizeof(line), "%s: %s", run->label[0] != '\0' ?
run->label : run->id, state != NULL ? state : "");
dtchat_ui_set_status(accounts->ui, line);
if (debug_on())
fprintf(stderr, "accounts %s: %s\n", run->id,
state != NULL ? state : "");
}
/* ------------------------------- events --------------------------------- */
typedef struct {
AccountRun *run;
int id;
} RequestCtx;
static void
request_answer(const char *value, void *arg)
{
RequestCtx *ctx = arg;
if (ctx->run->adapter != NULL)
(void)dc_adapter_answer(ctx->run->adapter, ctx->id, value);
free(ctx);
}
/* a file name that cannot leave DIR: no slashes, no leading dot */
static void
safe_name(const char *name, char *out, size_t outlen)
{
size_t i = 0;
const char *base = name != NULL ? name : "file";
if (strrchr(base, '/') != NULL)
base = strrchr(base, '/') + 1;
while (*base != '\0' && i + 1 < outlen) {
unsigned char c = (unsigned char)*base++;
if (c == '/' || c == '\\' || c < 0x20)
c = '_';
out[i++] = (char)c;
}
out[i] = '\0';
if (i == 0 || out[0] == '.') {
char tmp[300];
snprintf(tmp, sizeof(tmp), "file%s", out);
snprintf(out, outlen, "%s", tmp);
}
}
static void
unique_path(const char *dir, const char *name, char *out, size_t outlen)
{
int n;
for (n = 0; n < 1000; n++) {
if (n == 0)
snprintf(out, outlen, "%s/%s", dir, name);
else
snprintf(out, outlen, "%s/%s.%d", dir, name, n);
if (access(out, F_OK) != 0)
return;
}
snprintf(out, outlen, "%s/%s.%ld", dir, name, (long)time(NULL));
}
static int
b64_decode(const char *in, unsigned char *out, size_t outlen, size_t *len)
{
int val = 0;
int bits = -8;
size_t o = 0;
if (in == NULL)
return -1;
for (; *in != '\0'; in++) {
int c = (unsigned char)*in;
int v;
if (c == '=')
break;
if (c >= 'A' && c <= 'Z')
v = c - 'A';
else if (c >= 'a' && c <= 'z')
v = c - 'a' + 26;
else if (c >= '0' && c <= '9')
v = c - '0' + 52;
else if (c == '+')
v = 62;
else if (c == '/')
v = 63;
else
continue;
val = (val << 6) | v;
bits += 6;
if (bits >= 0) {
if (o >= outlen)
return -1;
out[o++] = (unsigned char)((val >> bits) & 0xff);
bits -= 8;
}
}
*len = o;
return 0;
}
static Incoming *
incoming_find(DtAccounts *accounts, AccountRun *run, const char *id)
{
Incoming *in;
for (in = accounts->incoming; in != NULL; in = in->next)
if (in->run == run && strcmp(in->id, id) == 0)
return in;
return NULL;
}
static void
incoming_free(DtAccounts *accounts, Incoming *in, int remove_part)
{
Incoming **slot;
for (slot = &accounts->incoming; *slot != NULL; slot = &(*slot)->next)
if (*slot == in) {
*slot = in->next;
break;
}
if (in->fp != NULL)
fclose(in->fp);
if (remove_part && in->part[0] != '\0')
(void)unlink(in->part);
free(in);
}
static void
incoming_answer(int accepted, void *arg)
{
Incoming *in = arg;
DtAccounts *accounts = in->accounts;
in->answered = 1;
if (!accepted) {
(void)dc_adapter_file_answer(in->run->adapter, in->id, 0,
"rejected");
set_account_status(accounts, in->run, "file rejected");
incoming_free(accounts, in, 1);
return;
}
if (dc_adapter_file_answer(in->run->adapter, in->id, 1, NULL) != 0) {
set_account_status(accounts, in->run, "cannot answer the offer");
incoming_free(accounts, in, 1);
return;
}
set_account_status(accounts, in->run, "receiving a file");
}
static void
file_offer(DtAccounts *accounts, AccountRun *run, const DcJson *event)
{
const char *id = dc_json_string(dc_json_get(event, "id"));
const char *conv = dc_json_string(dc_json_get(event, "conv"));
const char *name = dc_json_string(dc_json_get(event, "name"));
const char *sha256 = dc_json_string(dc_json_get(event, "sha256"));
long long size = dc_json_get(event, "size") != NULL ?
dc_json_int(dc_json_get(event, "size")) : 0;
Incoming *in;
const char *dir = dc_store_dir(accounts->store);
char safe[256];
if (id == NULL || conv == NULL)
return;
if (incoming_find(accounts, run, id) != NULL)
return;
in = calloc(1, sizeof(*in));
if (in == NULL)
return;
safe_name(name, safe, sizeof(safe));
unique_path(dir, safe, in->final, sizeof(in->final));
snprintf(in->part, sizeof(in->part), "%s.part", in->final);
in->accounts = accounts;
in->run = run;
snprintf(in->id, sizeof(in->id), "%s", id);
snprintf(in->conv, sizeof(in->conv), "%s", conv);
snprintf(in->sha256, sizeof(in->sha256), "%s",
sha256 != NULL ? sha256 : "");
in->size = size;
in->fp = fopen(in->part, "wb");
if (in->fp == NULL) {
(void)dc_adapter_file_answer(run->adapter, id, 0,
"cannot write the file");
free(in);
set_account_status(accounts, run, "cannot write the file");
return;
}
in->next = accounts->incoming;
accounts->incoming = in;
(void)dc_model_add_conv(accounts->model, run->id, conv,
DC_CONV_DIRECT, conv);
dtchat_ui_refresh(accounts->ui);
if (debug_on())
fprintf(stderr, "accounts %s: file offer %s (%s, %lld)\n",
run->id, id, safe, size);
if (getenv("DTCHAT_TEST_FILE_ACCEPT") != NULL) {
incoming_answer(1, in);
return;
}
if (dtchat_file_offer_dialog(accounts->shell, conv, safe, size,
incoming_answer, in) == NULL) {
(void)dc_adapter_file_answer(run->adapter, id, 0,
"no dialog");
incoming_free(accounts, in, 1);
}
}
static void
file_data(DtAccounts *accounts, AccountRun *run, const DcJson *event)
{
const char *id = dc_json_string(dc_json_get(event, "id"));
const char *data = dc_json_string(dc_json_get(event, "data"));
unsigned char buf[8192];
size_t len = 0;
Incoming *in = id != NULL ? incoming_find(accounts, run, id) : NULL;
if (in == NULL || in->fp == NULL || data == NULL)
return;
if (b64_decode(data, buf, sizeof(buf), &len) != 0 ||
fwrite(buf, 1, len, in->fp) != len) {
set_account_status(accounts, run, "cannot write the file");
(void)dc_adapter_file_answer(run->adapter, in->id, 0,
"write failed");
incoming_free(accounts, in, 1);
return;
}
in->got += (long long)len;
}
static void
file_end(DtAccounts *accounts, AccountRun *run, const DcJson *event)
{
const char *id = dc_json_string(dc_json_get(event, "id"));
const char *end_sha = dc_json_string(dc_json_get(event, "sha256"));
Incoming *in = id != NULL ? incoming_find(accounts, run, id) : NULL;
const char *expect;
char line[700];
DcConv *convp;
if (in == NULL)
return;
if (in->fp != NULL) {
fclose(in->fp);
in->fp = NULL;
}
/* Telegram and WhatsApp learn the hash only when the transfer is done,
* so the file-end may carry the first one we see */
expect = in->sha256[0] != '\0' ? in->sha256 : end_sha;
if (expect != NULL && *expect != '\0') {
char got[65];
if (dc_file_sha256(in->part, got, NULL) != 0 ||
strcasecmp(got, expect) != 0) {
(void)unlink(in->part);
set_account_status(accounts, run,
"file rejected: checksum mismatch");
convp = dc_model_add_conv(accounts->model, run->id,
in->conv, DC_CONV_DIRECT, in->conv);
if (convp != NULL) {
(void)dc_conv_add_message(convp, "system",
"file rejected: checksum mismatch",
(long long)time(NULL),
DTCHAT_MSG_SYSTEM);
dtchat_ui_message_added(accounts->ui,
run->id, in->conv);
}
incoming_free(accounts, in, 0);
return;
}
}
if (rename(in->part, in->final) != 0) {
snprintf(line, sizeof(line), "cannot rename %s", in->part);
set_account_status(accounts, run, line);
} else {
snprintf(line, sizeof(line), "file received: %s (%lld bytes)",
in->final, in->got);
set_account_status(accounts, run, line);
}
convp = dc_model_add_conv(accounts->model, run->id, in->conv,
DC_CONV_DIRECT, in->conv);
if (convp != NULL) {
char text[700];
snprintf(text, sizeof(text), "file received: %s (%lld bytes)",
strrchr(in->final, '/') != NULL ?
strrchr(in->final, '/') + 1 : in->final, in->got);
(void)dc_conv_add_message(convp, "system", text,
(long long)time(NULL), DTCHAT_MSG_SYSTEM);
dtchat_ui_message_added(accounts->ui, run->id, in->conv);
}
if (debug_on())
fprintf(stderr, "accounts %s: file end %s %lld bytes\n",
run->id, in->id, in->got);
incoming_free(accounts, in, 0);
}
static void
file_failed(DtAccounts *accounts, AccountRun *run, const DcJson *event)
{
const char *id = dc_json_string(dc_json_get(event, "id"));
Incoming *in = id != NULL ? incoming_find(accounts, run, id) : NULL;
char line[300];
snprintf(line, sizeof(line), "%s: %s", id != NULL ? id : "file",
dc_json_string(dc_json_get(event, "text")) != NULL ?
dc_json_string(dc_json_get(event, "text")) : "transfer failed");
set_account_status(accounts, run, line);
if (in != NULL)
incoming_free(accounts, in, 1);
}
static void
handle_message(DtAccounts *accounts, AccountRun *run, const DcJson *event)
{
const char *conv = dc_json_string(dc_json_get(event, "conv"));
const char *from = dc_json_string(dc_json_get(event, "from"));
const char *kind = dc_json_string(dc_json_get(event, "kind"));
const char *text = dc_json_string(dc_json_get(event, "text"));
int self = dc_json_bool(dc_json_get(event, "self"));
long long ts = dc_json_int(dc_json_get(event, "ts"));
DcConv *convp;
int flags = 0;
if (conv == NULL || text == NULL)
return;
convp = dc_model_find_conv(accounts->model, run->id, conv);
if (convp == NULL)
convp = dc_model_add_conv(accounts->model, run->id, conv,
DC_CONV_DIRECT, conv);
if (convp == NULL)
return;
if (kind != NULL && strcmp(kind, "action") == 0)
flags |= DTCHAT_MSG_ACTION;
else if (kind != NULL && strcmp(kind, "system") == 0)
flags |= DTCHAT_MSG_SYSTEM;
else if (kind != NULL && strcmp(kind, "notice") == 0)
flags |= DTCHAT_MSG_NOTICE;
if (ts <= 0)
ts = (long long)time(NULL);
(void)dc_conv_add_message(convp, self ? "me" :
(from != NULL ? from : "?"), text, ts, flags);
dtchat_ui_message_added(accounts->ui, run->id, conv);
if (debug_on())
fprintf(stderr, "accounts %s: message %s from %s\n", run->id,
conv, self ? "me" : (from != NULL ? from : "?"));
}
static void
handle_event(DcAdapter *adapter, const DcJson *event, void *arg)
{
AccountRun *run = arg;
DtAccounts *accounts = run->accounts;
const char *type = dc_json_string(dc_json_get(event, "type"));
(void)adapter;
if (type == NULL)
return;
if (strcmp(type, "state") == 0) {
const char *state = dc_json_string(dc_json_get(event, "state"));
const char *detail = dc_json_string(dc_json_get(event,
"detail"));
char line[256];
if (state == NULL)
return;
run->online = strcmp(state, "online") == 0;
snprintf(line, sizeof(line), "%s%s%s", state,
detail != NULL && *detail != '\0' ? " - " : "",
detail != NULL ? detail : "");
set_account_status(accounts, run, line);
if (run->online && !accounts->test_sent) {
const char *send = getenv("DTCHAT_TEST_ACCOUNTS_SEND");
if (send != NULL) {
char *copy = strdup(send);
char *sep;
if (copy != NULL &&
(sep = strchr(copy, '|')) != NULL) {
*sep++ = '\0';
accounts->test_sent = 1;
(void)dtchat_accounts_send(accounts,
run->id, copy, sep);
}
free(copy);
}
}
return;
}
if (strcmp(type, "conversation") == 0) {
const char *conv = dc_json_string(dc_json_get(event, "conv"));
const char *kind = dc_json_string(dc_json_get(event, "kind"));
const char *title = dc_json_string(dc_json_get(event, "title"));
if (conv == NULL)
return;
(void)dc_model_add_conv(accounts->model, run->id, conv,
conv_kind(kind), title != NULL ? title : conv);
dtchat_ui_refresh(accounts->ui);
if (debug_on())
fprintf(stderr, "accounts %s: conversation %s\n",
run->id, conv);
return;
}
if (strcmp(type, "message") == 0) {
handle_message(accounts, run, event);
return;
}
if (strcmp(type, "roster") == 0) {
const DcJson *contact = dc_json_get(event, "contact");
const char *id = dc_json_string(dc_json_get(contact, "id"));
const char *name = dc_json_string(dc_json_get(contact, "name"));
int online = dc_json_bool(dc_json_get(contact, "online"));
if (id == NULL)
return;
{
DcConv *convp = dc_model_add_conv(accounts->model,
run->id, id, DC_CONV_DIRECT,
name != NULL ? name : id);
if (convp != NULL)
dc_conv_set_presence(convp, online ?
DC_PRESENCE_ONLINE : DC_PRESENCE_OFFLINE);
}
dtchat_ui_refresh(accounts->ui);
if (debug_on())
fprintf(stderr, "accounts %s: roster %s\n", run->id,
id);
return;
}
if (strcmp(type, "presence") == 0) {
const char *buddy = dc_json_string(dc_json_get(event, "buddy"));
const char *show = dc_json_string(dc_json_get(event, "show"));
const char *status = dc_json_string(dc_json_get(event,
"status"));
DcConv *convp;
char line[300];
if (buddy == NULL || show == NULL)
return;
convp = dc_model_find_conv(accounts->model, run->id, buddy);
if (convp != NULL) {
if (strcmp(show, "online") == 0)
dc_conv_set_presence(convp,
DC_PRESENCE_ONLINE);
else
dc_conv_set_presence(convp,
DC_PRESENCE_OFFLINE);
}
snprintf(line, sizeof(line), "%s is %s%s%s", buddy, show,
status != NULL && *status != '\0' ? " - " : "",
status != NULL ? status : "");
dtchat_ui_set_status(accounts->ui, line);
if (debug_on())
fprintf(stderr, "accounts %s: presence %s %s\n",
run->id, buddy, show);
return;
}
if (strcmp(type, "file-offer") == 0) {
file_offer(accounts, run, event);
return;
}
if (strcmp(type, "file-data") == 0) {
file_data(accounts, run, event);
return;
}
if (strcmp(type, "file-end") == 0) {
file_end(accounts, run, event);
return;
}
if (strcmp(type, "file-sent") == 0) {
const char *id = dc_json_string(dc_json_get(event, "id"));
set_account_status(accounts, run, "file sent");
if (debug_on())
fprintf(stderr, "accounts %s: file sent %s\n",
run->id, id != NULL ? id : "?");
return;
}
if (strcmp(type, "file-reject") == 0 ||
strcmp(type, "file-error") == 0) {
file_failed(accounts, run, event);
return;
}
if (strcmp(type, "typing") == 0) {
const char *conv = dc_json_string(dc_json_get(event, "conv"));
int on = dc_json_bool(dc_json_get(event, "on"));
char line[256];
snprintf(line, sizeof(line), "%s is %s", conv != NULL ? conv :
"someone", on ? "typing" : "not typing");
dtchat_ui_set_status(accounts->ui, line);
return;
}
if (strcmp(type, "request") == 0) {
RequestCtx *ctx = calloc(1, sizeof(*ctx));
if (ctx == NULL)
return;
ctx->run = run;
ctx->id = (int)dc_json_int(dc_json_get(event, "id"));
if (dtchat_request_dialog_create(accounts->shell, event, 0,
request_answer, ctx) == NULL) {
(void)dc_adapter_answer(run->adapter, ctx->id, NULL);
free(ctx);
}
return;
}
if (strcmp(type, "error") == 0) {
const char *text = dc_json_string(dc_json_get(event, "text"));
dtchat_error_dialog(accounts->shell, run->label[0] != '\0' ?
run->label : run->id, text != NULL ? text :
"The adapter reported an error.");
set_account_status(accounts, run, "adapter error");
return;
}
if (strcmp(type, "bye") == 0) {
run->online = 0;
set_account_status(accounts, run, "adapter said goodbye");
}
}
/* ------------------------------- sending -------------------------------- */
static void
accounts_file_send(const char *peer_id, const char *path, void *arg)
{
DtAccounts *accounts = arg;
AccountRun *run = run_current(accounts, peer_id);
const char *name;
char id[64];
if (run == NULL || run->adapter == NULL || path == NULL)
return;
name = strrchr(path, '/') != NULL ? strrchr(path, '/') + 1 : path;
snprintf(id, sizeof(id), "f%d", ++accounts->file_seq);
if (dc_adapter_send_file(run->adapter, peer_id, id, name, path) == 0) {
set_account_status(accounts, run, "sending a file");
if (debug_on())
fprintf(stderr, "accounts %s: file send %s to %s\n",
run->id, id, peer_id);
}
}
static void
accounts_join_hook(void *arg, const char *account, const char *conv)
{
DtAccounts *accounts = arg;
AccountRun *run = run_find(accounts, account);
if (run == NULL || run->adapter == NULL || conv == NULL)
return;
if (dc_adapter_join(run->adapter, conv) != 0) {
set_account_status(accounts, run, "cannot join");
return;
}
(void)dc_model_add_conv(accounts->model, run->id, conv,
strcmp(run->protocol, "irc") == 0 ? DC_CONV_CHANNEL :
DC_CONV_GROUP, conv);
dtchat_ui_refresh(accounts->ui);
set_account_status(accounts, run, "joining");
if (debug_on())
fprintf(stderr, "accounts %s: join %s\n", run->id, conv);
}
static void
accounts_typing_hook(void *arg, const char *conv, int on)
{
DtAccounts *accounts = arg;
AccountRun *run = run_current(accounts, conv);
if (run != NULL && run->adapter != NULL) {
(void)dc_adapter_send_typing(run->adapter, conv, on);
if (debug_on())
fprintf(stderr, "accounts %s: typing %d for %s\n",
run->id, on, conv);
}
}
static int
accounts_send_hook(void *arg, const char *conv, const char *text)
{
DtAccounts *accounts = arg;
AccountRun *run = run_current(accounts, conv);
if (run == NULL || run->adapter == NULL || conv == NULL ||
text == NULL)
return -1;
return dtchat_accounts_send(accounts, run->id, conv, text);
}
int
dtchat_accounts_send(DtAccounts *accounts, const char *account,
const char *conv, const char *text)
{
AccountRun *run;
char client_id[32];
if (accounts == NULL || conv == NULL || text == NULL)
return -1;
run = run_find(accounts, account);
if (run == NULL || run->adapter == NULL)
return -1;
snprintf(client_id, sizeof(client_id), "c%d", ++accounts->client_seq);
if (dc_adapter_send_text(run->adapter, conv, text, client_id) != 0)
return -1;
if (debug_on())
fprintf(stderr, "accounts %s: sent %s\n", run->id, conv);
return 0;
}
int
dtchat_accounts_join(DtAccounts *accounts, const char *account,
const char *conv)
{
AccountRun *run;
if (accounts == NULL || conv == NULL)
return -1;
run = run_find(accounts, account);
if (run == NULL || run->adapter == NULL)
return -1;
return dc_adapter_join(run->adapter, conv);
}
int
dtchat_accounts_typing(DtAccounts *accounts, const char *account,
const char *conv, int on)
{
AccountRun *run;
if (accounts == NULL || conv == NULL)
return -1;
run = run_find(accounts, account);
if (run == NULL || run->adapter == NULL)
return -1;
return dc_adapter_send_typing(run->adapter, conv, on);
}
size_t
dtchat_accounts_count(const DtAccounts *accounts)
{
return accounts != NULL ? accounts->count : 0;
}
int
dtchat_accounts_online(const DtAccounts *accounts)
{
size_t i;
int n = 0;
if (accounts == NULL)
return 0;
for (i = 0; i < accounts->count; i++)
if (accounts->run[i].online)
n++;
return n;
}
/* -------------------------------- start --------------------------------- */
static void
poll_cb(XtPointer client, XtIntervalId *id)
{
DtAccounts *accounts = client;
(void)id;
accounts->timer = 0;
if (accounts->loop != NULL)
(void)dc_loop_run(accounts->loop, 0);
schedule_poll(accounts);
}
static const DcJson *
secrets_for(const DcJson *secrets, const char *id)
{
const DcJson *map = dc_json_get(secrets, "accounts");
const DcJson *entry;
entry = dc_json_get(map, id);
if (entry == NULL)
entry = dc_json_get(secrets, id);
return entry;
}
static void
account_path(const char *adapter_dir, const char *adapter,
const char *protocol, char *out, size_t outlen)
{
if (adapter != NULL && *adapter != '\0') {
if (adapter[0] == '/')
snprintf(out, outlen, "%s", adapter);
else
snprintf(out, outlen, "%s/%s",
adapter_dir != NULL ? adapter_dir : ".", adapter);
return;
}
snprintf(out, outlen, "%s/dtchat-%s",
adapter_dir != NULL ? adapter_dir : ".", protocol);
}
static DcJson *
clone_json(const DcJson *json)
{
char *text;
size_t len = 0;
DcJson *copy;
if (json == NULL)
return dc_json_new_object();
text = dc_json_write(json, &len);
if (text == NULL)
return NULL;
copy = dc_json_parse(text, len, NULL, 0);
free(text);
return copy;
}
static void
stop_adapters(DtAccounts *accounts)
{
size_t i;
for (i = 0; i < accounts->count; i++) {
if (accounts->run[i].adapter != NULL) {
dc_adapter_stop(accounts->run[i].adapter);
dc_adapter_free(accounts->run[i].adapter);
accounts->run[i].adapter = NULL;
}
}
accounts->count = 0;
}
/* start one adapter per enabled account in the stored JSON */
static void
accounts_spawn(DtAccounts *accounts)
{
const DcJson *list = dc_json_get(accounts->accounts_json, "accounts");
const DcJson *secrets = accounts->secrets_json;
size_t i;
accounts->count = 0;
for (i = 0; list != NULL && i < dc_json_array_size(list) &&
accounts->count < MAX_ACCOUNTS; i++) {
const DcJson *entry = dc_json_array_get(list, i);
const DcJson *settings;
DcJson *secret;
DcJson *secret_empty = NULL;
const DcJson *enabled = dc_json_get(entry, "enabled");
const char *id = dc_json_string(dc_json_get(entry, "id"));
const char *protocol = dc_json_string(dc_json_get(entry,
"protocol"));
const char *label = dc_json_string(dc_json_get(entry, "label"));
const char *adapter = dc_json_string(dc_json_get(entry,
"adapter"));
DcJson *empty;
AccountRun *run;
if (id == NULL || *id == '\0')
continue;
if (enabled != NULL && !dc_json_bool(enabled))
continue;
run = &accounts->run[accounts->count];
memset(run, 0, sizeof(*run));
run->accounts = accounts;
snprintf(run->id, sizeof(run->id), "%s", id);
snprintf(run->protocol, sizeof(run->protocol), "%s",
protocol != NULL ? protocol : "unknown");
snprintf(run->label, sizeof(run->label), "%s",
label != NULL ? label : id);
account_path(accounts->adapter_dir, adapter, run->protocol,
run->path, sizeof(run->path));
settings = dc_json_get(entry, "settings");
secret = (DcJson *)secrets_for(secrets, id);
if (secret == NULL)
secret = secret_empty = dc_json_new_object();
if (settings == NULL) {
empty = dc_json_new_object();
settings = empty;
} else {
empty = NULL;
}
run->adapter = dc_adapter_start(accounts->loop, run->path,
run->id, settings, secret, handle_event, run);
dc_json_free(empty);
dc_json_free(secret_empty);
if (run->adapter == NULL) {
if (debug_on())
fprintf(stderr,
"accounts %s: cannot start %s\n", id,
run->path);
continue;
}
(void)dc_model_add_account(accounts->model, run->id,
run->protocol, run->label);
accounts->count++;
if (debug_on())
fprintf(stderr, "accounts %s: started %s\n", run->id,
run->path);
}
}
static int
account_in_json(const DcJson *json, const char *id)
{
const DcJson *list = dc_json_get(json, "accounts");
size_t i;
for (i = 0; i < dc_json_array_size(list); i++) {
const char *want = dc_json_string(dc_json_get(
dc_json_array_get(list, i), "id"));
if (want != NULL && strcmp(want, id) == 0)
return 1;
}
return 0;
}
/* the editor's writer: files, then the adapters restart from the new set */
static int
accounts_save_cb(void *arg, const DcJson *accounts_json,
const DcJson *secrets_json)
{
DtAccounts *accounts = arg;
DcJson *new_accounts;
DcJson *new_secrets;
size_t i;
if (accounts == NULL || accounts->store == NULL)
return -1;
if (dc_store_save_accounts(accounts->store, accounts_json) != 0)
return -1;
if (dc_store_save_secrets(accounts->store, secrets_json) != 0)
return -1;
new_accounts = clone_json(accounts_json);
new_secrets = clone_json(secrets_json);
if (new_accounts == NULL || new_secrets == NULL) {
dc_json_free(new_accounts);
dc_json_free(new_secrets);
return -1;
}
while (accounts->incoming != NULL)
incoming_free(accounts, accounts->incoming, 1);
stop_adapters(accounts);
dc_json_free(accounts->accounts_json);
dc_json_free(accounts->secrets_json);
accounts->accounts_json = new_accounts;
accounts->secrets_json = new_secrets;
/* accounts that were deleted in the editor leave the model */
for (i = dc_model_account_count(accounts->model); i-- > 0;) {
DcAccount *acct = dc_model_account_at(accounts->model, i);
if (acct != NULL &&
!account_in_json(accounts->accounts_json,
dc_account_id(acct)))
(void)dc_model_remove_account(accounts->model,
dc_account_id(acct));
}
accounts_spawn(accounts);
dtchat_ui_set_accounts_data(accounts->ui, accounts->accounts_json,
accounts->secrets_json, accounts_save_cb, accounts);
dtchat_ui_refresh(accounts->ui);
if (debug_on())
fprintf(stderr, "accounts: saved and restarted (%zu)\n",
accounts->count);
return 0;
}
DtAccounts *
dtchat_accounts_start(Widget shell, DtChatUi *ui, DcModel *model,
const char *config_dir, const char *adapter_dir)
{
DtAccounts *accounts;
if (shell == NULL || ui == NULL || model == NULL)
return NULL;
accounts = calloc(1, sizeof(*accounts));
if (accounts == NULL)
return NULL;
accounts->shell = shell;
accounts->ui = ui;
accounts->model = model;
accounts->adapter_dir = strdup(adapter_dir != NULL ? adapter_dir : ".");
accounts->store = dc_store_open(config_dir);
if (accounts->store == NULL || accounts->adapter_dir == NULL) {
dc_store_close(accounts->store);
free(accounts->adapter_dir);
free(accounts);
return NULL;
}
accounts->loop = dc_loop_new();
if (accounts->loop == NULL) {
dc_store_close(accounts->store);
free(accounts->adapter_dir);
free(accounts);
return NULL;
}
accounts->accounts_json = dc_store_load_accounts(accounts->store);
accounts->secrets_json = dc_store_load_secrets(accounts->store);
if (accounts->accounts_json == NULL || accounts->secrets_json == NULL) {
dc_json_free(accounts->accounts_json);
dc_json_free(accounts->secrets_json);
dc_loop_free(accounts->loop);
dc_store_close(accounts->store);
free(accounts->adapter_dir);
free(accounts);
return NULL;
}
accounts_spawn(accounts);
dtchat_ui_set_accounts_data(ui, accounts->accounts_json,
accounts->secrets_json, accounts_save_cb, accounts);
dtchat_ui_refresh(ui);
dtchat_ui_set_send_hook(ui, accounts_send_hook, accounts);
dtchat_ui_set_file_send(ui, accounts_file_send, accounts);
dtchat_ui_set_typing_hook(ui, accounts_typing_hook, accounts);
dtchat_ui_set_join_hook(ui, accounts_join_hook, accounts);
schedule_poll(accounts);
return accounts;
}
void
dtchat_accounts_stop(DtAccounts *accounts)
{
if (accounts == NULL)
return;
if (accounts->timer != 0) {
(void)XtRemoveTimeOut(accounts->timer);
accounts->timer = 0;
}
dtchat_ui_set_send_hook(accounts->ui, NULL, NULL);
dtchat_ui_set_file_send(accounts->ui, NULL, NULL);
dtchat_ui_set_typing_hook(accounts->ui, NULL, NULL);
dtchat_ui_set_join_hook(accounts->ui, NULL, NULL);
while (accounts->incoming != NULL)
incoming_free(accounts, accounts->incoming, 1);
stop_adapters(accounts);
if (accounts->loop != NULL)
dc_loop_free(accounts->loop);
if (accounts->store != NULL)
dc_store_close(accounts->store);
dc_json_free(accounts->accounts_json);
dc_json_free(accounts->secrets_json);
free(accounts->adapter_dir);
free(accounts);
}