Files
mcde/lib/libDtChat/local.c
T
lotherk ea31073ce0 dtchat: exchange media keys and wire live calls into the UI (T6.5)
The local protocol gets media-key: each side sends its ephemeral X25519 public key (base64) and UDP port over the ready text connection; both derive the direction keys with HKDF-SHA256, the caller is the initiator. localui sends the key on Conversation > Call, answers an offer with its own key, creates the call with dc_call_new_bound on the listener port (TLS and media share the number), rings, and opens the call window; an incoming ring enables Answer. The Xt loop pumps the call: drain, Opus decode to the playback stream, capture and encode only while our own PTT is held, video frames to the window, ring timeout. dc_local_conn_remote_addr gives the numeric peer address; dc_call_new_bound binds the announced port. dc_call_talking() is now only our own key, dc_call_peer_talking() the peer's (a received PTT used to start our microphone too). The call window has an Answer button and lays the buttons above the video so they stay visible. --call-first and DTCHAT_TEST_TRUST/DTCHAT_TEST_AUTOANSWER/DTCHAT_TEST_PTT drive the test: two UI instances auto-paired, exchanged media-key, rang, answered, reached IN_CALL and carried 200 Opus frames caller->callee with the callee silent (audio out 200 on the receiver, audio in 200 on the sender); screenshot build/mcde-shots/dtchat-t65-live.png. The smoke still passes; test_media_call uses peer_talking; test_media_packet covers the base64 key exchange. The test switch is documented in the security review.
2026-11-17 08:49:25 +00:00

1202 lines
27 KiB
C

