1795 lines
98 KiB
C
1795 lines
98 KiB
C
#include "chat_sync.h"
|
|
#include "chat_core.h"
|
|
#include "chat_core_priv.h"
|
|
#include "chat_member.h"
|
|
#include "chat_setting.h"
|
|
#include "chat_event.h"
|
|
#include "chat_admin.h"
|
|
#include "chat_join.h"
|
|
#include "chat_join_port.h"
|
|
#include "invite_link.h"
|
|
#include "invite_build.h"
|
|
#include <openssl/crypto.h>
|
|
#include "group_avatar.h"
|
|
#include "../routing_layer/topo_node_sqlite.h"
|
|
#include "../routing_layer/topo_group.h"
|
|
#include "../routing_layer/topo_group_invite.h"
|
|
#include "../routing_layer/topo_group_connect.h"
|
|
#include "../../lib/json_flat.h"
|
|
#include "member_sync.h"
|
|
#include "merkle_sync.h"
|
|
#include "chat_feedback.h"
|
|
|
|
#include "../utun_instance.h"
|
|
#include "../transport_layer/etcp_api.h"
|
|
#include "../transport_layer/etcp.h"
|
|
#include "../transport_layer/node_conn_direct.h"
|
|
#include "../transport_layer/secure_channel.h"
|
|
#include "../ntp_time.h"
|
|
#include "../../lib/u_async.h"
|
|
#include "../../lib/ll_queue.h"
|
|
#include "../../lib/debug_config.h"
|
|
#include "../../lib/mem.h"
|
|
#include "../../lib/platform_compat.h"
|
|
#ifdef UTUN_HAVE_STANDBY
|
|
#include "standby.h"
|
|
#endif
|
|
|
|
#include <string.h>
|
|
#include <sqlite3.h>
|
|
#include <openssl/rand.h>
|
|
#ifdef __ANDROID__
|
|
#include <android/log.h>
|
|
#endif
|
|
|
|
static inline struct chat_sync* cs_of(struct UTUN_INSTANCE* inst) {
|
|
return inst ? inst->chat_sync : NULL;
|
|
}
|
|
|
|
struct channel_cache {
|
|
char channel_id[64];
|
|
uint64_t* peer_ids;
|
|
int peer_count;
|
|
};
|
|
|
|
/* Только отложенный запрос запуска; состоянием активного обмена владеет Merkle. */
|
|
struct pending_sync {
|
|
struct pending_sync* next;
|
|
uint64_t channel_id, peer_id;
|
|
const char* reason; /* статическая строка вызывающего обработчика */
|
|
uint8_t in_batch; /* задание присутствовало в начале текущего прохода таймера */
|
|
};
|
|
|
|
struct join_pending {
|
|
uint64_t node_id; /* joiner node_id */
|
|
char ch_id[64];
|
|
uint64_t attempt; /* идентификатор конкретного JOIN_REQUEST */
|
|
uint64_t expires; /* deadline ожидания записи, timebase */
|
|
struct join_pending* next;
|
|
};
|
|
|
|
struct chat_sync {
|
|
struct chat_join_port* port;
|
|
struct UTUN_INSTANCE* inst;
|
|
struct channel_cache* channels;
|
|
int channel_count;
|
|
void* refresh_timer;
|
|
void* refresh_wait; /* standby_wait handle (Android) */
|
|
void* info_req_timer;
|
|
void* join_timer;
|
|
void* sync_timer;
|
|
struct pending_sync* sync_pending;
|
|
uint8_t sync_draining; /* новые задания во время flush обслужит следующий проход */
|
|
void* invite_send_timer; /* timer waiting for joiner to respond to CHANNEL_INVITE */
|
|
uint8_t initialized;
|
|
uint8_t direct_bound, admin_bound, join_bound; /* Только успешно установленные service bindings снимаются в destroy. */
|
|
struct {
|
|
uint64_t channel, peer, key, request, attempt;
|
|
uint8_t inviter, phase; /* 0=idle, 1=connect, 2=info, 3=ready, 4=offer, 5=prepare */
|
|
char password[INVITE_PASS_MAX];
|
|
struct NODE_CONN_DIRECT* handle;
|
|
void* transport_timer;
|
|
uint8_t server_offer; /* отправляем серверу обычное приглашение после проверки add_key */
|
|
uint8_t add_key[INVITE_ADD_KEY_SIZE]; /* только исходящий SERVER_JOIN_REQ */
|
|
char offer_link[INVITE_LINK_MAX]; /* подтверждённое обычное приглашение, одинаковое при повторах */
|
|
struct chat_invite_build* offer_build;
|
|
void* operation_timer; /* общий deadline серверной операции, сохраняется при reconnect */
|
|
uint64_t origin_operation; /* входящий запрос сервера: ответить peer после обычного JOIN */
|
|
} join;
|
|
struct join_pending* join_pending; /* connection-узел: ожидающие ready джойнеры */
|
|
/* Pending incoming invites (для ask/deny) */
|
|
uint64_t pending_inv_in_ch_id[4];
|
|
uint64_t pending_inv_in_node_id[4];
|
|
uint64_t pending_inv_in_key[4];
|
|
int pending_inv_in_count;
|
|
};
|
|
|
|
#define CS_ID "chat_sync"
|
|
#define CS_INFO_REQ_TIMEOUT_MS 5000
|
|
#define CS_JOIN_TIMEOUT_MS 8000
|
|
#define CS_INVITE_SEND_TIMEOUT_MS 3000 /* inviter waits for joiner to respond */
|
|
#define CS_SYNC_INTERVAL_MS 1000
|
|
|
|
static void cs_info_req_timeout_cb(void* arg);
|
|
static void cs_join_finish(struct chat_sync* cs, int result);
|
|
static int cs_server_join_reply(struct chat_sync* cs, const char* channel, uint64_t peer, uint64_t operation, int result);
|
|
|
|
static void cs_join_connect_timeout(void* arg) {
|
|
struct chat_sync* cs = arg;
|
|
cs->join.transport_timer = NULL;
|
|
cs_info_req_timeout_cb(cs);
|
|
}
|
|
|
|
static void cs_server_operation_timeout(void* arg) {
|
|
struct chat_sync* cs = arg;
|
|
cs->join.operation_timer = NULL;
|
|
cs_info_req_timeout_cb(cs);
|
|
}
|
|
|
|
static void cs_join_release_transport(struct chat_sync* cs) {
|
|
if (cs->join.transport_timer) {
|
|
uasync_cancel_timeout(cs->inst->ua, cs->join.transport_timer); cs->join.transport_timer = NULL;
|
|
}
|
|
struct NODE_CONN_DIRECT* handle = cs->join.handle;
|
|
cs->join.handle = NULL;
|
|
if (handle) {
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "join transport release peer=%016llx",
|
|
(unsigned long long)node_conn_direct_node_id(handle));
|
|
node_conn_direct_close(handle);
|
|
}
|
|
}
|
|
|
|
static void cs_invitation_remove(struct chat_sync* cs, int index) {
|
|
for (int i = index + 1; i < cs->pending_inv_in_count; i++) {
|
|
cs->pending_inv_in_ch_id[i - 1] = cs->pending_inv_in_ch_id[i];
|
|
cs->pending_inv_in_node_id[i - 1] = cs->pending_inv_in_node_id[i];
|
|
cs->pending_inv_in_key[i - 1] = cs->pending_inv_in_key[i];
|
|
}
|
|
cs->pending_inv_in_count--;
|
|
cs->pending_inv_in_ch_id[cs->pending_inv_in_count] = 0;
|
|
cs->pending_inv_in_node_id[cs->pending_inv_in_count] = 0;
|
|
cs->pending_inv_in_key[cs->pending_inv_in_count] = 0;
|
|
}
|
|
|
|
static int cs_join_hold_transport(struct chat_sync* cs, uint64_t node_id, struct TOPO_NODE* ni) {
|
|
if (cs->join.handle) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "join already owns transport"); return -1; }
|
|
void* timer = uasync_set_timeout(cs->inst->ua, CS_INFO_REQ_TIMEOUT_MS * 10, cs,
|
|
cs_join_connect_timeout, "join_transport_timeout");
|
|
if (!timer) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "cannot reserve join deadline"); return -1; }
|
|
struct NODE_CONN_DIRECT* handle = NULL;
|
|
int rc = ni ? node_conn_direct_open_node(cs->inst, node_id, NULL, NULL, &handle, ni, NULL)
|
|
: node_conn_direct_open(cs->inst, node_id, NULL, NULL, &handle, NULL);
|
|
if (rc == NCD_ERR) {
|
|
uasync_cancel_timeout(cs->inst->ua, timer);
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "cannot acquire join transport peer=%016llx", (unsigned long long)node_id);
|
|
return -1;
|
|
}
|
|
cs->join.handle = handle; cs->join.transport_timer = timer; cs->join.phase = 1;
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "join transport acquired peer=%016llx", (unsigned long long)node_id);
|
|
return 0;
|
|
}
|
|
|
|
static const char* cs_msg_name(uint8_t type) {
|
|
switch (type) {
|
|
case CS_MSG_SERVER_JOIN_REQ: return "SERVER_JOIN_REQ";
|
|
case CS_MSG_SERVER_JOIN_RESULT: return "SERVER_JOIN_RESULT";
|
|
case CS_MSG_ERROR: return "ERROR";
|
|
case CS_MSG_CHANNEL_INVITE: return "CHANNEL_INVITE";
|
|
case CS_MSG_JOIN_INFO_REQ: return "JOIN_INFO_REQ";
|
|
case CS_MSG_JOIN_INFO_RESP: return "JOIN_INFO_RESP";
|
|
case CS_MSG_JOIN_REQUEST: return "JOIN_REQUEST";
|
|
case CS_MSG_JOIN_READY: return "JOIN_READY";
|
|
case CS_MSG_SOUND_SETTING: return "SOUND_SETTING";
|
|
default: return "???";
|
|
}
|
|
}
|
|
|
|
static void cs_cancel_proto_timers(struct chat_sync* cs) {
|
|
if (cs->info_req_timer) { uasync_cancel_timeout(cs->inst->ua, cs->info_req_timer); cs->info_req_timer = NULL; }
|
|
if (cs->join_timer) { uasync_cancel_timeout(cs->inst->ua, cs->join_timer); cs->join_timer = NULL; }
|
|
if (cs->invite_send_timer) { uasync_cancel_timeout(cs->inst->ua, cs->invite_send_timer); cs->invite_send_timer = NULL; }
|
|
}
|
|
|
|
void chat_sync_join_result(struct UTUN_INSTANCE* inst, uint64_t request, uint64_t channel, uint64_t peer, int result) {
|
|
uint8_t data[28]; int32_t code = result;
|
|
memcpy(data, &peer, 8); memcpy(data + 8, &code, 4); memcpy(data + 12, &channel, 8); memcpy(data + 20, &request, 8);
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "join result request=%llu channel=%llu peer=%016llx result=%d",
|
|
(unsigned long long)request, (unsigned long long)channel, (unsigned long long)peer, result);
|
|
chat_event_post(inst, CHAT_EVT_CONNECT_RESULT, data, sizeof(data));
|
|
}
|
|
|
|
static void cs_join_end(struct chat_sync* cs, int result, int notify) {
|
|
if (!cs->join.channel) return;
|
|
struct UTUN_INSTANCE* inst = cs->inst;
|
|
uint64_t channel = cs->join.channel, peer = cs->join.peer, request = cs->join.request;
|
|
struct NODE_CONN_DIRECT* handle = cs->join.handle;
|
|
struct chat_invite_build* build = cs->join.offer_build;
|
|
uint64_t origin = cs->join.origin_operation;
|
|
cs_cancel_proto_timers(cs);
|
|
if (cs->join.transport_timer) uasync_cancel_timeout(inst->ua, cs->join.transport_timer);
|
|
if (cs->join.operation_timer) uasync_cancel_timeout(inst->ua, cs->join.operation_timer);
|
|
OPENSSL_cleanse(&cs->join, sizeof(cs->join));
|
|
chat_join_port_complete(cs->port, request);
|
|
if (build) chat_invite_build_cancel(build);
|
|
if (origin && notify) {
|
|
char name[64]; snprintf(name, sizeof(name), "%llu", (unsigned long long)channel);
|
|
cs_server_join_reply(cs, name, peer, origin, result);
|
|
}
|
|
if (handle) node_conn_direct_close(handle);
|
|
if (notify) chat_sync_join_result(inst, request, channel, peer, result);
|
|
}
|
|
|
|
static void cs_join_finish(struct chat_sync* cs, int result) { cs_join_end(cs, result, 1); }
|
|
|
|
static int cs_join_reserve(struct chat_sync* cs, uint64_t channel, uint64_t peer, uint64_t request, int inviter) {
|
|
if (!cs || !cs->initialized || !channel || channel > INT64_MAX || !peer || peer == cs->inst->node_id) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "invalid or stopped local join"); return CHAT_CONNECT_INVALID;
|
|
}
|
|
if (cs->join.channel) { DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "local join busy"); return CHAT_CONNECT_BUSY; }
|
|
uint64_t attempt;
|
|
if (RAND_bytes((uint8_t*)&attempt, sizeof(attempt)) != 1 || !attempt) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "join attempt random generation failed"); return CHAT_CONNECT_ERROR;
|
|
}
|
|
cs->join.channel = channel; cs->join.peer = peer; cs->join.request = request;
|
|
cs->join.attempt = attempt; cs->join.inviter = inviter; cs->join.phase = 5;
|
|
return 0;
|
|
}
|
|
|
|
/* ── Forward decl ── */
|
|
static struct ETCP_CONN* cs_find_conn_for_node(struct UTUN_INSTANCE* inst, uint64_t node_id);
|
|
|
|
/* ── Send ── */
|
|
|
|
/* group_id в wire: [group_id:8] вместо [ch_len:1][ch_id] */
|
|
static void cs_write_group_id(uint8_t* p, const char* ch_id) {
|
|
uint64_t gb = htobe64(strtoull(ch_id, NULL, 10));
|
|
memcpy(p, &gb, 8);
|
|
}
|
|
|
|
/* group_id → ch_id через группу канала (требует существующую CHAT-группу). 0=ок, -1=нет группы */
|
|
static int cs_group_id_to_ch_id(struct UTUN_INSTANCE* inst, uint64_t group_id, char* ch_id, size_t sz) {
|
|
if (!inst || !inst->topo_groups) return -1;
|
|
struct TOPO_GROUP* g = topo_groups_find(inst->topo_groups, group_id);
|
|
if (!g || g->group_type != TOPO_GROUP_TYPE_CHAT || !g->channel_id[0]) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: recv — no CHAT group for group=%016llx, drop", CS_ID, (unsigned long long)group_id);
|
|
return -1;
|
|
}
|
|
snprintf(ch_id, sz, "%s", g->channel_id);
|
|
return 0;
|
|
}
|
|
|
|
static int cs_send(struct chat_sync* cs, const char* ch_id, uint64_t dst,
|
|
const uint8_t* payload, size_t len) {
|
|
if (len < 1) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "%s: cs_send len<1", CS_ID); return -1; }
|
|
size_t total = 1 + 8 + len;
|
|
uint8_t* buf = u_malloc(total);
|
|
if (!buf) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "%s: cs_send alloc(%zu) failed", CS_ID, total); return -1; }
|
|
uint8_t* p = buf;
|
|
*p++ = ETCP_ID_CHAT_SYNC;
|
|
cs_write_group_id(p, ch_id); p += 8;
|
|
memcpy(p, payload, len);
|
|
struct ll_entry* entry = queue_entry_new(0);
|
|
if (!entry) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "%s: cs_send queue_entry_new failed", CS_ID); u_free(buf); return -1; }
|
|
entry->dgram = buf; entry->len = total;
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: SEND %s to=%016llx ch=%s len=%zu",
|
|
CS_ID, cs_msg_name(payload[0]), (unsigned long long)dst, ch_id, len);
|
|
struct ETCP_CONN* conn = cs_find_conn_for_node(cs->inst, dst);
|
|
if (!conn) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "%s: no conn for node %016llx", CS_ID, (unsigned long long)dst); u_free(buf); queue_entry_free(entry); return -1; }
|
|
int rc = etcp_send(conn, entry);
|
|
if (rc != 0) { queue_dgram_free(entry); queue_entry_free(entry); }
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "%s: etcp_send rc=%d id=0x%02x to=%016llx conn=%s", CS_ID, rc, payload[0], (unsigned long long)dst, conn->log_name);
|
|
return rc;
|
|
}
|
|
|
|
static int cs_send_attempt(struct chat_sync* cs, const char* channel, uint64_t peer,
|
|
const uint8_t* payload, size_t len, uint64_t attempt) {
|
|
if (!attempt || !len) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "missing join attempt"); return -1; }
|
|
uint8_t* data = u_malloc(len + 8);
|
|
if (!data) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "join wire allocation failed"); return -1; }
|
|
data[0] = payload[0]; uint64_t wire = htobe64(attempt); memcpy(data + 1, &wire, 8);
|
|
memcpy(data + 9, payload + 1, len - 1);
|
|
int rc = cs_send(cs, channel, peer, data, len + 8); u_free(data); return rc;
|
|
}
|
|
|
|
/* ── Channel cache ── */
|
|
|
|
static int cs_server_join_reply(struct chat_sync* cs, const char* channel, uint64_t peer, uint64_t operation, int result) {
|
|
uint8_t data[5] = {CS_MSG_SERVER_JOIN_RESULT};
|
|
uint32_t code = htonl((uint32_t)result); memcpy(data + 1, &code, sizeof(code));
|
|
DEBUG_INFO(DEBUG_CATEGORY_CHAT_SYNC, "server join reply operation=%016llx channel=%s peer=%016llx result=%d",
|
|
(unsigned long long)operation, channel, (unsigned long long)peer, result);
|
|
int rc = cs_send_attempt(cs, channel, peer, data, sizeof(data), operation);
|
|
if (rc) DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "server join reply failed operation=%016llx rc=%d", (unsigned long long)operation, rc);
|
|
return rc;
|
|
}
|
|
|
|
static void cs_handle_server_join(struct chat_sync* cs, uint64_t peer, const char* channel,
|
|
const uint8_t* data, size_t len, uint64_t operation) {
|
|
const struct global_config* cfg = &cs->inst->config->global;
|
|
int result = CHAT_CONNECT_INVALID;
|
|
if (len < INVITE_ADD_KEY_SIZE + 2 || !cfg->chatserver_enabled || !cfg->chatserver_has_add_key ||
|
|
CRYPTO_memcmp(data, cfg->chatserver_add_key, INVITE_ADD_KEY_SIZE)) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_CHAT_SYNC, "server join authorization rejected channel=%s peer=%016llx key_configured=%d bytes=%zu",
|
|
channel, (unsigned long long)peer, cfg->chatserver_has_add_key, len);
|
|
cs_server_join_reply(cs, channel, peer, operation, CHAT_CONNECT_AUTH); return;
|
|
}
|
|
size_t size = ((size_t)data[32] << 8) | data[33];
|
|
struct InviteData invite;
|
|
if (size != len - 34 || invite_link_decode((const char*)data + 34, size, &invite, NULL, 0) ||
|
|
invite.kind != INVITE_KIND_CHANNEL || invite.channelId != chat_channel_id(channel) || invite.nodeId != peer) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_CHAT_SYNC, "server join invitation rejected channel=%s peer=%016llx bytes=%zu",
|
|
channel, (unsigned long long)peer, size);
|
|
} else if (cs->join.channel) {
|
|
if (cs->join.origin_operation == operation && cs->join.peer == peer && cs->join.channel == invite.channelId &&
|
|
cs->join.key == invite.join_key) {
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_CHAT_SYNC, "server join duplicate active operation=%016llx", (unsigned long long)operation); return;
|
|
}
|
|
result = CHAT_CONNECT_BUSY;
|
|
} else if (topo_node_sqlite_member_allowed(cs->inst->topo_sqlite_db, channel, cs->inst->node_id) &&
|
|
topo_node_sqlite_member_allowed(cs->inst->topo_sqlite_db, channel, peer)) {
|
|
result = 0;
|
|
} else {
|
|
result = chat_sync_join_link(cs->inst, 0, (const char*)data + 34, size);
|
|
if (!result) {
|
|
cs->join.origin_operation = operation;
|
|
DEBUG_INFO(DEBUG_CATEGORY_CHAT_SYNC, "server join authorized; ordinary JOIN started operation=%016llx channel=%s peer=%016llx",
|
|
(unsigned long long)operation, channel, (unsigned long long)peer); return;
|
|
}
|
|
}
|
|
cs_server_join_reply(cs, channel, peer, operation, result);
|
|
}
|
|
|
|
static void cs_handle_server_join_result(struct chat_sync* cs, uint64_t peer, const char* channel,
|
|
const uint8_t* data, size_t len, uint64_t operation) {
|
|
if (!cs->join.server_offer || cs->join.phase != 4 || cs->join.peer != peer ||
|
|
cs->join.channel != chat_channel_id(channel) || cs->join.attempt != operation) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_CHAT_SYNC, "ignore stale server join result operation=%016llx channel=%s peer=%016llx",
|
|
(unsigned long long)operation, channel, (unsigned long long)peer); return;
|
|
}
|
|
if (len != 4) { DEBUG_WARN(DEBUG_CATEGORY_CHAT_SYNC, "invalid server join result bytes=%zu", len); return; }
|
|
uint32_t code; memcpy(&code, data, sizeof(code));
|
|
int result = (int32_t)ntohl(code);
|
|
if (result != 0 && result != CHAT_CONNECT_ERROR && result != CHAT_CONNECT_TIMEOUT && result != CHAT_CONNECT_INVALID &&
|
|
result != CHAT_CONNECT_BUSY && result != CHAT_CONNECT_CANCELLED && result != CHAT_CONNECT_AUTH) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_CHAT_SYNC, "unknown server join result=%d", result); return;
|
|
}
|
|
cs_join_finish(cs, result);
|
|
}
|
|
|
|
/* ── Forward declarations for new message handlers ── */
|
|
|
|
static void cs_handle_join_info_req(struct chat_sync* cs, uint64_t peer,
|
|
const char* ch_id, const uint8_t* pl, size_t len, uint64_t attempt);
|
|
static void cs_handle_join_info_resp(struct chat_sync* cs, uint64_t peer,
|
|
const char* ch_id, const uint8_t* pl, size_t len);
|
|
static void cs_handle_join_request(struct chat_sync* cs, uint64_t peer,
|
|
const char* ch_id, const uint8_t* pl, size_t len, uint64_t attempt);
|
|
static void cs_handle_join_ready(struct chat_sync* cs, uint64_t peer,
|
|
const char* ch_id, const uint8_t* pl, size_t len);
|
|
static void cs_handle_channel_invite(struct chat_sync* cs, uint64_t peer,
|
|
const char* ch_id, const uint8_t* pl, size_t len);
|
|
static int cs_send_channel_invite(struct chat_sync* cs, struct UTUN_INSTANCE* inst,
|
|
const char* ch_id, uint64_t target_node_id,
|
|
const char* ch_name, uint64_t owner,
|
|
const uint8_t* ch_x25519, const uint8_t* ch_ed,
|
|
const uint8_t* ch_sig);
|
|
static void cs_on_member_applied(const char* ch_id, uint64_t node_id,
|
|
const uint8_t* x25519, uint64_t signed_by,
|
|
const uint8_t* signature, void* arg);
|
|
static void cs_pending_free_all(struct chat_sync* cs);
|
|
static void cs_pending_prune(struct chat_sync* cs);
|
|
/* ── Recv dispatcher ── */
|
|
|
|
static void chat_sync_recv_cb(struct ETCP_CONN* conn, struct ll_entry* entry) {
|
|
if (!entry || !entry->dgram || !conn || entry->len < 10) {
|
|
if (entry) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: recv short entry len=%zu conn=%s", CS_ID, entry->len, conn ? conn->log_name : "?");
|
|
if (entry->dgram) u_free(entry->dgram); queue_entry_free(entry);
|
|
}
|
|
return;
|
|
}
|
|
struct chat_sync* cs = cs_of(conn->instance);
|
|
if (!cs || !cs->initialized) { u_free(entry->dgram); queue_entry_free(entry); return; }
|
|
|
|
uint64_t peer = conn ? conn->peer_node_id : 0;
|
|
const uint8_t* d = entry->dgram;
|
|
size_t dlen = entry->len;
|
|
|
|
uint64_t group_id; memcpy(&group_id, d + 1, sizeof(group_id));
|
|
group_id = be64toh(group_id);
|
|
if (!group_id || group_id > INT64_MAX) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "chat_sync: invalid wire channel=%llu", (unsigned long long)group_id);
|
|
u_free(entry->dgram); queue_entry_free(entry); return;
|
|
}
|
|
uint8_t type = d[9];
|
|
char ch_id[64];
|
|
if (cs_group_id_to_ch_id(cs->inst, group_id, ch_id, sizeof(ch_id)) != 0) {
|
|
/* CHANNEL_INVITE/JOIN_INFO_REQ приходят для ещё не созданного у нас канала:
|
|
group_id == channel_id (numeric), поэтому выводим ch_id напрямую. */
|
|
if (type == CS_MSG_CHANNEL_INVITE || type == CS_MSG_JOIN_INFO_REQ || type == CS_MSG_JOIN_INFO_RESP ||
|
|
type == CS_MSG_JOIN_REQUEST || type == CS_MSG_JOIN_READY || type == CS_MSG_ERROR ||
|
|
type == CS_MSG_SERVER_JOIN_REQ || type == CS_MSG_SERVER_JOIN_RESULT) {
|
|
snprintf(ch_id, sizeof(ch_id), "%llu", (unsigned long long)group_id);
|
|
} else {
|
|
u_free(entry->dgram); queue_entry_free(entry); return;
|
|
}
|
|
}
|
|
DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "%s: recv %s(%02x) from=%016llx ch=%s len=%zu",
|
|
CS_ID, cs_msg_name(type), type, (unsigned long long)peer, ch_id, dlen);
|
|
const uint8_t* pl = d + 10;
|
|
size_t plen = dlen - 10;
|
|
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: RECV %s from=%016llx ch=%s len=%zu",
|
|
CS_ID, cs_msg_name(type), (unsigned long long)peer, ch_id, plen);
|
|
|
|
uint64_t attempt = 0;
|
|
if (type == CS_MSG_JOIN_INFO_REQ || type == CS_MSG_JOIN_INFO_RESP || type == CS_MSG_JOIN_REQUEST ||
|
|
type == CS_MSG_JOIN_READY || type == CS_MSG_ERROR || type == CS_MSG_SERVER_JOIN_REQ || type == CS_MSG_SERVER_JOIN_RESULT) {
|
|
if (plen < 8) { DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "join missing attempt type=%u", type); goto received; }
|
|
memcpy(&attempt, pl, 8); attempt = be64toh(attempt); pl += 8; plen -= 8;
|
|
if (!attempt) { DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "join zero attempt type=%u", type); goto received; }
|
|
}
|
|
if ((type == CS_MSG_JOIN_INFO_RESP || type == CS_MSG_JOIN_READY || type == CS_MSG_ERROR) &&
|
|
(cs->join.peer != peer || cs->join.channel != group_id || cs->join.attempt != attempt ||
|
|
(type == CS_MSG_JOIN_INFO_RESP && cs->join.phase != 2) || (type == CS_MSG_JOIN_READY && cs->join.phase != 3))) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "ignore stale join response peer=%016llx group=%016llx type=%u",
|
|
(unsigned long long)peer, (unsigned long long)group_id, type);
|
|
u_free(entry->dgram); queue_entry_free(entry); return;
|
|
}
|
|
|
|
switch (type) {
|
|
case CS_MSG_JOIN_INFO_REQ: DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "%s: → handle JOIN_INFO_REQ", CS_ID); cs_handle_join_info_req(cs, peer, ch_id, pl, plen, attempt); break;
|
|
case CS_MSG_JOIN_INFO_RESP: DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "%s: → handle JOIN_INFO_RESP", CS_ID); cs_handle_join_info_resp(cs, peer, ch_id, pl, plen); break;
|
|
case CS_MSG_JOIN_REQUEST: DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "%s: → handle JOIN_REQUEST", CS_ID); cs_handle_join_request(cs, peer, ch_id, pl, plen, attempt); break;
|
|
case CS_MSG_JOIN_READY: DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "%s: → handle JOIN_READY", CS_ID); cs_handle_join_ready(cs, peer, ch_id, pl, plen); break;
|
|
case CS_MSG_ERROR: {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: RECV ERROR from=%016llx ch=%s", CS_ID, (unsigned long long)peer, ch_id);
|
|
cs_join_finish(cs, CHAT_CONNECT_ERROR);
|
|
break;
|
|
}
|
|
case CS_MSG_CHANNEL_INVITE: cs_handle_channel_invite(cs, peer, ch_id, pl, plen); break;
|
|
case CS_MSG_SERVER_JOIN_REQ: cs_handle_server_join(cs, peer, ch_id, pl, plen, attempt); break;
|
|
case CS_MSG_SERVER_JOIN_RESULT: cs_handle_server_join_result(cs, peer, ch_id, pl, plen, attempt); break;
|
|
case CS_MSG_SOUND_SETTING:
|
|
if (plen == 1 && pl[0] <= 1) db_sync_set_peer_sound(cs->inst, group_id, peer, pl[0]);
|
|
else DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "invalid SOUND_SETTING size=%zu", plen);
|
|
break;
|
|
default: DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: UNKNOWN msg type=%02x from=%016llx", CS_ID, type, (unsigned long long)peer); break;
|
|
}
|
|
received:
|
|
u_free(entry->dgram); queue_entry_free(entry);
|
|
}
|
|
|
|
/* ── Connection callbacks ── */
|
|
|
|
static void cs_info_req_timeout_cb(void* arg) {
|
|
struct chat_sync* cs = arg;
|
|
if (!cs || !cs->initialized) return;
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "join timeout phase=%u channel=%llu peer=%016llx",
|
|
cs->join.phase, (unsigned long long)cs->join.channel, (unsigned long long)cs->join.peer);
|
|
cs_join_finish(cs, CHAT_CONNECT_TIMEOUT);
|
|
}
|
|
static void cs_join_timeout_cb(void* arg) { cs_info_req_timeout_cb(arg); }
|
|
static void cs_invite_send_timeout_cb(void* arg) { cs_info_req_timeout_cb(arg); }
|
|
|
|
/* ── helper: find active ETCP_CONN for node ── */
|
|
|
|
static struct ETCP_CONN* cs_find_conn_for_node(struct UTUN_INSTANCE* inst, uint64_t node_id) {
|
|
struct ETCP_CONN* conn = instance_find_conn(inst, node_id);
|
|
if (conn && conn->initialized && conn->links_up) return conn;
|
|
if (!inst->connections) { DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: find_conn connections=NULL", CS_ID); return NULL; }
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "%s: find_conn node=%016llx NOT FOUND (head=%p count=%d)",
|
|
CS_ID, (unsigned long long)node_id, (void*)inst->connections->head, queue_entry_count(inst->connections));
|
|
return NULL;
|
|
}
|
|
|
|
/* ── helper: check if peer has active ETCP link ── */
|
|
|
|
static int cs_is_peer_online(struct UTUN_INSTANCE* inst, uint64_t peer_id) {
|
|
if (!inst->connections) { DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "%s: is_online peer=0x%016llx CONNS=NULL", CS_ID, (unsigned long long)peer_id); return 0; }
|
|
struct ETCP_CONN* conn = instance_find_conn(inst, peer_id);
|
|
if (conn) return conn->initialized && conn->links_up;
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "%s: is_online peer=0x%016llx NOT FOUND", CS_ID, (unsigned long long)peer_id);
|
|
return 0;
|
|
}
|
|
|
|
/* ── post per-channel online peers count to GUI ── */
|
|
|
|
static void cs_post_channel_online(struct chat_sync* cs, const char* ch_id) {
|
|
char channel[64]; snprintf(channel, sizeof(channel), "%s", ch_id); ch_id = channel;
|
|
int online = 0;
|
|
struct channel_cache* ch = NULL;
|
|
for (int i = 0; i < cs->channel_count; i++)
|
|
if (strcmp(cs->channels[i].channel_id, ch_id) == 0) { ch = &cs->channels[i]; break; }
|
|
if (ch) {
|
|
for (int j = 0; j < ch->peer_count; j++) {
|
|
int p_on = cs_is_peer_online(cs->inst, ch->peer_ids[j]);
|
|
if (p_on) online++;
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "%s: PEERS_ONLINE peer[%d]=0x%016llx online=%d",
|
|
CS_ID, j, (unsigned long long)ch->peer_ids[j], p_on);
|
|
}
|
|
}
|
|
size_t cl = strlen(ch_id);
|
|
if (cl > 63) cl = 63;
|
|
uint8_t evt[66]; evt[0] = (uint8_t)cl;
|
|
memcpy(evt + 1, ch_id, cl);
|
|
uint16_t oc = online > UINT16_MAX ? UINT16_MAX : (uint16_t)online; memcpy(evt + 1 + cl, &oc, 2);
|
|
chat_event_post(cs->inst, CHAT_EVT_CHANNEL_PEERS_ONLINE, evt, 1 + (int)cl + 2);
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "%s: PEERS_ONLINE ch=%.*s total_online=%d", CS_ID, (int)cl, ch_id, online);
|
|
}
|
|
|
|
/* ── Адресные запросы синхронизации; один таймер на накопленные пары ── */
|
|
|
|
static void _on_member_sync_done(uint64_t peer, const char* ns, int result, void* arg);
|
|
static void cs_sync_timer_cb(void* arg);
|
|
|
|
/* Членство читается из БД, как list_peers: кеш GUI может ещё не знать нового участника. */
|
|
static int cs_sync_member(struct chat_sync* cs, uint64_t channel_id, uint64_t peer) {
|
|
struct TOPO_GROUP* group = topo_groups_find(cs->inst->topo_groups, channel_id);
|
|
if (!group || group->group_type != TOPO_GROUP_TYPE_CHAT) return 0;
|
|
char sql[160]; sqlite3_stmt* st = NULL;
|
|
snprintf(sql, sizeof(sql), "SELECT 1 FROM peers_%llu WHERE node_id=? AND deleted=0", (unsigned long long)channel_id);
|
|
int rc = sqlite3_prepare_v2(cs->inst->topo_sqlite_db, sql, -1, &st, NULL);
|
|
if (rc == SQLITE_OK) rc = sqlite3_bind_int64(st, 1, (sqlite3_int64)peer);
|
|
if (rc == SQLITE_OK) rc = sqlite3_step(st);
|
|
int found = rc == SQLITE_ROW;
|
|
if (rc != SQLITE_ROW && rc != SQLITE_DONE)
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "sync membership read failed ch=%llu peer=%016llx rc=%d: %s",
|
|
(unsigned long long)channel_id, (unsigned long long)peer, rc, sqlite3_errmsg(cs->inst->topo_sqlite_db));
|
|
int final = sqlite3_finalize(st);
|
|
if (final != SQLITE_OK) DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "sync membership finalize failed rc=%d", final);
|
|
return found && final == SQLITE_OK;
|
|
}
|
|
|
|
static int cs_sync_peer_available(struct chat_sync* cs, uint64_t peer) {
|
|
struct ETCP_CONN* conn = instance_find_conn(cs->inst, peer);
|
|
return conn && peer != cs->inst->node_id && conn->initialized && conn->links_up && conn->state != 2
|
|
&& !conn->close_requested && !conn->reinit_pending && !conn->session_required && !conn->peer_sleep_phase;
|
|
}
|
|
|
|
/* Нулевой peer/channel выбирает все задания соответствующего измерения. Сессии Merkle здесь не трогаем. */
|
|
static void cs_cancel_sync(struct chat_sync* cs, uint64_t peer, uint64_t channel_id, const char* reason) {
|
|
struct pending_sync** p = &cs->sync_pending;
|
|
while (*p) {
|
|
struct pending_sync* job = *p;
|
|
if ((peer && job->peer_id != peer) || (channel_id && job->channel_id != channel_id)) { p = &job->next; continue; }
|
|
*p = job->next;
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "sync request cancelled ch=%llu peer=%016llx reason=%s",
|
|
(unsigned long long)job->channel_id, (unsigned long long)job->peer_id, reason);
|
|
u_free(job);
|
|
}
|
|
if (!cs->sync_pending && cs->sync_timer) {
|
|
uasync_cancel_timeout(cs->inst->ua, cs->sync_timer); cs->sync_timer = NULL;
|
|
}
|
|
}
|
|
|
|
/* Срок первого задания не переносится последующими событиями других пиров. */
|
|
static int cs_arm_sync(struct chat_sync* cs) {
|
|
if (!cs->sync_pending || cs->sync_timer || cs->sync_draining) return 0;
|
|
cs->sync_timer = uasync_set_timeout(cs->inst->ua, CS_SYNC_INTERVAL_MS * 10, cs, cs_sync_timer_cb, "cs_sync");
|
|
if (cs->sync_timer) return 0;
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "sync request timer allocation failed; cancelling pending requests");
|
|
cs_cancel_sync(cs, 0, 0, "timer_failed");
|
|
return -1;
|
|
}
|
|
|
|
/* Извлекаем задание до callbacks; отмена видит все оставшиеся, новые идут в конец очереди. */
|
|
static void cs_sync_timer_cb(void* arg) {
|
|
struct chat_sync* cs = arg;
|
|
cs->sync_timer = NULL;
|
|
if (!cs->initialized) return;
|
|
for (struct pending_sync* job = cs->sync_pending; job; job = job->next) job->in_batch = 1;
|
|
cs->sync_draining = 1;
|
|
while (cs->sync_pending && cs->sync_pending->in_batch) {
|
|
struct pending_sync* job = cs->sync_pending;
|
|
cs->sync_pending = job->next;
|
|
uint64_t peer = job->peer_id, channel_id = job->channel_id;
|
|
const char* reason = job->reason;
|
|
u_free(job);
|
|
if (!cs_sync_peer_available(cs, peer) || !cs_sync_member(cs, channel_id, peer)) {
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "sync request discarded ch=%llu peer=%016llx reason=%s unavailable",
|
|
(unsigned long long)channel_id, (unsigned long long)peer, reason);
|
|
continue;
|
|
}
|
|
char channel[21]; snprintf(channel, sizeof(channel), "%llu", (unsigned long long)channel_id);
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "sync request started ch=%s peer=%016llx reason=%s", channel,
|
|
(unsigned long long)peer, reason);
|
|
if (member_sync_start(cs->inst, peer, channel, _on_member_sync_done, cs) < 0)
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "sync request rejected ch=%s peer=%016llx reason=%s", channel,
|
|
(unsigned long long)peer, reason);
|
|
}
|
|
cs->sync_draining = 0;
|
|
cs_arm_sync(cs);
|
|
}
|
|
|
|
/* Запрос одной пары: объединяем дубликаты, без ссылок на транспорт и заменяемый кеш. */
|
|
static int cs_schedule_sync(struct chat_sync* cs, uint64_t channel_id, uint64_t peer, const char* reason) {
|
|
if (!cs->initialized || !channel_id || !peer || !cs_sync_peer_available(cs, peer)
|
|
|| !cs_sync_member(cs, channel_id, peer)) return 0;
|
|
struct pending_sync** tail = &cs->sync_pending;
|
|
while (*tail) {
|
|
if ((*tail)->channel_id == channel_id && (*tail)->peer_id == peer) {
|
|
DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "sync request coalesced ch=%llu peer=%016llx reason=%s",
|
|
(unsigned long long)channel_id, (unsigned long long)peer, reason);
|
|
return 0;
|
|
}
|
|
tail = &(*tail)->next;
|
|
}
|
|
struct pending_sync* job = u_calloc(1, sizeof(*job));
|
|
if (!job) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "sync request allocation failed ch=%llu peer=%016llx reason=%s",
|
|
(unsigned long long)channel_id, (unsigned long long)peer, reason); return -1;
|
|
}
|
|
job->channel_id = channel_id; job->peer_id = peer; job->reason = reason; *tail = job;
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "sync request queued ch=%llu peer=%016llx reason=%s",
|
|
(unsigned long long)channel_id, (unsigned long long)peer, reason);
|
|
return cs_arm_sync(cs);
|
|
}
|
|
|
|
/* Событие транспорта относится только к общим каналам этого пира; группы актуальнее кеша. */
|
|
static void cs_schedule_peer_sync(struct chat_sync* cs, uint64_t peer, const char* reason) {
|
|
if (!cs_sync_peer_available(cs, peer)) return;
|
|
struct TOPO_GROUPS* groups = cs->inst->topo_groups;
|
|
for (struct ll_entry* e = groups && groups->group_list ? groups->group_list->head : NULL; e; e = e->next) {
|
|
struct TOPO_GROUP* group = (struct TOPO_GROUP*)e;
|
|
if (group->group_type == TOPO_GROUP_TYPE_CHAT) cs_schedule_sync(cs, group->group_id, peer, reason);
|
|
}
|
|
}
|
|
|
|
/* ── Peer sleep (keepalive-протокол): спячка → отменить сессии; пробуждение → пересинхронизация ── */
|
|
|
|
static void cs_on_peer_sleep(struct UTUN_INSTANCE* inst, uint64_t peer_node_id, int sleeping, void* arg) {
|
|
struct chat_sync* cs = (struct chat_sync*)arg;
|
|
if (!cs || !cs->initialized) return;
|
|
if (sleeping) {
|
|
cs_cancel_sync(cs, peer_node_id, 0, "peer_sleep");
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: peer sleep peer=0x%016llx — cancel member_sync sessions", CS_ID, (unsigned long long)peer_node_id);
|
|
merkle_sync_recheck_peer(inst, peer_node_id);
|
|
} else {
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: peer awake peer=0x%016llx — schedule sync", CS_ID, (unsigned long long)peer_node_id);
|
|
cs_schedule_peer_sync(cs, peer_node_id, "peer_awake");
|
|
}
|
|
db_sync_peer_policy_changed(inst, peer_node_id);
|
|
}
|
|
|
|
/* ── Per-chat «play sound on message» (троттлинг db_sync на сервере) ── */
|
|
|
|
static void cs_send_sound_setting(struct chat_sync* cs, const char* ch_id, uint64_t dst, int on) {
|
|
uint8_t p[2] = { CS_MSG_SOUND_SETTING, (uint8_t)(on ? 1 : 0) };
|
|
cs_send(cs, ch_id, dst, p, sizeof(p));
|
|
}
|
|
|
|
void chat_sync_broadcast_sound_setting(struct UTUN_INSTANCE* inst, const char* ch_id, int on) {
|
|
struct chat_sync* cs = cs_of(inst);
|
|
if (!cs || !cs->initialized || !ch_id || !ch_id[0]) return;
|
|
for (int i = 0; i < cs->channel_count; i++) {
|
|
if (strcmp(cs->channels[i].channel_id, ch_id) != 0) continue;
|
|
for (int j = 0; j < cs->channels[i].peer_count; j++) {
|
|
uint64_t pid = cs->channels[i].peer_ids[j];
|
|
if (pid == inst->node_id || !cs_is_peer_online(inst, pid)) continue;
|
|
cs_send_sound_setting(cs, ch_id, pid, on);
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
|
|
/* На поднятии соединения: отправить пиру свои per-chat настройки звука (начальная синхронизация). */
|
|
static void cs_send_all_sound_settings(struct chat_sync* cs, uint64_t peer) {
|
|
for (int i = 0; i < cs->channel_count; i++) {
|
|
int on = chat_core_get_sound_on_message(cs->inst, cs->channels[i].channel_id);
|
|
if (on >= 0) cs_send_sound_setting(cs, cs->channels[i].channel_id, peer, on);
|
|
else DEBUG_WARN(DEBUG_CATEGORY_CHAT_SYNC, "sound setting: skip unreadable channel=%s peer=%016llx",
|
|
cs->channels[i].channel_id, (unsigned long long)peer);
|
|
}
|
|
}
|
|
|
|
/* ── Peer status change (только GUI + online-бар; онлайн в БД не хранится) ── */
|
|
|
|
static void cs_on_peer_status_changed(struct chat_sync* cs, uint64_t peer, int online) {
|
|
int count = 0;
|
|
char (*channels)[64] = cs->channel_count ? u_malloc((size_t)cs->channel_count * 64) : NULL;
|
|
if (cs->channel_count && !channels) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "peer status snapshot allocation failed"); return;
|
|
}
|
|
for (int i = 0; i < cs->channel_count; i++) for (int j = 0; j < cs->channels[i].peer_count; j++) {
|
|
if (cs->channels[i].peer_ids[j] != peer) continue;
|
|
strcpy(channels[count++], cs->channels[i].channel_id); break;
|
|
}
|
|
for (int i = 0; i < count; i++) {
|
|
const char* channel = channels[i];
|
|
if (!topo_groups_find(cs->inst->topo_groups, strtoull(channel, NULL, 10))) continue;
|
|
size_t length = strlen(channel);
|
|
uint8_t event[1 + 64 + 1 + CHAT_MEMBER_DISPLAY_SIZE];
|
|
event[0] = (uint8_t)length; memcpy(event + 1, channel, length); event[1 + length] = 1;
|
|
if (!chat_core_get_single_member(cs->inst, channel, peer, event + 2 + length))
|
|
chat_event_post(cs->inst, CHAT_EVT_MEMBER_UPDATED, event, 2 + (int)length + CHAT_MEMBER_DISPLAY_SIZE);
|
|
cs_post_channel_online(cs, channel);
|
|
}
|
|
u_free(channels);
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "peer status peer=%016llx online=%d channels=%d",
|
|
(unsigned long long)peer, online, count);
|
|
}
|
|
|
|
static void cs_resume_db_sync(struct chat_sync* cs, const char* ch_id) {
|
|
if (!cs || !ch_id || !ch_id[0]) return;
|
|
struct DB_SYNC_INSTANCE* si = si_find(cs->inst, ch_id);
|
|
if (si) db_sync_instance_set_gated(si, 0);
|
|
}
|
|
|
|
/* Подтверждение feedback не управляет готовностью участников или истории сообщений. */
|
|
static void cs_feedback_done(uint64_t peer, const char* channel, int result, void* arg) {
|
|
(void)arg;
|
|
DEBUG_INFO(DEBUG_CATEGORY_CHAT_SYNC, "%s: feedback sync ch=%s peer=%016llx result=%d",
|
|
CS_ID, channel, (unsigned long long)peer, result);
|
|
}
|
|
|
|
static void _on_member_sync_done(uint64_t peer, const char* ns, int result, void* arg) {
|
|
struct chat_sync* cs = (struct chat_sync*)arg;
|
|
if (result == MT_OK) {
|
|
cs_resume_db_sync(cs, ns);
|
|
if (cs && merkle_sync_start(cs->inst, MT_DATA_FEEDBACK, peer, ns, cs_feedback_done, cs) < 0)
|
|
DEBUG_WARN(DEBUG_CATEGORY_CHAT_SYNC, "%s: feedback sync unavailable ch=%s peer=%016llx", CS_ID, ns, (unsigned long long)peer);
|
|
}
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: member_sync %s ns=%s peer=%016llx",
|
|
CS_ID, result == MT_OK ? "OK" : "FAIL", ns, (unsigned long long)peer);
|
|
}
|
|
|
|
/* ── send JOIN_INFO_REQ to start join handshake ── */
|
|
|
|
static int cs_start_channel_join(struct chat_sync* cs, uint64_t peer) {
|
|
if (!cs || cs->info_req_timer || cs->join_timer) return 0;
|
|
char channel[64]; snprintf(channel, sizeof(channel), "%llu", (unsigned long long)cs->join.channel);
|
|
size_t len = strlen(cs->join.password);
|
|
uint8_t data[140]; data[0] = CS_MSG_JOIN_INFO_REQ;
|
|
memcpy(data + 1, &cs->join.key, 8); data[9] = (uint8_t)len; memcpy(data + 10, cs->join.password, len);
|
|
cs->info_req_timer = uasync_set_timeout(cs->inst->ua, CS_INFO_REQ_TIMEOUT_MS * 10, cs,
|
|
cs_info_req_timeout_cb, "cs_info_req");
|
|
if (!cs->info_req_timer) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "join info deadline allocation failed"); return -1; }
|
|
cs->join.phase = 2;
|
|
if (cs_send_attempt(cs, channel, peer, data, len + 10, cs->join.attempt)) return -1;
|
|
if (cs->join.transport_timer) { uasync_cancel_timeout(cs->inst->ua, cs->join.transport_timer); cs->join.transport_timer = NULL; }
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "join info requested channel=%s attempt=%016llx", channel,
|
|
(unsigned long long)cs->join.attempt);
|
|
return 0;
|
|
}
|
|
|
|
static int cs_send_server_offer(struct chat_sync* cs) {
|
|
char channel[64]; snprintf(channel, sizeof(channel), "%llu", (unsigned long long)cs->join.channel);
|
|
size_t len = strlen(cs->join.offer_link);
|
|
uint8_t data[35 + INVITE_LINK_MAX] = {CS_MSG_SERVER_JOIN_REQ};
|
|
memcpy(data + 1, cs->join.add_key, INVITE_ADD_KEY_SIZE);
|
|
data[33] = (uint8_t)(len >> 8); data[34] = (uint8_t)len; memcpy(data + 35, cs->join.offer_link, len);
|
|
cs->join.phase = 4;
|
|
int rc = cs_send_attempt(cs, channel, cs->join.peer, data, len + 35, cs->join.attempt);
|
|
OPENSSL_cleanse(data, sizeof(data));
|
|
if (rc) DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "server join request send failed channel=%s rc=%d", channel, rc);
|
|
return rc;
|
|
}
|
|
|
|
static void cs_server_invite_ready(void* arg, int result, const char* link) {
|
|
struct chat_sync* cs = arg;
|
|
if (!cs->join.server_offer) return; /* отмена обнулила join до cancel регистрации */
|
|
cs->join.offer_build = NULL;
|
|
if (result != CHAT_JOIN_OK) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_CHAT_SYNC, "server invitation registration failed result=%d", result);
|
|
cs_join_finish(cs, result == CHAT_JOIN_TIMEOUT ? CHAT_CONNECT_TIMEOUT : CHAT_CONNECT_ERROR); return;
|
|
}
|
|
struct InviteData invitation;
|
|
if (!link || invite_link_decode(link, strlen(link), &invitation, NULL, 0) ||
|
|
invitation.kind != INVITE_KIND_CHANNEL || invitation.channelId != cs->join.channel || invitation.nodeId != cs->inst->node_id) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "server invitation builder returned unexpected target");
|
|
cs_join_finish(cs, CHAT_CONNECT_ERROR); return;
|
|
}
|
|
strcpy(cs->join.offer_link, link); cs->join.key = invitation.join_key;
|
|
struct ETCP_CONN* conn = node_conn_direct_get_conn(cs->join.handle);
|
|
if (conn && conn->initialized && conn->links_up) {
|
|
if (cs_send_server_offer(cs)) cs_join_finish(cs, CHAT_CONNECT_ERROR);
|
|
} else cs->join.phase = 1;
|
|
}
|
|
|
|
static int cs_start_channel_offer(struct chat_sync* cs, uint64_t peer) {
|
|
if (cs->join.server_offer) {
|
|
if (cs->join.offer_link[0]) return cs_send_server_offer(cs);
|
|
if (cs->join.offer_build) return 0;
|
|
cs->join.phase = 6;
|
|
cs->join.offer_build = chat_invite_build_link(cs->inst, cs->join.channel, cs->inst->node_id, NULL, cs_server_invite_ready, cs);
|
|
if (!cs->join.offer_build) { DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "cannot build ordinary invitation for server"); return -1; }
|
|
return 0;
|
|
}
|
|
char channel[64], name[128]; uint64_t owner;
|
|
uint8_t x[32], ed[32], signature[64];
|
|
snprintf(channel, sizeof(channel), "%llu", (unsigned long long)cs->join.channel);
|
|
if (topo_node_sqlite_channel_get(cs->inst->topo_sqlite_db, channel, name, sizeof(name), &owner, x, ed, signature)) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "offer channel missing ch=%s", channel); return -1;
|
|
}
|
|
cs->invite_send_timer = uasync_set_timeout(cs->inst->ua, CS_INVITE_SEND_TIMEOUT_MS * 10, cs,
|
|
cs_invite_send_timeout_cb, "cs_invite_send");
|
|
if (!cs->invite_send_timer) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "offer deadline allocation failed"); return -1; }
|
|
cs->join.phase = 4;
|
|
if (cs_send_channel_invite(cs, cs->inst, channel, peer, name, owner, x, ed, signature)) return -1;
|
|
if (cs->join.transport_timer) { uasync_cancel_timeout(cs->inst->ua, cs->join.transport_timer); cs->join.transport_timer = NULL; }
|
|
return 0;
|
|
}
|
|
|
|
/* ── Connection callbacks ── */
|
|
|
|
static void cs_on_conn_up(struct ETCP_CONN* conn, int event, void* arg) {
|
|
struct chat_sync* cs = (struct chat_sync*)arg;
|
|
if (!conn || !cs) return;
|
|
uint64_t peer = conn->peer_node_id;
|
|
if (peer == 0 || peer == cs->inst->node_id) return;
|
|
DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "%s: conn_up peer=%016llx init=%d links=%d", CS_ID, (unsigned long long)peer, conn->initialized, conn->links_up);
|
|
if (!conn->initialized) { DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: conn_up SKIP — not initialized peer=%016llx", CS_ID, (unsigned long long)peer); return; }
|
|
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "%s: conn_up peer=%016llx pending_invite=%llu links_up=%d", CS_ID, (unsigned long long)peer, (unsigned long long)cs->join.channel, conn->links_up);
|
|
cs_schedule_peer_sync(cs, peer, event == ETCP_CBK_EVENT_REINIT ? "reinit" : "transport_up");
|
|
|
|
if (cs->join.channel != 0 && cs->join.peer == peer && cs->join.phase == 1) {
|
|
if (cs->join.transport_timer) {
|
|
uasync_cancel_timeout(cs->inst->ua, cs->join.transport_timer); cs->join.transport_timer = NULL;
|
|
}
|
|
int rc = cs->join.inviter ? cs_start_channel_offer(cs, peer) : cs_start_channel_join(cs, peer);
|
|
if (rc < 0) cs_join_finish(cs, CHAT_CONNECT_ERROR);
|
|
cs_on_peer_status_changed(cs, peer, 1);
|
|
return;
|
|
}
|
|
|
|
cs_on_peer_status_changed(cs, peer, 1);
|
|
cs_send_all_sound_settings(cs, peer);
|
|
}
|
|
|
|
static void cs_on_conn_down(struct ETCP_CONN* conn, int event, void* arg) { (void)event;
|
|
struct chat_sync* cs = (struct chat_sync*)arg;
|
|
if (!conn || !cs) return;
|
|
uint64_t peer = conn->peer_node_id;
|
|
DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "%s: conn_down peer=%016llx", CS_ID, (unsigned long long)peer);
|
|
cs_cancel_sync(cs, peer, 0, "transport_down");
|
|
|
|
cs_on_peer_status_changed(cs, peer, 0);
|
|
|
|
if (cs->join.peer == peer && cs->join.phase != 5) {
|
|
cs_cancel_proto_timers(cs);
|
|
cs->join.phase = 1;
|
|
if (cs->join.transport_timer) uasync_cancel_timeout(cs->inst->ua, cs->join.transport_timer);
|
|
cs->join.transport_timer = uasync_set_timeout(cs->inst->ua, CS_INFO_REQ_TIMEOUT_MS * 10,
|
|
cs, cs_join_connect_timeout, "join_reconnect_timeout");
|
|
if (!cs->join.transport_timer) { cs_join_finish(cs, CHAT_CONNECT_ERROR); return; }
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: conn down while waiting invite resp peer=%016llx, timers cancelled, state kept for retry on reconnect",
|
|
CS_ID, (unsigned long long)peer);
|
|
/* invite state survives connection flaps: only timeout or explicit protocol end clears it */
|
|
}
|
|
}
|
|
|
|
static void cs_on_conn_status(struct ETCP_CONN* conn, int status, void* arg) {
|
|
switch (status) {
|
|
case ETCP_CONN_STATUS_UP: cs_on_conn_up(conn, ETCP_CBK_EVENT_UP, arg); break;
|
|
case ETCP_CONN_STATUS_REINIT:
|
|
cs_on_conn_down(conn, ETCP_CBK_EVENT_DOWN, arg);
|
|
cs_on_conn_up(conn, ETCP_CBK_EVENT_REINIT, arg);
|
|
break;
|
|
case ETCP_CONN_STATUS_DOWN:
|
|
case ETCP_CONN_STATUS_DELETE: cs_on_conn_down(conn, ETCP_CBK_EVENT_DOWN, arg); break;
|
|
default: break;
|
|
}
|
|
}
|
|
|
|
/* ── Periodic refresh from DB ── */
|
|
|
|
static void cs_cache_free(struct channel_cache* channels, int count) {
|
|
for (int i = 0; i < count; i++) u_free(channels[i].peer_ids);
|
|
u_free(channels);
|
|
}
|
|
|
|
/* Новый снимок строится целиком без callbacks; ошибка сохраняет предыдущий кеш. */
|
|
static int cs_refresh_channels(struct chat_sync* cs) {
|
|
cs_pending_prune(cs);
|
|
struct channel_cache* channels = NULL; int count = 0, capacity = 0;
|
|
sqlite3* db = cs->inst->topo_sqlite_db;
|
|
sqlite3_stmt* st = NULL;
|
|
int rc = sqlite3_prepare_v2(db, "SELECT channel_id FROM channels ORDER BY created_at,channel_id", -1, &st, NULL);
|
|
if (rc == SQLITE_OK) while ((rc = sqlite3_step(st)) == SQLITE_ROW) {
|
|
const char* id = (const char*)sqlite3_column_text(st, 0);
|
|
int bytes = sqlite3_column_bytes(st, 0);
|
|
if (!id || bytes <= 0 || bytes >= 64 || strlen(id) != (size_t)bytes || !chat_channel_id(id)) {
|
|
rc = SQLITE_CORRUPT; break;
|
|
}
|
|
if (count == capacity) {
|
|
int next = capacity ? capacity * 2 : 8;
|
|
if (capacity >= 65536) { rc = SQLITE_TOOBIG; break; }
|
|
void* grown = u_realloc(channels, (size_t)next * sizeof(*channels));
|
|
if (!grown) { rc = SQLITE_NOMEM; break; }
|
|
channels = grown; capacity = next;
|
|
}
|
|
struct channel_cache* channel = &channels[count++]; memset(channel, 0, sizeof(*channel)); strcpy(channel->channel_id, id);
|
|
char sql[160]; snprintf(sql, sizeof(sql), "SELECT node_id FROM peers_%s WHERE deleted=0 ORDER BY node_id", id);
|
|
sqlite3_stmt* peers = NULL; int peer_capacity = 0;
|
|
int prc = sqlite3_prepare_v2(db, sql, -1, &peers, NULL);
|
|
if (prc == SQLITE_OK) while ((prc = sqlite3_step(peers)) == SQLITE_ROW) {
|
|
if (sqlite3_column_type(peers, 0) != SQLITE_INTEGER || !sqlite3_column_int64(peers, 0)) { prc = SQLITE_CORRUPT; break; }
|
|
if (channel->peer_count == peer_capacity) {
|
|
int next = peer_capacity ? peer_capacity * 2 : 16;
|
|
if (peer_capacity >= 65536) { prc = SQLITE_TOOBIG; break; }
|
|
void* grown = u_realloc(channel->peer_ids, (size_t)next * sizeof(uint64_t));
|
|
if (!grown) { prc = SQLITE_NOMEM; break; }
|
|
channel->peer_ids = grown; peer_capacity = next;
|
|
}
|
|
channel->peer_ids[channel->peer_count++] = (uint64_t)sqlite3_column_int64(peers, 0);
|
|
}
|
|
int final = sqlite3_finalize(peers);
|
|
if (prc != SQLITE_DONE || final != SQLITE_OK) { rc = prc == SQLITE_DONE ? final : prc; break; }
|
|
}
|
|
int final = sqlite3_finalize(st);
|
|
char (*notifications)[64] = count ? u_malloc((size_t)count * 64) : NULL;
|
|
if (rc != SQLITE_DONE || final != SQLITE_OK || (count && !notifications)) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "channel cache refresh failed rc=%d finalize=%d channels=%d: %s",
|
|
rc, final, count, sqlite3_errmsg(db));
|
|
u_free(notifications); cs_cache_free(channels, count); return -1;
|
|
}
|
|
for (int i = 0; i < count; i++) strcpy(notifications[i], channels[i].channel_id);
|
|
cs_cache_free(cs->channels, cs->channel_count); cs->channels = channels; cs->channel_count = count;
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "channel cache refreshed channels=%d", count);
|
|
/* Получатель может удалить канал или инициировать новый refresh; имена принадлежат этому вызову. */
|
|
for (int i = 0; i < count; i++) cs_post_channel_online(cs, notifications[i]);
|
|
u_free(notifications); return 0;
|
|
}
|
|
|
|
static void refresh_timer_cb(void* arg) {
|
|
struct chat_sync* cs = (struct chat_sync*)arg;
|
|
if (!cs || !cs->initialized) return;
|
|
cs->refresh_timer = NULL;
|
|
#ifdef UTUN_HAVE_STANDBY
|
|
if (standby_get_sleep_tb() > 0) {
|
|
cs->refresh_wait = standby_wait(cs, refresh_timer_cb);
|
|
return;
|
|
}
|
|
cs->refresh_wait = NULL;
|
|
#endif
|
|
cs_refresh_channels(cs);
|
|
cs->refresh_timer = uasync_set_timeout(cs->inst->ua,
|
|
30u * 10000u, cs, refresh_timer_cb, "cs_refresh");
|
|
if (!cs->refresh_timer) DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "channel cache refresh timer allocation failed");
|
|
}
|
|
|
|
/* ── TTL cleanup ── */
|
|
|
|
|
|
/* ── Public API ── */
|
|
|
|
int chat_sync_init(struct UTUN_INSTANCE* inst) {
|
|
if (!inst || !inst->ua || !chat_core_is_initialized(inst)) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "chat_sync: running chat_core required"); return -1;
|
|
}
|
|
if (inst->chat_sync) return 0;
|
|
DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "%s: init", CS_ID);
|
|
struct chat_sync* cs = u_calloc(1, sizeof(*cs));
|
|
if (!cs) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "chat_sync context allocation failed"); return -1; }
|
|
cs->inst = inst;
|
|
cs->initialized = 1;
|
|
inst->chat_sync = cs;
|
|
cs->port = chat_join_port_create(inst);
|
|
if (!cs->port) { chat_join_port_close(cs->port); chat_join_port_release(cs->port); inst->chat_sync = NULL; u_free(cs); return -1; }
|
|
|
|
if (member_sync_init(inst) < 0) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "%s: member synchronization initialization failed", CS_ID);
|
|
chat_join_port_close(cs->port); chat_join_port_release(cs->port); inst->chat_sync = NULL; u_free(cs); return -1;
|
|
}
|
|
if (chat_feedback_init(inst) < 0) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: feedback initialization failed", CS_ID);
|
|
member_sync_destroy(inst); chat_join_port_close(cs->port); chat_join_port_release(cs->port); inst->chat_sync = NULL; u_free(cs); return -1;
|
|
}
|
|
if (db_sync_register_model(inst) < 0) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "%s: history model initialization failed", CS_ID);
|
|
member_sync_destroy(inst); chat_join_port_close(cs->port); chat_join_port_release(cs->port); inst->chat_sync = NULL; u_free(cs); return -1;
|
|
}
|
|
if (group_avatar_init(inst) < 0) {
|
|
member_sync_destroy(inst); chat_join_port_close(cs->port); chat_join_port_release(cs->port); inst->chat_sync = NULL; u_free(cs); return -1;
|
|
}
|
|
|
|
if (etcp_bind(inst, ETCP_ID_CHAT_SYNC, chat_sync_recv_cb)) goto fail;
|
|
cs->direct_bound = 1;
|
|
etcp_add_conn_status_cbk(inst, cs_on_conn_status, cs);
|
|
struct etcp_status_cbk_entry* status = inst->conn_status_cbks;
|
|
while (status && (status->fn != cs_on_conn_status || status->arg != cs)) status = status->next;
|
|
if (!status) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "chat_sync status subscription failed"); goto fail; }
|
|
|
|
if (cs_refresh_channels(cs)) goto fail;
|
|
|
|
cs->refresh_timer = uasync_set_timeout(inst->ua, 50000u, cs,
|
|
refresh_timer_cb, "cs_refresh");
|
|
if (!cs->refresh_timer) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "chat_sync refresh timer allocation failed"); goto fail; }
|
|
cs->info_req_timer = NULL;
|
|
cs->join_timer = NULL;
|
|
|
|
if (member_sync_add_apply_cbk(inst, cs_on_member_applied, cs)) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "%s: member apply subscription failed", CS_ID); chat_sync_destroy(inst); return -1;
|
|
}
|
|
utun_add_peer_sleep_cbk(inst, cs_on_peer_sleep, cs);
|
|
struct peer_sleep_cbk_entry* sleep = inst->peer_sleep_cbks;
|
|
while (sleep && (sleep->removed || sleep->fn != cs_on_peer_sleep || sleep->arg != cs)) sleep = sleep->next;
|
|
if (!sleep) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "chat_sync sleep subscription failed"); goto fail; }
|
|
if (chat_admin_init(inst)) goto fail;
|
|
cs->admin_bound = 1;
|
|
if (chat_join_init(inst)) goto fail;
|
|
cs->join_bound = 1;
|
|
|
|
/* После restart транспорт может уже быть UP: нового conn_up не будет. */
|
|
for (struct ll_entry* e = inst->connections ? inst->connections->head : NULL; e; e = e->next) {
|
|
struct conn_queue_entry* ce = (struct conn_queue_entry*)e->data;
|
|
cs_schedule_peer_sync(cs, ce->peer_node_id, "startup");
|
|
}
|
|
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: initialized", CS_ID);
|
|
return 0;
|
|
fail:
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "chat_sync initialization failed; releasing partial runtime");
|
|
chat_sync_destroy(inst); return -1;
|
|
}
|
|
|
|
void chat_sync_quiesce(struct UTUN_INSTANCE* inst) {
|
|
struct chat_sync* cs = cs_of(inst);
|
|
if (!cs) return;
|
|
cs->initialized = 0; chat_join_port_close(cs->port); cs_join_finish(cs, CHAT_CONNECT_CANCELLED);
|
|
}
|
|
void chat_sync_cancel_join(struct UTUN_INSTANCE* inst, uint64_t request) {
|
|
struct chat_sync* cs = cs_of(inst);
|
|
if (cs && cs->join.channel && cs->join.request == request) cs_join_finish(cs, CHAT_CONNECT_CANCELLED);
|
|
}
|
|
|
|
void chat_sync_destroy(struct UTUN_INSTANCE* inst) {
|
|
struct chat_sync* cs = cs_of(inst);
|
|
if (!cs || !inst) return;
|
|
DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "%s: destroy", CS_ID);
|
|
cs->initialized = 0;
|
|
chat_join_port_close(cs->port);
|
|
cs_join_finish(cs, CHAT_CONNECT_CANCELLED);
|
|
cs_cancel_sync(cs, 0, 0, "service_stop");
|
|
if (cs->invite_send_timer) { uasync_cancel_timeout(inst->ua, cs->invite_send_timer); cs->invite_send_timer = NULL; }
|
|
member_sync_remove_apply_cbk(inst, cs_on_member_applied, cs);
|
|
utun_remove_peer_sleep_cbk(inst, cs_on_peer_sleep, cs);
|
|
cs_pending_free_all(cs);
|
|
group_avatar_destroy(inst);
|
|
member_sync_destroy(inst);
|
|
if (cs->admin_bound) chat_admin_destroy(inst);
|
|
if (cs->join_bound) chat_join_destroy(inst);
|
|
cs->initialized = 0; inst->chat_sync = NULL;
|
|
|
|
if (cs->direct_bound) etcp_unbind(inst, ETCP_ID_CHAT_SYNC);
|
|
etcp_remove_conn_status_cbk(inst, cs_on_conn_status, cs);
|
|
if (cs->refresh_timer) { uasync_cancel_timeout(inst->ua, cs->refresh_timer); cs->refresh_timer = NULL; }
|
|
#ifdef UTUN_HAVE_STANDBY
|
|
if (cs->refresh_wait) { standby_wait_cancel(cs->refresh_wait); cs->refresh_wait = NULL; }
|
|
#endif
|
|
cs_cancel_proto_timers(cs);
|
|
cs_join_release_transport(cs);
|
|
|
|
cs_cache_free(cs->channels, cs->channel_count);
|
|
chat_join_port_release(cs->port);
|
|
u_free(cs);
|
|
}
|
|
|
|
struct chat_join_port* chat_sync_join_port(struct UTUN_INSTANCE* inst) {
|
|
struct chat_sync* cs = cs_of(inst);
|
|
if (!cs || !cs->initialized) return NULL;
|
|
chat_join_port_retain(cs->port); return cs->port;
|
|
}
|
|
|
|
void chat_sync_retry_channels_on_socket_change(struct UTUN_INSTANCE* inst) {
|
|
struct chat_sync* cs = cs_of(inst);
|
|
if (!cs || !cs->initialized || !inst->topo_groups) return;
|
|
for (int i = 0; i < cs->channel_count; i++) {
|
|
uint64_t gid = strtoull(cs->channels[i].channel_id, NULL, 10);
|
|
struct TOPO_GROUP* group = topo_groups_find(inst->topo_groups, gid);
|
|
if (!group || !group->connect) continue;
|
|
topo_group_connect_restart(group);
|
|
}
|
|
}
|
|
|
|
void chat_sync_on_channel_deleted(struct UTUN_INSTANCE* inst, const char* ch_id) {
|
|
struct chat_sync* cs = cs_of(inst);
|
|
uint64_t channel = chat_channel_id(ch_id);
|
|
if (!cs || !channel) return;
|
|
cs_cancel_sync(cs, 0, channel, "channel_deleted");
|
|
struct join_pending** link = &cs->join_pending;
|
|
while (*link) {
|
|
struct join_pending* item = *link;
|
|
if (strcmp(item->ch_id, ch_id)) { link = &item->next; continue; }
|
|
*link = item->next; u_free(item);
|
|
}
|
|
for (int i = 0; i < cs->pending_inv_in_count; ) {
|
|
if (cs->pending_inv_in_ch_id[i] == channel) cs_invitation_remove(cs, i); else i++;
|
|
}
|
|
for (int i = 0; i < cs->channel_count; i++) {
|
|
if (strcmp(cs->channels[i].channel_id, ch_id) != 0) continue;
|
|
if (cs->channels[i].peer_ids) u_free(cs->channels[i].peer_ids);
|
|
memmove(&cs->channels[i], &cs->channels[i + 1],
|
|
(size_t)(cs->channel_count - i - 1) * sizeof(struct channel_cache));
|
|
cs->channel_count--;
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: channel removed from cache ch=%s", CS_ID, ch_id);
|
|
break;
|
|
}
|
|
if (cs->join.channel == channel) cs_join_finish(cs, CHAT_CONNECT_CANCELLED);
|
|
}
|
|
|
|
static void cs_node_clear(struct TOPO_NODE* node) {
|
|
while (node->v4_addrs) { struct TOPO_ADDR4* next = node->v4_addrs->next; u_free(node->v4_addrs); node->v4_addrs = next; }
|
|
while (node->v6_addrs) { struct TOPO_ADDR6* next = node->v6_addrs->next; u_free(node->v6_addrs); node->v6_addrs = next; }
|
|
while (node->reality_socks) {
|
|
struct TOPO_REALITY_SOCK* next = node->reality_socks->next; u_free(node->reality_socks); node->reality_socks = next;
|
|
}
|
|
}
|
|
|
|
static int cs_connect_invite(struct UTUN_INSTANCE* inst, uint64_t request, const struct InviteData* data, uint64_t offer_channel) {
|
|
struct chat_sync* cs = cs_of(inst);
|
|
const struct InviteData invite = *data;
|
|
int rc = cs_join_reserve(cs, offer_channel ? offer_channel : invite.channelId, invite.nodeId, request, offer_channel != 0);
|
|
if (rc) return rc;
|
|
cs->join.server_offer = offer_channel && invite.kind == INVITE_KIND_SERVER;
|
|
if (cs->join.server_offer) {
|
|
memcpy(cs->join.add_key, invite.add_key, sizeof(cs->join.add_key));
|
|
cs->join.operation_timer = uasync_set_timeout(inst->ua, 300000, cs, cs_server_operation_timeout, "server_join_deadline");
|
|
if (!cs->join.operation_timer) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_CHAT_SYNC, "server join deadline allocation failed");
|
|
cs_join_end(cs, CHAT_CONNECT_ERROR, 0); return CHAT_CONNECT_ERROR;
|
|
}
|
|
}
|
|
struct TOPO_NODE node = { .node_id = invite.nodeId };
|
|
memcpy(node.public_key, invite.pubkey, 32);
|
|
for (unsigned i = 0; i < invite.addrCount; i++) {
|
|
const struct InviteAddr* source = &invite.addrs[i];
|
|
if (source->family == 4) {
|
|
struct TOPO_ADDR4* a = u_calloc(1, sizeof(*a));
|
|
if (!a) goto failure;
|
|
memcpy(a->addr, source->address, 4); a->port = source->port;
|
|
a->socket_id = source->socketId; a->protocol = source->proto; a->type = TOPO_ADDR_NAT;
|
|
a->next = node.v4_addrs; node.v4_addrs = a;
|
|
} else {
|
|
struct TOPO_ADDR6* a = u_calloc(1, sizeof(*a));
|
|
if (!a) goto failure;
|
|
memcpy(a->addr, source->address, 16); a->port = source->port;
|
|
a->socket_id = source->socketId; a->protocol = source->proto; a->type = TOPO_ADDR_NAT;
|
|
a->next = node.v6_addrs; node.v6_addrs = a;
|
|
}
|
|
if (source->proto & INVITE_PROTO_REALITY) {
|
|
struct TOPO_REALITY_SOCK* r = u_calloc(1, sizeof(*r));
|
|
if (!r) goto failure;
|
|
r->socket_id = source->socketId; memcpy(r->short_id, invite.reality.short_id, 8);
|
|
memcpy(r->server_pubkey, invite.reality.server_pubkey, 32); memcpy(r->version, invite.reality.version, 3);
|
|
snprintf(r->server_name, sizeof(r->server_name), "%s", invite.reality.server_name);
|
|
r->next = node.reality_socks; node.reality_socks = r;
|
|
}
|
|
}
|
|
cs->join.key = invite.join_key; memcpy(cs->join.password, invite.password, sizeof(cs->join.password));
|
|
rc = cs_join_hold_transport(cs, invite.nodeId, &node);
|
|
if (rc < 0) goto failure;
|
|
struct ETCP_CONN* conn = node_conn_direct_get_conn(cs->join.handle);
|
|
if (conn && conn->links_up && conn->initialized) {
|
|
int started = offer_channel ? cs_start_channel_offer(cs, invite.nodeId) : cs_start_channel_join(cs, invite.nodeId);
|
|
if (started < 0) goto failure;
|
|
}
|
|
cs_node_clear(&node);
|
|
return 0;
|
|
failure:
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "join preparation failed request=%llu", (unsigned long long)request);
|
|
cs_node_clear(&node);
|
|
cs_join_end(cs, CHAT_CONNECT_ERROR, 0);
|
|
return CHAT_CONNECT_ERROR;
|
|
}
|
|
|
|
int chat_sync_join_link(struct UTUN_INSTANCE* inst, uint64_t request, const char* link, size_t len) {
|
|
struct InviteData invite;
|
|
if (invite_link_decode(link, len, &invite, NULL, 0) || invite.kind != INVITE_KIND_CHANNEL) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_CHAT_SYNC, "ordinary JOIN requires a channel invitation"); return CHAT_CONNECT_INVALID;
|
|
}
|
|
return cs_connect_invite(inst, request, &invite, 0);
|
|
}
|
|
int chat_sync_offer_link(struct UTUN_INSTANCE* inst, uint64_t request, uint64_t channel, const char* link, size_t len) {
|
|
struct InviteData invite;
|
|
if (!channel || invite_link_decode(link, len, &invite, NULL, 0)) return CHAT_CONNECT_INVALID;
|
|
return cs_connect_invite(inst, request, &invite, channel);
|
|
}
|
|
|
|
/* ─── chat_sync_join_channel: join channel via already-connected peer ─── */
|
|
|
|
static int cs_join_existing(struct UTUN_INSTANCE* inst, const char* channel, uint64_t peer, uint64_t key) {
|
|
struct chat_sync* cs = cs_of(inst);
|
|
uint64_t group = chat_channel_id(channel);
|
|
int rc = cs_join_reserve(cs, group, peer, 0, 0);
|
|
if (rc) return rc;
|
|
cs->join.key = key;
|
|
if (cs_join_hold_transport(cs, peer, NULL) < 0 || cs_start_channel_join(cs, peer) < 0) {
|
|
cs_join_finish(cs, CHAT_CONNECT_ERROR); return CHAT_CONNECT_ERROR;
|
|
}
|
|
return 0;
|
|
}
|
|
/* ─── JOIN_INFO_REQ (0x10): joiner → connection-узел ─── */
|
|
|
|
static void cs_handle_join_info_req(struct chat_sync* cs, uint64_t peer,
|
|
const char* ch_id, const uint8_t* pl, size_t len, uint64_t attempt) {
|
|
/* payload: [join_key:8][pass_len:1][password] */
|
|
if (len < 9 || pl[8] >= INVITE_PASS_MAX || len != 9 + (size_t)pl[8] || memchr(pl + 9, 0, pl[8])) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: invalid JOIN_INFO_REQ size=%zu", CS_ID, len); return;
|
|
}
|
|
uint64_t join_key; memcpy(&join_key, pl, 8);
|
|
uint64_t channel_id = strtoull(ch_id, NULL, 10);
|
|
DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_INFO_REQ ch=%s from=%016llx len=%zu",
|
|
CS_ID, ch_id, (unsigned long long)peer, len);
|
|
|
|
/* 1. валидация join-ключа (зарегистрирован инвайтером на connection-узле, TTL 10 мин) */
|
|
uint64_t inviter = chat_join_lookup_inviter(cs->inst, channel_id, join_key);
|
|
if (inviter == 0) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_INFO_REQ invalid/expired join key ch=%s from=%016llx",
|
|
CS_ID, ch_id, (unsigned long long)peer);
|
|
uint8_t err[1] = { CS_MSG_ERROR }; cs_send_attempt(cs, ch_id, peer, err, 1, attempt);
|
|
return;
|
|
}
|
|
|
|
/* 2. инфо канала */
|
|
char name[128]; uint64_t owner; uint8_t ch_x25519[32], ch_ed[32], ch_sig[64];
|
|
if (topo_node_sqlite_channel_get(cs->inst->topo_sqlite_db,
|
|
ch_id, name, (int)sizeof(name), &owner, ch_x25519, ch_ed, ch_sig) != 0) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_INFO_REQ unknown ch=%s from=%016llx", CS_ID, ch_id, (unsigned long long)peer);
|
|
uint8_t err[1] = { CS_MSG_ERROR }; cs_send_attempt(cs, ch_id, peer, err, 1, attempt);
|
|
return;
|
|
}
|
|
|
|
/* 4. мой мембер-рекорд (join_sig/update_sig + дерево приглашений) */
|
|
uint64_t myid = cs->inst->node_id;
|
|
uint8_t my_join_sig[64] = {0}; uint64_t my_join_ts = 0;
|
|
{
|
|
sqlite3* vdb = cs->inst->topo_sqlite_db;
|
|
if (topo_node_sqlite_member_get_join(vdb, ch_id, myid, my_join_sig, &my_join_ts) != 0) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "JOIN_INFO_REQ: own JOIN unavailable ch=%s", ch_id);
|
|
uint8_t error = CS_MSG_ERROR; cs_send_attempt(cs, ch_id, peer, &error, 1, attempt); return;
|
|
}
|
|
}
|
|
uint8_t my_update_sig[64] = {0}; uint64_t my_update_ts;
|
|
char juser[MS_USERINFO_MAX + 1];
|
|
if (chat_core_get_my_profile(cs->inst, ch_id, juser, sizeof(juser), my_update_sig, &my_update_ts) < 0) {
|
|
chat_core_update_my_member(cs->inst);
|
|
if (chat_core_get_my_profile(cs->inst, ch_id, juser, sizeof(juser), my_update_sig, &my_update_ts) < 0) {
|
|
uint8_t err[1] = { CS_MSG_ERROR }; cs_send_attempt(cs, ch_id, peer, err, sizeof(err), attempt); return;
|
|
}
|
|
}
|
|
uint64_t my_signed_by = 0; uint8_t my_signature[64] = {0};
|
|
if (topo_node_sqlite_member_get_sign(cs->inst->topo_sqlite_db, ch_id, myid, &my_signed_by, my_signature)) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "JOIN_INFO_REQ: own invitation unavailable ch=%s", ch_id);
|
|
uint8_t error = CS_MSG_ERROR; cs_send_attempt(cs, ch_id, peer, &error, 1, attempt); return;
|
|
}
|
|
|
|
/* 5. JOIN_INFO_RESP: инфо канала + мой мембер-рекорд */
|
|
size_t il = strlen(juser);
|
|
|
|
uint8_t buf[MS_USERINFO_MAX + 768]; size_t boff = 0;
|
|
buf[boff++] = CS_MSG_JOIN_INFO_RESP;
|
|
uint8_t cnl = (uint8_t)strlen(name); buf[boff++] = cnl; memcpy(buf + boff, name, cnl); boff += cnl;
|
|
memcpy(buf + boff, &owner, 8); boff += 8;
|
|
memcpy(buf + boff, ch_x25519, 32); boff += 32;
|
|
memcpy(buf + boff, ch_ed, 32); boff += 32;
|
|
memcpy(buf + boff, ch_sig, 64); boff += 64;
|
|
memcpy(buf + boff, &myid, 8); boff += 8;
|
|
memcpy(buf + boff, cs->inst->my_keys.public_key, 32); boff += 32;
|
|
memcpy(buf + boff, cs->inst->my_ed25519_pubkey, 32); boff += 32;
|
|
memcpy(buf + boff, my_join_sig, 64); boff += 64;
|
|
memcpy(buf + boff, &my_join_ts, 8); boff += 8;
|
|
memcpy(buf + boff, my_update_sig, 64); boff += 64;
|
|
memcpy(buf + boff, &my_update_ts, 8); boff += 8;
|
|
buf[boff++] = (uint8_t)(il >> 8); buf[boff++] = (uint8_t)il; memcpy(buf + boff, juser, il); boff += il;
|
|
memcpy(buf + boff, &my_signed_by, 8); boff += 8;
|
|
memcpy(buf + boff, my_signature, 64); boff += 64;
|
|
cs_send_attempt(cs, ch_id, peer, buf, boff, attempt);
|
|
}
|
|
|
|
/* ─── JOIN_INFO_RESP (0x11): connection-узел → joiner ─── */
|
|
|
|
static void cs_handle_join_info_resp(struct chat_sync* cs, uint64_t peer,
|
|
const char* ch_id, const uint8_t* pl, size_t len) {
|
|
DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_INFO_RESP ch=%s from=%016llx len=%zu", CS_ID, ch_id, (unsigned long long)peer, len);
|
|
if (len < 1) { DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_INFO_RESP too short len=%zu", CS_ID, len); return; }
|
|
const uint8_t* p = pl;
|
|
uint8_t cnl = *p++;
|
|
if (1 + cnl + 8 + 32 + 32 + 64 + 8 + 32 + 32 + 64 + 8 + 64 + 8 + 2 + 8 + 64 > len) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_INFO_RESP truncated len=%zu", CS_ID, len); return;
|
|
}
|
|
if (cnl >= 128 || memchr(p, 0, cnl)) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "JOIN_INFO_RESP: invalid name length=%u", cnl); return;
|
|
}
|
|
char name[128]; memcpy(name, p, cnl); name[cnl] = '\0'; p += cnl;
|
|
uint64_t owner; memcpy(&owner, p, 8); p += 8;
|
|
const uint8_t* ch_x25519 = p; p += 32;
|
|
const uint8_t* ch_ed = p; p += 32;
|
|
const uint8_t* ch_sig = p; p += 64;
|
|
|
|
uint64_t c_node_id; memcpy(&c_node_id, p, 8); p += 8;
|
|
const uint8_t* c_x25519 = p; p += 32;
|
|
const uint8_t* c_ed = p; p += 32;
|
|
const uint8_t* c_join_sig = p; p += 64;
|
|
uint64_t c_join_ts; memcpy(&c_join_ts, p, 8); p += 8;
|
|
const uint8_t* c_update_sig = p; p += 64;
|
|
uint64_t c_update_ts; memcpy(&c_update_ts, p, 8); p += 8;
|
|
size_t c_uil = ((size_t)p[0] << 8) | p[1]; p += 2;
|
|
char c_userinfo[MS_USERINFO_MAX + 1] = "";
|
|
if (c_uil > MS_USERINFO_MAX || (size_t)(pl + len - p) != c_uil + 8 + 64 || memchr(p, 0, c_uil)) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_INFO_RESP invalid profile bytes=%zu remaining=%zu", CS_ID, c_uil,
|
|
(size_t)(pl + len - p)); return;
|
|
}
|
|
memcpy(c_userinfo, p, c_uil); p += c_uil;
|
|
uint64_t c_signed_by; memcpy(&c_signed_by, p, 8); p += 8;
|
|
const uint8_t* c_signature = p; p += 64;
|
|
|
|
uint64_t ch_x_prefix, ch_ed_prefix;
|
|
memcpy(&ch_x_prefix, ch_x25519, sizeof(ch_x_prefix)); memcpy(&ch_ed_prefix, ch_ed, sizeof(ch_ed_prefix));
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_INFO_RESP from=%016llx owner=%016llx ch_x=%016llx ch_ed=%016llx name=%s conn_node=%016llx",
|
|
CS_ID, (unsigned long long)peer, (unsigned long long)owner,
|
|
(unsigned long long)ch_x_prefix, (unsigned long long)ch_ed_prefix, name, (unsigned long long)c_node_id);
|
|
|
|
/* verify channel signature */
|
|
uint8_t vmsg[CHAT_CHANNEL_DESCRIPTION_MAX];
|
|
int vlen = chat_channel_description_data(ch_id, name, owner, ch_x25519, ch_ed, vmsg, sizeof(vmsg));
|
|
if (vlen < 0 || sc_ed25519_verify(ch_ed, vmsg, (size_t)vlen, ch_sig) != SC_OK) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_INFO_RESP invalid ch_sig ch=%s", CS_ID, ch_id);
|
|
return;
|
|
}
|
|
|
|
uint8_t known_x[32], known_ed[32];
|
|
int known = topo_node_sqlite_channel_get(cs->inst->topo_sqlite_db, ch_id, NULL, 0, NULL, known_x, known_ed, NULL);
|
|
if (known == TOPO_SQLITE_LOOKUP_ERROR || (known == 0 &&
|
|
(memcmp(known_x, ch_x25519, 32) || memcmp(known_ed, ch_ed, 32)))) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "join response conflicts with known channel keys"); cs_join_finish(cs, CHAT_CONNECT_ERROR); return;
|
|
}
|
|
/* Запись описания и участника атомарна; runtime-группа публикуется после commit. */
|
|
sqlite3* db = cs->inst->topo_sqlite_db;
|
|
struct ms_member_rec connection_member = {
|
|
.node_id = c_node_id, .x25519 = c_x25519, .ed25519 = c_ed,
|
|
.join_sig = c_join_sig, .join_ts = c_join_ts, .update_sig = c_update_sig, .update_ts = c_update_ts,
|
|
.userinfo = c_userinfo, .signed_by = c_signed_by, .signature = c_signature
|
|
};
|
|
struct ETCP_CONN* response_conn = cs_find_conn_for_node(cs->inst, peer);
|
|
if (!response_conn || c_node_id != peer || memcmp(c_x25519, response_conn->crypto_ctx.peer_public_key, 32)) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "join response connection identity mismatch"); cs_join_finish(cs, CHAT_CONNECT_ERROR); return;
|
|
}
|
|
if (!sqlite3_get_autocommit(db) || sqlite3_exec(db, "SAVEPOINT join_channel", NULL, NULL, NULL) != SQLITE_OK) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "join transaction begin: %s", sqlite3_errmsg(db)); cs_join_finish(cs, CHAT_CONNECT_ERROR); return;
|
|
}
|
|
int mrc = -1;
|
|
if (topo_node_sqlite_channel_put(db, ch_id, name, owner, ch_x25519, NULL, ch_ed, NULL, ch_sig) == 0 &&
|
|
topo_node_sqlite_member_local_init(db, ch_id) == 0 && chat_feedback_ensure_channel(cs->inst, ch_id) == 0)
|
|
mrc = member_sync_apply_record(cs->inst, ch_id, peer, &connection_member);
|
|
if (mrc < 0 || sqlite3_exec(db, "RELEASE join_channel", NULL, NULL, NULL) != SQLITE_OK) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "join channel commit failed member=%d: %s", mrc, sqlite3_errmsg(db));
|
|
if (sqlite3_exec(db, "ROLLBACK TO join_channel; RELEASE join_channel", NULL, NULL, NULL) != SQLITE_OK)
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "join channel rollback failed: %s", sqlite3_errmsg(db));
|
|
if (!sqlite3_get_autocommit(db)) utun_instance_stop(cs->inst);
|
|
cs_join_finish(cs, CHAT_CONNECT_ERROR); return;
|
|
}
|
|
if (cs->info_req_timer) { uasync_cancel_timeout(cs->inst->ua, cs->info_req_timer); cs->info_req_timer = NULL; }
|
|
uint64_t active_attempt = cs->join.attempt;
|
|
if (chat_core_ensure_channel_ready(cs->inst, ch_id) < 0) { cs_join_finish(cs, CHAT_CONNECT_ERROR); return; }
|
|
member_sync_record_committed(cs->inst, ch_id, c_node_id, (unsigned)mrc);
|
|
if (cs->join.attempt != active_attempt || cs->join.phase != 2) return; /* UI мог отменить JOIN/удалить канал. */
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "join channel committed ch=%s member=%016llx", ch_id, (unsigned long long)c_node_id);
|
|
|
|
/* построить собственный join_sig */
|
|
uint64_t myid = cs->inst->node_id;
|
|
const uint8_t* my_x25519 = cs->inst->my_keys.public_key;
|
|
uint8_t join_sig[64]; uint64_t join_ts;
|
|
{
|
|
uint8_t msg[128];
|
|
join_ts = (uint64_t)ntp_time_get_seconds(cs->inst);
|
|
int mlen = member_sync_build_join_msg(ch_x25519, ch_ed, myid, my_x25519, join_ts, msg, (int)sizeof(msg));
|
|
if (mlen < 0) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "join signature input invalid"); cs_join_finish(cs, CHAT_CONNECT_ERROR); return; }
|
|
if (sc_ed25519_sign(cs->inst->my_ed25519_privkey, msg, (size_t)mlen, join_sig) != SC_OK) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "join signing failed"); cs_join_finish(cs, CHAT_CONNECT_ERROR); return;
|
|
}
|
|
}
|
|
uint8_t my_update_sig[64] = {0}; uint64_t my_update_ts;
|
|
char own_info[MS_USERINFO_MAX + 1];
|
|
if (chat_core_name_userinfo(cs->inst->name, own_info, sizeof(own_info)) < 0) { cs_join_finish(cs, CHAT_CONNECT_ERROR); return; }
|
|
{
|
|
my_update_ts = (uint64_t)ntp_time_get_seconds(cs->inst);
|
|
uint8_t umsg[MS_USERINFO_MAX + 73];
|
|
int ulen = member_sync_build_update_msg(join_sig, my_update_ts, own_info, umsg, (int)sizeof(umsg));
|
|
if (ulen < 0 || sc_ed25519_sign(cs->inst->my_ed25519_privkey, umsg, (size_t)ulen, my_update_sig) != SC_OK) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "join profile signing failed"); cs_join_finish(cs, CHAT_CONNECT_ERROR); return;
|
|
}
|
|
}
|
|
|
|
/* send JOIN_REQUEST: [join_key:8][member...] */
|
|
struct join_member_data jm;
|
|
memset(&jm, 0, sizeof(jm));
|
|
jm.node_id = myid; jm.x25519 = my_x25519; jm.ed25519 = cs->inst->my_ed25519_pubkey;
|
|
jm.join_sig = join_sig; jm.join_ts = join_ts;
|
|
jm.update_sig = my_update_sig; jm.update_ts = my_update_ts;
|
|
snprintf(jm.userinfo, sizeof(jm.userinfo), "%s", own_info);
|
|
|
|
uint8_t jm_buf[MS_USERINFO_MAX + 256]; size_t jm_len = 0;
|
|
if (chat_join_serialize_member(&jm, jm_buf, sizeof(jm_buf), &jm_len) != 0) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_REQUEST serialize failed", CS_ID);
|
|
cs_join_finish(cs, CHAT_CONNECT_ERROR); return;
|
|
}
|
|
uint8_t jbuf[MS_USERINFO_MAX + 265]; size_t joff = 0;
|
|
jbuf[joff++] = CS_MSG_JOIN_REQUEST;
|
|
memcpy(jbuf + joff, &cs->join.key, 8); joff += 8;
|
|
memcpy(jbuf + joff, jm_buf, jm_len); joff += jm_len;
|
|
cs->join_timer = uasync_set_timeout(cs->inst->ua, CS_JOIN_TIMEOUT_MS * 10, cs, cs_join_timeout_cb, "cs_join");
|
|
if (!cs->join_timer) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "join ready deadline allocation failed"); cs_join_finish(cs, CHAT_CONNECT_ERROR); return; }
|
|
cs->join.phase = 3;
|
|
int jrc = cs_send_attempt(cs, ch_id, peer, jbuf, joff, cs->join.attempt);
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_REQUEST sent myid=%016llx ch=%s to=0x%016llx rc=%d",
|
|
CS_ID, (unsigned long long)myid, ch_id, (unsigned long long)peer, jrc);
|
|
if (jrc) cs_join_finish(cs, CHAT_CONNECT_ERROR);
|
|
}
|
|
|
|
/* ─── pending-джойнеры (connection-узел): node_id → прямое соединение ─── */
|
|
|
|
static int cs_pending_add(struct chat_sync* cs, uint64_t node_id, const char* ch_id, struct ETCP_CONN* conn, uint64_t attempt) {
|
|
(void)conn;
|
|
unsigned count = 0; uint64_t now = get_time_tb();
|
|
struct join_pending** link = &cs->join_pending;
|
|
while (*link) {
|
|
struct join_pending* item = *link;
|
|
if (item->expires <= now) { *link = item->next; u_free(item); continue; }
|
|
if (item->node_id == node_id) {
|
|
if (item->attempt == attempt && !strcmp(item->ch_id, ch_id)) return 0;
|
|
count++;
|
|
}
|
|
link = &item->next;
|
|
}
|
|
if (count >= 8) { DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "too many pending join attempts for peer"); return -1; }
|
|
struct join_pending* jp = u_calloc(1, sizeof(*jp));
|
|
if (!jp) { DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "join waiter allocation failed"); return -1; }
|
|
jp->attempt = attempt; jp->node_id = node_id; jp->expires = now + CS_JOIN_TIMEOUT_MS * 10;
|
|
snprintf(jp->ch_id, sizeof(jp->ch_id), "%s", ch_id); jp->next = cs->join_pending; cs->join_pending = jp;
|
|
return 0;
|
|
}
|
|
|
|
static void cs_pending_free_all(struct chat_sync* cs) {
|
|
struct join_pending* jp = cs->join_pending;
|
|
while (jp) { struct join_pending* n = jp->next; u_free(jp); jp = n; }
|
|
cs->join_pending = NULL;
|
|
}
|
|
|
|
static void cs_pending_prune(struct chat_sync* cs) {
|
|
uint64_t now = get_time_tb();
|
|
struct join_pending** link = &cs->join_pending;
|
|
while (*link) {
|
|
struct join_pending* item = *link;
|
|
if (item->expires > now) { link = &item->next; continue; }
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "join waiter expired peer=%016llx attempt=%016llx",
|
|
(unsigned long long)item->node_id, (unsigned long long)item->attempt);
|
|
*link = item->next; u_free(item);
|
|
}
|
|
}
|
|
|
|
/* ─── отправка JOIN_READY джойнеру + снятие pending (connection-узел) ─── */
|
|
|
|
static void cs_send_join_ready(struct chat_sync* cs, const char* ch_id, uint64_t node_id) {
|
|
uint64_t group = strtoull(ch_id, NULL, 10);
|
|
uint8_t data[9] = { CS_MSG_JOIN_READY }; memcpy(data + 1, &group, 8);
|
|
struct join_pending** link = &cs->join_pending;
|
|
while (*link) {
|
|
struct join_pending* pending = *link;
|
|
if (pending->node_id != node_id || strcmp(pending->ch_id, ch_id)) { link = &pending->next; continue; }
|
|
if (cs_send_attempt(cs, ch_id, node_id, data, sizeof(data), pending->attempt)) { link = &pending->next; continue; }
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "join ready peer=%016llx attempt=%016llx",
|
|
(unsigned long long)node_id, (unsigned long long)pending->attempt);
|
|
*link = pending->next; u_free(pending);
|
|
}
|
|
cs_schedule_sync(cs, group, node_id, "join_accepted");
|
|
}
|
|
|
|
static void cs_on_member_applied(const char* ch_id, uint64_t node_id, const uint8_t* x25519,
|
|
uint64_t signed_by, const uint8_t* signature, void* arg) {
|
|
(void)x25519; (void)signed_by; (void)signature;
|
|
struct chat_sync* cs = arg;
|
|
if (cs && cs->initialized && topo_node_sqlite_member_allowed(cs->inst->topo_sqlite_db, ch_id, node_id))
|
|
cs_send_join_ready(cs, ch_id, node_id);
|
|
}
|
|
|
|
/* ─── JOIN_REQUEST (0x12): joiner → connection-узел ─── */
|
|
|
|
static void cs_handle_join_request(struct chat_sync* cs, uint64_t peer,
|
|
const char* ch_id, const uint8_t* pl, size_t len, uint64_t attempt) {
|
|
/* payload: [join_key:8][member...] */
|
|
if (len < 8 + 1) { DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_REQUEST too short len=%zu peer=%016llx", CS_ID, len, (unsigned long long)peer); return; }
|
|
uint64_t join_key; memcpy(&join_key, pl, 8);
|
|
uint64_t channel_id = strtoull(ch_id, NULL, 10);
|
|
const uint8_t* member_data = pl + 8; size_t member_len = len - 8;
|
|
|
|
struct join_member_data m;
|
|
if (chat_join_parse_member(member_data, member_len, &m) != 0) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_REQUEST parse failed ch=%s from=%016llx", CS_ID, ch_id, (unsigned long long)peer);
|
|
return;
|
|
}
|
|
DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_REQUEST ch=%s joiner=%016llx from=%016llx",
|
|
CS_ID, ch_id, (unsigned long long)m.node_id, (unsigned long long)peer);
|
|
|
|
/* привязка идентичности: pubkey из ETCP-соединения == заявленный x25519 */
|
|
struct ETCP_CONN* jconn = cs_find_conn_for_node(cs->inst, peer);
|
|
if (!jconn || m.node_id != peer || memcmp(jconn->crypto_ctx.peer_public_key, m.x25519, 32) != 0) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_REQUEST identity mismatch joiner=0x%016llx peer=0x%016llx — drop",
|
|
CS_ID, (unsigned long long)m.node_id, (unsigned long long)peer);
|
|
return;
|
|
}
|
|
|
|
/* валидация ключа */
|
|
uint64_t inviter = chat_join_lookup_inviter(cs->inst, channel_id, join_key);
|
|
if (inviter == 0) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_REQUEST invalid/expired join key ch=%s joiner=0x%016llx",
|
|
CS_ID, ch_id, (unsigned long long)m.node_id);
|
|
uint8_t err[1] = { CS_MSG_ERROR }; cs_send_attempt(cs, ch_id, peer, err, 1, attempt);
|
|
return;
|
|
}
|
|
|
|
/* Ключ разрешает протокол добавления. BGP начнётся после сохранения мембера,
|
|
локально либо через Merkle; существующий транспорт обслуживает JOIN_REQUEST. */
|
|
|
|
/* добавить в pending (ждут JOIN_READY по приходу рекорда через merkle) */
|
|
if (cs_pending_add(cs, m.node_id, ch_id, jconn, attempt) < 0) return;
|
|
|
|
/* форвард инвайтеру (или локальная обработка, если инвайтер == мы) */
|
|
if (inviter == cs->inst->node_id) {
|
|
chat_join_process_request(cs->inst, channel_id, peer, join_key, member_data, member_len);
|
|
/* мы и есть connection-узел + инвайтер: рекорд добавлен локально,
|
|
merkle-apply-коллбэк (cs_on_member_applied) здесь не сработает —
|
|
отправляем JOIN_READY напрямую, если мембер реально добавлен. */
|
|
if (topo_node_sqlite_member_allowed(cs->inst->topo_sqlite_db, ch_id, m.node_id)) {
|
|
cs_send_join_ready(cs, ch_id, m.node_id);
|
|
if (cs->join.inviter && !cs->join.server_offer && cs->join.channel == channel_id &&
|
|
cs->join.peer == m.node_id && cs->join.key == join_key)
|
|
cs_join_finish(cs, 0);
|
|
} else {
|
|
uint8_t error = CS_MSG_ERROR; cs_send_attempt(cs, ch_id, peer, &error, 1, attempt);
|
|
}
|
|
} else {
|
|
if (chat_join_forward_request(cs->inst, channel_id, inviter, join_key, &m) < 0) {
|
|
uint8_t error = CS_MSG_ERROR; cs_send_attempt(cs, ch_id, peer, &error, 1, attempt);
|
|
} else if (topo_node_sqlite_member_allowed(cs->inst->topo_sqlite_db, ch_id, m.node_id)) cs_send_join_ready(cs, ch_id, m.node_id);
|
|
}
|
|
|
|
cs_refresh_channels(cs);
|
|
cs_post_channel_online(cs, ch_id);
|
|
}
|
|
|
|
/* ─── JOIN_READY (0x13): connection-узел → joiner (можно запускать BGP) ─── */
|
|
|
|
static void cs_handle_join_ready(struct chat_sync* cs, uint64_t peer,
|
|
const char* ch_id, const uint8_t* pl, size_t len) {
|
|
if (len != 8) { DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "invalid JOIN_READY size=%zu", len); cs_join_finish(cs, CHAT_CONNECT_ERROR); return; }
|
|
uint64_t group_id; memcpy(&group_id, pl, 8);
|
|
if (group_id != cs->join.channel) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "JOIN_READY group mismatch"); cs_join_finish(cs, CHAT_CONNECT_ERROR); return;
|
|
}
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: JOIN_READY ch=%s group=%016llx from=%016llx — joining complete, starting BGP",
|
|
CS_ID, ch_id, (unsigned long long)group_id, (unsigned long long)peer);
|
|
|
|
/* запуск BGP + полноценное участие в канале */
|
|
{
|
|
struct TOPO_GROUP* g = topo_groups_find(cs->inst->topo_groups, group_id);
|
|
if (g && g->group_type == TOPO_GROUP_TYPE_CHAT) {
|
|
struct ETCP_CONN* c = cs_find_conn_for_node(cs->inst, peer);
|
|
if (c) topo_group_connect_node_once(g, c->peer_node_id);
|
|
}
|
|
}
|
|
if (chat_core_ensure_channel_ready(cs->inst, ch_id)) { cs_join_finish(cs, CHAT_CONNECT_ERROR); return; }
|
|
cs_refresh_channels(cs);
|
|
/* Транспорт может быть открыт до добавления участника, без нового UP. */
|
|
cs_schedule_sync(cs, strtoull(ch_id, NULL, 10), peer, "join_ready");
|
|
|
|
uint8_t evt[65]; uint8_t ch_id_len = (uint8_t)strlen(ch_id);
|
|
evt[0] = ch_id_len; memcpy(evt + 1, ch_id, ch_id_len);
|
|
chat_event_post(cs->inst, CHAT_EVT_CHANNEL_UPDATED, evt, 1 + ch_id_len);
|
|
cs_post_channel_online(cs, ch_id);
|
|
|
|
cs_join_finish(cs, 0);
|
|
}
|
|
|
|
/* ─── CHANNEL_INVITE (0x0F): inviter → joiner (push-приглашение в канал) ─── */
|
|
|
|
static void cs_handle_channel_invite(struct chat_sync* cs, uint64_t peer,
|
|
const char* ch_id, const uint8_t* pl, size_t len) {
|
|
if (cs->inst->config->global.chatserver_enabled) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_CHAT_SYNC, "server rejects unauthenticated CHANNEL_INVITE channel=%s peer=%016llx; use SERVER_JOIN_REQ",
|
|
ch_id, (unsigned long long)peer); return;
|
|
}
|
|
DEBUG_TRACE(DEBUG_CATEGORY_MEMBER_SYNC, "%s: CHANNEL_INVITE ch=%s from=%016llx len=%zu",
|
|
CS_ID, ch_id, (unsigned long long)peer, len);
|
|
if (len < 1 + 8 + 32 + 32 + 64 + 1 + 64 + 8 + 2 + 8) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: CHANNEL_INVITE too short len=%zu peer=%016llx", CS_ID, len, (unsigned long long)peer);
|
|
return;
|
|
}
|
|
/* Same payload format as CHANNEL_INFO_RESP */
|
|
const uint8_t* p = pl;
|
|
uint8_t nl = *p++;
|
|
if (nl >= 128 || 1 + nl + 8 + 32 + 32 + 64 + 1 + 64 + 8 + 2 + 8 > (int)len || memchr(p, 0, nl)) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: CHANNEL_INVITE truncated or name too long", CS_ID); return;
|
|
}
|
|
char name[128]; memcpy(name, p, nl); name[nl] = '\0'; p += nl;
|
|
uint64_t owner; memcpy(&owner, p, 8); p += 8;
|
|
const uint8_t* x25519 = p; p += 32;
|
|
const uint8_t* ed_pub = p; p += 32;
|
|
const uint8_t* ch_sig = p; p += 64;
|
|
uint8_t inv_flags = *p++;
|
|
if (inv_flags & ~PEERS_FLAG_HAS_JOIN) { DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "CHANNEL_INVITE: unknown flags=%u", inv_flags); return; }
|
|
const uint8_t* inviter_join_sig = NULL; uint64_t inviter_join_ts = 0;
|
|
if (inv_flags & PEERS_FLAG_HAS_JOIN) {
|
|
if (p + 72 > pl + len) { DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: CHANNEL_INVITE truncated at join_sig/ts from=%016llx", CS_ID, (unsigned long long)peer); return; }
|
|
inviter_join_sig = p; p += 64; memcpy(&inviter_join_ts, p, 8); p += 8; }
|
|
if ((size_t)(pl + len - p) < 64 + 8 + 2 + 8) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: CHANNEL_INVITE truncated profile header", CS_ID); return;
|
|
}
|
|
/* skip inviter_update_sig/ts/userinfo for now — verify channel sig only */
|
|
p += 64; uint64_t inviter_update_ts; memcpy(&inviter_update_ts, p, 8); p += 8;
|
|
size_t userinfo_len = ((size_t)p[0] << 8) | p[1]; p += 2;
|
|
if (userinfo_len > MS_USERINFO_MAX || (size_t)(pl + len - p) != userinfo_len + 8 || memchr(p, 0, userinfo_len)) {
|
|
DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: CHANNEL_INVITE invalid profile bytes=%zu", CS_ID, userinfo_len); return;
|
|
}
|
|
p += userinfo_len;
|
|
/* join-ключ (зарегистрирован инвайтером) — хвостовые 8 байт */
|
|
uint64_t join_key = 0;
|
|
if (p + 8 > pl + len) { DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "%s: CHANNEL_INVITE truncated (no join_key) from=%016llx", CS_ID, (unsigned long long)peer); return; }
|
|
memcpy(&join_key, p, 8); p += 8;
|
|
if (!join_key) { DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "CHANNEL_INVITE: missing join key"); return; }
|
|
|
|
/* Verify channel signature */
|
|
uint8_t vmsg[CHAT_CHANNEL_DESCRIPTION_MAX];
|
|
int vlen = chat_channel_description_data(ch_id, name, owner, x25519, ed_pub, vmsg, sizeof(vmsg));
|
|
if (vlen < 0 || sc_ed25519_verify(ed_pub, vmsg, (size_t)vlen, ch_sig) != SC_OK) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "%s: CHANNEL_INVITE invalid ch_sig ch=%s from=%016llx", CS_ID, ch_id, (unsigned long long)peer);
|
|
return;
|
|
}
|
|
|
|
/* Обычные узлы используют настройку GUI; сервер принимает только авторизованный SERVER_JOIN_REQ. */
|
|
int policy;
|
|
{
|
|
policy = chat_setting_get_int(cs->inst, "join_policy", 1);
|
|
}
|
|
DEBUG_DEBUG(DEBUG_CATEGORY_MEMBER_SYNC, "%s: CHANNEL_INVITE policy=%d (chatserver=%d) ch=%s from=%016llx",
|
|
CS_ID, policy, cs->inst->config->global.chatserver_enabled, ch_id, (unsigned long long)peer);
|
|
|
|
if (policy == 2) { /* deny */
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: CHANNEL_INVITE denied (policy=deny) ch=%s from=%016llx",
|
|
CS_ID, ch_id, (unsigned long long)peer);
|
|
return;
|
|
}
|
|
|
|
if (policy == 0) { /* autojoin */
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: CHANNEL_INVITE autojoin ch=%s from=%016llx owner=%016llx name=%s",
|
|
CS_ID, ch_id, (unsigned long long)peer, (unsigned long long)owner, name);
|
|
/* Описание и участника сохраняет проверенный JOIN_INFO_RESP. */
|
|
cs_join_existing(cs->inst, ch_id, peer, join_key);
|
|
return;
|
|
}
|
|
|
|
/* policy == ask — post event to GUI */
|
|
{
|
|
/* сохранить join-ключ, чтобы принять инвайт позже через chat_sync_accept_invite */
|
|
uint64_t ch_num = strtoull(ch_id, NULL, 10);
|
|
int slot = -1;
|
|
for (int i = 0; i < cs->pending_inv_in_count; i++)
|
|
if (cs->pending_inv_in_ch_id[i] == ch_num && cs->pending_inv_in_node_id[i] == peer) { slot = i; break; }
|
|
if (slot < 0 && cs->pending_inv_in_count < 4) slot = cs->pending_inv_in_count++;
|
|
if (slot >= 0) {
|
|
cs->pending_inv_in_ch_id[slot] = ch_num;
|
|
cs->pending_inv_in_node_id[slot] = peer;
|
|
cs->pending_inv_in_key[slot] = join_key;
|
|
} else { DEBUG_WARN(DEBUG_CATEGORY_MEMBER_SYNC, "CHANNEL_INVITE: pending invitation limit reached"); return; }
|
|
|
|
size_t inv_name_len = 0; char inv_name[128] = "";
|
|
chat_core_get_node_name(cs->inst, peer, inv_name, sizeof(inv_name)); inv_name_len = strlen(inv_name);
|
|
uint8_t evt[512]; int epos = 0;
|
|
uint8_t cl = (uint8_t)strlen(ch_id); evt[epos++] = cl; memcpy(evt + epos, ch_id, cl); epos += cl;
|
|
evt[epos++] = nl; memcpy(evt + epos, name, nl); epos += nl;
|
|
memcpy(evt + epos, &peer, 8); epos += 8;
|
|
evt[epos++] = (uint8_t)inv_name_len;
|
|
if (inv_name_len) { memcpy(evt + epos, inv_name, inv_name_len); epos += inv_name_len; }
|
|
chat_event_post(cs->inst, CHAT_EVT_INVITE_RECEIVED, evt, epos);
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: CHANNEL_INVITE ask posted to GUI ch=%s name=%s from=%016llx (%s)",
|
|
CS_ID, ch_id, name, (unsigned long long)peer, inv_name);
|
|
}
|
|
}
|
|
|
|
/* ─── helper: build and send CS_MSG_CHANNEL_INVITE to peer ─── */
|
|
|
|
static int cs_send_channel_invite(struct chat_sync* cs, struct UTUN_INSTANCE* inst,
|
|
const char* ch_id, uint64_t target_node_id,
|
|
const char* ch_name, uint64_t owner,
|
|
const uint8_t* ch_x25519, const uint8_t* ch_ed,
|
|
const uint8_t* ch_sig) {
|
|
uint8_t join_sig[64] = {0}; uint64_t join_ts = 0;
|
|
{ sqlite3* vdb = inst->topo_sqlite_db;
|
|
topo_node_sqlite_member_get_join(vdb, ch_id, inst->node_id, join_sig, &join_ts); }
|
|
uint8_t upd_sig[64] = {0}; uint64_t upd_ts;
|
|
char juser[MS_USERINFO_MAX + 1];
|
|
if (chat_core_get_my_profile(inst, ch_id, juser, sizeof(juser), upd_sig, &upd_ts) < 0) {
|
|
chat_core_update_my_member(inst);
|
|
if (chat_core_get_my_profile(inst, ch_id, juser, sizeof(juser), upd_sig, &upd_ts) < 0) return -1;
|
|
}
|
|
/* join-ключ: генерируем и регистрируем локально (инвайтер == connection-узел),
|
|
чтобы джойнер смог пройти JOIN_INFO_REQ с валидным ключом. */
|
|
uint64_t join_key = 0;
|
|
if (RAND_bytes((uint8_t*)&join_key, sizeof(join_key)) != 1 || join_key == 0) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "%s: join_key generation failed ch=%s", CS_ID, ch_id);
|
|
return -1;
|
|
}
|
|
if (chat_join_store_local_key(inst, strtoull(ch_id, NULL, 10), join_key) != 0) return -1;
|
|
if (cs->join.inviter && cs->join.peer == target_node_id) cs->join.key = join_key;
|
|
|
|
uint8_t buf[MS_USERINFO_MAX + 768]; size_t boff = 0;
|
|
buf[boff++] = CS_MSG_CHANNEL_INVITE;
|
|
uint8_t cnl = (uint8_t)strlen(ch_name);
|
|
buf[boff++] = cnl; memcpy(buf + boff, ch_name, cnl); boff += cnl;
|
|
memcpy(buf + boff, &owner, 8); boff += 8;
|
|
memcpy(buf + boff, ch_x25519, 32); boff += 32;
|
|
memcpy(buf + boff, ch_ed, 32); boff += 32;
|
|
memcpy(buf + boff, ch_sig, 64); boff += 64;
|
|
uint8_t inv_flags = (join_sig[0] || join_ts) ? PEERS_FLAG_HAS_JOIN : 0;
|
|
buf[boff++] = inv_flags;
|
|
if (inv_flags & PEERS_FLAG_HAS_JOIN) {
|
|
memcpy(buf + boff, join_sig, 64); boff += 64;
|
|
memcpy(buf + boff, &join_ts, 8); boff += 8;
|
|
}
|
|
memcpy(buf + boff, upd_sig, 64); boff += 64;
|
|
memcpy(buf + boff, &upd_ts, 8); boff += 8;
|
|
size_t il = strlen(juser);
|
|
buf[boff++] = (uint8_t)(il >> 8); buf[boff++] = (uint8_t)il; memcpy(buf + boff, juser, il); boff += il;
|
|
memcpy(buf + boff, &join_key, 8); boff += 8;
|
|
int rc = cs_send(cs, ch_id, target_node_id, buf, boff);
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: sent CHANNEL_INVITE to 0x%016llx ch=%s rc=%d",
|
|
CS_ID, (unsigned long long)target_node_id, ch_id, rc);
|
|
return rc;
|
|
}
|
|
|
|
/* ─── chat_sync_invite_to_channel: пригласить узел в наш канал ─── */
|
|
|
|
void chat_sync_invite_to_channel(struct UTUN_INSTANCE* inst, const char* channel, uint64_t peer) {
|
|
struct chat_sync* cs = cs_of(inst);
|
|
uint64_t group = chat_channel_id(channel);
|
|
if (cs_join_reserve(cs, group, peer, 0, 1)) return;
|
|
if (cs_join_hold_transport(cs, peer, NULL) < 0) { cs_join_finish(cs, CHAT_CONNECT_ERROR); return; }
|
|
struct ETCP_CONN* conn = node_conn_direct_get_conn(cs->join.handle);
|
|
if (conn && conn->initialized && conn->links_up && cs_start_channel_offer(cs, peer) < 0)
|
|
cs_join_finish(cs, CHAT_CONNECT_ERROR);
|
|
}
|
|
|
|
/* ─── accept/deny incoming invite ─── */
|
|
|
|
void chat_sync_accept_invite(struct UTUN_INSTANCE* inst, uint64_t channel_id, uint64_t inviter_node_id) {
|
|
struct chat_sync* cs = cs_of(inst);
|
|
if (!cs || !inst) return;
|
|
char ch_id[64]; snprintf(ch_id, sizeof(ch_id), "%llu", (unsigned long long)channel_id);
|
|
if (channel_id == 0 || channel_id > INT64_MAX || inviter_node_id == 0) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "%s: accept_invite invalid params ch=%llu node=%016llx",
|
|
CS_ID, (unsigned long long)channel_id, (unsigned long long)inviter_node_id);
|
|
return;
|
|
}
|
|
/* достать join-ключ, сохранённый при приёме CHANNEL_INVITE (ask) */
|
|
uint64_t join_key = 0; int slot = -1;
|
|
for (int i = 0; i < cs->pending_inv_in_count; i++) {
|
|
if (cs->pending_inv_in_ch_id[i] == channel_id && cs->pending_inv_in_node_id[i] == inviter_node_id) {
|
|
join_key = cs->pending_inv_in_key[i];
|
|
slot = i;
|
|
break;
|
|
}
|
|
}
|
|
if (join_key == 0) {
|
|
DEBUG_ERROR(DEBUG_CATEGORY_MEMBER_SYNC, "%s: accept_invite no join_key for ch=%llu inviter=0x%016llx",
|
|
CS_ID, (unsigned long long)channel_id, (unsigned long long)inviter_node_id);
|
|
return;
|
|
}
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: accept_invite ch=%llu inviter=0x%016llx",
|
|
CS_ID, (unsigned long long)channel_id, (unsigned long long)inviter_node_id);
|
|
if (!cs_join_existing(inst, ch_id, inviter_node_id, join_key)) cs_invitation_remove(cs, slot);
|
|
}
|
|
|
|
void chat_sync_deny_invite(struct UTUN_INSTANCE* inst, uint64_t channel_id, uint64_t inviter_node_id) {
|
|
struct chat_sync* cs = cs_of(inst);
|
|
if (!cs) return;
|
|
for (int i = 0; i < cs->pending_inv_in_count; ) {
|
|
if (cs->pending_inv_in_ch_id[i] == channel_id && cs->pending_inv_in_node_id[i] == inviter_node_id)
|
|
cs_invitation_remove(cs, i);
|
|
else i++;
|
|
}
|
|
DEBUG_INFO(DEBUG_CATEGORY_MEMBER_SYNC, "%s: deny_invite ch=%llu inviter=0x%016llx",
|
|
CS_ID, (unsigned long long)channel_id, (unsigned long long)inviter_node_id);
|
|
}
|