/*
* local.c -- dtchat's local TLS peer protocol
*
* License: CNCL 1.0 (Could Not Care Less), see LICENSE at the top of the tree.
*
* One listener per dtchat and one client connection per peer, all driven by
* DcLoop. The identity's Ed25519 certificate is the TLS certificate; the
* certificate's SHA-256 pin is the peer's TOFU anchor. After the handshake
* the client sends {"type":"hello","id":...,"pin":...}; the server checks
* ID and PIN, answers {"type":"hello-ack","ok":true|false,"pin":...} and
* closes on a mismatch. A client checks that the ack's pin is the pin of the
* certificate it actually saw, and against EXPECT_PIN when one is known.
*
* On a ready connection the peers exchange presence, msg, msg-ack and typing
* as JSON lines. dc_local_peer_* wraps a client connection with reconnect
* (2, 4, 8 ... 60 s) and an online/offline callback; the hello-ack has a 5 s
* timeout.
*/
#include "dc_internal.h"
#include <arpa/inet.h>
#include <errno.h>
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <tls.h>
#define LOCAL_BUF (128 * 1024)
#define LOCAL_HS 0
#define LOCAL_HELLO 1 /* server: read hello; client: send hello */
#define LOCAL_WAIT_ACK 2 /* client */
#define LOCAL_ACK 3 /* server: flush the ack */
#define LOCAL_READY 4
struct DcLocalConn {
DcLocalServer *server; /* NULL for a client connection */
DcLocalPeer *peer; /* set by the peer wrapper */
DcLoop *loop;
int fd;
int fd_id;
int is_client;
struct tls *tls;
int state;
int hello_ok;
char in[LOCAL_BUF];
size_t inlen;
char out[LOCAL_BUF];
size_t outlen;
size_t outoff;
char peer_id[128];
char peer_pin[128];
char cert_pin[128];
char own_pin[128];
char own_id[128];
char *expect_id;
char *expect_pin;
DcLocalHelloFn hello_fn;
DcLocalLineFn line;
void *arg;
DcLocalReadyFn ready;
DcLocalCloseFn closed;
int timer;
int ready_called;
int close_called;
int closed_notified;
DcLocalConn *next;
};
struct DcLocalServer {
DcLoop *loop;
int fd;
int fd_id;
int port;
struct tls_config *cfg;
struct tls *ctx;
char *own_pin;
char *own_id;
char *expect_id;
char *expect_pin;
DcLocalHelloFn hello_fn;
DcLocalLineFn line;
DcLocalCloseFn closed;
void *arg;
DcLocalConn *conns;
};
struct DcLocalPeer {
DcLoop *loop;
DcIdentity *identity;
char *host;
int port;
char *expect_pin;
DcLocalPeerLineFn line;
DcLocalPeerStateFn state_fn;
void *arg;
DcLocalConn *conn;
int online;
int backoff_ms;
int timer;
int stopped;
};
static const char *dc_local_conn_peer_cert_pin(const DcLocalConn *conn);
static void conn_pump(DcLocalConn *conn);
static void conn_cb(int fd, short revents, void *arg);
static void peer_connect(DcLocalPeer *peer);
static void
peer_retry(void *arg)
{
peer_connect(arg);
}
/* "sha256:aa:bb", "SHA256:AABB", "aa:bb" -> 64 lowercase hex, or -1. */
static int
normalize_pin(const char *text, char out[65])
{
size_t i = 0, o = 0;
if (text == NULL)
return -1;
if (strncasecmp(text, "sha256:", 7) == 0)
text += 7;
for (; text[i] != '\0'; i++) {
char c = text[i];
if (c == ':')
continue;
if (c >= 'A' && c <= 'F')
c = (char)(c - 'A' + 'a');
if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')))
return -1;
if (o >= 64)
return -1;
out[o++] = c;
}
out[o] = '\0';
return o == 64 ? 0 : -1;
}
static void
set_events(DcLocalConn *conn, short events)
{
if (conn->fd_id > 0)
(void)dc_loop_del_fd(conn->loop, conn->fd_id);
conn->fd_id = dc_loop_add_fd(conn->loop, conn->fd, events, conn_cb,
conn);
}
static void
conn_unlink(DcLocalConn *conn)
{
if (conn->server != NULL) {
DcLocalConn **slot = &conn->server->conns;
while (*slot != NULL) {
if (*slot == conn) {
*slot = conn->next;
return;
}
slot = &(*slot)->next;
}
}
}
static void
notify_close(DcLocalConn *conn)
{
if (conn->closed_notified)
return;
conn->closed_notified = 1;
if (conn->closed != NULL)
conn->closed(conn, conn->arg);
}
void
dc_local_conn_close(DcLocalConn *conn)
{
if (conn == NULL)
return;
if (conn->timer > 0) {
(void)dc_loop_del_timer(conn->loop, conn->timer);
conn->timer = 0;
}
if (conn->fd_id > 0)
(void)dc_loop_del_fd(conn->loop, conn->fd_id);
if (conn->tls != NULL) {
(void)tls_close(conn->tls);
tls_free(conn->tls);
conn->tls = NULL;
}
if (conn->fd >= 0)
close(conn->fd);
conn->fd = -1;
conn_unlink(conn);
free(conn->expect_id);
free(conn->expect_pin);
notify_close(conn);
free(conn);
}
/* Append a line to the connection's output buffer (compacting first). */
static int
queue_line(DcLocalConn *conn, const char *line, size_t len)
{
if (conn->outoff > 0) {
memmove(conn->out, conn->out + conn->outoff,
conn->outlen - conn->outoff);
conn->outlen -= conn->outoff;
conn->outoff = 0;
}
if (conn->outlen + len + 1 > sizeof(conn->out))
return -1;
memcpy(conn->out + conn->outlen, line, len);
conn->outlen += len;
conn->out[conn->outlen++] = '\n';
return 0;
}
int
dc_local_conn_busy(const DcLocalConn *conn)
{
return conn != NULL && conn->outoff < conn->outlen;
}
int
dc_local_conn_send_json(DcLocalConn *conn, const DcJson *json)
{
size_t len = 0;
char *text;
int rc;
if (conn == NULL || json == NULL ||
(conn->state != LOCAL_READY && conn->state != LOCAL_ACK &&
conn->state != LOCAL_WAIT_ACK))
return -1;
text = dc_json_write(json, &len);
if (text == NULL)
return -1;
rc = queue_line(conn, text, len);
free(text);
if (rc != 0)
return -1;
set_events(conn, POLLIN | POLLOUT);
return 0;
}
static int
send_object(DcLocalConn *conn, DcJson *json)
{
int rc = dc_local_conn_send_json(conn, json);
dc_json_free(json);
return rc;
}
int
dc_local_send_presence(DcLocalConn *conn, const char *show, const char *status)
{
DcJson *json = dc_json_new_object();
(void)dc_json_object_set(json, "type",
dc_json_new_string("presence"));
(void)dc_json_object_set(json, "show",
dc_json_new_string(show != NULL ? show : "online"));
if (status != NULL && *status != '\0')
(void)dc_json_object_set(json, "status",
dc_json_new_string(status));
return send_object(conn, json);
}
int
dc_local_send_msg(DcLocalConn *conn, const char *text, const char *client_id)
{
DcJson *json = dc_json_new_object();
(void)dc_json_object_set(json, "type", dc_json_new_string("msg"));
(void)dc_json_object_set(json, "text",
dc_json_new_string(text != NULL ? text : ""));
if (client_id != NULL)
(void)dc_json_object_set(json, "client_id",
dc_json_new_string(client_id));
return send_object(conn, json);
}
int
dc_local_send_msg_ack(DcLocalConn *conn, const char *client_id)
{
DcJson *json = dc_json_new_object();
(void)dc_json_object_set(json, "type",
dc_json_new_string("msg-ack"));
if (client_id != NULL)
(void)dc_json_object_set(json, "client_id",
dc_json_new_string(client_id));
return send_object(conn, json);
}
int
dc_local_send_typing(DcLocalConn *conn, int on)
{
DcJson *json = dc_json_new_object();
(void)dc_json_object_set(json, "type", dc_json_new_string("typing"));
(void)dc_json_object_set(json, "on", dc_json_new_bool(on));
return send_object(conn, json);
}
/* Flush pending output; returns 0 when empty, 1 when it wants more. */
static int
flush_out(DcLocalConn *conn)
{
while (conn->outoff < conn->outlen) {
ssize_t n = tls_write(conn->tls, conn->out + conn->outoff,
conn->outlen - conn->outoff);
if (n == TLS_WANT_POLLIN || n == TLS_WANT_POLLOUT) {
set_events(conn, n == TLS_WANT_POLLIN ? POLLIN :
POLLOUT);
return 1;
}
if (n <= 0)
return -1;
conn->outoff += (size_t)n;
}
conn->outlen = 0;
conn->outoff = 0;
return 0;
}
static void
dispatch_line(DcLocalConn *conn, const char *line)
{
DcJson *json;
if (conn->state == LOCAL_HELLO) {
const char *type;
const char *id;
const char *pin;
char normalized[65];
char expected[65];
json = dc_json_parse(line, strlen(line), NULL, 0);
if (json == NULL) {
conn->hello_ok = 0;
conn->state = LOCAL_ACK;
return;
}
type = dc_json_string(dc_json_get(json, "type"));
id = dc_json_string(dc_json_get(json, "id"));
pin = dc_json_string(dc_json_get(json, "pin"));
if (type == NULL || strcmp(type, "hello") != 0 || id == NULL ||
*id == '\0' || pin == NULL) {
conn->hello_ok = 0;
} else {
char certpin[65], claimed[65];
snprintf(conn->peer_id, sizeof(conn->peer_id), "%s",
id);
snprintf(conn->peer_pin, sizeof(conn->peer_pin), "%s",
pin);
conn->hello_ok = 1;
/* bind the claimed identity to the TLS key */
if (normalize_pin(conn->peer_pin, claimed) != 0 ||
normalize_pin(dc_local_conn_peer_cert_pin(conn),
certpin) != 0 ||
strcmp(claimed, certpin) != 0)
conn->hello_ok = 0;
if (conn->expect_id != NULL &&
strcmp(conn->expect_id, id) != 0)
conn->hello_ok = 0;
if (conn->expect_pin != NULL) {
if (normalize_pin(pin, normalized) != 0 ||
normalize_pin(conn->expect_pin,
expected) != 0 ||
strcmp(normalized, expected) != 0)
conn->hello_ok = 0;
}
}
conn->state = LOCAL_ACK;
{
DcJson *ack = dc_json_new_object();
(void)dc_json_object_set(ack, "type",
dc_json_new_string("hello-ack"));
(void)dc_json_object_set(ack, "ok",
dc_json_new_bool(conn->hello_ok));
(void)dc_json_object_set(ack, "pin",
dc_json_new_string(conn->own_pin));
(void)dc_json_object_set(ack, "id",
dc_json_new_string(conn->own_id));
(void)send_object(conn, ack);
}
if (conn->hello_ok && conn->hello_fn != NULL) {
DcLocalHelloFn fn = conn->hello_fn;
fn(conn, json, conn->arg);
}
dc_json_free(json);
return;
}
if (conn->state == LOCAL_WAIT_ACK) {
const char *type;
int ok;
const char *pin;
char normalized[65];
char expected[65];
json = dc_json_parse(line, strlen(line), NULL, 0);
if (json == NULL)
return;
type = dc_json_string(dc_json_get(json, "type"));
if (type == NULL || strcmp(type, "hello-ack") != 0) {
dc_json_free(json);
return;
}
ok = dc_json_bool(dc_json_get(json, "ok"));
pin = dc_json_string(dc_json_get(json, "pin"));
{
const char *id = dc_json_string(dc_json_get(json, "id"));
if (id != NULL)
snprintf(conn->peer_id, sizeof(conn->peer_id),
"%s", id);
}
if (conn->timer > 0) {
(void)dc_loop_del_timer(conn->loop, conn->timer);
conn->timer = 0;
}
if (ok && pin != NULL) {
/* the claimed pin must be the certificate's pin */
if (normalize_pin(pin, normalized) != 0 ||
strcmp(normalized, conn->peer_pin) != 0)
ok = 0;
if (ok && conn->expect_pin != NULL) {
if (normalize_pin(conn->expect_pin,
expected) != 0 ||
strcmp(expected, normalized) != 0)
ok = 0;
}
} else {
ok = 0;
}
dc_json_free(json);
if (!ok) {
conn->state = LOCAL_ACK;
conn->ready_called = 1;
if (conn->ready != NULL)
conn->ready(conn, 0, conn->arg);
return;
}
conn->state = LOCAL_READY;
conn->ready_called = 1;
if (conn->ready != NULL)
conn->ready(conn, 1, conn->arg);
return;
}
if (conn->state == LOCAL_READY) {
json = dc_json_parse(line, strlen(line), NULL, 0);
if (json == NULL)
return;
if (conn->line != NULL)
conn->line(conn, json, conn->arg);
dc_json_free(json);
}
}
static int
take_line(DcLocalConn *conn, char *out, size_t outlen)
{
char *nl = strchr(conn->in, '\n');
size_t used;
if (nl == NULL)
return 0;
*nl = '\0';
if (nl > conn->in && nl[-1] == '\r')
nl[-1] = '\0';
snprintf(out, outlen, "%s", conn->in);
used = (size_t)(nl - conn->in) + 1;
memmove(conn->in, conn->in + used, conn->inlen - used);
conn->inlen -= used;
conn->in[conn->inlen] = '\0';
return 1;
}
static void
process_lines(DcLocalConn *conn)
{
char line[LOCAL_BUF];
while (take_line(conn, line, sizeof(line))) {
dispatch_line(conn, line);
if (conn->state == LOCAL_ACK)
break; /* flush the ack before more input */
if (conn->state != LOCAL_HELLO &&
conn->state != LOCAL_WAIT_ACK &&
conn->state != LOCAL_READY)
break;
}
}
static void
conn_pump(DcLocalConn *conn)
{
for (;;) {
if (conn->state == LOCAL_HS) {
int rc = tls_handshake(conn->tls);
if (rc == 0) {
{
const char *hash =
tls_peer_cert_hash(conn->tls);
if (hash != NULL) {
char normalized[65];
if (normalize_pin(hash,
normalized) == 0) {
snprintf(conn->peer_pin,
sizeof(conn->peer_pin),
"%s", normalized);
snprintf(conn->cert_pin,
sizeof(conn->cert_pin),
"%s", normalized);
}
}
}
if (conn->is_client) {
DcJson *hello = dc_json_new_object();
conn->state = LOCAL_WAIT_ACK;
(void)dc_json_object_set(hello, "type",
dc_json_new_string("hello"));
(void)dc_json_object_set(hello, "id",
dc_json_new_string(conn->own_id));
(void)dc_json_object_set(hello, "pin",
dc_json_new_string(conn->own_pin));
(void)send_object(conn, hello);
(void)flush_out(conn);
} else {
conn->state = LOCAL_HELLO;
}
set_events(conn, POLLIN | POLLOUT);
continue;
}
if (rc == TLS_WANT_POLLIN) {
set_events(conn, POLLIN);
return;
}
if (rc == TLS_WANT_POLLOUT) {
set_events(conn, POLLOUT);
return;
}
dc_local_conn_close(conn);
return;
}
if (conn->state == LOCAL_HELLO ||
conn->state == LOCAL_WAIT_ACK) {
ssize_t n;
char *nl;
if (conn->outoff < conn->outlen) {
int rc = flush_out(conn);
if (rc > 0)
return;
if (rc < 0) {
dc_local_conn_close(conn);
return;
}
}
n = tls_read(conn->tls, conn->in + conn->inlen,
sizeof(conn->in) - 1 - conn->inlen);
if (n == TLS_WANT_POLLIN) {
set_events(conn, POLLIN);
return;
}
if (n == TLS_WANT_POLLOUT) {
set_events(conn, POLLOUT);
return;
}
if (n <= 0) {
dc_local_conn_close(conn);
return;
}
conn->inlen += (size_t)n;
conn->in[conn->inlen] = '\0';
(void)nl;
process_lines(conn);
if (conn->state == LOCAL_ACK) {
set_events(conn, POLLOUT);
if (!conn->is_client)
continue;
}
set_events(conn, POLLIN);
continue;
}
if (conn->state == LOCAL_ACK) {
int rc = flush_out(conn);
if (rc > 0)
return;
if (rc < 0) {
dc_local_conn_close(conn);
return;
}
if (conn->is_client) {
/* rejected: report and close */
if (!conn->ready_called && conn->ready != NULL) {
conn->ready_called = 1;
conn->ready(conn, 0, conn->arg);
}
dc_local_conn_close(conn);
return;
}
conn->state = LOCAL_READY;
set_events(conn, POLLIN);
continue;
}
if (conn->state == LOCAL_READY) {
int rc;
if (conn->outoff < conn->outlen) {
rc = flush_out(conn);
if (rc > 0)
return;
if (rc < 0) {
dc_local_conn_close(conn);
return;
}
}
{
ssize_t n = tls_read(conn->tls,
conn->in + conn->inlen,
sizeof(conn->in) - 1 - conn->inlen);
char *nl;
if (n == TLS_WANT_POLLIN) {
set_events(conn, POLLIN |
(conn->outoff < conn->outlen ?
POLLOUT : 0));
return;
}
if (n == TLS_WANT_POLLOUT) {
set_events(conn, POLLOUT);
return;
}
if (n <= 0) {
dc_local_conn_close(conn);
return;
}
conn->inlen += (size_t)n;
conn->in[conn->inlen] = '\0';
(void)nl;
process_lines(conn);
set_events(conn, POLLIN);
continue;
}
}
return;
}
}
static void
conn_cb(int fd, short revents, void *arg)
{
DcLocalConn *conn = arg;
(void)fd;
(void)revents;
conn_pump(conn);
}
static void
server_accept(DcLocalServer *server)
{
for (;;) {
int fd = accept(server->fd, NULL, NULL);
DcLocalConn *conn;
if (fd < 0)
return;
conn = calloc(1, sizeof(*conn));
if (conn == NULL) {
close(fd);
return;
}
conn->server = server;
conn->loop = server->loop;
conn->fd = fd;
conn->fd_id = -1;
conn->state = LOCAL_HS;
conn->hello_fn = server->hello_fn;
conn->line = server->line;
conn->closed = server->closed;
conn->arg = server->arg;
conn->expect_id = server->expect_id != NULL ?
strdup(server->expect_id) : NULL;
conn->expect_pin = server->expect_pin != NULL ?
strdup(server->expect_pin) : NULL;
snprintf(conn->own_id, sizeof(conn->own_id), "%s",
server->own_id);
snprintf(conn->own_pin, sizeof(conn->own_pin), "%s",
server->own_pin);
(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
if (tls_accept_socket(server->ctx, &conn->tls, fd) != 0) {
close(fd);
free(conn);
return;
}
{
int fl = fcntl(fd, F_GETFL, 0);
if (fl >= 0)
(void)fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}
conn->next = server->conns;
server->conns = conn;
conn->fd_id = dc_loop_add_fd(server->loop, fd, POLLIN,
conn_cb, conn);
if (conn->fd_id <= 0) {
dc_local_conn_close(conn);
return;
}
}
}
static void
listen_cb(int fd, short revents, void *arg)
{
(void)fd;
(void)revents;
server_accept(arg);
}
DcLocalServer *
dc_local_server_new(DcLoop *loop, const DcIdentity *identity, const char *host,
int port, const char *expect_id, const char *expect_pin,
DcLocalHelloFn hello, DcLocalLineFn line, DcLocalCloseFn closed, void *arg)
{
DcLocalServer *server;
struct sockaddr_in addr;
int fd;
int yes = 1;
if (loop == NULL || identity == NULL)
return NULL;
server = calloc(1, sizeof(*server));
if (server == NULL)
return NULL;
server->loop = loop;
server->hello_fn = hello;
server->line = line;
server->closed = closed;
server->arg = arg;
server->own_pin = strdup(dc_identity_pin(identity));
server->own_id = strdup(dc_identity_public_b64(identity));
server->expect_id = expect_id != NULL ? strdup(expect_id) : NULL;
server->expect_pin = expect_pin != NULL ? strdup(expect_pin) : NULL;
if (server->own_pin == NULL || server->own_id == NULL ||
(expect_id != NULL && server->expect_id == NULL) ||
(expect_pin != NULL && server->expect_pin == NULL))
goto fail;
if (tls_init() != 0)
goto fail;
server->cfg = tls_config_new();
if (server->cfg == NULL ||
tls_config_set_cert_mem(server->cfg,
(const uint8_t *)dc_identity_cert_pem(identity),
strlen(dc_identity_cert_pem(identity))) != 0 ||
tls_config_set_key_mem(server->cfg,
(const uint8_t *)dc_identity_key_pem(identity),
strlen(dc_identity_key_pem(identity))) != 0)
goto fail;
/*
* Ask for the peer's certificate so the pin in its hello is bound to
* the key that completed the handshake. The chain is not verified
* (TOFU by pin), hence no CA and noverifycert.
*/
tls_config_verify_client_optional(server->cfg);
tls_config_insecure_noverifycert(server->cfg);
server->ctx = tls_server();
if (server->ctx == NULL || tls_configure(server->ctx, server->cfg) != 0)
goto fail;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0)
goto fail;
(void)setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_port = htons((uint16_t)port);
if (host == NULL || strcmp(host, "0.0.0.0") == 0)
addr.sin_addr.s_addr = htonl(INADDR_ANY);
else if (inet_pton(AF_INET, host, &addr.sin_addr) != 1) {
close(fd);
goto fail;
}
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) != 0 ||
listen(fd, 8) != 0) {
close(fd);
goto fail;
}
{
socklen_t len = sizeof(addr);
if (getsockname(fd, (struct sockaddr *)&addr, &len) == 0)
server->port = ntohs(addr.sin_port);
}
{
int fl = fcntl(fd, F_GETFL, 0);
if (fl >= 0)
(void)fcntl(fd, F_SETFL, fl | O_NONBLOCK);
(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
}
server->fd = fd;
server->fd_id = dc_loop_add_fd(loop, fd, POLLIN, listen_cb, server);
if (server->fd_id <= 0)
goto fail;
return server;
fail:
dc_local_server_free(server);
return NULL;
}
int
dc_local_server_port(const DcLocalServer *server)
{
return server != NULL ? server->port : 0;
}
void
dc_local_server_free(DcLocalServer *server)
{
if (server == NULL)
return;
if (server->fd_id > 0)
(void)dc_loop_del_fd(server->loop, server->fd_id);
while (server->conns != NULL)
dc_local_conn_close(server->conns);
if (server->fd >= 0)
close(server->fd);
if (server->ctx != NULL) {
(void)tls_close(server->ctx);
tls_free(server->ctx);
}
if (server->cfg != NULL)
tls_config_free(server->cfg);
free(server->own_pin);
free(server->own_id);
free(server->expect_id);
free(server->expect_pin);
free(server);
}
static void
ack_timeout(void *arg)
{
DcLocalConn *conn = arg;
conn->timer = 0;
if (!conn->ready_called && conn->ready != NULL) {
conn->ready_called = 1;
conn->ready(conn, 0, conn->arg);
}
dc_local_conn_close(conn);
}
DcLocalConn *
dc_local_connect(DcLoop *loop, const DcIdentity *identity, const char *host,
int port, const char *expect_pin, DcLocalLineFn line,
DcLocalReadyFn ready, DcLocalCloseFn closed, void *arg)
{
DcLocalConn *conn;
struct addrinfo hints;
struct addrinfo *res = NULL;
struct addrinfo *ai;
char service[16];
int fd = -1;
if (loop == NULL || identity == NULL || host == NULL)
return NULL;
conn = calloc(1, sizeof(*conn));
if (conn == NULL)
return NULL;
conn->loop = loop;
conn->is_client = 1;
conn->fd = -1;
conn->fd_id = -1;
conn->state = LOCAL_HS;
conn->line = line;
conn->ready = ready;
conn->closed = closed;
conn->arg = arg;
conn->expect_pin = expect_pin != NULL ? strdup(expect_pin) : NULL;
snprintf(conn->own_id, sizeof(conn->own_id), "%s",
dc_identity_public_b64(identity));
snprintf(conn->own_pin, sizeof(conn->own_pin), "%s",
dc_identity_pin(identity));
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
snprintf(service, sizeof(service), "%d", port);
if (getaddrinfo(host, service, &hints, &res) != 0)
goto fail;
for (ai = res; ai != NULL; ai = ai->ai_next) {
struct pollfd p;
int err = 0;
socklen_t errlen = sizeof(err);
fd = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
if (fd < 0)
continue;
{
int fl = fcntl(fd, F_GETFL, 0);
if (fl >= 0)
(void)fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}
if (connect(fd, ai->ai_addr, ai->ai_addrlen) != 0) {
if (errno != EINPROGRESS) {
close(fd);
fd = -1;
continue;
}
p.fd = fd;
p.events = POLLOUT;
p.revents = 0;
if (poll(&p, 1, 5000) <= 0 ||
getsockopt(fd, SOL_SOCKET, SO_ERROR, &err,
&errlen) != 0 || err != 0) {
close(fd);
fd = -1;
continue;
}
}
break;
}
freeaddrinfo(res);
res = NULL;
if (fd < 0)
goto fail;
(void)fcntl(fd, F_SETFD, FD_CLOEXEC);
if (tls_init() != 0)
goto fail;
{
struct tls_config *cfg = tls_config_new();
if (cfg == NULL)
goto fail;
tls_config_insecure_noverifycert(cfg);
tls_config_insecure_noverifyname(cfg);
if (tls_config_set_cert_mem(cfg,
(const uint8_t *)dc_identity_cert_pem(identity),
strlen(dc_identity_cert_pem(identity))) != 0 ||
tls_config_set_key_mem(cfg,
(const uint8_t *)dc_identity_key_pem(identity),
strlen(dc_identity_key_pem(identity))) != 0) {
tls_config_free(cfg);
goto fail;
}
conn->tls = tls_client();
if (conn->tls == NULL || tls_configure(conn->tls, cfg) != 0) {
tls_config_free(cfg);
goto fail;
}
tls_config_free(cfg);
}
if (tls_connect_socket(conn->tls, fd, host) != 0)
goto fail;
conn->fd = fd;
conn->fd_id = dc_loop_add_fd(loop, fd, POLLIN, conn_cb, conn);
if (conn->fd_id <= 0)
goto fail;
conn->timer = dc_loop_add_timer(loop, 5000, ack_timeout, conn);
if (conn->timer <= 0)
goto fail;
conn_pump(conn); /* start the TLS handshake */
return conn;
fail:
if (res != NULL)
freeaddrinfo(res);
if (conn->tls != NULL) {
(void)tls_close(conn->tls);
tls_free(conn->tls);
conn->tls = NULL;
}
if (fd >= 0)
close(fd);
free(conn->expect_pin);
free(conn);
return NULL;
}
const char *
dc_local_conn_peer_id(const DcLocalConn *conn)
{
return conn != NULL ? conn->peer_id : NULL;
}
const char *
dc_local_conn_peer_pin(const DcLocalConn *conn)
{
return conn != NULL ? conn->peer_pin : NULL;
}
int
dc_local_conn_remote_addr(const DcLocalConn *conn, char *host, size_t len)
{
struct sockaddr_in addr;
socklen_t alen = sizeof(addr);
if (conn == NULL || conn->fd < 0 || host == NULL || len == 0)
return -1;
if (getpeername(conn->fd, (struct sockaddr *)&addr, &alen) != 0)
return -1;
if (inet_ntop(AF_INET, &addr.sin_addr, host, (socklen_t)len) == NULL)
return -1;
return 0;
}
static const char *
dc_local_conn_peer_cert_pin(const DcLocalConn *conn)
{
return conn != NULL ? conn->cert_pin : NULL;
}
/* ------------------------------ the peer link ---------------------------- */
static void
peer_schedule(DcLocalPeer *peer)
{
if (peer->stopped || peer->timer > 0)
return;
if (peer->backoff_ms < 2000)
peer->backoff_ms = 2000;
peer->timer = dc_loop_add_timer(peer->loop, peer->backoff_ms,
peer_retry, peer);
peer->backoff_ms = peer->backoff_ms * 2 > 60000 ?
60000 : peer->backoff_ms * 2;
}
static void
peer_closed(DcLocalConn *conn, void *arg)
{
DcLocalPeer *peer = arg;
(void)conn;
peer->conn = NULL;
if (peer->online) {
peer->online = 0;
if (peer->state_fn != NULL && !peer->stopped)
peer->state_fn(peer, 0, peer->arg);
}
peer_schedule(peer);
}
static void
peer_ready(DcLocalConn *conn, int ok, void *arg)
{
DcLocalPeer *peer = arg;
(void)conn;
if (!ok)
return; /* the connection is closed by its own ACK state */
peer->online = 1;
peer->backoff_ms = 2000;
if (peer->state_fn != NULL)
peer->state_fn(peer, 1, peer->arg);
}
static void
peer_line(DcLocalConn *conn, const DcJson *json, void *arg)
{
DcLocalPeer *peer = arg;
if (peer->line != NULL)
peer->line(peer, json, peer->arg);
(void)conn;
}
static void
peer_connect(DcLocalPeer *peer)
{
if (peer->timer > 0) {
(void)dc_loop_del_timer(peer->loop, peer->timer);
peer->timer = 0;
}
if (peer->stopped || peer->online)
return;
peer->conn = dc_local_connect(peer->loop, peer->identity, peer->host,
peer->port, peer->expect_pin, peer_line, peer_ready, peer_closed,
peer);
if (peer->conn == NULL)
peer_schedule(peer);
else
peer->conn->peer = peer;
}
DcLocalPeer *
dc_local_peer_new(DcLoop *loop, const DcIdentity *identity, const char *host,
int port, const char *expect_pin, DcLocalPeerLineFn line,
DcLocalPeerStateFn state_fn, void *arg)
{
DcLocalPeer *peer;
if (loop == NULL || identity == NULL || host == NULL)
return NULL;
peer = calloc(1, sizeof(*peer));
if (peer == NULL)
return NULL;
peer->loop = loop;
peer->identity = (DcIdentity *)identity;
peer->host = strdup(host);
peer->port = port;
peer->expect_pin = expect_pin != NULL ? strdup(expect_pin) : NULL;
peer->line = line;
peer->state_fn = state_fn;
peer->arg = arg;
peer->backoff_ms = 2000;
if (peer->host == NULL || (expect_pin != NULL && peer->expect_pin == NULL)) {
dc_local_peer_free(peer);
return NULL;
}
return peer;
}
int
dc_local_peer_start(DcLocalPeer *peer)
{
if (peer == NULL)
return -1;
peer->stopped = 0;
peer_connect(peer);
return peer->conn != NULL ? 0 : -1;
}
void
dc_local_peer_stop(DcLocalPeer *peer)
{
if (peer == NULL)
return;
peer->stopped = 1;
if (peer->timer > 0) {
(void)dc_loop_del_timer(peer->loop, peer->timer);
peer->timer = 0;
}
if (peer->conn != NULL) {
DcLocalConn *conn = peer->conn;
peer->conn = NULL;
conn->closed = NULL;
dc_local_conn_close(conn);
}
peer->online = 0;
}
void
dc_local_peer_free(DcLocalPeer *peer)
{
if (peer == NULL)
return;
dc_local_peer_stop(peer);
free(peer->host);
free(peer->expect_pin);
free(peer);
}
int
dc_local_peer_send(DcLocalPeer *peer, const DcJson *json)
{
if (peer == NULL || peer->conn == NULL || !peer->online)
return -1;
return dc_local_conn_send_json(peer->conn, json);
}
int
dc_local_peer_online(const DcLocalPeer *peer)
{
return peer != NULL ? peer->online : 0;
}
DcLocalConn *
dc_local_peer_conn(const DcLocalPeer *peer)
{
return peer != NULL ? peer->conn : NULL;
}