summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAnton <anton@picapica.im>2026-11-22 18:43:34 +0400
committerAnton <anton@picapica.im>2026-11-22 18:43:34 +0400
commit05b82a33c145f768de9b3b3abca18630a798aabb (patch)
treedf4e709e70f8c67d691ad0264a2191f30cfb3715
parentee5e6b4dac1d2cf0c2c5a29fe69efd7adf8d4bf6 (diff)
downloadpica-pica-05b82a33c145f768de9b3b3abca18630a798aabb.tar.gz
pica-pica-05b82a33c145f768de9b3b3abca18630a798aabb.zip
rework network settings, add multiple addresses, UDP hole punching
-rw-r--r--Makefile.am4
-rw-r--r--PICA_client.c562
-rw-r--r--PICA_client.h102
-rw-r--r--PICA_media.c627
-rw-r--r--PICA_media.h151
-rw-r--r--PICA_netconf.c753
-rw-r--r--PICA_netconf.h160
-rw-r--r--PICA_node.c86
-rw-r--r--PICA_proto.h10
-rw-r--r--doc/proto-doc-latest.txt141
-rw-r--r--pica-client/dialogs/settingsdialog.cpp502
-rw-r--r--pica-client/dialogs/settingsdialog.h45
-rw-r--r--pica-client/directc2csettings.h145
-rw-r--r--pica-client/directlistener.cpp282
-rw-r--r--pica-client/directlistener.h85
-rw-r--r--pica-client/pica-client.pro3
-rw-r--r--pica-client/skynet.cpp123
-rw-r--r--pica-client/skynet.h17
-rw-r--r--pica-node.conf.53
-rw-r--r--tests/test_client.c36
20 files changed, 3474 insertions, 363 deletions
diff --git a/Makefile.am b/Makefile.am
index 3d9c565..ee18901 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -169,6 +169,9 @@ pica-client/picasystray.cpp \
pica-client/picasystray.h \
pica-client/skynet.cpp \
pica-client/skynet.h \
+pica-client/directlistener.cpp \
+pica-client/directlistener.h \
+pica-client/directc2csettings.h \
pica-client/history.h \
pica-client/history.cpp \
pica-client/dhparam.h \
@@ -245,6 +248,7 @@ moc_registeraccountdialog.cpp \
moc_filetransferdialog.cpp \
moc_audiovideocallcontroller.cpp \
moc_skynet.cpp \
+moc_directlistener.cpp \
moc_settingsdialog.cpp \
moc_viewcertdialog.cpp \
moc_showpicaiddialog.cpp \
diff --git a/PICA_client.c b/PICA_client.c
index c994089..4dfc809 100644
--- a/PICA_client.c
+++ b/PICA_client.c
@@ -21,6 +21,7 @@
#include "PICA_msgproc.h"
#include "PICA_common.h"
#include "PICA_signverify.h"
+#include "PICA_netconf.h"
#include <openssl/dh.h>
#include <string.h>
#include <time.h>
@@ -126,8 +127,8 @@ const struct PICA_msginfo c2c_messages[] =
{
{PICA_PROTO_MSGUTF8, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MSGUTF8},
{PICA_PROTO_MSGOK, PICA_MSG_FIXED_SIZE, PICA_PROTO_MSGOK_SIZE, procmsg_MSGOK},
- {PICA_PROTO_CALLREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALLREQ_SIZE, procmsg_CALLREQ},
- {PICA_PROTO_CALLANS, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALLANS_SIZE, procmsg_CALLANS},
+ {PICA_PROTO_CALLREQ, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALLREQ},
+ {PICA_PROTO_CALLANS, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_CALLANS},
{PICA_PROTO_CALLREJ, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALLREJ_SIZE, procmsg_CALLREJ},
{PICA_PROTO_CALLFIN, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALLFIN_SIZE, procmsg_CALLFIN},
{PICA_PROTO_CALL_AUDIOPARAM, PICA_MSG_FIXED_SIZE, PICA_PROTO_CALL_AUDIOPARAM_SIZE, procmsg_CALL_AUDIOPARAM},
@@ -642,12 +643,17 @@ static int directc2c_connect_next(struct PICA_directc2c *dc2c, struct PICA_c2c *
CLOSE(dc2c->sck);
dc2c->sck = -1;
+ /* the list holds IPv4 elements only, behind a length field in host byte
+ * order - see procmsg_PICA_PROTO_DIRECTC2C_ADDRLIST()
+ */
if (dc2c->addrpos == 0)
dc2c->addrpos += 2;
- if (dc2c->addrpos >= *(uint16_t*)dc2c->addrlist)
+ if (dc2c->addrpos + PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE > *(uint16_t*)dc2c->addrlist + 2)
return PICA_ERRNOTFOUND;
+ dc2c->attempt_started = time(0);
+
switch(dc2c->addrlist[dc2c->addrpos])
{
case PICA_PROTO_DIRECTC2C_IPV4:
@@ -674,14 +680,61 @@ static int directc2c_connect_next(struct PICA_directc2c *dc2c, struct PICA_c2c *
dc2c->addrpos += PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE;
break;
- case PICA_PROTO_DIRECTC2C_IPV6:
- break;
-
+ default:
+ return PICA_ERRNOTFOUND;
}
return PICA_OK;
}
+/* Picks the IPv4 elements out of a received address list, in their order,
+ * into list, behind a length field in host byte order.
+ * Elements of the other types are stepped over by their size, see the 0xA4
+ * message. An element of an unknown type ends the list, as there is no
+ * knowing where it ends; so does a truncated one.
+ * \return size of what was written to list
+ */
+static unsigned int directc2c_addrlist_ipv4(const unsigned char *items, unsigned int len, uint8_t *list)
+{
+ unsigned int pos = 0;
+ uint16_t n = 0;
+
+ while (pos < len && n < PICA_DIRECTC2C_MAX_ADDRS)
+ {
+ switch (items[pos])
+ {
+ case PICA_PROTO_DIRECTC2C_IPV4:
+ if (pos + PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE > len)
+ goto end;
+
+ memcpy(list + 2 + n * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE,
+ items + pos, PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE);
+ n++;
+ pos += PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE;
+ break;
+
+ case PICA_PROTO_DIRECTC2C_IPV6:
+ pos += PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV6_SIZE;
+ break;
+
+ case PICA_PROTO_DIRECTC2C_DNS:
+ if (pos + 1 >= len)
+ goto end;
+
+ pos += 2 + items[pos + 1] + 2;
+ break;
+
+ default:
+ goto end;
+ }
+ }
+
+end:
+ *(uint16_t*)list = n * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE;
+
+ return 2 + n * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE;
+}
+
static unsigned int procmsg_PICA_PROTO_DIRECTC2C_ADDRLIST(unsigned char* buf, unsigned int nb, void* p)
{
PICA_TRACEFUNC
@@ -693,6 +746,10 @@ static unsigned int procmsg_PICA_PROTO_DIRECTC2C_ADDRLIST(unsigned char* buf, un
if (cc->directc2c_state != PICA_DIRECTC2C_STATE_INACTIVE && cc->directc2c_state != PICA_DIRECTC2C_STATE_WAITINGINCOMING)
return 0;
+ /* the peer announces its addresses once */
+ if (cc->direct)
+ return 1;
+
if (cc->outgoing == PICA_C2C_OUTGOING || cc->conn->directc2c_config == PICA_DIRECTC2C_CFG_CONNECTONLY)
cc->directc2c_state = PICA_DIRECTC2C_STATE_CONNECTING;
@@ -704,13 +761,12 @@ static unsigned int procmsg_PICA_PROTO_DIRECTC2C_ADDRLIST(unsigned char* buf, un
cc->direct->is_outgoing = PICA_DIRECTC2C_OUTGOING;
cc->direct->state = PICA_DIRECTC2C_CONNSTATE_NEW;
cc->direct->sck = -1;
- cc->direct->addrlist = malloc(nb - 2 + 1);
+ cc->direct->addrlist = malloc(2 + PICA_DIRECTC2C_MAX_ADDRS * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE);
if (!cc->direct->addrlist)
return 1;
- memcpy(cc->direct->addrlist, buf + 2, nb - 2);// copy size and address list
- cc->direct->addrlist[nb - 2] = 0;
+ directc2c_addrlist_ipv4(buf + 4, nb - 4, cc->direct->addrlist);
cc->direct->addrpos = 0;
if (cc->outgoing == PICA_C2C_INCOMING && cc->conn->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING)
@@ -1164,7 +1220,14 @@ static unsigned int procmsg_MYUDPADDR(unsigned char* buf, unsigned int nb, void*
/* before the callback, which is free to make another request */
c2n->udpaddr_state = PICA_UDPADDR_STATE_IDLE;
- if (callbacks.udp_address_cb)
+ if (c2n->udpaddr_c2c)
+ {
+ struct PICA_c2c *c2c = c2n->udpaddr_c2c;
+
+ c2n->udpaddr_c2c = NULL;
+ PICA_media_call_learned(c2c, PICA_OK, buf + 4, buf[3], port);
+ }
+ else if (callbacks.udp_address_cb)
callbacks.udp_address_cb(c2n, PICA_OK, buf[3], buf + 4, addr_str, port);
return 1;
@@ -1186,7 +1249,14 @@ static void process_udpaddr(struct PICA_c2n *c2n)
{
c2n->udpaddr_state = PICA_UDPADDR_STATE_IDLE;
- if (callbacks.udp_address_cb)
+ if (c2n->udpaddr_c2c)
+ {
+ struct PICA_c2c *c2c = c2n->udpaddr_c2c;
+
+ c2n->udpaddr_c2c = NULL;
+ PICA_media_call_learned(c2c, PICA_ERRTIMEDOUT, NULL, 0, 0);
+ }
+ else if (callbacks.udp_address_cb)
callbacks.udp_address_cb(c2n, PICA_ERRTIMEDOUT, 0, NULL, NULL, 0);
return;
@@ -1235,6 +1305,14 @@ int PICA_request_udp_address(struct PICA_c2n *c2n, SOCKET udp_sck)
c2n->udpaddr_started = time(0);
c2n->udpaddr_probes_sent = 0;
c2n->udpaddr_state = PICA_UDPADDR_STATE_WAITINGTOKEN;
+ /* a request of the application replaces one the library made for a
+ * call, which then sends its address list without that address
+ */
+ if (c2n->udpaddr_c2c)
+ {
+ PICA_media_call_learned(c2n->udpaddr_c2c, PICA_ERRTIMEDOUT, NULL, 0, 0);
+ c2n->udpaddr_c2c = NULL;
+ }
return PICA_OK;
}
@@ -1652,14 +1730,13 @@ static int check_pkey_passphrase(const char *pkey_file,
}
-int PICA_new_listener(const struct PICA_acc *acc, const char *public_addr, int public_port, int local_port, struct PICA_listener **l)
+int PICA_new_listener(const struct PICA_acc *acc, int local_port, struct PICA_listener **l)
{
- int ret, ret_err, flag;
+ int ret, ret_err;
struct PICA_listener *lst = NULL;
struct sockaddr_in s;
-
- if (!acc || !public_addr || public_port <= 0 || public_port > 65535 || local_port <= 0 || local_port > 65535 || !l)
+ if (!acc || local_port <= 0 || local_port > 65535 || !l)
return PICA_ERRINVARG;
lst = *l = (struct PICA_listener*)calloc(sizeof(struct PICA_listener), 1);
@@ -1667,18 +1744,7 @@ int PICA_new_listener(const struct PICA_acc *acc, const char *public_addr, int p
if (!lst)
return PICA_ERRNOMEM;
- lst->public_addr_dns = strdup(public_addr);
-
- if (!lst->public_addr_dns)
- {
- ret_err = PICA_ERRNOMEM;
- goto error_ret_0;
- }
-
- lst->public_addr_ipv4 = inet_addr(public_addr);
-
lst->acc = acc;
- lst->public_port = public_port;
lst->local_port = local_port;
lst->sck_listener = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); //(1)
@@ -1686,11 +1752,21 @@ int PICA_new_listener(const struct PICA_acc *acc, const char *public_addr, int p
if (lst->sck_listener == SOCKET_ERROR)
{
ret_err = PICA_ERRSOCK;
- goto error_ret_1;
+ goto error_ret_0;
}
- flag = 1;
- setsockopt(lst->sck_listener, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
+#ifndef WIN32
+ {
+ int flag = 1;
+
+ /* Lets the port be listened on again right after a restart, while
+ * connections of the previous run linger in TIME_WAIT. On Windows the
+ * same option lets a socket take over a port that another one is
+ * listening on, which would hide that the port is taken.
+ */
+ setsockopt(lst->sck_listener, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
+ }
+#endif
IOCTLSETNONBLOCKINGSOCKET(lst->sck_listener, 1);
@@ -1704,7 +1780,7 @@ int PICA_new_listener(const struct PICA_acc *acc, const char *public_addr, int p
if (ret == SOCKET_ERROR)
{
ret_err = PICA_ERRSOCK;
- goto error_ret_2;
+ goto error_ret_1;
}
ret = listen(lst->sck_listener, 10);
@@ -1712,28 +1788,29 @@ int PICA_new_listener(const struct PICA_acc *acc, const char *public_addr, int p
if (ret == SOCKET_ERROR)
{
ret_err = PICA_ERRSOCK;
- goto error_ret_2;
+ goto error_ret_1;
}
/* The UDP port with the same number carries call media, see PICA_media.h.
- * Failing to open it is not fatal: direct connections still work and
- * calls keep their media on the c2c connection.
+ * The announced port numbers are used for both protocols, so a listener
+ * that has only one of them is no good - the caller can try another
+ * number instead.
*/
- if (PICA_media_listener_new(acc, public_port, local_port, &lst->media) != PICA_OK)
+ ret = PICA_media_listener_new(acc, local_port, local_port, &lst->media);
+
+ if (ret != PICA_OK)
{
fprintf(stderr, "failed to open UDP port %i for call media\n", local_port);
lst->media = NULL;
+ ret_err = ret;
+ goto error_ret_1;
}
return PICA_OK;
-error_ret_2: //(2)
-
- CLOSE(lst->sck_listener);
-
error_ret_1: //(1)
- free(lst->public_addr_dns);
+ CLOSE(lst->sck_listener);
error_ret_0: //(0)
@@ -1743,6 +1820,85 @@ error_ret_0: //(0)
return ret_err;
}
+/* IPv4 address of an address string, resolving a DNS name if it is one. */
+static int resolve_ipv4(const char *name, in_addr_t *addr)
+{
+ struct addrinfo h, *r;
+
+ *addr = inet_addr(name);
+
+ if (*addr != INADDR_NONE)
+ return PICA_OK;
+
+ memset(&h, 0, sizeof(h));
+ h.ai_family = AF_INET;
+ h.ai_socktype = SOCK_STREAM;
+ h.ai_protocol = IPPROTO_TCP;
+
+ if (getaddrinfo(name, NULL, &h, &r) != 0)
+ return PICA_ERRDNSRESOLVE;
+
+ *addr = ((struct sockaddr_in*)r->ai_addr)->sin_addr.s_addr;
+
+ freeaddrinfo(r);
+
+ return PICA_OK;
+}
+
+int PICA_listener_set_addrlist(struct PICA_listener *l, const char *const *addrs, const int *ports, int count)
+{
+ struct PICA_listener_addr list[PICA_DIRECTC2C_MAX_ADDRS];
+ int i, ret;
+
+ if (!l || count < 0 || count > PICA_DIRECTC2C_MAX_ADDRS || (count > 0 && (!addrs || !ports)))
+ return PICA_ERRINVARG;
+
+ for (i = 0; i < count; i++)
+ {
+ if (ports[i] <= 0 || ports[i] > 65535)
+ return PICA_ERRINVARG;
+
+ list[i].port = htons((uint16_t)ports[i]);
+ list[i].is_upnp = addrs[i] == NULL;
+ list[i].addr = INADDR_ANY;
+
+ if (addrs[i])
+ {
+ ret = resolve_ipv4(addrs[i], &list[i].addr);
+
+ if (ret != PICA_OK)
+ return ret;
+ }
+ }
+
+ memcpy(l->addrs, list, count * sizeof(list[0]));
+ l->addrs_count = count;
+ l->addrs_manual = count > 0;
+
+ return PICA_OK;
+}
+
+int PICA_listener_set_upnp_addr(struct PICA_listener *l, const char *addr, int port)
+{
+ if (!l)
+ return PICA_ERRINVARG;
+
+ if (!addr)
+ {
+ l->upnp_addr = 0;
+ l->upnp_port = 0;
+ return PICA_OK;
+ }
+
+ if (port <= 0 || port > 65535 || inet_addr(addr) == INADDR_NONE)
+ return PICA_ERRINVARG;
+
+ l->upnp_addr = inet_addr(addr);
+ l->upnp_port = htons((uint16_t)port);
+
+ return PICA_OK;
+}
+
int PICA_open_acc(const char *cert_file,
const char *pkey_file,
const char *dh_param_file,
@@ -2166,6 +2322,99 @@ multilogin_err1:
return 1;
}
+/* Everything a call held, given back when it ends. */
+static void call_release(struct PICA_c2c *chn)
+{
+ chn->call_state = PICA_CALL_STATE_IDLE;
+
+ PICA_media_close(chn);
+ PICA_media_call_free(chn);
+
+ chn->call_audio_params_are_set = 0;
+ chn->call_video_params_are_set = 0;
+}
+
+/* Sends 0x70 or 0x71 with the probe token and the addresses of the call
+ * socket. */
+static int call_send_info(struct PICA_c2c *chn, unsigned int msgid)
+{
+ struct PICA_proto_msg *mp;
+ unsigned char info[PICA_MEDIA_CALL_INFO_MAXSIZE];
+ unsigned int len;
+
+ len = PICA_media_call_write_info(chn, info);
+
+ mp = c2c_writebuf_push(chn, msgid, 4 + len);
+
+ if (!mp)
+ return PICA_ERRNOMEM;
+
+ mp->tail[0] = len & 0xFF;
+ mp->tail[1] = (len >> 8) & 0xFF;
+ memcpy(mp->tail + 2, info, len);
+
+ if (chn->media_call)
+ chn->media_call->pending_msg = 0;
+
+ return PICA_OK;
+}
+
+static int call_send_audio_params(struct PICA_c2c *chn, const char *codec_name, uint16_t sample_rate);
+static int call_send_video_params(struct PICA_c2c *chn, const char *codec_name, uint16_t width, uint16_t height);
+
+/* 0x71 is out, the call is active for the callee now. */
+static int call_answered(struct PICA_c2c *chn)
+{
+ struct PICA_media_call *mc = chn->media_call;
+ int ret;
+
+ ret = call_send_info(chn, PICA_PROTO_CALLANS);
+
+ if (ret != PICA_OK)
+ return ret;
+
+ chn->call_state = PICA_CALL_STATE_ACTIVE;
+
+ /* the parameters set while 0x71 was waiting, which the caller must not
+ * see before it
+ */
+ if (mc && mc->audio_params_pending)
+ call_send_audio_params(chn, mc->audio_codec, mc->audio_sample_rate);
+
+ if (mc && mc->video_params_pending)
+ call_send_video_params(chn, mc->video_codec, mc->video_width, mc->video_height);
+
+ if (mc)
+ mc->audio_params_pending = mc->video_params_pending = 0;
+
+ PICA_media_start(chn);
+
+ return PICA_OK;
+}
+
+/* Sends 0x70 and 0x71 that were waiting for the address of the call socket
+ * once it is known, or once waiting for it is over.
+ */
+static void process_calls(struct PICA_c2n *c2n)
+{
+ struct PICA_c2c *c2c;
+
+ for (c2c = c2n->chan_list_head; c2c; c2c = c2c->next)
+ {
+ struct PICA_media_call *mc = c2c->media_call;
+
+ if (!mc || !mc->pending_msg || !PICA_media_call_ready(c2c))
+ continue;
+
+ if (mc->pending_msg == PICA_PROTO_CALLREQ && c2c->call_state == PICA_CALL_STATE_CALLING)
+ call_send_info(c2c, PICA_PROTO_CALLREQ);
+ else if (mc->pending_msg == PICA_PROTO_CALLANS && c2c->call_state == PICA_CALL_STATE_ANSWERING)
+ call_answered(c2c);
+ else
+ mc->pending_msg = 0;
+ }
+}
+
static unsigned int procmsg_CALLREQ(unsigned char* buf, unsigned int nb, void *p)
{
struct PICA_c2c *chan = (struct PICA_c2c *)p;
@@ -2186,6 +2435,12 @@ static unsigned int procmsg_CALLREQ(unsigned char* buf, unsigned int nb, void *p
return 1;
}
+ /* The callee starts finding out the address of its call socket now,
+ * while the call rings, so that answering is not held up by it. A call
+ * that cannot have it still rings.
+ */
+ PICA_media_call_prepare(chan, 0, buf + 4, nb - 4);
+
chan->call_state = PICA_CALL_STATE_INCOMINGCALL;
callbacks.incoming_call_cb(chan->peer_id);
@@ -2202,6 +2457,9 @@ static unsigned int procmsg_CALLANS(unsigned char* buf, unsigned int nb, void *p
return 0;
}
+ /* a malformed list only costs the call its hole punching */
+ PICA_media_call_read_info(chan, buf + 4, nb - 4);
+
chan->call_state = PICA_CALL_STATE_ACTIVE;
callbacks.call_picked_up_cb(chan->peer_id);
@@ -2220,7 +2478,7 @@ static unsigned int procmsg_CALLREJ(unsigned char* buf, unsigned int nb, void *p
return 0;
}
- chan->call_state = PICA_CALL_STATE_IDLE;
+ call_release(chan);
callbacks.call_rejected_cb(chan->peer_id);
@@ -2237,13 +2495,9 @@ static unsigned int procmsg_CALLFIN(unsigned char* buf, unsigned int nb, void *p
return 0;
}
- chan->call_state = PICA_CALL_STATE_IDLE;
-
- PICA_media_close(chan);
+ call_release(chan);
callbacks.call_hangup_cb(chan->peer_id);
- chan->call_audio_params_are_set = 0;
- chan->call_video_params_are_set = 0;
return 1;
}
@@ -3141,6 +3395,14 @@ static void process_directc2c(struct PICA_c2n *c2n, fd_set *rfds, fd_set *wfds)
d = c2c->direct;
ret = PICA_OK;
+ /* on to the next address, see PICA_DIRECTC2C_CONNECT_TIMEOUT */
+ if ((d->state == PICA_DIRECTC2C_CONNSTATE_CONNECTING || d->state == PICA_DIRECTC2C_CONNSTATE_WAITINGTLS)
+ && time(0) - d->attempt_started > PICA_DIRECTC2C_CONNECT_TIMEOUT)
+ {
+ printf("direct connection to %s port %i timed out\n", inet_ntoa(d->addr.sin_addr), ntohs(d->addr.sin_port));
+ d->state = PICA_DIRECTC2C_CONNSTATE_FAILED;
+ }
+
switch(d->state)
{
case PICA_DIRECTC2C_CONNSTATE_CONNECTING:
@@ -3579,6 +3841,8 @@ int PICA_event_loop(struct PICA_c2n **connections, int timeout)
//processing media connections of calls in progress
PICA_media_process(*ic2n, &rfds);
+ process_calls(*ic2n);
+
process_udpaddr(*ic2n);
}
ic2n++;
@@ -3818,21 +4082,96 @@ struct PICA_proto_msg* c2c_writebuf_push(struct PICA_c2c *chn, unsigned int msgi
return mp;
}
+/* Adds an address to a list under construction, unless it is in it already
+ * - an interface address that is public is what UPnP reports too, when the
+ * IGD runs on this very machine.
+ */
+static void addrlist_add(struct PICA_listener_addr *list, int *count, in_addr_t addr, uint16_t port)
+{
+ int i;
+
+ if (addr == INADDR_ANY || port == 0 || *count >= PICA_DIRECTC2C_MAX_ADDRS)
+ return;
+
+ for (i = 0; i < *count; i++)
+ if (list[i].addr == addr && list[i].port == port)
+ return;
+
+ list[*count].addr = addr;
+ list[*count].port = port;
+ list[*count].is_upnp = 0;
+ (*count)++;
+}
+
+/* The addresses to announce in 0x0B, see the description of the message:
+ * private ones first, then public ones. Built when it is sent rather than
+ * once, since interfaces come and go - a VPN connected, a laptop moved to
+ * another network.
+ */
+static int listener_addrlist(const struct PICA_listener *l, struct PICA_listener_addr *list)
+{
+ int count = 0;
+ int i;
+
+ if (l->addrs_manual)
+ {
+ for (i = 0; i < l->addrs_count; i++)
+ {
+ if (l->addrs[i].is_upnp)
+ addrlist_add(list, &count, l->upnp_addr, l->upnp_port);
+ else
+ addrlist_add(list, &count, l->addrs[i].addr, l->addrs[i].port);
+ }
+ }
+ else
+ {
+ in_addr_t ifaddrs[PICA_IFADDRS_MAX];
+ int n;
+
+ n = PICA_get_ifaddrs_ipv4(ifaddrs, PICA_IFADDRS_MAX);
+
+ for (i = 0; i < n; i++)
+ addrlist_add(list, &count, ifaddrs[i], htons((uint16_t)l->local_port));
+
+ addrlist_add(list, &count, l->upnp_addr, l->upnp_port);
+ }
+
+ return count;
+}
+
int PICA_send_directc2caddrlist(struct PICA_c2c *chn)
{
PICA_TRACEFUNC
if (chn->conn->directc2c_config == PICA_DIRECTC2C_CFG_ALLOWINCOMING && chn->conn->directc2c_listener)
{
struct PICA_proto_msg *mp;
- //TODO send all possible interface addresses, not one
- unsigned int len = PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE;
+ struct PICA_listener_addr list[PICA_DIRECTC2C_MAX_ADDRS];
+ int count, i;
+ unsigned int len;
+ unsigned char *p;
+
+ count = listener_addrlist(chn->conn->directc2c_listener, list);
+
+ /* nothing a peer could connect to */
+ if (count == 0)
+ return PICA_OK;
+
+ len = count * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE;
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_DIRECTC2C_ADDRLIST, len + 4)))
{
- *((uint16_t*)mp->tail) = len;
- *((uint8_t*)mp->tail + 2) = PICA_PROTO_DIRECTC2C_IPV4;
- *((uint32_t*)(mp->tail + 3)) = chn->conn->directc2c_listener->public_addr_ipv4;
- *((uint16_t*)(mp->tail + 7)) = htons(chn->conn->directc2c_listener->public_port);
+ mp->tail[0] = len & 0xFF;
+ mp->tail[1] = (len >> 8) & 0xFF;
+
+ p = mp->tail + 2;
+
+ for (i = 0; i < count; i++)
+ {
+ *p++ = PICA_PROTO_DIRECTC2C_IPV4;
+ memcpy(p, &list[i].addr, 4);
+ memcpy(p + 4, &list[i].port, 2);
+ p += 6;
+ }
chn->directc2c_state = PICA_DIRECTC2C_STATE_WAITINGINCOMING;
}
@@ -4098,46 +4437,63 @@ int PICA_send_file_fragment(struct PICA_c2c *chn)
int PICA_start_call(struct PICA_c2c *chn)
{
- struct PICA_proto_msg *mp;
+ int ret;
if (chn->call_state != PICA_CALL_STATE_IDLE)
return PICA_ERRCALLINPROGRESS;
- if ((mp = c2c_writebuf_push(chn, PICA_PROTO_CALLREQ, PICA_PROTO_CALLREQ_SIZE)))
- {
- RAND_pseudo_bytes(mp->tail, 2);
- }
- else
+ ret = PICA_media_call_prepare(chn, 1, NULL, 0);
+
+ if (ret != PICA_OK)
+ return ret;
+
+ chn->call_state = PICA_CALL_STATE_CALLING;
+
+ /* 0x70 carries the address the node sees the call socket at, so it
+ * waits for the node's answer - normally one round trip - for a limited
+ * time, see process_calls()
+ */
+ chn->media_call->pending_deadline = PICA_media_now() + PICA_MEDIA_LEARN_TIMEOUT;
+
+ if (!PICA_media_call_ready(chn))
{
- return PICA_ERRNOMEM;
+ chn->media_call->pending_msg = PICA_PROTO_CALLREQ;
+ return PICA_OK;
}
- chn->call_state = PICA_CALL_STATE_CALLING;
+ ret = call_send_info(chn, PICA_PROTO_CALLREQ);
- return PICA_OK;
+ if (ret != PICA_OK)
+ call_release(chn);
+
+ return ret;
}
int PICA_pickup_call(struct PICA_c2c *chn)
{
- struct PICA_proto_msg *mp;
+ int ret;
if (chn->call_state != PICA_CALL_STATE_INCOMINGCALL)
return PICA_ERRCALLNOTINPROGRESS;
- if ((mp = c2c_writebuf_push(chn, PICA_PROTO_CALLANS, PICA_PROTO_CALLANS_SIZE)))
+ /* The address of the call socket has been asked for since the call
+ * started ringing and is usually known by now. If it is not, 0x71 waits
+ * for it a little longer; the call counts as answered for the user
+ * meanwhile.
+ */
+ if (chn->media_call)
+ chn->media_call->pending_deadline = PICA_media_now() + PICA_MEDIA_LEARN_TIMEOUT;
+
+ if (!PICA_media_call_ready(chn))
{
- RAND_pseudo_bytes(mp->tail, 2);
+ chn->media_call->pending_msg = PICA_PROTO_CALLANS;
+ chn->call_state = PICA_CALL_STATE_ANSWERING;
+ return PICA_OK;
}
- else
- {
- return PICA_ERRNOMEM;
- }
-
- chn->call_state = PICA_CALL_STATE_ACTIVE;
- PICA_media_start(chn);
+ ret = call_answered(chn);
- return PICA_OK;
+ return ret;
}
int PICA_reject_call(struct PICA_c2c *chn)
@@ -4156,7 +4512,7 @@ int PICA_reject_call(struct PICA_c2c *chn)
return PICA_ERRNOMEM;
}
- chn->call_state = PICA_CALL_STATE_IDLE;
+ call_release(chn);
return PICA_OK;
}
@@ -4168,6 +4524,16 @@ int PICA_hangup_call(struct PICA_c2c *chn)
if (chn->call_state == PICA_CALL_STATE_IDLE)
return PICA_ERRCALLNOTINPROGRESS;
+ /* A call whose 0x70 is still waiting to be sent does not exist for the
+ * peer yet, and a 0x73 would be a protocol error to it.
+ */
+ if (chn->call_state == PICA_CALL_STATE_CALLING && chn->media_call
+ && chn->media_call->pending_msg == PICA_PROTO_CALLREQ)
+ {
+ call_release(chn);
+ return PICA_OK;
+ }
+
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_CALLFIN, PICA_PROTO_CALLFIN_SIZE)))
{
RAND_pseudo_bytes(mp->tail, 2);
@@ -4177,22 +4543,16 @@ int PICA_hangup_call(struct PICA_c2c *chn)
return PICA_ERRNOMEM;
}
- // release call resources??
// handle incoming last stream packets?
- chn->call_state = PICA_CALL_STATE_IDLE;
-
- PICA_media_close(chn);
+ call_release(chn);
return PICA_OK;
}
-int PICA_set_call_audio_params(struct PICA_c2c *chn, const char *codec_name, uint16_t sample_rate)
+static int call_send_audio_params(struct PICA_c2c *chn, const char *codec_name, uint16_t sample_rate)
{
struct PICA_proto_msg *mp;
- if (chn->call_state != PICA_CALL_STATE_ACTIVE)
- return PICA_ERRCALLNOTINPROGRESS;
-
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_CALL_AUDIOPARAM, PICA_PROTO_CALL_AUDIOPARAM_SIZE)))
{
strncpy(mp->tail, codec_name, PICA_PROTO_CALL_CODECNAMESIZE);
@@ -4207,13 +4567,29 @@ int PICA_set_call_audio_params(struct PICA_c2c *chn, const char *codec_name, uin
return PICA_OK;
}
-int PICA_set_call_video_params(struct PICA_c2c *chn, const char *codec_name, uint16_t width, uint16_t height)
+int PICA_set_call_audio_params(struct PICA_c2c *chn, const char *codec_name, uint16_t sample_rate)
{
- struct PICA_proto_msg *mp;
+ struct PICA_media_call *mc = chn->media_call;
+
+ /* kept until 0x71 is out, see call_answered() */
+ if (chn->call_state == PICA_CALL_STATE_ANSWERING && mc)
+ {
+ snprintf(mc->audio_codec, sizeof(mc->audio_codec), "%s", codec_name);
+ mc->audio_sample_rate = sample_rate;
+ mc->audio_params_pending = 1;
+ return PICA_OK;
+ }
if (chn->call_state != PICA_CALL_STATE_ACTIVE)
return PICA_ERRCALLNOTINPROGRESS;
+ return call_send_audio_params(chn, codec_name, sample_rate);
+}
+
+static int call_send_video_params(struct PICA_c2c *chn, const char *codec_name, uint16_t width, uint16_t height)
+{
+ struct PICA_proto_msg *mp;
+
if ((mp = c2c_writebuf_push(chn, PICA_PROTO_CALL_VIDEOPARAM, PICA_PROTO_CALL_VIDEOPARAM_SIZE)))
{
strncpy(mp->tail, codec_name, PICA_PROTO_CALL_CODECNAMESIZE);
@@ -4229,6 +4605,25 @@ int PICA_set_call_video_params(struct PICA_c2c *chn, const char *codec_name, uin
return PICA_OK;
}
+int PICA_set_call_video_params(struct PICA_c2c *chn, const char *codec_name, uint16_t width, uint16_t height)
+{
+ struct PICA_media_call *mc = chn->media_call;
+
+ if (chn->call_state == PICA_CALL_STATE_ANSWERING && mc)
+ {
+ snprintf(mc->video_codec, sizeof(mc->video_codec), "%s", codec_name);
+ mc->video_width = width;
+ mc->video_height = height;
+ mc->video_params_pending = 1;
+ return PICA_OK;
+ }
+
+ if (chn->call_state != PICA_CALL_STATE_ACTIVE)
+ return PICA_ERRCALLNOTINPROGRESS;
+
+ return call_send_video_params(chn, codec_name, width, height);
+}
+
static int PICA_send_call_packet(struct PICA_c2c *chn, unsigned int msgid, uint16_t seq_num,
uint32_t timestamp, const char *buf, unsigned int len)
{
@@ -4337,6 +4732,7 @@ void PICA_close_c2c(struct PICA_c2c *chn)
//puts("PICA_close_c2c_chkp1");//debug
PICA_media_close(chn);
+ PICA_media_call_free(chn);
if (chn -> sendfile_stream)
fclose(chn -> sendfile_stream);
@@ -4415,8 +4811,6 @@ void PICA_close_listener(struct PICA_listener *l)
if (l->media)
PICA_media_listener_close(l->media);
- free(l->public_addr_dns);
-
while(l->accepted_connections)
{
struct PICA_directc2c *c = l->accepted_connections;
diff --git a/PICA_client.h b/PICA_client.h
index fe6ab5e..2bbbefa 100644
--- a/PICA_client.h
+++ b/PICA_client.h
@@ -156,6 +156,19 @@ typedef u_short in_port_t;
#define PICA_DIRECTC2C_ACCEPT_TIMEOUT 30
#define PICA_DIRECTC2C_MAX_ACCEPTED 32
+/* How long an outgoing direct connection may take to connect and finish its
+ * TLS handshake before the next announced address is tried. Without it, an
+ * address that silently drops the packets - a private address of the peer's
+ * network, seen from another one - would hold up the addresses after it for
+ * as long as the system keeps retrying the connection, minutes.
+ */
+#define PICA_DIRECTC2C_CONNECT_TIMEOUT 5
+
+/* Most addresses of a received 0x0B message that are tried, and most that
+ * a listener announces.
+ */
+#define PICA_DIRECTC2C_MAX_ADDRS 32
+
#define PICA_C2C_INCOMING 0
#define PICA_C2C_OUTGOING 1
@@ -247,6 +260,11 @@ struct PICA_c2n
time_t udpaddr_started;
time_t udpaddr_last_probe;
int udpaddr_probes_sent;
+ /* The call the request was made for by the library itself, or NULL when
+ * the application made it. The answer goes to that call instead of
+ * udp_address_cb.
+ */
+ struct PICA_c2c *udpaddr_c2c;
};
enum PICA_c2c_state
@@ -285,6 +303,12 @@ enum PICA_call_state
PICA_CALL_STATE_IDLE = 0,
PICA_CALL_STATE_CALLING,
PICA_CALL_STATE_INCOMINGCALL,
+ /* Answered by the user, but 0x71 not sent yet: it waits for the node to
+ * report the address of the media socket, see PICA_media_call. Call
+ * parameters set meanwhile are sent right after 0x71, media packets are
+ * dropped.
+ */
+ PICA_CALL_STATE_ANSWERING,
PICA_CALL_STATE_ACTIVE
};
@@ -303,6 +327,11 @@ struct PICA_directc2c
enum PICA_directc2c_connection_state state;
+ /* when the connection to the current address was started, see
+ * PICA_DIRECTC2C_CONNECT_TIMEOUT
+ */
+ time_t attempt_started;
+
/* When this incoming connection was accepted, used to reap it if its TLS
* handshake never completes. Only meaningful for accepted (incoming)
* connections held in a listener's accepted_connections list.
@@ -362,6 +391,20 @@ struct PICA_c2c
int call_video_params_are_set;
/** media connection of the call in progress, see PICA_media.h */
struct PICA_media_channel *media;
+ /** what the call in progress needs for UDP hole punching, see PICA_media.h */
+ struct PICA_media_call *media_call;
+};
+
+/* One entry of a manually configured address list, see
+ * PICA_listener_set_addrlist()
+ */
+struct PICA_listener_addr
+{
+ in_addr_t addr;
+ /** network byte order */
+ uint16_t port;
+ /** stands for the external address and port of the UPnP port mapping */
+ int is_upnp;
};
struct PICA_listener
@@ -369,11 +412,21 @@ struct PICA_listener
const struct PICA_acc *acc;
SOCKET sck_listener;
- int public_port;
+ /** TCP and UDP port listened on */
int local_port;
- in_addr_t public_addr_ipv4;
- const char *public_addr_dns;
+ /** The addresses announced in 0x0B. Automatic configuration when 0: the
+ * addresses of the network interfaces with local_port, then the UPnP
+ * mapping. Otherwise the list below, in its order.
+ */
+ int addrs_manual;
+ struct PICA_listener_addr addrs[PICA_DIRECTC2C_MAX_ADDRS];
+ int addrs_count;
+
+ /** external address and port of the UPnP port mapping made for this
+ * listener, network byte order; 0 when there is none */
+ in_addr_t upnp_addr;
+ uint16_t upnp_port;
struct PICA_directc2c *accepted_connections;
@@ -542,17 +595,44 @@ int PICA_new_c2n(const struct PICA_acc *acc, const char *nodeaddr, unsigned int
struct PICA_listener *l, struct PICA_c2n **ci);
int PICA_new_c2c(struct PICA_c2n *ci, const unsigned char *peer_id, struct PICA_listener *l, struct PICA_c2c **chn);
- /**
- * Opens socket to listen for incoming direct c2c connections bypassing nodes
+/**
+ * Opens the TCP port for incoming direct c2c connections bypassing nodes, and
+ * the UDP port with the same number for the media of calls.
+ *
+ * The addresses announced to peers are configured automatically until
+ * PICA_listener_set_addrlist() says otherwise: the addresses of the network
+ * interfaces, private ones first, with local_port, followed by the UPnP
+ * mapping once PICA_listener_set_upnp_addr() reports one.
+ *
* \param acc - pointer to opened account instance
- * \param public_addr - DNS name or IP address string,
- * it is an address that will be used for connecting from global Internet.
- * Should be set to router's external IP if computer running pica-client is located behind the NAT.
- * \param public_port - TCP port for incoming connections from global Internet
- * \param local_port - TCP port that will be actually opened on computer listening for direct c2c connections
+ * \param local_port - port number to listen on, TCP and UDP
* \param l - address of pointer that will be filled with address of created PICA_listener structure
+ * \retval PICA_ERRSOCK one of the two ports could not be opened, e.g. it is
+ * in use already
+ */
+int PICA_new_listener(const struct PICA_acc *acc, int local_port, struct PICA_listener **l);
+
+/**
+ * Sets the addresses announced to peers manually, in the order given.
+ * \param addrs IPv4 addresses or DNS names, the latter resolved here, which
+ * can block. A NULL entry stands for the external address of the UPnP port
+ * mapping, see PICA_listener_set_upnp_addr(), and is left out while there is
+ * none.
+ * \param ports the external port number of each address; for the UPnP entry
+ * the mapped port is announced instead
+ * \param count number of entries, up to PICA_DIRECTC2C_MAX_ADDRS; 0 goes
+ * back to automatic configuration
+ * \retval PICA_ERRDNSRESOLVE an address could not be resolved; the list is
+ * left as it was
+ */
+int PICA_listener_set_addrlist(struct PICA_listener *l, const char *const *addrs, const int *ports, int count);
+
+/**
+ * Reports the external address and port of a UPnP port mapping made for
+ * this listener, or that there is none any more when addr is NULL. Takes
+ * effect for the 0x0B messages sent from then on.
*/
-int PICA_new_listener(const struct PICA_acc *acc, const char *public_addr, int public_port, int local_port, struct PICA_listener **l);
+int PICA_listener_set_upnp_addr(struct PICA_listener *l, const char *addr, int port);
int PICA_open_acc(const char *cert_file,
const char *pkey_file,
diff --git a/PICA_media.c b/PICA_media.c
index 6d68c0b..c13c497 100644
--- a/PICA_media.c
+++ b/PICA_media.c
@@ -19,6 +19,8 @@
#include "PICA_media.h"
#include "PICA_proto.h"
#include "PICA_common.h"
+#include "PICA_netconf.h"
+#include <openssl/rand.h>
#include <string.h>
#include <time.h>
@@ -32,10 +34,37 @@
static void media_fail(struct PICA_media_channel *m);
static void media_handshake(struct PICA_media_channel *m);
+static int media_punch_start(struct PICA_c2c *c2c);
+
+#ifdef WIN32
+uint64_t PICA_media_now(void)
+{
+ /* GetTickCount64() would be simpler, but needs Vista as the minimum
+ * target and the headers are set up for XP
+ */
+ static LARGE_INTEGER freq;
+ LARGE_INTEGER count;
+
+ if (freq.QuadPart == 0)
+ QueryPerformanceFrequency(&freq);
+
+ QueryPerformanceCounter(&count);
+
+ return (uint64_t)(count.QuadPart / (freq.QuadPart / 1000));
+}
+#else
+uint64_t PICA_media_now(void)
+{
+ struct timespec ts;
+
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+
+ return (uint64_t)ts.tv_sec * 1000 + (uint64_t)ts.tv_nsec / 1000000;
+}
+#endif
static int media_socket_open(SOCKET *s, int local_port)
{
- int flag = 1;
struct sockaddr_in a;
*s = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
@@ -43,8 +72,11 @@ static int media_socket_open(SOCKET *s, int local_port)
if (*s == SOCKET_ERROR)
return PICA_ERRSOCK;
- setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, (const char*)&flag, sizeof(flag));
-
+ /* No SO_REUSEADDR: UDP has no TIME_WAIT for it to get around, while for
+ * UDP it lets a second socket bind to a port another one already uses -
+ * and the listener has to find out when its port is taken, so that it
+ * can try the next one instead of sharing it.
+ */
memset(&a, 0, sizeof(a));
a.sin_family = AF_INET;
a.sin_addr.s_addr = INADDR_ANY;
@@ -204,30 +236,309 @@ static struct PICA_media_channel *media_channel_new(struct PICA_c2c *c2c)
return m;
}
-void PICA_media_start(struct PICA_c2c *c2c)
+/* Whether an address from the peer's 0x70/0x71 is one worth sending probes
+ * to: a unicast address of a host, not of this one, and a port.
+ */
+static int is_probe_target(const struct sockaddr_in *a)
{
- struct PICA_media_channel *m;
- int ret;
+ in_addr_t addr = a->sin_addr.s_addr;
- PICA_TRACEFUNC
+ if (a->sin_port == 0)
+ return 0;
+
+ return PICA_is_private_addr_ipv4(addr) || !PICA_is_reserved_addr_ipv4(addr);
+}
+
+/* Stops a request for the call socket's address still waiting for the node,
+ * so that a late answer is not delivered to a call that no longer wants it.
+ */
+static void media_call_stop_learning(struct PICA_c2c *c2c)
+{
+ struct PICA_media_call *mc = c2c->media_call;
- if (c2c->media)
+ if (!mc->learning)
return;
- /* Media over UDP is only attempted between clients that already reached
- * each other directly over TCP: that address is known to work and the
- * user has already agreed to reveal it by enabling direct connections.
+ mc->learning = 0;
+
+ if (c2c->conn->udpaddr_c2c == c2c)
+ {
+ c2c->conn->udpaddr_c2c = NULL;
+ c2c->conn->udpaddr_state = PICA_UDPADDR_STATE_IDLE;
+ }
+}
+
+int PICA_media_call_prepare(struct PICA_c2c *c2c, int is_caller,
+ const unsigned char *peer_info, unsigned int peer_info_len)
+{
+ struct PICA_media_call *mc;
+ struct sockaddr_in a;
+#ifdef WIN32
+ int alen = sizeof(a);
+#else
+ socklen_t alen = sizeof(a);
+#endif
+
+ PICA_TRACEFUNC
+
+ PICA_media_call_free(c2c);
+
+ mc = (struct PICA_media_call*)calloc(sizeof(struct PICA_media_call), 1);
+
+ if (!mc)
+ return PICA_ERRNOMEM;
+
+ mc->sck = -1;
+ mc->is_caller = is_caller;
+
+ if (RAND_bytes(mc->token, sizeof(mc->token)) != 1)
+ {
+ free(mc);
+ return PICA_ERRSSL;
+ }
+
+ c2c->media_call = mc;
+
+ if (peer_info)
+ PICA_media_call_read_info(c2c, peer_info, peer_info_len);
+
+ /* Hole punching reveals this client's addresses to the peer, which the
+ * user has not agreed to with direct connections disabled. A callee
+ * whose caller sent no addresses could not punch anywhere either.
*/
- if (c2c->directc2c_state != PICA_DIRECTC2C_STATE_ACTIVE || !c2c->direct)
+ if (c2c->conn->directc2c_config == PICA_DIRECTC2C_CFG_DISABLED || !c2c->acc->dtls_ctx)
+ return PICA_OK;
+
+ if (!is_caller && mc->peer_addrs_count == 0)
+ return PICA_OK;
+
+ if (media_socket_open(&mc->sck, 0) != PICA_OK)
+ return PICA_OK;
+
+ if (getsockname(mc->sck, (struct sockaddr*)&a, &alen) == SOCKET_ERROR)
+ {
+ CLOSE(mc->sck);
+ mc->sck = -1;
+ return PICA_OK;
+ }
+
+ mc->local_port = ntohs(a.sin_port);
+
+ /* What the node sees is what the NAT in front of us maps this socket to
+ * - the one address a peer outside the local network can punch through
+ * to. Without it, only the interface addresses are announced.
+ */
+ if (PICA_request_udp_address(c2c->conn, mc->sck) == PICA_OK)
+ {
+ c2c->conn->udpaddr_c2c = c2c;
+ mc->learning = 1;
+ mc->learn_started = PICA_media_now();
+ }
+
+ return PICA_OK;
+}
+
+void PICA_media_call_learned(struct PICA_c2c *c2c, int status, const unsigned char *addr_bin, int type, uint16_t port)
+{
+ struct PICA_media_call *mc = c2c->media_call;
+
+ PICA_TRACEFUNC
+
+ if (!mc || !mc->learning)
+ return;
+
+ mc->learning = 0;
+
+ if (status != PICA_OK || type != PICA_PROTO_MYUDPADDR_IPV4)
return;
- if (!c2c->acc->dtls_ctx)
+ memset(&mc->learned_addr, 0, sizeof(mc->learned_addr));
+ mc->learned_addr.sin_family = AF_INET;
+ memcpy(&mc->learned_addr.sin_addr.s_addr, addr_bin, 4);
+ mc->learned_addr.sin_port = htons(port);
+ mc->learned = 1;
+}
+
+int PICA_media_call_ready(struct PICA_c2c *c2c)
+{
+ struct PICA_media_call *mc = c2c->media_call;
+
+ if (!mc || !mc->learning)
+ return 1;
+
+ return PICA_media_now() >= mc->pending_deadline;
+}
+
+static unsigned char *write_addr_ipv4(unsigned char *p, in_addr_t addr, uint16_t port_netorder)
+{
+ *p++ = PICA_PROTO_DIRECTC2C_IPV4;
+ memcpy(p, &addr, 4);
+ p += 4;
+ memcpy(p, &port_netorder, 2);
+
+ return p + 2;
+}
+
+unsigned int PICA_media_call_write_info(struct PICA_c2c *c2c, unsigned char *buf)
+{
+ struct PICA_media_call *mc = c2c->media_call;
+ unsigned char *p = buf;
+ in_addr_t ifaddrs[PICA_IFADDRS_MAX];
+ int n, i, count = 0;
+ int learned_is_ifaddr = 0;
+
+ PICA_TRACEFUNC
+
+ if (!mc)
+ return 0;
+
+ /* whatever the node did not answer in time stays unknown */
+ media_call_stop_learning(c2c);
+
+ memcpy(p, mc->token, PICA_PROTO_CALL_TOKENSIZE);
+ p += PICA_PROTO_CALL_TOKENSIZE;
+
+ if (mc->sck < 0)
+ return (unsigned int)(p - buf);
+
+ /* The interface addresses first, so that two clients on the same local
+ * network reach each other inside it, which works whether or not their
+ * router can loop traffic for its own external address back in. One
+ * place is kept for the address the node reported.
+ */
+ n = PICA_get_ifaddrs_ipv4(ifaddrs, PICA_IFADDRS_MAX);
+
+ for (i = 0; i < n && count < PICA_PROTO_CALL_MAXADDRS - 1; i++)
+ {
+ if (mc->learned && ifaddrs[i] == mc->learned_addr.sin_addr.s_addr
+ && ntohs(mc->learned_addr.sin_port) == mc->local_port)
+ learned_is_ifaddr = 1;
+
+ p = write_addr_ipv4(p, ifaddrs[i], htons((uint16_t)mc->local_port));
+ count++;
+ }
+
+ /* the same as an interface address when there is no NAT on the way */
+ if (mc->learned && !learned_is_ifaddr)
+ p = write_addr_ipv4(p, mc->learned_addr.sin_addr.s_addr, mc->learned_addr.sin_port);
+
+ return (unsigned int)(p - buf);
+}
+
+int PICA_media_call_read_info(struct PICA_c2c *c2c, const unsigned char *buf, unsigned int len)
+{
+ struct PICA_media_call *mc = c2c->media_call;
+ unsigned int pos;
+ int addresses = 0;
+
+ if (!mc)
+ return 0;
+
+ mc->peer_info_received = 1;
+ mc->peer_addrs_count = 0;
+
+ if (len < PICA_PROTO_CALL_TOKENSIZE)
+ return 0;
+
+ memcpy(mc->peer_token, buf, PICA_PROTO_CALL_TOKENSIZE);
+ pos = PICA_PROTO_CALL_TOKENSIZE;
+
+ while (pos < len && addresses < PICA_PROTO_CALL_MAXADDRS)
+ {
+ struct sockaddr_in *a;
+
+ switch (buf[pos])
+ {
+ case PICA_PROTO_DIRECTC2C_IPV4:
+ if (pos + PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE > len)
+ goto malformed;
+
+ addresses++;
+ a = &mc->peer_addrs[mc->peer_addrs_count];
+ memset(a, 0, sizeof(*a));
+ a->sin_family = AF_INET;
+ memcpy(&a->sin_addr.s_addr, buf + pos + 1, 4);
+ memcpy(&a->sin_port, buf + pos + 5, 2);
+
+ if (is_probe_target(a))
+ mc->peer_addrs_count++;
+
+ pos += PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE;
+ break;
+
+ case PICA_PROTO_DIRECTC2C_IPV6:
+ /* counts as an address, but the media sockets are IPv4 ones */
+ if (pos + PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV6_SIZE > len)
+ goto malformed;
+
+ addresses++;
+ pos += PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV6_SIZE;
+ break;
+
+ case PICA_PROTO_DIRECTC2C_DNS:
+ if (pos + 1 >= len || pos + 2 + buf[pos + 1] + 2 > len)
+ goto malformed;
+
+ pos += 2 + buf[pos + 1] + 2;
+ break;
+
+ default:
+ /* no way of knowing where an element of an unknown type ends */
+ goto malformed;
+ }
+ }
+
+ return 1;
+
+malformed:
+ /* An address list that does not parse cannot be relied on in any of its
+ * parts. The call goes ahead, only without hole punching.
+ */
+ mc->peer_addrs_count = 0;
+ return 0;
+}
+
+void PICA_media_call_free(struct PICA_c2c *c2c)
+{
+ struct PICA_media_call *mc = c2c->media_call;
+
+ if (!mc)
return;
+ /* the media connection of attempt 2 uses the call socket */
+ if (c2c->media && c2c->media->attempt == 2)
+ PICA_media_close(c2c);
+
+ media_call_stop_learning(c2c);
+
+ if (mc->sck >= 0)
+ CLOSE(mc->sck);
+
+ c2c->media_call = NULL;
+ free(mc);
+}
+
+/* Attempt 1, over the address of the directc2c connection. It goes first
+ * because that address is known to work already - the port behind it is
+ * public or forwarded, whatever the NATs on the way do with UDP.
+ */
+static int media_direct_start(struct PICA_c2c *c2c)
+{
+ struct PICA_media_channel *m;
+ int ret;
+
+ PICA_TRACEFUNC
+
+ if (c2c->directc2c_state != PICA_DIRECTC2C_STATE_ACTIVE || !c2c->direct)
+ return PICA_ERRNOTFOUND;
+
m = media_channel_new(c2c);
if (!m)
- return;
+ return PICA_ERRNOMEM;
+
+ m->attempt = 1;
+ m->deadline = PICA_media_now() + PICA_MEDIA_DIRECT_TIMEOUT;
if (c2c->direct->is_outgoing == PICA_DIRECTC2C_OUTGOING)
{
@@ -243,7 +554,7 @@ void PICA_media_start(struct PICA_c2c *c2c)
if (ret != PICA_OK)
{
free(m);
- return;
+ return ret;
}
m->owns_sck = 1;
@@ -252,14 +563,14 @@ void PICA_media_start(struct PICA_c2c *c2c)
{
CLOSE(m->sck);
free(m);
- return;
+ return PICA_ERRSOCK;
}
if (media_ssl_new(m) != PICA_OK)
{
CLOSE(m->sck);
free(m);
- return;
+ return PICA_ERRSSL;
}
SSL_set_connect_state(m->ssl);
@@ -267,6 +578,7 @@ void PICA_media_start(struct PICA_c2c *c2c)
m->state = PICA_MEDIA_STATE_HANDSHAKE;
c2c->media = m;
+ /* can fail, and start attempt 2 from there */
media_handshake(m);
}
else
@@ -276,7 +588,7 @@ void PICA_media_start(struct PICA_c2c *c2c)
if (!c2c->conn->directc2c_listener || !c2c->conn->directc2c_listener->media)
{
free(m);
- return;
+ return PICA_ERRNOTFOUND;
}
ml = c2c->conn->directc2c_listener->media;
@@ -284,7 +596,7 @@ void PICA_media_start(struct PICA_c2c *c2c)
if (ml->sck < 0 || ml->channel)
{
free(m);
- return;
+ return PICA_ERRSOCK;
}
/* Nothing to do until the peer sends its first datagram: the source
@@ -299,6 +611,91 @@ void PICA_media_start(struct PICA_c2c *c2c)
ml->channel = m;
c2c->media = m;
}
+
+ return PICA_OK;
+}
+
+static void media_send_probe_to(struct PICA_media_channel *m, const struct sockaddr_in *to)
+{
+ unsigned char probe[PICA_PROTO_MEDIAPROBE_SIZE];
+
+ probe[0] = probe[1] = PICA_PROTO_MEDIAPROBE;
+ memcpy(probe + 2, m->c2c->media_call->peer_token, PICA_PROTO_CALL_TOKENSIZE);
+
+ /* A failed send is the same as a datagram lost on the way. Once an
+ * address is selected the socket is connected to it, and sendto() with
+ * an address is not allowed on a connected socket everywhere.
+ */
+ if (to)
+ sendto(m->sck, (const char*)probe, sizeof(probe), 0, (const struct sockaddr*)to, sizeof(*to));
+ else
+ send(m->sck, (const char*)probe, sizeof(probe), 0);
+}
+
+/* Sends the probes that are due: to every address of the peer until one is
+ * selected, to the selected one afterwards until the peer's first DTLS
+ * datagram shows that it has selected us too.
+ */
+static void media_send_probes(struct PICA_media_channel *m, uint64_t now)
+{
+ struct PICA_media_call *mc = m->c2c->media_call;
+ int i;
+
+ if (m->dtls_seen || now - m->last_probe < PICA_MEDIA_PROBE_INTERVAL)
+ return;
+
+ m->last_probe = now;
+
+ if (m->state == PICA_MEDIA_STATE_PUNCHING)
+ {
+ for (i = 0; i < mc->peer_addrs_count; i++)
+ media_send_probe_to(m, &mc->peer_addrs[i]);
+ }
+ else
+ media_send_probe_to(m, NULL);
+}
+
+/* Attempt 2, by hole punching between the call sockets. */
+static int media_punch_start(struct PICA_c2c *c2c)
+{
+ struct PICA_media_call *mc = c2c->media_call;
+ struct PICA_media_channel *m;
+
+ PICA_TRACEFUNC
+
+ if (c2c->media || !mc || mc->sck < 0 || mc->peer_addrs_count == 0)
+ return PICA_ERRNOTFOUND;
+
+ m = media_channel_new(c2c);
+
+ if (!m)
+ return PICA_ERRNOMEM;
+
+ m->attempt = 2;
+ m->sck = mc->sck;
+ m->owns_sck = 0;
+ m->is_dtls_client = mc->is_caller;
+ m->state = PICA_MEDIA_STATE_PUNCHING;
+ m->deadline = PICA_media_now() + PICA_MEDIA_PUNCH_TIMEOUT;
+
+ c2c->media = m;
+
+ media_send_probes(m, PICA_media_now());
+
+ return PICA_OK;
+}
+
+void PICA_media_start(struct PICA_c2c *c2c)
+{
+ PICA_TRACEFUNC
+
+ if (c2c->media || !c2c->acc->dtls_ctx)
+ return;
+
+ if (media_direct_start(c2c) == PICA_OK)
+ return;
+
+ media_punch_start(c2c);
}
void PICA_media_close(struct PICA_c2c *c2c)
@@ -336,11 +733,16 @@ void PICA_media_close(struct PICA_c2c *c2c)
static void media_fail(struct PICA_media_channel *m)
{
struct PICA_c2c *c2c = m->c2c;
+ /* attempt 2 follows attempt 1 that did not succeed, see PICA_media.h */
+ int try_punching = m->attempt == 1 && m->state != PICA_MEDIA_STATE_ACTIVE;
PICA_TRACEFUNC
PICA_media_close(c2c);
+ if (try_punching && media_punch_start(c2c) == PICA_OK)
+ return;
+
/* the call carries on, its media goes back to the c2c connection */
PICA_media_transport_changed(c2c, PICA_CALL_TRANSPORT_C2C, NULL);
}
@@ -513,6 +915,151 @@ static void media_accept(struct PICA_media_channel *m)
media_handshake(m);
}
+/* Whether a datagram is a probe carrying our own token, i.e. one that comes
+ * from the peer of this call.
+ */
+static int is_our_probe(struct PICA_media_channel *m, const unsigned char *buf, int len)
+{
+ return len == PICA_PROTO_MEDIAPROBE_SIZE
+ && buf[0] == PICA_PROTO_MEDIAPROBE && buf[1] == PICA_PROTO_MEDIAPROBE
+ && memcmp(buf + 2, m->c2c->media_call->token, PICA_PROTO_CALL_TOKENSIZE) == 0;
+}
+
+/* The peer's probe came from this address, so this is where its NAT lets
+ * our datagrams through to it. From now on the socket only talks to it.
+ */
+static void media_punch_select(struct PICA_media_channel *m, const struct sockaddr_in *from)
+{
+ PICA_TRACEFUNC
+
+ m->peer_addr = *from;
+
+ if (connect(m->sck, (const struct sockaddr*)&m->peer_addr, sizeof(m->peer_addr)) == SOCKET_ERROR)
+ {
+ media_fail(m);
+ return;
+ }
+
+ m->deadline = PICA_media_now() + PICA_MEDIA_PUNCH_HANDSHAKE_TIMEOUT;
+
+ if (!m->is_dtls_client)
+ {
+ /* the caller learns that it can reach us from our probes */
+ m->state = PICA_MEDIA_STATE_SELECTED;
+ m->last_probe = 0;
+ media_send_probes(m, PICA_media_now());
+ return;
+ }
+
+ if (media_ssl_new(m) != PICA_OK)
+ {
+ media_fail(m);
+ return;
+ }
+
+ SSL_set_connect_state(m->ssl);
+
+ m->state = PICA_MEDIA_STATE_HANDSHAKE;
+ m->last_probe = 0;
+ media_send_probes(m, PICA_media_now());
+
+ media_handshake(m);
+}
+
+/* Reads what has arrived while no address is selected yet. Only a probe
+ * with our token counts; a DTLS datagram arriving this early is dropped and
+ * retransmitted by the peer later on, anything else is not from the peer.
+ */
+static void media_punch_read(struct PICA_media_channel *m)
+{
+ unsigned char buf[PICA_MEDIA_READBUFSIZE];
+ struct sockaddr_in from;
+#ifdef WIN32
+ int fromlen;
+#else
+ socklen_t fromlen;
+#endif
+ int ret;
+
+ while (1)
+ {
+ fromlen = sizeof(from);
+
+ ret = recvfrom(m->sck, (char*)buf, sizeof(buf), 0, (struct sockaddr*)&from, &fromlen);
+
+ if (ret < 0)
+ {
+#ifdef WIN32
+ /* Windows reports an ICMP port unreachable, caused by a probe
+ * sent to an address where nothing listens, on the next
+ * recvfrom() of the socket - which says nothing about the
+ * datagrams queued behind it.
+ */
+ if (WSAGetLastError() == WSAECONNRESET)
+ continue;
+#endif
+ return;
+ }
+
+ if (from.sin_family == AF_INET && is_our_probe(m, buf, ret))
+ {
+ /* can free m */
+ media_punch_select(m, &from);
+ return;
+ }
+ }
+}
+
+/* Takes the probes that are still arriving after an address was selected
+ * off the socket, before DTLS gets to read it - a DTLS record never starts
+ * with the octet of a probe.
+ * \return 1 if a datagram other than a probe is waiting
+ */
+static int media_skip_probes(struct PICA_media_channel *m)
+{
+ unsigned char buf[PICA_MEDIA_READBUFSIZE];
+ int ret;
+
+ while (1)
+ {
+ /* Large enough for any datagram, so that the peek never truncates:
+ * a truncated peek is reported as an error on Windows.
+ */
+ ret = recv(m->sck, (char*)buf, sizeof(buf), MSG_PEEK);
+
+ if (ret < 0)
+ return 0;
+
+ if (ret == 0 || buf[0] == PICA_PROTO_MEDIAPROBE)
+ {
+ recv(m->sck, (char*)buf, sizeof(buf), 0);
+ continue;
+ }
+
+ m->dtls_seen = 1;
+
+ return 1;
+ }
+}
+
+/* Attempt 2, the callee: the caller's handshake has started arriving. */
+static void media_punch_accept(struct PICA_media_channel *m)
+{
+ PICA_TRACEFUNC
+
+ if (media_ssl_new(m) != PICA_OK)
+ {
+ media_fail(m);
+ return;
+ }
+
+ SSL_set_accept_state(m->ssl);
+
+ m->state = PICA_MEDIA_STATE_HANDSHAKE;
+
+ media_handshake(m);
+}
+
static void media_read(struct PICA_media_channel *m)
{
struct PICA_c2c *c2c = m->c2c;
@@ -523,6 +1070,10 @@ static void media_read(struct PICA_media_channel *m)
*/
while (1)
{
+ /* a late probe of a hole punched connection */
+ if (m->attempt == 2 && SSL_pending(m->ssl) == 0 && !media_skip_probes(m))
+ return;
+
ret = SSL_read(m->ssl, m->read_buf, PICA_MEDIA_READBUFSIZE);
if (ret <= 0)
@@ -584,47 +1135,69 @@ void PICA_media_process(struct PICA_c2n *c2n, fd_set *rfds)
{
struct PICA_c2c *chan = c2n->chan_list_head;
time_t now = time(0);
+ uint64_t now_ms = PICA_media_now();
while (chan)
{
struct PICA_c2c *c2c = chan;
struct PICA_media_channel *m = c2c->media;
+ int readable;
chan = chan->next;
if (!m)
continue;
- if (m->state != PICA_MEDIA_STATE_ACTIVE
- && (now - m->started) > PICA_MEDIA_HANDSHAKE_TIMEOUT)
+ if (m->state != PICA_MEDIA_STATE_ACTIVE && now_ms >= m->deadline)
{
- fprintf(stderr, "media connection was not established in time\n");
+ fprintf(stderr, "media connection attempt %i was not completed in time\n", m->attempt);
media_fail(m);
continue;
}
- /* Anything below can close the media connection, which frees m -
- * hence the checks through c2c, which stays valid.
+ readable = m->sck >= 0 && FD_ISSET(m->sck, rfds);
+
+ /* Anything below that can close the media connection - which frees m,
+ * and can start another attempt in its place - is the last thing
+ * done with m in this pass, or is followed by a check through c2c,
+ * which stays valid.
*/
switch (m->state)
{
case PICA_MEDIA_STATE_LISTENING:
- if (m->sck >= 0 && FD_ISSET(m->sck, rfds))
+ if (readable)
media_accept(m);
break;
+ case PICA_MEDIA_STATE_PUNCHING:
+ media_send_probes(m, now_ms);
+
+ if (readable)
+ media_punch_read(m);
+ break;
+
+ case PICA_MEDIA_STATE_SELECTED:
+ media_send_probes(m, now_ms);
+
+ if (readable && media_skip_probes(m))
+ media_punch_accept(m);
+ break;
+
case PICA_MEDIA_STATE_HANDSHAKE:
+ if (m->attempt == 2)
+ media_send_probes(m, now_ms);
+
/* Lost handshake messages are retransmitted by OpenSSL, but
* only when it is told that its timer has expired.
*/
DTLSv1_handle_timeout(m->ssl);
- if (m->sck >= 0 && FD_ISSET(m->sck, rfds))
+ if (readable && (m->attempt != 2 || media_skip_probes(m)))
media_handshake(m);
break;
case PICA_MEDIA_STATE_ACTIVE:
- if (m->sck >= 0 && FD_ISSET(m->sck, rfds))
+ if (readable)
media_read(m);
if (!PICA_media_is_active(c2c))
diff --git a/PICA_media.h b/PICA_media.h
index 971b918..9a71302 100644
--- a/PICA_media.h
+++ b/PICA_media.h
@@ -17,12 +17,19 @@
/* mediac2c connections - call media over UDP, protected by DTLS.
*
- * A mediac2c connection exists only while a call is in progress and only
- * between two clients that already have an established directc2c connection.
- * It reuses that connection's address and port number with UDP instead of
- * TCP, so nothing has to be announced or negotiated over the c2c connection:
- * the client that made the outgoing directc2c connection is the DTLS client,
- * the one that accepted it is the DTLS server.
+ * A mediac2c connection exists only while a call is in progress. When the
+ * call becomes active, up to two attempts are made, one after another - see
+ * "Establishing the media connection" in doc/proto-doc-latest.txt:
+ *
+ * 1. Over the directc2c connection's address and port number, with UDP
+ * instead of TCP, if the call's c2c connection has an established directc2c
+ * one: the client that made the outgoing directc2c connection is the DTLS
+ * client, the one that accepted it is the DTLS server, listening on its
+ * PICA_media_listener.
+ *
+ * 2. By UDP hole punching between the media sockets the two clients opened
+ * for the call (PICA_media_call), over the addresses exchanged in 0x70 and
+ * 0x71. The caller is the DTLS client.
*
* Media packets are sent over this connection whenever it is established and
* over the c2c/directc2c connection otherwise; the receiving side accepts
@@ -53,11 +60,23 @@
*/
#define PICA_MEDIA_SAFE_PAYLOAD (PICA_MEDIA_LINK_MTU - 100)
-/* How long a call keeps trying to bring the media connection up before
- * giving up and carrying the media over the c2c connection for the rest of
- * the call, in seconds.
+/* The time limits of the two attempts, in milliseconds. A failed attempt 1
+ * is followed by attempt 2; once that fails too, the media stays on the c2c
+ * connection for the rest of the call.
+ */
+/* attempt 1, from the call becoming active to the handshake completing */
+#define PICA_MEDIA_DIRECT_TIMEOUT 5000
+/* attempt 2: probes are sent this often... */
+#define PICA_MEDIA_PROBE_INTERVAL 200
+/* ...for at most this long, until an address is selected */
+#define PICA_MEDIA_PUNCH_TIMEOUT 10000
+/* and the handshake has this long to complete once it is */
+#define PICA_MEDIA_PUNCH_HANDSHAKE_TIMEOUT 10000
+
+/* How long 0x70 and 0x71 wait for the node to report the address of the
+ * media socket before they are sent without it, in milliseconds.
*/
-#define PICA_MEDIA_HANDSHAKE_TIMEOUT 10
+#define PICA_MEDIA_LEARN_TIMEOUT 2000
/* An established media connection with no datagram received for this many
* seconds is considered broken; media falls back to the c2c connection.
@@ -71,6 +90,11 @@
#define PICA_MEDIA_READBUFSIZE 4096
+/* largest tail of 0x70/0x71 after the length field: the token and the
+ * addresses, IPv4 ones being the only kind sent
+ */
+#define PICA_MEDIA_CALL_INFO_MAXSIZE (PICA_PROTO_CALL_TOKENSIZE + PICA_PROTO_CALL_MAXADDRS * PICA_PROTO_DIRECTC2C_ADDRLIST_ITEM_IPV4_SIZE)
+
/* transport of the media packets of a call, reported by call_media_transport_cb */
#define PICA_CALL_TRANSPORT_C2C 0
#define PICA_CALL_TRANSPORT_MEDIAC2C 1
@@ -78,8 +102,15 @@
enum PICA_media_state
{
PICA_MEDIA_STATE_NEW = 0,
- /* DTLS server role, socket bound, waiting for the first datagram */
+ /* attempt 1, DTLS server role, socket bound, waiting for the first
+ * datagram */
PICA_MEDIA_STATE_LISTENING,
+ /* attempt 2, sending probes to every address of the peer, waiting for
+ * one of its probes to arrive */
+ PICA_MEDIA_STATE_PUNCHING,
+ /* attempt 2, DTLS server role, address selected, waiting for the first
+ * datagram of the handshake from it */
+ PICA_MEDIA_STATE_SELECTED,
PICA_MEDIA_STATE_HANDSHAKE,
PICA_MEDIA_STATE_ACTIVE,
PICA_MEDIA_STATE_FAILED
@@ -98,9 +129,53 @@ struct PICA_media_listener
struct PICA_media_channel *channel;
};
+/* Everything a call needs for hole punching, from the moment it starts to
+ * ring until it ends. Created by PICA_media_call_prepare(), freed by
+ * PICA_media_call_free().
+ */
+struct PICA_media_call
+{
+ /* the call socket, -1 if this side does not take part in hole punching */
+ SOCKET sck;
+ /* its port number, host byte order */
+ int local_port;
+ int is_caller;
+
+ unsigned char token[PICA_PROTO_CALL_TOKENSIZE];
+
+ /* the node is being asked for the address of sck */
+ int learning;
+ uint64_t learn_started;
+ /* what it answered, valid when learned is set */
+ int learned;
+ struct sockaddr_in learned_addr;
+
+ /* PICA_PROTO_CALLREQ or PICA_PROTO_CALLANS while that message waits for
+ * the address, 0 otherwise */
+ int pending_msg;
+ uint64_t pending_deadline;
+
+ /* from the peer's 0x70 or 0x71 */
+ int peer_info_received;
+ unsigned char peer_token[PICA_PROTO_CALL_TOKENSIZE];
+ struct sockaddr_in peer_addrs[PICA_PROTO_CALL_MAXADDRS];
+ int peer_addrs_count;
+
+ /* call parameters set while the call was PICA_CALL_STATE_ANSWERING */
+ int audio_params_pending;
+ char audio_codec[PICA_PROTO_CALL_CODECNAMESIZE + 1];
+ uint16_t audio_sample_rate;
+ int video_params_pending;
+ char video_codec[PICA_PROTO_CALL_CODECNAMESIZE + 1];
+ uint16_t video_width;
+ uint16_t video_height;
+};
+
struct PICA_media_channel
{
struct PICA_c2c *c2c;
+ /* 1 - over the directc2c address, 2 - by hole punching */
+ int attempt;
/* set when this side has the DTLS server role */
struct PICA_media_listener *listener;
@@ -117,6 +192,15 @@ struct PICA_media_channel
enum PICA_media_state state;
time_t started;
+ /* when the current stage of setting the connection up has to be
+ * complete, PICA_media_now() milliseconds */
+ uint64_t deadline;
+
+ /* attempt 2 */
+ uint64_t last_probe;
+ /* the first DTLS datagram has arrived from the selected address, the
+ * peer no longer needs probes */
+ int dtls_seen;
time_t last_rx;
time_t last_tx;
@@ -136,11 +220,48 @@ int PICA_media_listener_new(const struct PICA_acc *acc, int public_port, int loc
struct PICA_media_listener **ml);
void PICA_media_listener_close(struct PICA_media_listener *ml);
+/** Milliseconds from an arbitrary point, never going backwards. */
+uint64_t PICA_media_now(void);
+
+/**
+ * Starts preparing for hole punching: opens the call socket and asks the
+ * node for its address - for the caller before it sends 0x70, for the
+ * callee when 0x70 arrives. Without hole punching, e.g. with direct
+ * connections disabled, only creates c2c->media_call, whose address list is
+ * then empty.
+ * \param peer_info for the callee, the tail of the caller's 0x70 after the
+ * length field, see PICA_media_call_read_info(); NULL for the caller
+ */
+int PICA_media_call_prepare(struct PICA_c2c *c2c, int is_caller,
+ const unsigned char *peer_info, unsigned int peer_info_len);
+
+/** The node's answer about the call socket's address; status as in
+ * udp_address_cb. */
+void PICA_media_call_learned(struct PICA_c2c *c2c, int status, const unsigned char *addr_bin, int type, uint16_t port);
+
+/** Whether 0x70/0x71 can be sent now: the address is known, or will not be. */
+int PICA_media_call_ready(struct PICA_c2c *c2c);
+
+/**
+ * Writes the probe token and the address list of 0x70/0x71 to buf.
+ * \return number of octets written, at most PICA_MEDIA_CALL_INFO_MAXSIZE
+ */
+unsigned int PICA_media_call_write_info(struct PICA_c2c *c2c, unsigned char *buf);
+
+/**
+ * Takes the probe token and the address list from the tail of the peer's
+ * 0x70/0x71, after the length field.
+ * \return 0 if it is malformed
+ */
+int PICA_media_call_read_info(struct PICA_c2c *c2c, const unsigned char *buf, unsigned int len);
+
+/** Releases everything PICA_media_call_prepare() made. */
+void PICA_media_call_free(struct PICA_c2c *c2c);
+
/**
- * Brings up a media connection for a call that has just become active.
- * Does nothing if the preconditions (an established directc2c connection,
- * and a media listener on the accepting side) are not met - the media then
- * stays on the c2c connection.
+ * Brings up a media connection for a call that has just become active, see
+ * the two attempts above. Does nothing if neither of them can be made - the
+ * media then stays on the c2c connection.
*/
void PICA_media_start(struct PICA_c2c *c2c);
void PICA_media_close(struct PICA_c2c *c2c);
diff --git a/PICA_netconf.c b/PICA_netconf.c
index 551c395..1407834 100644
--- a/PICA_netconf.c
+++ b/PICA_netconf.c
@@ -1,5 +1,5 @@
/*
- (c) Copyright 2012 - 2018 Anton Sviridenko
+ (c) Copyright 2012 - 2026 Anton Sviridenko
https://picapica.im
This program is free software: you can redistribute it and/or modify
@@ -16,13 +16,14 @@
*/
#include "PICA_netconf.h"
#include <stddef.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
#ifdef HAVE_LIBMINIUPNPC
#include <miniupnpc/miniupnpc.h>
-#include <miniupnpc/miniwget.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
-#include <stdio.h>
#endif
#ifndef WIN32
@@ -59,136 +60,726 @@ int PICA_is_reserved_addr_ipv4(in_addr_t addr)
return 0;
}
-in_addr_t PICA_guess_listening_addr_ipv4()
+int PICA_is_private_addr_ipv4(in_addr_t addr)
{
- in_addr_t retaddr = INADDR_ANY;
- int found_global = 0;
-#ifndef WIN32
- struct ifaddrs *ifaddr, *ifa;
+ return (addr & PREFIX8) == MAKEIP(10, 0, 0, 0)
+ || (addr & PREFIX12) == MAKEIP(172, 16, 0, 0)
+ || (addr & PREFIX16) == MAKEIP(192, 168, 0, 0)
+ || (addr & PREFIX10) == MAKEIP(100, 64, 0, 0);
+}
- if (getifaddrs(&ifaddr) == -1)
- return INADDR_ANY;
+/* Whether an interface address is worth telling a peer about at all: either
+ * a private one, reachable from the same network, or a public one.
+ */
+static int is_usable_ifaddr_ipv4(in_addr_t addr)
+{
+ return PICA_is_private_addr_ipv4(addr) || !PICA_is_reserved_addr_ipv4(addr);
+}
- for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
- {
- if (ifa->ifa_addr == NULL)
- continue;
+/* Collects the usable addresses into addrs, the private ones (want_private)
+ * or the public ones, skipping the ones already there.
+ */
+static void ifaddr_add(in_addr_t *addrs, int maxcount, int *count, in_addr_t a, int want_private)
+{
+ int i;
+
+ if (!is_usable_ifaddr_ipv4(a) || PICA_is_private_addr_ipv4(a) != want_private)
+ return;
- if (ifa->ifa_addr->sa_family != AF_INET)
- continue;
+ for (i = 0; i < *count; i++)
+ if (addrs[i] == a)
+ return;
+
+ if (*count < maxcount)
+ addrs[(*count)++] = a;
+}
+
+#ifndef WIN32
+int PICA_get_ifaddrs_ipv4(in_addr_t *addrs, int maxcount)
+{
+ struct ifaddrs *ifaddr, *ifa;
+ int count = 0;
+ int want_private;
- if (ifa->ifa_flags & IFF_LOOPBACK)
- continue;
+ if (!addrs || maxcount <= 0)
+ return 0;
- if (!((ifa->ifa_flags & IFF_RUNNING) && (ifa->ifa_flags & IFF_UP)))
- continue;
+ if (getifaddrs(&ifaddr) == -1)
+ return 0;
- if (!found_global)
+ /* two passes: the private addresses go first, see the 0x0B message */
+ for (want_private = 1; want_private >= 0; want_private--)
+ for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
{
- retaddr = ((struct sockaddr_in*)ifa->ifa_addr)->sin_addr.s_addr;
+ if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET)
+ continue;
- if (!PICA_is_reserved_addr_ipv4(retaddr))
- found_global = 1;
+ if (ifa->ifa_flags & IFF_LOOPBACK)
+ continue;
+
+ if (!((ifa->ifa_flags & IFF_RUNNING) && (ifa->ifa_flags & IFF_UP)))
+ continue;
+
+ ifaddr_add(addrs, maxcount, &count,
+ ((struct sockaddr_in*)ifa->ifa_addr)->sin_addr.s_addr, want_private);
}
- }
freeifaddrs(ifaddr);
+
+ return count;
+}
#else
- char databuf[16384];
- ULONG size = sizeof databuf;
+int PICA_get_ifaddrs_ipv4(in_addr_t *addrs, int maxcount)
+{
+ PIP_ADAPTER_ADDRESSES buf = NULL, ap;
+ PIP_ADAPTER_UNICAST_ADDRESS ua;
+ ULONG size = 16384;
ULONG ret;
- PIP_ADAPTER_ADDRESSES addrs = (PIP_ADAPTER_ADDRESSES)databuf;
- PIP_ADAPTER_ADDRESSES ap;
-
- ret = GetAdaptersAddresses(AF_INET,
- GAA_FLAG_SKIP_ANYCAST
- | GAA_FLAG_SKIP_MULTICAST
- | GAA_FLAG_SKIP_DNS_SERVER
- | GAA_FLAG_SKIP_FRIENDLY_NAME,
- NULL,
- addrs, &size);
-
- if (ret != NO_ERROR)
- return INADDR_ANY;
+ int count = 0;
+ int want_private;
+ int tries;
+
+ if (!addrs || maxcount <= 0)
+ return 0;
- ap = addrs;
- while(ap)
+ /* The size needed is only known by trying, and can grow between the
+ * attempts if an adapter appears meanwhile.
+ */
+ for (tries = 0; tries < 3; tries++)
{
- retaddr = ((struct sockaddr_in*)ap->FirstUnicastAddress->Address.lpSockaddr)->sin_addr.s_addr;
- if (!PICA_is_reserved_addr_ipv4(retaddr))
+ buf = (PIP_ADAPTER_ADDRESSES)malloc(size);
+
+ if (!buf)
+ return 0;
+
+ ret = GetAdaptersAddresses(AF_INET,
+ GAA_FLAG_SKIP_ANYCAST
+ | GAA_FLAG_SKIP_MULTICAST
+ | GAA_FLAG_SKIP_DNS_SERVER
+ | GAA_FLAG_SKIP_FRIENDLY_NAME,
+ NULL, buf, &size);
+
+ if (ret == NO_ERROR)
break;
- ap = ap->Next;
+
+ free(buf);
+ buf = NULL;
+
+ if (ret != ERROR_BUFFER_OVERFLOW)
+ return 0;
}
+ if (!buf)
+ return 0;
+
+ for (want_private = 1; want_private >= 0; want_private--)
+ for (ap = buf; ap; ap = ap->Next)
+ {
+ if (ap->OperStatus != IfOperStatusUp || ap->IfType == IF_TYPE_SOFTWARE_LOOPBACK)
+ continue;
+
+ for (ua = ap->FirstUnicastAddress; ua; ua = ua->Next)
+ {
+ if (ua->Address.lpSockaddr->sa_family != AF_INET)
+ continue;
+
+ ifaddr_add(addrs, maxcount, &count,
+ ((struct sockaddr_in*)ua->Address.lpSockaddr)->sin_addr.s_addr, want_private);
+ }
+ }
+
+ free(buf);
+
+ return count;
+}
#endif
- return retaddr;
+
+in_addr_t PICA_guess_listening_addr_ipv4()
+{
+ in_addr_t addrs[PICA_IFADDRS_MAX];
+ int n, i;
+
+ n = PICA_get_ifaddrs_ipv4(addrs, PICA_IFADDRS_MAX);
+
+ if (n == 0)
+ return INADDR_ANY;
+
+ /* the first public address if there is one, the first private one
+ * otherwise
+ */
+ for (i = 0; i < n; i++)
+ if (!PICA_is_private_addr_ipv4(addrs[i]))
+ return addrs[i];
+
+ return addrs[0];
}
#ifdef HAVE_LIBMINIUPNPC
-int PICA_upnp_autoconfigure_ipv4(int public_port, int local_port, char *public_ip)
+
+/* UPnP error codes this code acts on, rather than just reporting */
+#define UPNP_ERR_CONFLICT 718
+#define UPNP_ERR_PERMONLY 725
+#define UPNP_ERR_CONFLICTOTHERMECH 729
+
+/* sizes the IGD's mapping table entries are read into, from
+ * UPNP_GetSpecificPortMappingEntry()
+ */
+#define ENTRY_CLIENT_SIZE 16
+#define ENTRY_PORT_SIZE 6
+#define ENTRY_DESC_SIZE 80
+#define ENTRY_FLAG_SIZE 4
+#define ENTRY_LEASE_SIZE 16
+
+struct PICA_upnp_ctx
{
- struct UPNPDev *devlist = NULL;
- int error = 0;
struct UPNPUrls urls;
struct IGDdatas data;
+ /* our address on the side the IGD is on - what mappings point at */
char lanaddr[64];
- char wanaddr[64];
- char ppstr[8];
- char lpstr[8];
+ int discover_timeout_ms;
+
+ /* the mapping held through this context, if any */
+ int mapped;
+ int port;
+ /* lease asked for, 0 for a permanent mapping */
+ unsigned int lease_asked;
+ /* lease the IGD granted, which can be less */
+ unsigned int lease;
+ char desc[ENTRY_DESC_SIZE];
+};
+
+static void portstr(char *buf, size_t buflen, int port)
+{
+ snprintf(buf, buflen, "%d", port);
+}
+
+/* Whether the request reached the IGD at all. miniupnpc answers its own
+ * problems - the control URL not responding, a reply that did not parse -
+ * with negative values, and anything the device itself refused with the
+ * positive UPnP error code it sent.
+ */
+static int comm_error(int ret)
+{
+ return ret < 0;
+}
+
+static int is_conflict(int ret)
+{
+ return ret == UPNP_ERR_CONFLICT || ret == UPNP_ERR_CONFLICTOTHERMECH;
+}
+
+static void drop_igd(struct PICA_upnp_ctx *ctx)
+{
+ if (ctx->urls.controlURL)
+ {
+ FreeUPNPUrls(&ctx->urls);
+ memset(&ctx->urls, 0, sizeof(ctx->urls));
+ }
+}
+
+static int find_igd(struct PICA_upnp_ctx *ctx)
+{
+ struct UPNPDev *devlist;
+ int error = 0;
int ret;
+#if MINIUPNPC_API_VERSION >= 18
+ char wanaddr[64];
+#endif
+
+ drop_igd(ctx);
#if MINIUPNPC_API_VERSION < 14
- devlist = upnpDiscover(2000, 0, 0, 0, 0, &error);
+ devlist = upnpDiscover(ctx->discover_timeout_ms, 0, 0, 0, 0, &error);
#else
- devlist = upnpDiscover(2000, 0, 0, 0, 0, 2, &error);
+ devlist = upnpDiscover(ctx->discover_timeout_ms, 0, 0, 0, 0, 2, &error);
#endif
+ if (!devlist)
+ return PICA_UPNP_ERRNOIGD;
+
+#if MINIUPNPC_API_VERSION < 18
+ ret = UPNP_GetValidIGD(devlist, &ctx->urls, &ctx->data, ctx->lanaddr, sizeof(ctx->lanaddr));
+#else
+ ret = UPNP_GetValidIGD(devlist, &ctx->urls, &ctx->data, ctx->lanaddr, sizeof(ctx->lanaddr),
+ wanaddr, sizeof(wanaddr));
+#endif
+
+ freeUPNPDevlist(devlist);
+
+ if (ret == 1)
+ return PICA_UPNP_OK;
+
+ /* Every outcome but "nothing found" leaves the URLs allocated, usable or
+ * not.
+ */
+ drop_igd(ctx);
+
+ /* The meaning of the other values changed when the wanaddr parameter
+ * appeared: before that there were three of them, now there are four and
+ * an IGD whose own external address is private has one of its own.
+ */
#if MINIUPNPC_API_VERSION < 18
- ret = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
+ if (ret == 2)
+ return PICA_UPNP_ERRNOTCONN;
#else
- ret = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr), wanaddr, sizeof(wanaddr));
+ if (ret == 2)
+ return PICA_UPNP_ERRPRIVADDR;
+
+ if (ret == 3)
+ return PICA_UPNP_ERRNOTCONN;
#endif
- if (ret != 1)
+
+ return PICA_UPNP_ERRNOIGD;
+}
+
+/* The control URLs are gone when an earlier attempt to find the IGD again
+ * failed - after it rebooted, say - and have to be looked for once more
+ * before anything can be asked of it.
+ */
+static int ensure_igd(struct PICA_upnp_ctx *ctx)
+{
+ if (ctx->urls.controlURL)
+ return PICA_UPNP_OK;
+
+ return find_igd(ctx);
+}
+
+/* Reads the IGD's mapping table entry for this port.
+ * \return PICA_UPNP_OK and whether the entry points at the same port of this
+ * very machine - i.e. whether it is ours, made by this client now or by an
+ * earlier run of it - through ours, and the remaining lease through lease;
+ * otherwise the UPnP error (714 NoSuchEntryInArray when there is none)
+ */
+static int read_entry(struct PICA_upnp_ctx *ctx, const char *proto, int port, int *ours, unsigned int *lease)
+{
+ char portbuf[8];
+ char client[ENTRY_CLIENT_SIZE] = "";
+ char intport[ENTRY_PORT_SIZE] = "";
+ char desc[ENTRY_DESC_SIZE] = "";
+ char enabled[ENTRY_FLAG_SIZE] = "";
+ char leasebuf[ENTRY_LEASE_SIZE] = "";
+ int ret;
+
+ portstr(portbuf, sizeof(portbuf), port);
+
+ ret = UPNP_GetSpecificPortMappingEntry(ctx->urls.controlURL, ctx->data.first.servicetype,
+ portbuf, proto, NULL,
+ client, intport, desc, enabled, leasebuf);
+
+ if (ret != UPNPCOMMAND_SUCCESS)
+ return comm_error(ret) ? PICA_UPNP_ERRIGD : ret;
+
+ if (ours)
+ *ours = strcmp(client, ctx->lanaddr) == 0 && atoi(intport) == port;
+
+ if (lease)
+ *lease = (unsigned int)strtoul(leasebuf, NULL, 10);
+
+ return PICA_UPNP_OK;
+}
+
+static int entry_is_ours(struct PICA_upnp_ctx *ctx, const char *proto, int port)
+{
+ int ours = 0;
+
+ return read_entry(ctx, proto, port, &ours, NULL) == PICA_UPNP_OK && ours;
+}
+
+static void del_mapping(struct PICA_upnp_ctx *ctx, const char *proto, int port)
+{
+ char portbuf[8];
+
+ if (!ctx->urls.controlURL)
+ return;
+
+ portstr(portbuf, sizeof(portbuf), port);
+
+ UPNP_DeletePortMapping(ctx->urls.controlURL, ctx->data.first.servicetype,
+ portbuf, proto, NULL);
+}
+
+/* One AddPortMapping, external and internal port the same, with the lease
+ * this context settled on. A device that only supports permanent mappings
+ * says so with 725 instead of mapping anything; the context remembers that
+ * and stops asking for a lease.
+ */
+static int add_mapping(struct PICA_upnp_ctx *ctx, const char *proto, int port)
+{
+ char portbuf[8], leasebuf[16];
+ int ret;
+
+ portstr(portbuf, sizeof(portbuf), port);
+ snprintf(leasebuf, sizeof(leasebuf), "%u", ctx->lease_asked);
+
+ ret = UPNP_AddPortMapping(ctx->urls.controlURL, ctx->data.first.servicetype,
+ portbuf, portbuf, ctx->lanaddr, ctx->desc, proto, NULL, leasebuf);
+
+ if (ret == UPNP_ERR_PERMONLY && ctx->lease_asked != 0)
{
- freeUPNPDevlist(devlist);
- return 0;
+ ctx->lease_asked = 0;
+ snprintf(leasebuf, sizeof(leasebuf), "0");
+
+ ret = UPNP_AddPortMapping(ctx->urls.controlURL, ctx->data.first.servicetype,
+ portbuf, portbuf, ctx->lanaddr, ctx->desc, proto, NULL, leasebuf);
}
- ret = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, public_ip);
+ /* A conflict with a mapping that is ours anyway - this client having been
+ * killed before it could delete it, or a renewal on a device that does
+ * not let a mapping be added over itself - is no conflict. Taking it out
+ * and making it again is what gets it a fresh lease.
+ */
+ if (is_conflict(ret) && entry_is_ours(ctx, proto, port))
+ {
+ del_mapping(ctx, proto, port);
- if (ret != UPNPCOMMAND_SUCCESS)
+ ret = UPNP_AddPortMapping(ctx->urls.controlURL, ctx->data.first.servicetype,
+ portbuf, portbuf, ctx->lanaddr, ctx->desc, proto, NULL, leasebuf);
+ }
+
+ if (ret == UPNPCOMMAND_SUCCESS)
+ return PICA_UPNP_OK;
+
+ if (comm_error(ret))
+ return PICA_UPNP_ERRIGD;
+
+ return is_conflict(ret) ? PICA_UPNP_ERRCONFLICT : ret;
+}
+
+/* Maps the port number for both protocols, or for none: a pair where only
+ * one half could be had is of no use and is given back. A failure of the
+ * second half after the first one succeeded means that this port number is
+ * not to be had, whatever the device answered, so it is reported as a
+ * conflict - the next number may well do.
+ */
+static int map_pair(struct PICA_upnp_ctx *ctx, int port)
+{
+ int ret;
+ unsigned int granted = 0;
+
+ ret = ensure_igd(ctx);
+
+ if (ret != PICA_UPNP_OK)
+ return ret;
+
+ ret = add_mapping(ctx, "TCP", port);
+
+ if (ret != PICA_UPNP_OK)
+ return ret;
+
+ ret = add_mapping(ctx, "UDP", port);
+
+ if (ret != PICA_UPNP_OK)
{
- freeUPNPDevlist(devlist);
- FreeUPNPUrls(&urls);
- return 0;
+ del_mapping(ctx, "TCP", port);
+ return ret == PICA_UPNP_ERRIGD ? ret : PICA_UPNP_ERRCONFLICT;
+ }
+
+ /* A device is free to grant a shorter lease than the one asked for -
+ * IGD:2 ones clamp it to a week at most - and renewal has to be timed by
+ * what it actually granted. Devices that do not report it are assumed to
+ * have granted the request.
+ */
+ ctx->lease = ctx->lease_asked;
+
+ if (read_entry(ctx, "TCP", port, NULL, &granted) == PICA_UPNP_OK
+ && granted > 0 && (ctx->lease == 0 || granted < ctx->lease))
+ ctx->lease = granted;
+
+ ctx->port = port;
+ ctx->mapped = 1;
+
+ return PICA_UPNP_OK;
+}
+
+int PICA_upnp_discover(int timeout_ms, struct PICA_upnp_ctx **ctx)
+{
+ struct PICA_upnp_ctx *c;
+ int ret;
+
+ if (!ctx || timeout_ms <= 0)
+ return PICA_UPNP_ERRINVARG;
+
+ c = (struct PICA_upnp_ctx*)calloc(1, sizeof(struct PICA_upnp_ctx));
+
+ if (!c)
+ return PICA_UPNP_ERRNOMEM;
+
+ c->discover_timeout_ms = timeout_ms;
+
+ ret = find_igd(c);
+
+ if (ret != PICA_UPNP_OK)
+ {
+ free(c);
+ return ret;
}
- sprintf(ppstr, "%u", public_port);
- sprintf(lpstr, "%u", local_port);
+ *ctx = c;
+
+ return PICA_UPNP_OK;
+}
+
+void PICA_upnp_free(struct PICA_upnp_ctx *ctx)
+{
+ if (!ctx)
+ return;
+
+ PICA_upnp_unmap(ctx);
+ drop_igd(ctx);
+ free(ctx);
+}
+
+int PICA_upnp_external_addr(struct PICA_upnp_ctx *ctx, char *addr, size_t addrlen)
+{
+ /* UPNP_GetExternalIPAddress() writes an address of up to 16 octets and
+ * nothing else, so it gets a buffer that is known to be big enough.
+ */
+ char buf[64] = "";
+ int ret;
+
+ if (!ctx || !addr || addrlen < 16)
+ return PICA_UPNP_ERRINVARG;
- ret = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
- ppstr, lpstr, lanaddr, "Pica Pica", "TCP", 0, "0");
+ ret = ensure_igd(ctx);
+ if (ret != PICA_UPNP_OK)
+ return ret;
+
+ ret = UPNP_GetExternalIPAddress(ctx->urls.controlURL, ctx->data.first.servicetype, buf);
if (ret != UPNPCOMMAND_SUCCESS)
- ret = 0;
- else
- ret = 1;
+ return comm_error(ret) ? PICA_UPNP_ERRIGD : ret;
+
+ if (inet_addr(buf) == INADDR_NONE)
+ return PICA_UPNP_ERRIGD;
+
+ /* Behind a second NAT - the provider's, usually - the IGD's external
+ * address is private too, and a mapping on it leads nowhere from the
+ * Internet.
+ */
+ if (PICA_is_reserved_addr_ipv4(inet_addr(buf)))
+ return PICA_UPNP_ERRPRIVADDR;
+
+ snprintf(addr, addrlen, "%s", buf);
+
+ return PICA_UPNP_OK;
+}
+
+const char *PICA_upnp_lan_addr(const struct PICA_upnp_ctx *ctx)
+{
+ return ctx ? ctx->lanaddr : "";
+}
+
+int PICA_upnp_map(struct PICA_upnp_ctx *ctx, int port, unsigned int lease_secs, const char *desc)
+{
+ if (!ctx || port <= 0 || port > 65535)
+ return PICA_UPNP_ERRINVARG;
+
+ PICA_upnp_unmap(ctx);
+
+ ctx->lease_asked = lease_secs;
+ snprintf(ctx->desc, sizeof(ctx->desc), "%s", desc ? desc : "Pica Pica");
+
+ return map_pair(ctx, port);
+}
+
+int PICA_upnp_refresh(struct PICA_upnp_ctx *ctx)
+{
+ int ret, ours = 0;
+ int port;
+
+ if (!ctx || !ctx->mapped)
+ return PICA_UPNP_ERRINVARG;
+
+ port = ctx->port;
- /* The port with the same number carries call media over UDP, see
- * PICA_media.h. Failing to map it only costs calls their UDP transport,
- * so it does not change the result reported for the TCP mapping.
+ ret = ensure_igd(ctx);
+
+ if (ret != PICA_UPNP_OK)
+ {
+ ctx->mapped = 0;
+ return ret;
+ }
+
+ /* Either the mapping is there and ours, or it is gone (714), or the port
+ * now points somewhere else, or the IGD does not answer at all - which of
+ * them it is decides what to do, so it has to be read rather than guessed.
*/
- if (UPNPCOMMAND_SUCCESS != UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
- ppstr, lpstr, lanaddr, "Pica Pica media", "UDP", 0, "0"))
+ ret = read_entry(ctx, "TCP", port, &ours, NULL);
+
+ if (ret == PICA_UPNP_ERRIGD)
{
- fprintf(stderr, "failed to forward UDP port %s for call media\n", ppstr);
+ /* The control URLs are an address and a path the IGD handed out
+ * once; after it rebooted, or changed address, they lead nowhere
+ * and the device has to be looked for again.
+ */
+ ret = find_igd(ctx);
+
+ if (ret != PICA_UPNP_OK)
+ {
+ ctx->mapped = 0;
+ return ret;
+ }
+ }
+ else if (ret == PICA_UPNP_OK && !ours)
+ {
+ /* Something else behind this IGD took the port over - another
+ * instance, another machine, or a different program altogether.
+ * Many devices let that happen silently instead of reporting a
+ * conflict. The mapping is not ours to renew any more.
+ */
+ fprintf(stderr, "UPnP: external port %i has been taken over by another host\n", port);
+ ctx->mapped = 0;
+ return PICA_UPNP_ERRCONFLICT;
}
- freeUPNPDevlist(devlist);
- FreeUPNPUrls(&urls);
- return ret;
+ /* Adding the mapping again is what renews its lease; it also puts it back
+ * when the IGD has dropped or forgotten it in the meantime.
+ */
+ ctx->mapped = 0;
+
+ return map_pair(ctx, port);
}
-#endif
+void PICA_upnp_unmap(struct PICA_upnp_ctx *ctx)
+{
+ if (!ctx || !ctx->mapped)
+ return;
+
+ del_mapping(ctx, "TCP", ctx->port);
+ del_mapping(ctx, "UDP", ctx->port);
+
+ ctx->mapped = 0;
+ ctx->port = 0;
+}
+
+int PICA_upnp_mapped(const struct PICA_upnp_ctx *ctx)
+{
+ return ctx && ctx->mapped;
+}
+
+int PICA_upnp_port(const struct PICA_upnp_ctx *ctx)
+{
+ return (ctx && ctx->mapped) ? ctx->port : 0;
+}
+
+unsigned int PICA_upnp_lease(const struct PICA_upnp_ctx *ctx)
+{
+ return ctx ? ctx->lease : 0;
+}
+
+const char *PICA_upnp_strerror(int ret)
+{
+ const char *s;
+
+ switch (ret)
+ {
+ case PICA_UPNP_OK:
+ return "success";
+
+ case PICA_UPNP_ERRNOIGD:
+ return "no UPnP internet gateway device found on the local network";
+
+ case PICA_UPNP_ERRNOTCONN:
+ return "the UPnP gateway reports that it has no internet connection";
+
+ case PICA_UPNP_ERRNOMEM:
+ return "out of memory";
+
+ case PICA_UPNP_ERRINVARG:
+ return "invalid argument";
+
+ case PICA_UPNP_ERRCONFLICT:
+ return "the port is already forwarded to another host";
+
+ case PICA_UPNP_ERRPRIVADDR:
+ return "the UPnP gateway itself has a private address, it is behind another NAT";
+
+ case PICA_UPNP_ERRIGD:
+ return "the UPnP gateway did not answer or answered something unusable";
+
+ case PICA_UPNP_ERRNOSUPPORT:
+ return "this build has no UPnP support";
+
+ default:
+ break;
+ }
+
+ s = strupnperror(ret);
+
+ return s ? s : "unknown UPnP error";
+}
+
+#else /* !HAVE_LIBMINIUPNPC */
+
+int PICA_upnp_discover(int timeout_ms, struct PICA_upnp_ctx **ctx)
+{
+ (void)timeout_ms;
+ (void)ctx;
+ return PICA_UPNP_ERRNOSUPPORT;
+}
+void PICA_upnp_free(struct PICA_upnp_ctx *ctx)
+{
+ (void)ctx;
+}
+
+int PICA_upnp_external_addr(struct PICA_upnp_ctx *ctx, char *addr, size_t addrlen)
+{
+ (void)ctx;
+ (void)addr;
+ (void)addrlen;
+ return PICA_UPNP_ERRNOSUPPORT;
+}
+
+const char *PICA_upnp_lan_addr(const struct PICA_upnp_ctx *ctx)
+{
+ (void)ctx;
+ return "";
+}
+
+int PICA_upnp_map(struct PICA_upnp_ctx *ctx, int port, unsigned int lease_secs, const char *desc)
+{
+ (void)ctx;
+ (void)port;
+ (void)lease_secs;
+ (void)desc;
+ return PICA_UPNP_ERRNOSUPPORT;
+}
+
+int PICA_upnp_refresh(struct PICA_upnp_ctx *ctx)
+{
+ (void)ctx;
+ return PICA_UPNP_ERRNOSUPPORT;
+}
+
+void PICA_upnp_unmap(struct PICA_upnp_ctx *ctx)
+{
+ (void)ctx;
+}
+
+int PICA_upnp_mapped(const struct PICA_upnp_ctx *ctx)
+{
+ (void)ctx;
+ return 0;
+}
+
+int PICA_upnp_port(const struct PICA_upnp_ctx *ctx)
+{
+ (void)ctx;
+ return 0;
+}
+
+unsigned int PICA_upnp_lease(const struct PICA_upnp_ctx *ctx)
+{
+ (void)ctx;
+ return 0;
+}
+
+const char *PICA_upnp_strerror(int ret)
+{
+ (void)ret;
+ return "this build has no UPnP support";
+}
+
+#endif
diff --git a/PICA_netconf.h b/PICA_netconf.h
index c9bc767..c6f4aa2 100644
--- a/PICA_netconf.h
+++ b/PICA_netconf.h
@@ -1,5 +1,5 @@
/*
- (c) Copyright 2012 - 2018 Anton Sviridenko
+ (c) Copyright 2012 - 2026 Anton Sviridenko
https://picapica.im
This program is free software: you can redistribute it and/or modify
@@ -17,6 +17,8 @@
#ifndef PICA_NETCONF_H
#define PICA_NETCONF_H
+#include <stddef.h>
+
#ifndef WIN32
#include <netinet/in.h>
@@ -24,8 +26,13 @@
#else
+#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN 1
+#endif
+/* PICA_client.c and PICA_media.c include this after the system headers */
+#ifndef _WIN32_WINNT
#define _WIN32_WINNT 0x501
+#endif
#include <winsock2.h>
#include <ws2ipdef.h>
#include <wincrypt.h>
@@ -36,21 +43,164 @@ typedef u_long in_addr_t;
typedef u_short in_port_t;
#endif
+/* Most interface addresses PICA_get_ifaddrs_ipv4() reports. */
+#define PICA_IFADDRS_MAX 32
+
+/* UPnP return values. Negative ones are detected here, zero is success, and
+ * positive ones are UPnP error codes answered by the device, as listed in
+ * miniupnpc's upnpcommands.h. PICA_upnp_strerror() turns any of them into
+ * something printable.
+ */
+#define PICA_UPNP_OK 0
+/** nothing answered the discovery, or what did is not an IGD */
+#define PICA_UPNP_ERRNOIGD -1
+/** an IGD, but its WAN connection is down */
+#define PICA_UPNP_ERRNOTCONN -2
+#define PICA_UPNP_ERRNOMEM -3
+#define PICA_UPNP_ERRINVARG -4
+/** the port number is taken on the IGD, for TCP or for UDP, by another host
+ * or another program - the next number may still be free */
+#define PICA_UPNP_ERRCONFLICT -5
+/** the IGD's own external address is private - carrier NAT behind the NAT,
+ * nothing mapped there can be reached from the Internet */
+#define PICA_UPNP_ERRPRIVADDR -6
+/** the request did not reach the IGD, or it answered something unusable */
+#define PICA_UPNP_ERRIGD -7
+/** this build has no UPnP support */
+#define PICA_UPNP_ERRNOSUPPORT -8
+
+/* Lease to ask for. Short enough that a mapping left behind by a client that
+ * died without deleting it disappears on its own; long enough that renewing
+ * it, at half of whatever the device granted, is a rare event.
+ */
+#define PICA_UPNP_LEASE_DEFAULT 3600
+
+/* How long PICA_upnp_discover() waits for devices to answer. */
+#define PICA_UPNP_DISCOVER_TIMEOUT 2000
+
+/* A port mapping on a UPnP IGD.
+ *
+ * The context holds the result of finding the IGD together with the mapping
+ * held through it, so that discovery - a multicast search that has to wait
+ * for devices to answer - is paid once, and the mapping can be renewed and
+ * deleted later on with the same control URLs.
+ *
+ * A mapping always covers TCP and UDP with the same port number, and the
+ * external port number is the same as the local one: the directc2c
+ * connection is made over TCP and the media of a call over UDP to the same
+ * announced port, see the 0x0B message in doc/proto-doc-latest.txt.
+ *
+ * A mapping is never permanent, whatever lease is asked for: IGD:2 devices
+ * clamp a request for an infinite lease to a week, and any device loses its
+ * mappings when it reboots. A mapping that is meant to stay up has to be
+ * renewed - see PICA_upnp_refresh().
+ *
+ * Every call blocks for as long as the device takes to answer, discovery for
+ * the whole timeout, so a context belongs on a thread that can afford to
+ * wait - never on one carrying media. Nothing here is thread safe; one
+ * context belongs to one thread.
+ *
+ * Without miniupnpc every function is still there and fails with
+ * PICA_UPNP_ERRNOSUPPORT, so that callers need no conditional code.
+ */
+struct PICA_upnp_ctx;
+
#ifdef __cplusplus
extern "C" {
#endif
+/** 0.0.0.0/8, loopback, link-local, multicast, the reserved 240.0.0.0/4,
+ * broadcast, and the private ranges of PICA_is_private_addr_ipv4() */
int PICA_is_reserved_addr_ipv4(in_addr_t);
+/** 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 and the shared address space
+ * 100.64.0.0/10 - addresses only reachable from the same local network,
+ * VPN or provider network */
+int PICA_is_private_addr_ipv4(in_addr_t);
+
+/**
+ * IPv4 addresses of the network interfaces that are up, other than loopback
+ * and link-local ones: the private addresses first, then the public ones, in
+ * the order the system lists the interfaces in.
+ * \param addrs filled with the addresses, network byte order
+ * \param maxcount size of addrs
+ * \return number of addresses stored, 0 if there are none or the system
+ * cannot be asked
+ */
+int PICA_get_ifaddrs_ipv4(in_addr_t *addrs, int maxcount);
+
in_addr_t PICA_guess_listening_addr_ipv4();
-#ifdef HAVE_LIBMINIUPNPC
-int PICA_upnp_autoconfigure_ipv4(int public_port, int local_port, char *public_ip);
-#endif
+/**
+ * Looks for an IGD on the local network and, having found one, returns a
+ * context to use it with.
+ * \param timeout_ms how long to wait for devices to answer,
+ * PICA_UPNP_DISCOVER_TIMEOUT is sensible
+ * \param ctx filled with the new context on success, untouched otherwise
+ */
+int PICA_upnp_discover(int timeout_ms, struct PICA_upnp_ctx **ctx);
+
+/** Deletes the mapping the context holds, if any, and frees it. */
+void PICA_upnp_free(struct PICA_upnp_ctx *ctx);
+
+/**
+ * The IGD's address on the Internet side, as it reports it itself.
+ * Fails with PICA_UPNP_ERRPRIVADDR if that address is a private one, since
+ * announcing it would be of no use to anybody.
+ * \param addr buffer for the address as a string, at least 16 octets
+ */
+int PICA_upnp_external_addr(struct PICA_upnp_ctx *ctx, char *addr, size_t addrlen);
+
+/** Our own address on the side the IGD is on, i.e. the address mappings made
+ * through this context point at. */
+const char *PICA_upnp_lan_addr(const struct PICA_upnp_ctx *ctx);
+
+/**
+ * Maps the external port number port, TCP and UDP both, to the same port
+ * number of this machine. Either both protocols are mapped or neither is.
+ *
+ * A mapping left behind by an earlier run of this same client (same machine,
+ * same port) is recognised as ours and replaced rather than treated as a
+ * conflict. A context holds one mapping; mapping again replaces it.
+ *
+ * \param lease_secs lease to ask for, 0 for a permanent mapping
+ * \param desc description for the IGD's mapping table, may be NULL
+ * \retval PICA_UPNP_ERRCONFLICT the port number is taken by somebody else,
+ * for one of the protocols at least; the next number may be free
+ */
+int PICA_upnp_map(struct PICA_upnp_ctx *ctx, int port, unsigned int lease_secs, const char *desc);
+
+/**
+ * Renews the lease of the mapping this context holds, also putting it back
+ * if the IGD dropped it in the meantime, and finding the IGD again if its
+ * control URLs stopped working (it rebooted or changed address).
+ *
+ * \retval PICA_UPNP_ERRCONFLICT the external port has been taken over by
+ * another host or program; the context no longer holds a mapping
+ */
+int PICA_upnp_refresh(struct PICA_upnp_ctx *ctx);
+
+/** Deletes the mapping the context holds. The context stays usable. */
+void PICA_upnp_unmap(struct PICA_upnp_ctx *ctx);
+
+/** Whether the context currently holds a mapping. */
+int PICA_upnp_mapped(const struct PICA_upnp_ctx *ctx);
+
+/** Port number of the mapping the context holds, 0 if it holds none. */
+int PICA_upnp_port(const struct PICA_upnp_ctx *ctx);
+
+/**
+ * Lease the IGD granted for the mapping, in seconds; 0 when it only supports
+ * permanent mappings. A device is free to grant less than was asked for, so
+ * this is what renewal has to be timed by.
+ */
+unsigned int PICA_upnp_lease(const struct PICA_upnp_ctx *ctx);
+
+/** Printable form of any of the UPnP return values. Never NULL. */
+const char *PICA_upnp_strerror(int ret);
#ifdef __cplusplus
}
#endif
#endif
-
diff --git a/PICA_node.c b/PICA_node.c
index 2eb97d6..ccfcf6d 100644
--- a/PICA_node.c
+++ b/PICA_node.c
@@ -3998,6 +3998,88 @@ void ReportSvcStatus( DWORD dwCurrentState,
}
#endif
+#ifdef HAVE_LIBMINIUPNPC
+/* The port mapping made for the node's listening port, kept for as long as
+ * the node runs so that its lease can be renewed.
+ */
+static struct PICA_upnp_ctx *upnp_ctx;
+static struct event *upnp_refresh_event;
+
+static void upnp_schedule_refresh(void);
+
+static void upnp_refresh_cb(evutil_socket_t fd, short event, void *arg)
+{
+ int ret;
+
+ /* Blocks the event loop for as long as the IGD takes to answer, normally
+ * a few milliseconds, once in half a lease.
+ */
+ ret = PICA_upnp_refresh(upnp_ctx);
+
+ if (ret != PICA_UPNP_OK)
+ {
+ PICA_error("UPnP: failed to renew the port mapping, the node may become unreachable from the Internet - %s",
+ PICA_upnp_strerror(ret));
+ return;
+ }
+
+ upnp_schedule_refresh();
+}
+
+static void upnp_schedule_refresh(void)
+{
+ struct timeval tv;
+ unsigned int lease = PICA_upnp_lease(upnp_ctx);
+
+ /* a permanent mapping still disappears when the IGD reboots */
+ if (lease == 0)
+ lease = PICA_UPNP_LEASE_DEFAULT;
+
+ tv.tv_sec = lease / 2;
+ tv.tv_usec = 0;
+
+ if (!upnp_refresh_event)
+ upnp_refresh_event = evtimer_new(pica_event_base, upnp_refresh_cb, NULL);
+
+ if (upnp_refresh_event)
+ evtimer_add(upnp_refresh_event, &tv);
+}
+
+/* Forwards the listening port, TCP and UDP - the latter carries the "get my
+ * UDP address" datagrams - and reports the IGD's external address.
+ * \return 1 on success
+ */
+static int upnp_forward_listen_port(int port, char *public_ip, size_t public_ip_size)
+{
+ int ret;
+
+ ret = PICA_upnp_discover(PICA_UPNP_DISCOVER_TIMEOUT, &upnp_ctx);
+
+ if (ret != PICA_UPNP_OK)
+ {
+ PICA_info("UPnP: %s", PICA_upnp_strerror(ret));
+ return 0;
+ }
+
+ ret = PICA_upnp_external_addr(upnp_ctx, public_ip, public_ip_size);
+
+ if (ret == PICA_UPNP_OK)
+ ret = PICA_upnp_map(upnp_ctx, port, PICA_UPNP_LEASE_DEFAULT, "Pica Pica node");
+
+ if (ret != PICA_UPNP_OK)
+ {
+ PICA_info("UPnP: failed to forward port %i - %s", port, PICA_upnp_strerror(ret));
+ PICA_upnp_free(upnp_ctx);
+ upnp_ctx = NULL;
+ return 0;
+ }
+
+ upnp_schedule_refresh();
+
+ return 1;
+}
+#endif
+
int pica_node_main(int argc, char** argv)
{
uint32_t pid;
@@ -4057,12 +4139,10 @@ int pica_node_main(int argc, char** argv)
if (PICA_is_reserved_addr_ipv4(guess) && nodecfg.disable_reserved_addrs)
{
char public_ip[64];
- int ret;
PICA_info("trying to get global IP with UPnP...");
- ret = PICA_upnp_autoconfigure_ipv4(atoi(nodecfg.listen_port), atoi(nodecfg.listen_port), public_ip);
- if (ret)
+ if (upnp_forward_listen_port(atoi(nodecfg.listen_port), public_ip, sizeof(public_ip)))
{
free(nodecfg.announced_addr);
nodecfg.announced_addr = strdup(public_ip);
diff --git a/PICA_proto.h b/PICA_proto.h
index cdf0eef..6529392 100644
--- a/PICA_proto.h
+++ b/PICA_proto.h
@@ -112,6 +112,9 @@
#define PICA_PROTO_CALL_VIDEOPARAM 0x75
#define PICA_PROTO_CALL_AUDIO_PACKET 0x76
#define PICA_PROTO_CALL_VIDEO_PACKET 0x77
+// The only datagram of a call sent outside of DTLS, see "Establishing the
+// media connection" in doc/proto-doc-latest.txt.
+#define PICA_PROTO_MEDIAPROBE 0x78
//size
#define PICA_PROTO_INITREQ_SIZE 4
@@ -171,8 +174,11 @@
#define PICA_PROTO_N2NALLOW_SIZE 58
#define PICA_PROTO_N2NNOTFOUND_SIZE 58
-#define PICA_PROTO_CALLREQ_SIZE 4
-#define PICA_PROTO_CALLANS_SIZE 4
+// 0x70 and 0x71: probe token, then a list of up to this many addresses in the
+// 0xA4 format that the receiver uses
+#define PICA_PROTO_CALL_TOKENSIZE 8
+#define PICA_PROTO_CALL_MAXADDRS 8
+#define PICA_PROTO_MEDIAPROBE_SIZE (2 + PICA_PROTO_CALL_TOKENSIZE)
#define PICA_PROTO_CALLREJ_SIZE 4
#define PICA_PROTO_CALLFIN_SIZE 4
#define PICA_PROTO_CALL_AUDIOPARAM_SIZE 24
diff --git a/doc/proto-doc-latest.txt b/doc/proto-doc-latest.txt
index 4644794..b5cf73b 100644
--- a/doc/proto-doc-latest.txt
+++ b/doc/proto-doc-latest.txt
@@ -31,17 +31,24 @@ communicated over a c2c connection.
carrying the real time media of an audio/video call. It uses UDP transport
and DTLS 1.2 with mutual certificate authentication.
-A mediac2c connection is established only while a call is in progress and
-only between clients that already have an established directc2c connection.
-It uses the address and port number the directc2c connection was made to,
-with UDP instead of TCP: the client that made the outgoing directc2c
-connection acts as the DTLS client and connects to that same address, the
-client that accepted it acts as the DTLS server and listens on the UDP port
-with the same number as its directc2c listening port. Each side verifies
-that the certificate presented by the peer hashes to the UH of the peer of
-the c2c connection the call belongs to, exactly as it does on a directc2c
-connection. No addresses are announced separately for this connection type
-and no additional protocol messages are needed to establish it.
+A mediac2c connection is established only while a call is in progress. It is
+made in one of two ways, see "Establishing the media connection" in the Audio
+and Video Calls section:
+
+-over the address of an established directc2c connection, with UDP instead
+of TCP: the client that made the outgoing directc2c connection acts as the
+DTLS client and connects to the address and port number that connection was
+made to, the client that accepted it acts as the DTLS server and listens on
+the UDP port with the same number as its directc2c listening port;
+
+-by UDP hole punching, between the media sockets the two clients opened for
+the call, over the addresses exchanged in the 0x70 and 0x71 messages: the
+caller acts as the DTLS client, the callee as the DTLS server. No directc2c
+connection is needed for this.
+
+Either way, each side verifies that the certificate presented by the peer
+hashes to the UH of the peer of the c2c connection the call belongs to,
+exactly as it does on a directc2c connection.
Media packets are carried over the mediac2c connection whenever it is
established, and over the c2c or directc2c connection otherwise. There is
@@ -350,12 +357,18 @@ Client direct address list.
If a client is configured to accept incoming direct client to client
connections (bypassing the node), it can send a list of its own addresses.
+The list can contain any number of addresses, e.g. one for every network
+interface of the client and the external address of a port forwarded to it.
Local network addresses (if there are any) from the 192.168.0.0/16,
172.16.0.0/12 and 10.0.0.0/8 subnets must be placed first in the list, so that
clients residing in the same local network are able to connect directly. Public
internet addresses follow them.
If the client is behind NAT and forwards an open port to its local address, the
external port number must be specified in the address.
+The connecting client tries the addresses one at a time, in the order of the
+list. It skips the elements of a type it does not connect to (e.g. 0xA1 without
+IPv6 connectivity), stepping over them by their size as given in the 0xA4
+description; such elements are not an error.
Having received the announcement, the other client can create a connection to
that address and close the connection through the node.
The announced port numbers are used both for TCP directc2c connections and for
@@ -443,20 +456,47 @@ that and must not treat a malformed or unexpected packet as a protocol error
breaking the connection. In particular, a media packet can arrive before the
0x74 or 0x75 message describing the stream it belongs to, because those travel
over a different connection; such a packet is discarded.
+The media connection probe is not a message of any connection: it is a UDP
+datagram sent while the media connection is being established, see below.
====================================================
Call request (ring)
-[0x70 0x70]
-[2 pseudo-random octets]
+[0x70 0x70][length, 2 octets][probe token, 8 octets][address list]
-4 octets
+length - covers everything following it: 8 + the size of the address list.
+
+probe token - random octets from a cryptographically secure generator, chosen
+anew for every call. The peer puts it into the media connection probes it sends
+to the sender of this message.
+
+address list - the addresses where the sender's media socket for this call may
+be reachable, as elements of the 0xA4 format, of types 0xA0 and 0xA1 only:
+first the socket's port number with each of the sender's own interface
+addresses, then the address and port the node reported for that socket in a
+0x12 message, if the sender got one. The list is empty if the sender does not
+take part in hole punching, e.g. because direct connections are disabled in its
+settings.
+
+Before sending this message the caller opens its media socket and asks the node
+for the socket's address (0x10 - 0x12), waiting for the answer at most 2
+seconds; when it does not come in time, the message is sent without that
+address.
+
+The receiver skips elements of other types and uses at most the first 8
+addresses of the list.
====================================================
Call answer (pick up)
-[0x71 0x71]
-[2 pseudo-random octets]
+[0x71 0x71][length, 2 octets][probe token, 8 octets][address list]
-4 octets
+The same format and meaning as in 0x70, for the callee's media socket.
+
+The callee opens its media socket and asks the node for its address when the
+0x70 message arrives, while the call is ringing, so that sending 0x71 is not
+delayed by it when the user answers; if the address has still not arrived by
+then, 0x71 waits for it at most 2 seconds. The callee's addresses are revealed
+only by this message, i.e. only if the call is answered. The list can be empty
+when the caller's list was.
====================================================
Call reject
@@ -562,6 +602,73 @@ rule, losing the first fragment of a frame would make the receiving side
treat the second one as the beginning of a frame and pass a truncated frame
to the decoder.
====================================================
+Establishing the media connection.
+
+When a call becomes active - for the callee when it sends 0x71, for the
+caller when 0x71 arrives - each side makes up to two attempts to establish a
+mediac2c connection, one after another. Until one succeeds, and for the rest
+of the call if neither does, the media packets travel over the c2c or
+directc2c connection.
+
+Attempt 1, over the directc2c address. Made only if the c2c connection the
+call belongs to has an established directc2c connection, as described in the
+Connections section. Given up when the DTLS handshake fails, or when the
+connection is not established 5 seconds after the call became active.
+
+Attempt 2, by UDP hole punching. Made when attempt 1 is not made or is given
+up, and only if both the 0x70 and the 0x71 message carried a non-empty address
+list. Each side uses its media socket for the call - the one its address list
+was made for - and the caller acts as the DTLS client.
+
+1. Each side sends a media connection probe to every address of the peer's
+list, repeating every 200 milliseconds.
+2. When a side receives a probe carrying its own probe token, it selects the
+address the probe came from. That address need not be in the peer's list: a
+NAT can map the peer's socket to another port for this destination than for
+the node. From then on the side sends probes to the selected address only and
+accepts datagrams only from it.
+3. The caller starts the DTLS handshake as soon as it has selected an address,
+and keeps sending probes to it until the first datagram of the handshake
+arrives from the callee. The callee keeps sending probes until the first
+datagram of the handshake arrives from the caller. DTLS datagrams that arrive
+before the receiving side has selected an address are discarded; the DTLS
+retransmission takes care of them.
+4. The attempt is given up if no address has been selected 10 seconds after
+the side started sending probes, or if the handshake fails or is not complete
+10 seconds after that.
+
+A side starting attempt 2 late - having given up attempt 1, or having become
+active later than the peer - is still within the 10 seconds the peer keeps
+sending probes for.
+
+Security considerations.
+The probe token, sent over the authenticated c2c connection, keeps a host
+that does not see the probes from steering the choice of the address. One that
+does see them can send copies from another address, the same as with the 0x10
+datagram; the DTLS handshake authenticates the peer regardless, and a failed
+handshake only leaves the media on the c2c connection.
+The addresses in a peer's list are not checked, so a peer can make a client
+send probes to any host. This is bounded by the limits above: 8 addresses,
+5 probes a second each, 10 seconds - at most 400 datagrams of 10 octets per
+call.
+====================================================
+Media connection probe.
+Sent as a UDP datagram from the media socket of a call, outside of DTLS.
+
+[0x78 0x78][probe token, 8 octets]
+
+10 octets, the whole datagram
+
+probe token - the token the receiver of the probe sent in its 0x70 or 0x71
+message.
+
+A probe carries nothing but the token and is discarded after it has been
+looked at. One that is exactly 10 octets long, carries the receiver's token
+and arrives before the receiver has selected an address makes the receiver
+select the address it came from, see step 2 above; all others have no effect.
+A DTLS record never starts with the octet 0x78, so probes are told apart from
+DTLS records by their first octet at any stage of the connection.
+====================================================
Ping.
diff --git a/pica-client/dialogs/settingsdialog.cpp b/pica-client/dialogs/settingsdialog.cpp
index fca9794..2df521d 100644
--- a/pica-client/dialogs/settingsdialog.cpp
+++ b/pica-client/dialogs/settingsdialog.cpp
@@ -20,6 +20,7 @@
#include "../audiodevice.h"
#include "../videodevice.h"
#include "../callsettings.h"
+#include "../directc2csettings.h"
#include "../../PICA_netconf.h"
#include "../../PICA_proto.h"
@@ -38,6 +39,10 @@
#include <QEvent>
#include <QTabWidget>
#include <QTimer>
+#include <QHeaderView>
+#include <QMessageBox>
+#include <QHostAddress>
+#include <memory>
// The device tests are not part of any call, but the devices only run for an
// open call session (see MediaCallSession) - so each test is one, under a name
@@ -136,51 +141,117 @@ SettingsDialog::SettingsDialog(QWidget *parent) :
rbEnableOutgoingConns = new QRadioButton(tr("Connect to the remote peer directly if possible"), this);
rbEnableIncomingConns = new QRadioButton(tr("Enable incoming direct connections"), this);
+ rbEnableIncomingConns->setChecked(true);
+
+ // Indented under "Enable incoming direct connections", which it all
+ // depends on. A widget of its own also keeps its radio buttons out of the
+ // exclusive group of the three above, QRadioButton grouping by parent.
+ incomingBox = new QWidget();
+ QVBoxLayout *incomingLayout = new QVBoxLayout();
+ incomingLayout->setContentsMargins(20, 0, 0, 0);
+
+ cbEnableUPnP = nullptr;
#ifdef HAVE_LIBMINIUPNPC
cbEnableUPnP = new QCheckBox(tr("Enable UPnP"));
+ cbEnableUPnP->setToolTip(tr("Ask the router to forward the port for incoming direct connections, TCP and UDP, "
+ "and announce the router's external address to peers"));
cbEnableUPnP->setChecked(true);
+ incomingLayout->addWidget(cbEnableUPnP);
#endif
- rbEnableIncomingConns->setChecked(true);
- connect(rbEnableIncomingConns, SIGNAL(toggled(bool)), this, SLOT(toggleIncomingConnections(bool)));
+ rbAddrAuto = new QRadioButton(tr("Automatic address configuration"));
+ rbAddrManual = new QRadioButton(tr("Manual"));
+ rbAddrAuto->setChecked(true);
- QLabel *lbAddr = new QLabel(tr("Public address for incoming connections"), this);
- addr = new QComboBox(this);
- QLabel *lbPubPort = new QLabel(tr("External TCP port for incoming connections"), this);
- publicPort = new QSpinBox(this);
- QLabel *lbLocPort = new QLabel(tr("Local TCP port for incoming connections"), this);
- localPort = new QSpinBox(this);
+ lbAutoAddrs = new QLabel();
+ lbAutoAddrs->setWordWrap(true);
+ lbAutoAddrs->setContentsMargins(20, 0, 0, 0);
- addr->setEditable(true);
+ incomingLayout->addWidget(rbAddrAuto);
+ incomingLayout->addWidget(lbAutoAddrs);
+ incomingLayout->addWidget(rbAddrManual);
- publicPort->setRange(1, 65535);
- localPort->setRange(1, 65535);
-
- publicPort->setValue(2298);
- localPort->setValue(2298);
-
- QList<QHostAddress> hostIfAddrs = QNetworkInterface::allAddresses();
- QHostAddress ifAddr;
+ manualBox = new QWidget();
+ QVBoxLayout *manualLayout = new QVBoxLayout();
+ manualLayout->setContentsMargins(20, 0, 0, 0);
- addr->addItem(QString("autoconfigure"));
+ QHBoxLayout *portRow = new QHBoxLayout();
+ localPort = new QSpinBox();
+ localPort->setRange(1, 65535);
+ localPort->setValue(DirectC2CSettings::DefaultPort);
+ portRow->addWidget(new QLabel(tr("Local TCP and UDP port")));
+ portRow->addWidget(localPort);
+ portRow->addStretch(1);
+ manualLayout->addLayout(portRow);
+
+ manualLayout->addWidget(new QLabel(tr("Addresses announced to peers, tried by them in this order. "
+ "Put the external address and port of a port forwarded "
+ "on your router here.")));
+
+ addrTable = new QTableWidget(0, 2);
+ addrTable->setHorizontalHeaderLabels(QStringList() << tr("Address") << tr("Port"));
+ addrTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch);
+ addrTable->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents);
+ addrTable->verticalHeader()->setVisible(false);
+ addrTable->setSelectionBehavior(QAbstractItemView::SelectRows);
+ addrTable->setSelectionMode(QAbstractItemView::SingleSelection);
+ manualLayout->addWidget(addrTable);
+
+ QHBoxLayout *addrButtons = new QHBoxLayout();
+ QPushButton *btAddrAdd = new QPushButton(tr("Add"));
+ QPushButton *btAddrRemove = new QPushButton(tr("Remove"));
+ QPushButton *btAddrUp = new QPushButton(tr("Move up"));
+ QPushButton *btAddrDown = new QPushButton(tr("Move down"));
+ addrButtons->addWidget(btAddrAdd);
+ addrButtons->addWidget(btAddrRemove);
+ addrButtons->addWidget(btAddrUp);
+ addrButtons->addWidget(btAddrDown);
+ addrButtons->addStretch(1);
+ manualLayout->addLayout(addrButtons);
+
+ QHBoxLayout *addrButtons2 = new QHBoxLayout();
+ QPushButton *btAddrIfaces = new QPushButton(tr("Add interface addresses"));
+ btAddrIfaces->setToolTip(tr("Add the addresses of this computer's network interfaces, with the local port"));
+ btAddrUpnp = new QPushButton(tr("Add UPnP address"));
+ btAddrUpnp->setToolTip(tr("Add an entry for the external address of the UPnP router, "
+ "filled in with the forwarded port when Pica Pica runs"));
+ btUpnpQuery = new QPushButton(tr("Ask router for external address"));
+ btUpnpQuery->setToolTip(tr("Get the router's external address through UPnP now and add it with the local port"));
+ addrButtons2->addWidget(btAddrIfaces);
+ addrButtons2->addWidget(btAddrUpnp);
+ addrButtons2->addWidget(btUpnpQuery);
+ addrButtons2->addStretch(1);
+ manualLayout->addLayout(addrButtons2);
+
+ lbUpnpInfo = new QLabel();
+ lbUpnpInfo->setWordWrap(true);
+ manualLayout->addWidget(lbUpnpInfo);
+
+#ifndef HAVE_LIBMINIUPNPC
+ btAddrUpnp->hide();
+ btUpnpQuery->hide();
+#endif
- foreach (ifAddr, hostIfAddrs)
- if (ifAddr.protocol() == QAbstractSocket::IPv4Protocol)
- addr->addItem(ifAddr.toString());
+ manualBox->setLayout(manualLayout);
+ incomingLayout->addWidget(manualBox);
+ incomingBox->setLayout(incomingLayout);
+ connect(rbEnableIncomingConns, SIGNAL(toggled(bool)), this, SLOT(toggleIncomingConnections(bool)));
+ connect(rbAddrManual, SIGNAL(toggled(bool)), this, SLOT(toggleIncomingConnections(bool)));
+ if (cbEnableUPnP)
+ connect(cbEnableUPnP, SIGNAL(toggled(bool)), this, SLOT(toggleIncomingConnections(bool)));
+ connect(btAddrAdd, SIGNAL(clicked()), this, SLOT(addAddr()));
+ connect(btAddrRemove, SIGNAL(clicked()), this, SLOT(removeAddr()));
+ connect(btAddrUp, SIGNAL(clicked()), this, SLOT(moveAddrUp()));
+ connect(btAddrDown, SIGNAL(clicked()), this, SLOT(moveAddrDown()));
+ connect(btAddrIfaces, SIGNAL(clicked()), this, SLOT(addInterfaceAddrs()));
+ connect(btAddrUpnp, SIGNAL(clicked()), this, SLOT(addUpnpAddrRow()));
+ connect(btUpnpQuery, SIGNAL(clicked()), this, SLOT(queryUpnpAddr()));
directc2cLayout->addWidget(rbDisableDirectConns);
directc2cLayout->addWidget(rbEnableOutgoingConns);
directc2cLayout->addWidget(rbEnableIncomingConns);
-#ifdef HAVE_LIBMINIUPNPC
- directc2cLayout->addWidget(cbEnableUPnP);
-#endif
- directc2cLayout->addWidget(lbAddr);
- directc2cLayout->addWidget(addr);
- directc2cLayout->addWidget(lbPubPort);
- directc2cLayout->addWidget(publicPort);
- directc2cLayout->addWidget(lbLocPort);
- directc2cLayout->addWidget(localPort);
+ directc2cLayout->addWidget(incomingBox);
directc2cLayout->addStretch(1);
directc2ctab->setLayout(directc2cLayout);
@@ -1633,12 +1704,289 @@ void SettingsDialog::fillAudioRingDevices()
void SettingsDialog::toggleIncomingConnections(bool checked)
{
- addr->setEnabled(checked);
- publicPort->setEnabled(checked);
- localPort->setEnabled(checked);
-#ifdef HAVE_LIBMINIUPNPC
- cbEnableUPnP->setEnabled(checked);
-#endif
+ Q_UNUSED(checked);
+
+ updateDirectConnWidgets();
+}
+
+void SettingsDialog::updateDirectConnWidgets()
+{
+ bool upnp = cbEnableUPnP && cbEnableUPnP->isChecked();
+
+ incomingBox->setEnabled(rbEnableIncomingConns->isChecked());
+ lbAutoAddrs->setEnabled(rbAddrAuto->isChecked());
+ manualBox->setEnabled(rbAddrManual->isChecked());
+ btAddrUpnp->setEnabled(upnp);
+
+ updateAutoAddrsLabel();
+}
+
+void SettingsDialog::updateAutoAddrsLabel()
+{
+ in_addr_t ifaddrs[PICA_IFADDRS_MAX];
+ QStringList addrs;
+ int n;
+
+ n = PICA_get_ifaddrs_ipv4(ifaddrs, PICA_IFADDRS_MAX);
+
+ for (int i = 0; i < n; i++)
+ {
+ struct in_addr in;
+
+ in.s_addr = ifaddrs[i];
+ addrs.append(QString::fromLatin1(inet_ntoa(in)));
+ }
+
+ QString text = addrs.isEmpty()
+ ? tr("No network interface address found.")
+ : tr("Announced to peers: %1, port %2 or the next free one")
+ .arg(addrs.join(", ")).arg(DirectC2CSettings::DefaultPort);
+
+ if (cbEnableUPnP && cbEnableUPnP->isChecked())
+ text += tr(", followed by the external address of the UPnP router with the forwarded port.");
+ else
+ text += ".";
+
+ lbAutoAddrs->setText(text);
+}
+
+void SettingsDialog::addAddrRow(const QString &host, int port, bool upnp)
+{
+ int row = addrTable->rowCount();
+ QTableWidgetItem *hostItem, *portItem;
+
+ addrTable->insertRow(row);
+
+ if (upnp)
+ {
+ // Filled in at run time, so there is nothing to edit; the role marks
+ // it as the UPnP entry.
+ hostItem = new QTableWidgetItem(tr("UPnP router's external address"));
+ portItem = new QTableWidgetItem(tr("forwarded port"));
+ hostItem->setData(Qt::UserRole, true);
+ hostItem->setFlags(hostItem->flags() & ~Qt::ItemIsEditable);
+ portItem->setFlags(portItem->flags() & ~Qt::ItemIsEditable);
+ }
+ else
+ {
+ hostItem = new QTableWidgetItem(host);
+ portItem = new QTableWidgetItem(QString::number(port));
+ }
+
+ addrTable->setItem(row, 0, hostItem);
+ addrTable->setItem(row, 1, portItem);
+}
+
+bool SettingsDialog::addrRowIsUpnp(int row) const
+{
+ QTableWidgetItem *item = addrTable->item(row, 0);
+
+ return item && item->data(Qt::UserRole).toBool();
+}
+
+void SettingsDialog::addAddr()
+{
+ addAddrRow(QString(), localPort->value(), false);
+
+ addrTable->setCurrentCell(addrTable->rowCount() - 1, 0);
+ addrTable->editItem(addrTable->item(addrTable->rowCount() - 1, 0));
+}
+
+void SettingsDialog::removeAddr()
+{
+ int row = addrTable->currentRow();
+
+ if (row >= 0)
+ addrTable->removeRow(row);
+}
+
+static void swapTableRows(QTableWidget *t, int a, int b)
+{
+ for (int col = 0; col < t->columnCount(); col++)
+ {
+ QTableWidgetItem *ia = t->takeItem(a, col);
+ QTableWidgetItem *ib = t->takeItem(b, col);
+
+ t->setItem(a, col, ib);
+ t->setItem(b, col, ia);
+ }
+}
+
+void SettingsDialog::moveAddrUp()
+{
+ int row = addrTable->currentRow();
+
+ if (row <= 0)
+ return;
+
+ swapTableRows(addrTable, row, row - 1);
+ addrTable->setCurrentCell(row - 1, addrTable->currentColumn());
+}
+
+void SettingsDialog::moveAddrDown()
+{
+ int row = addrTable->currentRow();
+
+ if (row < 0 || row + 1 >= addrTable->rowCount())
+ return;
+
+ swapTableRows(addrTable, row, row + 1);
+ addrTable->setCurrentCell(row + 1, addrTable->currentColumn());
+}
+
+void SettingsDialog::addInterfaceAddrs()
+{
+ in_addr_t ifaddrs[PICA_IFADDRS_MAX];
+ int n;
+
+ // private addresses come first already, as they should in the list
+ n = PICA_get_ifaddrs_ipv4(ifaddrs, PICA_IFADDRS_MAX);
+
+ for (int i = 0; i < n; i++)
+ {
+ struct in_addr in;
+ QString host;
+ bool present = false;
+
+ in.s_addr = ifaddrs[i];
+ host = QString::fromLatin1(inet_ntoa(in));
+
+ for (int row = 0; row < addrTable->rowCount(); row++)
+ if (!addrRowIsUpnp(row) && addrTable->item(row, 0)->text().trimmed() == host
+ && addrTable->item(row, 1)->text().trimmed().toInt() == localPort->value())
+ present = true;
+
+ if (!present)
+ addAddrRow(host, localPort->value(), false);
+ }
+
+ if (n == 0)
+ lbUpnpInfo->setText(tr("No network interface address found."));
+}
+
+void SettingsDialog::addUpnpAddrRow()
+{
+ for (int row = 0; row < addrTable->rowCount(); row++)
+ if (addrRowIsUpnp(row))
+ {
+ addrTable->setCurrentCell(row, 0);
+ return;
+ }
+
+ addAddrRow(QString(), 0, true);
+}
+
+void SettingsDialog::queryUpnpAddr()
+{
+ std::shared_ptr<int> status = std::make_shared<int>(PICA_UPNP_ERRNOIGD);
+ std::shared_ptr<QString> result = std::make_shared<QString>();
+
+ btUpnpQuery->setEnabled(false);
+ lbUpnpInfo->setText(tr("Asking the UPnP router..."));
+
+ // Parentless and deleting itself when done: the dialog may be closed
+ // before the router answers, and a QThread must not be destroyed while it
+ // runs. The answer only reaches the dialog if it is still there.
+ QThread *t = QThread::create([status, result]()
+ {
+ struct PICA_upnp_ctx *ctx = nullptr;
+ char addr[64];
+ int ret;
+
+ ret = PICA_upnp_discover(PICA_UPNP_DISCOVER_TIMEOUT, &ctx);
+
+ if (ret == PICA_UPNP_OK)
+ {
+ ret = PICA_upnp_external_addr(ctx, addr, sizeof(addr));
+
+ if (ret == PICA_UPNP_OK)
+ *result = QString::fromLatin1(addr);
+
+ PICA_upnp_free(ctx);
+ }
+
+ *status = ret;
+ });
+
+ connect(t, &QThread::finished, t, &QObject::deleteLater);
+ connect(t, &QThread::finished, this, [this, status, result]()
+ {
+ upnpQueryFinished(*status, *result);
+ });
+
+ t->start();
+}
+
+void SettingsDialog::upnpQueryFinished(int status, QString addr)
+{
+ btUpnpQuery->setEnabled(true);
+
+ if (status != PICA_UPNP_OK)
+ {
+ lbUpnpInfo->setText(tr("UPnP: %1").arg(PICA_upnp_strerror(status)));
+ return;
+ }
+
+ lbUpnpInfo->setText(tr("The router's external address is %1. Unless UPnP is enabled above, "
+ "the port has to be forwarded on the router by hand.").arg(addr));
+
+ for (int row = 0; row < addrTable->rowCount(); row++)
+ if (!addrRowIsUpnp(row) && addrTable->item(row, 0)->text().trimmed() == addr)
+ return;
+
+ addAddrRow(addr, localPort->value(), false);
+}
+
+bool SettingsDialog::validateAddrTable()
+{
+ bool upnp = cbEnableUPnP && cbEnableUPnP->isChecked();
+ int usable = 0;
+
+ if (!rbEnableIncomingConns->isChecked() || !rbAddrManual->isChecked())
+ return true;
+
+ for (int row = 0; row < addrTable->rowCount(); row++)
+ {
+ QString host;
+ bool ok = false;
+ int port;
+
+ if (addrRowIsUpnp(row))
+ {
+ usable += upnp ? 1 : 0;
+ continue;
+ }
+
+ host = addrTable->item(row, 0) ? addrTable->item(row, 0)->text().trimmed() : QString();
+ port = addrTable->item(row, 1) ? addrTable->item(row, 1)->text().trimmed().toInt(&ok) : 0;
+
+ // ';' and ':' would not survive DirectC2CSettings' stored form
+ if (host.isEmpty() || host.contains(';') || host.contains(':'))
+ {
+ QMessageBox::warning(this, tr("Direct connections"),
+ tr("Row %1 of the address list has no valid IPv4 address or host name.").arg(row + 1));
+ return false;
+ }
+
+ if (!ok || port <= 0 || port > 65535)
+ {
+ QMessageBox::warning(this, tr("Direct connections"),
+ tr("Row %1 of the address list has no valid port number.").arg(row + 1));
+ return false;
+ }
+
+ usable++;
+ }
+
+ if (usable == 0 && !upnp)
+ {
+ QMessageBox::warning(this, tr("Direct connections"),
+ tr("The address list is empty, so peers would have nowhere to connect to. "
+ "Add an address, or use the automatic configuration."));
+ return false;
+ }
+
+ return true;
}
void SettingsDialog::toggleMultipleLogins(bool checked)
@@ -1648,6 +1996,9 @@ void SettingsDialog::toggleMultipleLogins(bool checked)
void SettingsDialog::OK()
{
+ if (!validateAddrTable())
+ return;
+
storeSettings();
done(1);
}
@@ -1663,8 +2014,10 @@ void SettingsDialog::loadSettings()
//Direct c2c connections
int c2c_state;
+ DirectC2CSettings dcs;
- c2c_state = st.loadValue("direct_c2c.state", 1).toInt();
+ dcs.load(st);
+ c2c_state = dcs.state;
switch (c2c_state)
{
@@ -1684,40 +2037,22 @@ void SettingsDialog::loadSettings()
break;
}
-#ifdef HAVE_LIBMINIUPNPC
- cbEnableUPnP->setChecked(st.loadValue("direct_c2c.upnp_enabled", 1).toBool());
-#endif
+ if (cbEnableUPnP)
+ cbEnableUPnP->setChecked(dcs.upnp);
- addr->lineEdit()->setText(st.loadValue("direct_c2c.public_addr", "autoconfigure").toString());
+ if (dcs.addrConfig == DirectC2CSettings::AddrConfigManual)
+ rbAddrManual->setChecked(true);
+ else
+ rbAddrAuto->setChecked(true);
- if (addr->lineEdit()->text().contains(QString("autoconfigure")))
- {
- in_addr_t guess;
- struct in_addr in;
+ localPort->setValue(dcs.localPort);
- guess = PICA_guess_listening_addr_ipv4();
- in.s_addr = guess;
- addr->lineEdit()->setText(QString("autoconfigured(%1)").arg(inet_ntoa(in)));
+ addrTable->setRowCount(0);
-#ifdef HAVE_LIBMINIUPNPC
- if (cbEnableUPnP->isChecked() && PICA_is_reserved_addr_ipv4(guess))
- {
- int ret;
- char public_ip[64];
- ret = PICA_upnp_autoconfigure_ipv4(st.loadValue("direct_c2c.public_port", 2298).toInt(),
- st.loadValue("direct_c2c.local_port", 2298).toInt(),
- public_ip);
-
- if (ret)
- {
- addr->lineEdit()->setText(QString("autoconfigured(%1)").arg(public_ip));
- }
- }
-#endif
- }
+ foreach (const DirectC2CSettings::Addr &a, dcs.addrs)
+ addAddrRow(a.host, a.port, a.upnp);
- publicPort->setValue(st.loadValue("direct_c2c.public_port", 2298).toInt());
- localPort->setValue(st.loadValue("direct_c2c.local_port", 2298).toInt());
+ updateDirectConnWidgets();
//multiple logins
int mlpstate;
@@ -1836,24 +2171,37 @@ void SettingsDialog::storeSettings()
Settings st(config_dbname);
//Direct c2c connections
- int c2c_state;
+ DirectC2CSettings dcs;
+
+ dcs.state = 1;
if (rbDisableDirectConns->isChecked())
- c2c_state = 0;
+ dcs.state = 0;
else if (rbEnableOutgoingConns->isChecked())
- c2c_state = 1;
+ dcs.state = 1;
else if (rbEnableIncomingConns->isChecked())
- c2c_state = 2;
+ dcs.state = 2;
- st.storeValue("direct_c2c.state", QString::number(c2c_state));
+ dcs.upnp = cbEnableUPnP ? cbEnableUPnP->isChecked() : false;
+ dcs.addrConfig = rbAddrManual->isChecked() ? DirectC2CSettings::AddrConfigManual
+ : DirectC2CSettings::AddrConfigAuto;
+ dcs.localPort = localPort->value();
-#ifdef HAVE_LIBMINIUPNPC
- st.storeValue("direct_c2c.upnp_enabled", cbEnableUPnP->isChecked() ? "1" : "0");
-#endif
+ // Kept even when the automatic configuration is selected, so that
+ // switching back to the manual one finds it as it was.
+ for (int row = 0; row < addrTable->rowCount(); row++)
+ {
+ DirectC2CSettings::Addr a;
+
+ a.upnp = addrRowIsUpnp(row);
+ a.host = a.upnp ? QString() : addrTable->item(row, 0)->text().trimmed();
+ a.port = a.upnp ? 0 : addrTable->item(row, 1)->text().trimmed().toInt();
+
+ if (a.upnp || (!a.host.isEmpty() && a.port > 0 && a.port <= 65535))
+ dcs.addrs.append(a);
+ }
- st.storeValue("direct_c2c.public_addr", addr->lineEdit()->text());
- st.storeValue("direct_c2c.public_port", QString::number(publicPort->value()));
- st.storeValue("direct_c2c.local_port", QString::number(localPort->value()));
+ dcs.store(st);
//multiple logins
int mlpstate;
diff --git a/pica-client/dialogs/settingsdialog.h b/pica-client/dialogs/settingsdialog.h
index 50b90c8..ab1c7e7 100644
--- a/pica-client/dialogs/settingsdialog.h
+++ b/pica-client/dialogs/settingsdialog.h
@@ -25,6 +25,7 @@
#include <QComboBox>
#include <QCheckBox>
#include <QLabel>
+#include <QTableWidget>
#include <QThread>
#include <QImage>
#include <QList>
@@ -63,13 +64,37 @@ private:
QRadioButton *rbDisableDirectConns;
QRadioButton *rbEnableOutgoingConns;
QRadioButton *rbEnableIncomingConns;
-#ifdef HAVE_LIBMINIUPNPC
+ // Everything below "Enable incoming direct connections", disabled
+ // together with it.
+ QWidget *incomingBox;
+ // Null in a build without UPnP support, where offering it would only
+ // lead to an error message later on.
QCheckBox *cbEnableUPnP;
-#endif
- QComboBox *addr;
- QSpinBox *publicPort;
+ // direct_c2c.addr_config - which addresses go into the 0x0B message
+ QRadioButton *rbAddrAuto;
+ QRadioButton *rbAddrManual;
+ // what the automatic configuration would announce right now
+ QLabel *lbAutoAddrs;
+
+ // The manual configuration: the port listened on, and the announced
+ // addresses in the order peers try them. A row of the table can also
+ // stand for the UPnP router's external address, which is only known
+ // once the client runs - see addUpnpAddrRow().
+ QWidget *manualBox;
QSpinBox *localPort;
+ QTableWidget *addrTable;
+ QPushButton *btAddrUpnp;
+ QPushButton *btUpnpQuery;
+ QLabel *lbUpnpInfo;
+
+ void updateDirectConnWidgets();
+ void updateAutoAddrsLabel();
+ void addAddrRow(const QString &host, int port, bool upnp);
+ bool addrRowIsUpnp(int row) const;
+ // Checks the manual address list before it is stored; false, having
+ // told the user why, if it cannot be.
+ bool validateAddrTable();
QRadioButton *rbMLPProhibit;
QRadioButton *rbMLPReplace;
@@ -300,6 +325,18 @@ private slots:
void OK();
void Cancel();
void toggleIncomingConnections(bool checked);
+ // The manual address list's buttons. Declared unconditionally, see
+ // the note at audioDriver for why slots must not depend on a define.
+ void addAddr();
+ void removeAddr();
+ void moveAddrUp();
+ void moveAddrDown();
+ void addInterfaceAddrs();
+ void addUpnpAddrRow();
+ // Asks the UPnP router for its external address on a thread of its own -
+ // discovery alone takes two seconds - and adds it to the list.
+ void queryUpnpAddr();
+ void upnpQueryFinished(int status, QString addr);
void toggleMultipleLogins(bool checked);
void fillVideoDevices();
// Asks the newly selected camera what it can do and refills the two lists
diff --git a/pica-client/directc2csettings.h b/pica-client/directc2csettings.h
new file mode 100644
index 0000000..76f73aa
--- /dev/null
+++ b/pica-client/directc2csettings.h
@@ -0,0 +1,145 @@
+/*
+ (c) Copyright 2012 - 2026 Anton Sviridenko
+ https://picapica.im
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, version 3.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+*/
+#ifndef DIRECTC2CSETTINGS_H
+#define DIRECTC2CSETTINGS_H
+
+#include "settings.h"
+#include <QString>
+#include <QStringList>
+#include <QList>
+
+// The settings of the "Direct connections" tab, read and written in one place
+// because the settings dialog and SkyNet both need them, and because of the
+// single address earlier versions stored instead of a list.
+struct DirectC2CSettings
+{
+ // direct_c2c.addr_config
+ enum AddrConfig
+ {
+ // interface addresses, then the UPnP mapping; the port is looked for
+ // starting at DefaultPort
+ AddrConfigAuto = 0,
+ // the list below, listening on localPort
+ AddrConfigManual = 1
+ };
+
+ enum
+ {
+ DefaultPort = 2299
+ };
+
+ // One announced address. The UPnP entry stands for the external address
+ // of the UPnP port mapping, which is only known at run time.
+ struct Addr
+ {
+ QString host;
+ int port;
+ bool upnp;
+ };
+
+ // PICA_directc2c_config
+ int state;
+ bool upnp;
+ int addrConfig;
+ int localPort;
+ QList<Addr> addrs;
+
+ void load(Settings &st)
+ {
+ state = st.loadValue("direct_c2c.state", 1).toInt();
+ upnp = st.loadValue("direct_c2c.upnp_enabled", 1).toBool();
+ localPort = st.loadValue("direct_c2c.local_port", (int)DefaultPort).toInt();
+ addrConfig = st.loadValue("direct_c2c.addr_config", -1).toInt();
+ addrs = parseAddrs(st.loadValue("direct_c2c.addr_list", QString()).toString());
+
+ if (addrConfig == AddrConfigAuto || addrConfig == AddrConfigManual)
+ return;
+
+ // Never stored: either a fresh installation, or one from before the
+ // address list, whose single public address - "autoconfigure"
+ // unless the user typed one in - becomes a manual list of one.
+ QString oldAddr = st.loadValue("direct_c2c.public_addr", "autoconfigure").toString();
+
+ addrConfig = AddrConfigAuto;
+
+ if (!oldAddr.isEmpty() && !oldAddr.contains("autoconfigure"))
+ {
+ Addr a;
+
+ a.host = oldAddr;
+ a.port = st.loadValue("direct_c2c.public_port", localPort).toInt();
+ a.upnp = false;
+
+ addrConfig = AddrConfigManual;
+ addrs.clear();
+ addrs.append(a);
+ }
+ }
+
+ void store(Settings &st) const
+ {
+ st.storeValue("direct_c2c.state", QString::number(state));
+ st.storeValue("direct_c2c.upnp_enabled", upnp ? "1" : "0");
+ st.storeValue("direct_c2c.addr_config", QString::number(addrConfig));
+ st.storeValue("direct_c2c.local_port", QString::number(localPort));
+ st.storeValue("direct_c2c.addr_list", formatAddrs(addrs));
+ }
+
+ // "host:port;host:port;upnp"
+ static QList<Addr> parseAddrs(const QString &s)
+ {
+ QList<Addr> l;
+
+ foreach (const QString &item, s.split(';', QString::SkipEmptyParts))
+ {
+ Addr a;
+ QString entry = item.trimmed();
+ int colon = entry.lastIndexOf(':');
+
+ a.upnp = entry == "upnp";
+ a.port = 0;
+
+ if (!a.upnp)
+ {
+ if (colon <= 0)
+ continue;
+
+ a.host = entry.left(colon);
+ a.port = entry.mid(colon + 1).toInt();
+
+ if (a.port <= 0 || a.port > 65535)
+ continue;
+ }
+
+ l.append(a);
+ }
+
+ return l;
+ }
+
+ static QString formatAddrs(const QList<Addr> &l)
+ {
+ QStringList items;
+
+ foreach (const Addr &a, l)
+ items.append(a.upnp ? QString("upnp") : QString("%1:%2").arg(a.host).arg(a.port));
+
+ return items.join(';');
+ }
+};
+
+#endif // DIRECTC2CSETTINGS_H
diff --git a/pica-client/directlistener.cpp b/pica-client/directlistener.cpp
new file mode 100644
index 0000000..83e261d
--- /dev/null
+++ b/pica-client/directlistener.cpp
@@ -0,0 +1,282 @@
+/*
+ (c) Copyright 2012 - 2026 Anton Sviridenko
+ https://picapica.im
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, version 3.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+*/
+#include "directlistener.h"
+#include "directc2csettings.h"
+#include "../PICA_client.h"
+#include "../PICA_netconf.h"
+#include <QByteArray>
+#include <QList>
+#include <vector>
+
+// How soon a lost mapping is tried again, in seconds.
+static const int kUpnpRetryInterval = 300;
+
+DirectListener::DirectListener(QObject *parent)
+ : QObject(parent), upnp(nullptr), upnpPort(0), upnpLost(false), refreshTimer(nullptr)
+{
+}
+
+DirectListener::~DirectListener()
+{
+ // release() is expected to have run on this object's own thread already;
+ // this is only for a mapping left behind when it did not
+ PICA_upnp_free(upnp);
+}
+
+bool DirectListener::discoverUpnp()
+{
+ char addr[64];
+ int ret;
+
+ ret = PICA_upnp_discover(PICA_UPNP_DISCOVER_TIMEOUT, &upnp);
+
+ if (ret != PICA_UPNP_OK)
+ {
+ upnp = nullptr;
+ emit statusMsg(tr("UPnP: %1").arg(PICA_upnp_strerror(ret)), false);
+ return false;
+ }
+
+ // An external address that is private - the router is behind the
+ // provider's NAT - would lead nowhere; better not to forward anything
+ // than to announce it.
+ ret = PICA_upnp_external_addr(upnp, addr, sizeof(addr));
+
+ if (ret != PICA_UPNP_OK)
+ {
+ emit statusMsg(tr("UPnP: %1").arg(PICA_upnp_strerror(ret)), false);
+ dropUpnp();
+ return false;
+ }
+
+ upnpAddr = QString::fromLatin1(addr);
+
+ return true;
+}
+
+void DirectListener::dropUpnp()
+{
+ PICA_upnp_free(upnp);
+ upnp = nullptr;
+ upnpAddr.clear();
+ upnpPort = 0;
+}
+
+void DirectListener::setup(quintptr accp, int addrConfig, bool useUpnp, int localPort, QString addrList)
+{
+ const struct PICA_acc *acc = (const struct PICA_acc*)accp;
+ struct PICA_listener *l = nullptr;
+ bool manual = addrConfig == DirectC2CSettings::AddrConfigManual;
+ QList<DirectC2CSettings::Addr> addrs = DirectC2CSettings::parseAddrs(addrList);
+ // In automatic configuration a port that cannot be had is not worth a
+ // word: the next one is tried. The port of the manual one is the user's
+ // choice and is used as it is.
+ int firstPort = manual ? localPort : (int)DirectC2CSettings::DefaultPort;
+ int tries = manual ? 1 : (int)PortTries;
+ bool mapped = false;
+ int port = 0;
+ int i, ret;
+
+ if (useUpnp)
+ discoverUpnp();
+
+ for (i = 0; i < tries && firstPort + i <= 65535; i++)
+ {
+ port = firstPort + i;
+
+ if (PICA_new_listener(acc, port, &l) != PICA_OK)
+ {
+ l = nullptr;
+ continue;
+ }
+
+ if (!upnp)
+ break;
+
+ ret = PICA_upnp_map(upnp, port, PICA_UPNP_LEASE_DEFAULT, "Pica Pica");
+
+ if (ret == PICA_UPNP_OK)
+ {
+ mapped = true;
+ break;
+ }
+
+ // somebody else behind the router has this port number forwarded
+ if (ret == PICA_UPNP_ERRCONFLICT && i + 1 < tries)
+ {
+ PICA_close_listener(l);
+ l = nullptr;
+ continue;
+ }
+
+ emit statusMsg(tr("UPnP: failed to forward port %1 - %2").arg(port).arg(PICA_upnp_strerror(ret)), false);
+ dropUpnp();
+ break;
+ }
+
+ if (!l)
+ {
+ if (manual)
+ emit statusMsg(tr("Failed to open port %1 for incoming direct connections").arg(firstPort), true);
+ else
+ emit statusMsg(tr("Failed to open any of the ports %1 - %2 for incoming direct connections")
+ .arg(firstPort).arg(firstPort + tries - 1), true);
+
+ dropUpnp();
+ emit ready(0, QString(), 0);
+ return;
+ }
+
+ if (!mapped)
+ dropUpnp();
+
+ if (manual)
+ {
+ QList<QByteArray> hosts;
+ std::vector<const char *> hostPtrs;
+ std::vector<int> ports;
+ bool hasUpnpEntry = false;
+
+ foreach (const DirectC2CSettings::Addr &a, addrs)
+ {
+ hosts.append(a.upnp ? QByteArray() : a.host.toUtf8());
+ ports.push_back(a.upnp ? port : a.port);
+ hasUpnpEntry = hasUpnpEntry || a.upnp;
+ }
+
+ // A mapping with nowhere to announce it goes at the end.
+ if (mapped && !hasUpnpEntry)
+ {
+ hosts.append(QByteArray());
+ ports.push_back(port);
+ addrs.append(DirectC2CSettings::Addr {QString(), port, true});
+ }
+
+ for (int j = 0; j < hosts.size(); j++)
+ hostPtrs.push_back(addrs[j].upnp ? nullptr : hosts[j].constData());
+
+ // An empty list would make the listener fall back to automatic
+ // configuration, announcing addresses the user did not choose.
+ if (hostPtrs.empty())
+ {
+ emit statusMsg(tr("No addresses are configured for incoming direct connections"), true);
+ PICA_close_listener(l);
+ dropUpnp();
+ emit ready(0, QString(), 0);
+ return;
+ }
+
+ ret = PICA_listener_set_addrlist(l, hostPtrs.data(), ports.data(), (int)hostPtrs.size());
+
+ if (ret != PICA_OK)
+ {
+ emit statusMsg(tr("Unable to resolve the addresses configured for incoming direct connections"), true);
+ PICA_close_listener(l);
+ dropUpnp();
+ emit ready(0, QString(), 0);
+ return;
+ }
+ }
+
+ if (mapped)
+ {
+ upnpPort = port;
+ upnpLost = false;
+ scheduleRefresh();
+
+ emit statusMsg(tr("Port %1 is forwarded by the UPnP router, external address %2").arg(port).arg(upnpAddr), false);
+ }
+
+ emit statusMsg(tr("Listening for incoming direct connections on port %1").arg(port), false);
+
+ emit ready((quintptr)l, mapped ? upnpAddr : QString(), mapped ? port : 0);
+}
+
+void DirectListener::scheduleRefresh()
+{
+ unsigned int lease = PICA_upnp_lease(upnp);
+ int secs;
+
+ if (!refreshTimer)
+ {
+ refreshTimer = new QTimer(this);
+ refreshTimer->setSingleShot(true);
+ connect(refreshTimer, SIGNAL(timeout()), this, SLOT(refresh()));
+ }
+
+ // Renewed at half the lease the router granted. A permanent mapping is
+ // checked just as often: the router forgets it when it reboots.
+ if (upnpLost)
+ secs = kUpnpRetryInterval;
+ else if (lease == 0)
+ secs = PICA_UPNP_LEASE_DEFAULT / 2;
+ else
+ secs = (int)(lease / 2);
+
+ if (secs < 30)
+ secs = 30;
+
+ refreshTimer->start(secs * 1000);
+}
+
+void DirectListener::refresh()
+{
+ char addr[64];
+ int ret;
+
+ if (!upnp)
+ return;
+
+ if (PICA_upnp_mapped(upnp))
+ ret = PICA_upnp_refresh(upnp);
+ else
+ ret = PICA_upnp_map(upnp, upnpPort, PICA_UPNP_LEASE_DEFAULT, "Pica Pica");
+
+ // The router's external address can change on a renewal of its own
+ // lease with the provider, and is read again every time.
+ if (ret == PICA_UPNP_OK)
+ ret = PICA_upnp_external_addr(upnp, addr, sizeof(addr));
+
+ if (ret == PICA_UPNP_OK)
+ {
+ QString newAddr = QString::fromLatin1(addr);
+
+ if (upnpLost || newAddr != upnpAddr)
+ {
+ upnpAddr = newAddr;
+ emit upnpChanged(upnpAddr, upnpPort);
+ }
+
+ upnpLost = false;
+ }
+ else if (!upnpLost)
+ {
+ upnpLost = true;
+ emit upnpChanged(QString(), 0);
+ emit statusMsg(tr("UPnP: the forwarding of port %1 was lost - %2").arg(upnpPort).arg(PICA_upnp_strerror(ret)), false);
+ }
+
+ scheduleRefresh();
+}
+
+void DirectListener::release()
+{
+ if (refreshTimer)
+ refreshTimer->stop();
+
+ dropUpnp();
+}
diff --git a/pica-client/directlistener.h b/pica-client/directlistener.h
new file mode 100644
index 0000000..0e69d16
--- /dev/null
+++ b/pica-client/directlistener.h
@@ -0,0 +1,85 @@
+/*
+ (c) Copyright 2012 - 2026 Anton Sviridenko
+ https://picapica.im
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, version 3.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <https://www.gnu.org/licenses/>.
+*/
+#ifndef DIRECTLISTENER_H
+#define DIRECTLISTENER_H
+
+#include <QObject>
+#include <QString>
+#include <QTimer>
+
+struct PICA_upnp_ctx;
+
+// Opens the listener for incoming direct connections and keeps its UPnP port
+// mapping up for as long as the client runs.
+//
+// Talking to a UPnP router blocks - discovery for two seconds, every request
+// for as long as the router takes to answer - so this lives on a thread of
+// its own instead of SkyNet's, which carries the media of calls. The
+// listener it opens is handed over to SkyNet and used on SkyNet's thread
+// only; what changes about the mapping later on is reported with
+// upnpChanged(), for SkyNet to pass on to the listener.
+class DirectListener : public QObject
+{
+ Q_OBJECT
+public:
+ // Ports tried in automatic configuration, from DirectC2CSettings::DefaultPort
+ // on, until one can be opened for TCP and UDP and - with UPnP - forwarded.
+ enum
+ {
+ PortTries = 16
+ };
+
+ explicit DirectListener(QObject *parent = 0);
+ ~DirectListener();
+
+public slots:
+ // Opens the listener as the "Direct connections" settings say and reports
+ // the outcome with ready(). addrList is DirectC2CSettings' stored form.
+ void setup(quintptr acc, int addrConfig, bool useUpnp, int localPort, QString addrList);
+
+ // Deletes the port mapping. Called once, at shutdown.
+ void release();
+
+signals:
+ // listener is a struct PICA_listener *, 0 if none could be opened.
+ // upnpAddr is empty when no port mapping was made.
+ void ready(quintptr listener, QString upnpAddr, int upnpPort);
+
+ // The external address or port of the mapping changed - the router got a
+ // new address from the provider - or the mapping was lost, in which case
+ // upnpAddr is empty.
+ void upnpChanged(QString upnpAddr, int upnpPort);
+
+ void statusMsg(QString msg, bool isCritical);
+
+private slots:
+ void refresh();
+
+private:
+ struct PICA_upnp_ctx *upnp;
+ QString upnpAddr;
+ // the port the mapping is for, the same number as the listening port
+ int upnpPort;
+ bool upnpLost;
+ QTimer *refreshTimer;
+
+ bool discoverUpnp();
+ void dropUpnp();
+ void scheduleRefresh();
+};
+
+#endif // DIRECTLISTENER_H
diff --git a/pica-client/pica-client.pro b/pica-client/pica-client.pro
index 4823c8a..2838890 100644
--- a/pica-client/pica-client.pro
+++ b/pica-client/pica-client.pro
@@ -27,6 +27,7 @@ SOURCES += main.cpp\
contactlistwidget.cpp \
mediadevice.cpp \
skynet.cpp \
+ directlistener.cpp \
nodes.cpp \
accountswindow.cpp \
accounts.cpp \
@@ -56,6 +57,8 @@ SOURCES += main.cpp\
videodshow.cpp
HEADERS += mainwindow.h \
+ directlistener.h \
+ directc2csettings.h \
audiodevice.h \
audioring.h \
echocanceller.h \
diff --git a/pica-client/skynet.cpp b/pica-client/skynet.cpp
index 92257ca..b993dc9 100644
--- a/pica-client/skynet.cpp
+++ b/pica-client/skynet.cpp
@@ -29,7 +29,7 @@
#include "dhparam.h"
#include "askpassword.h"
#include "settings.h"
-#include "../PICA_netconf.h"
+#include "directc2csettings.h"
#include <time.h>
SkyNet::SkyNet()
@@ -80,6 +80,12 @@ SkyNet::SkyNet()
this->active_nodelink = NULL;
this->acc = NULL;
this->listener = NULL;
+ this->direct_listener = NULL;
+ listener_setup_pending = false;
+ listener_failed = false;
+ join_wanted = false;
+
+ qRegisterMetaType<quintptr>("quintptr");
connect(this, SIGNAL(PeerCertificateReceived(QByteArray, QString, bool*)), this, SLOT(verify_peer_cert(QByteArray, QString, bool*)), Qt::DirectConnection);
connect(this, SIGNAL(MultiloginMessageReceived(quint64,QString,quint16)), this, SLOT(multilogin_event(quint64,QString,quint16)), Qt::QueuedConnection);
@@ -92,6 +98,15 @@ SkyNet::SkyNet()
SkyNet::~SkyNet()
{
+ if (direct_listener)
+ {
+ // the UPnP mapping is deleted rather than left to expire
+ QMetaObject::invokeMethod(direct_listener, "release", Qt::BlockingQueuedConnection);
+ direct_listener_thread.quit();
+ direct_listener_thread.wait();
+ delete direct_listener;
+ }
+
delete nodes;
}
@@ -109,6 +124,16 @@ void SkyNet::init()
nodes = new Nodes(config_dbname, network_sql_connection_name);
+ direct_listener = new DirectListener();
+ direct_listener->moveToThread(&direct_listener_thread);
+ connect(direct_listener, SIGNAL(ready(quintptr,QString,int)),
+ this, SLOT(listener_ready(quintptr,QString,int)), Qt::QueuedConnection);
+ connect(direct_listener, SIGNAL(upnpChanged(QString,int)),
+ this, SLOT(listener_upnp_changed(QString,int)), Qt::QueuedConnection);
+ connect(direct_listener, SIGNAL(statusMsg(QString,bool)),
+ this, SLOT(listener_status_msg(QString,bool)), Qt::QueuedConnection);
+ direct_listener_thread.start();
+
event_loop_timer_id = startTimer(100);
c2c_reconnect_timer_id = startTimer(1000);
}
@@ -537,47 +562,37 @@ void SkyNet::do_Join(const Accounts::AccountRecord &accrec)
return;
}
- directc2c_cfg = (PICA_directc2c_config)st.loadValue("direct_c2c.state", 1).toInt();
+ DirectC2CSettings dcs;
+
+ dcs.load(st);
+
+ directc2c_cfg = (PICA_directc2c_config)dcs.state;
multilogin = st.loadValue("multiple_logins.state", PICA_MULTILOGIN_PROHIBIT).toInt();
+ join_wanted = true;
+
if (!listener && directc2c_cfg == PICA_DIRECTC2C_CFG_ALLOWINCOMING)
{
- int pub_port = st.loadValue("direct_c2c.public_port", 2298).toInt();
- int loc_port = st.loadValue("direct_c2c.local_port", 2298).toInt();
- QString public_addr = st.loadValue("direct_c2c.public_addr", "autoconfigure").toString();
-
- if (public_addr.contains("autoconfigure"))
+ if (listener_failed)
{
- in_addr_t guess;
- struct in_addr in;
-
- guess = PICA_guess_listening_addr_ipv4();
- in.s_addr = guess;
- public_addr = QString(inet_ntoa(in));
-#ifdef HAVE_LIBMINIUPNPC
- if (st.loadValue("direct_c2c.upnp_enabled", 1).toBool() && PICA_is_reserved_addr_ipv4(guess))
+ directc2c_cfg = PICA_DIRECTC2C_CFG_CONNECTONLY;
+ }
+ else
+ {
+ // joined from listener_ready(), once the listener is there
+ if (!listener_setup_pending)
{
- int ret;
- char public_ip[64];
- ret = PICA_upnp_autoconfigure_ipv4(pub_port, loc_port, public_ip);
-
- if (ret)
- {
- public_addr = QString(public_ip);
- }
+ listener_setup_pending = true;
+
+ QMetaObject::invokeMethod(direct_listener, "setup", Qt::QueuedConnection,
+ Q_ARG(quintptr, (quintptr)acc),
+ Q_ARG(int, dcs.addrConfig),
+ Q_ARG(bool, dcs.upnp),
+ Q_ARG(int, dcs.localPort),
+ Q_ARG(QString, DirectC2CSettings::formatAddrs(dcs.addrs)));
}
-#endif
- emit StatusMsg(QString(tr("Using autoconfigured address %1 port %2 for incoming direct connections")).arg(public_addr).arg(pub_port), false);
- }
- int ret = PICA_new_listener(acc,
- public_addr.toLatin1().constData(),
- pub_port,
- loc_port, &listener);
- if (ret != PICA_OK)
- {
- emit StatusMsg(QString(tr("Failed to open port %1 for incoming direct connections")).arg(loc_port), true);
- directc2c_cfg = PICA_DIRECTC2C_CFG_CONNECTONLY;
+ return;
}
}
@@ -613,8 +628,48 @@ void SkyNet::Exit()
QMetaObject::invokeMethod(this, "do_Exit", Qt::AutoConnection);
}
+void SkyNet::listener_ready(quintptr l, QString upnp_addr, int upnp_port)
+{
+ listener_setup_pending = false;
+
+ if (l)
+ {
+ listener = (struct PICA_listener *)l;
+
+ if (!upnp_addr.isEmpty())
+ PICA_listener_set_upnp_addr(listener, upnp_addr.toLatin1().constData(), upnp_port);
+ }
+ else
+ {
+ // connect-only until the next start, rather than failing again on
+ // every reconnection
+ listener_failed = true;
+ }
+
+ if (join_wanted)
+ do_Join(skynet_account);
+}
+
+void SkyNet::listener_upnp_changed(QString upnp_addr, int upnp_port)
+{
+ if (!listener)
+ return;
+
+ if (upnp_addr.isEmpty())
+ PICA_listener_set_upnp_addr(listener, NULL, 0);
+ else
+ PICA_listener_set_upnp_addr(listener, upnp_addr.toLatin1().constData(), upnp_port);
+}
+
+void SkyNet::listener_status_msg(QString msg, bool is_critical)
+{
+ emit StatusMsg(msg, is_critical);
+}
+
void SkyNet::do_Exit()
{
+ join_wanted = false;
+
if (self_aware && active_nodelink)
{
PICA_close_c2n(active_nodelink);
diff --git a/pica-client/skynet.h b/pica-client/skynet.h
index c7d1903..479ce3d 100644
--- a/pica-client/skynet.h
+++ b/pica-client/skynet.h
@@ -22,7 +22,9 @@
#include "../PICA_media.h"
#include "../PICA_proto.h"
#include "accounts.h"
+#include "directlistener.h"
#include <QObject>
+#include <QThread>
#include <QMap>
#include <QVector>
#include <QPair>
@@ -117,6 +119,17 @@ private:
struct PICA_c2n *active_nodelink;
struct PICA_acc *acc;
struct PICA_listener *listener;
+ // Opens the listener and looks after its UPnP mapping on a thread of its
+ // own, see directlistener.h. The listener is waited for before the nodes
+ // are connected to, so that the first 0x0B messages already carry the
+ // external address.
+ DirectListener *direct_listener;
+ QThread direct_listener_thread;
+ bool listener_setup_pending;
+ bool listener_failed;
+ // Join() was called and Exit() has not been since, so that a listener
+ // arriving late does not bring the client back online.
+ bool join_wanted;
Accounts::AccountRecord skynet_account;
QMap<QByteArray, QList<QString> > msgqueues;
@@ -266,6 +279,10 @@ private slots:
void multilogin_event(quint64 timestamp, QString node_addr, quint16 node_port);
void node_status_changed(Nodes::NodeRecord nr, bool alive);
+
+ void listener_ready(quintptr l, QString upnp_addr, int upnp_port);
+ void listener_upnp_changed(QString upnp_addr, int upnp_port);
+ void listener_status_msg(QString msg, bool is_critical);
void verify_peer_cert(QByteArray peer_id, QString cert_pem, bool *verified);
// Connected to the network thread's QThread::started() signal. Runs
diff --git a/pica-node.conf.5 b/pica-node.conf.5
index e1a84f8..29b9b43 100644
--- a/pica-node.conf.5
+++ b/pica-node.conf.5
@@ -23,7 +23,8 @@ future releases). If the computer running pica-node is behind the NAT, external
configured. Default value is "autoconfigure" which makes pica-node try to guess
its external IP address. If pica-node is build with miniupnpc support, it will
try to employ UPnP protocol to get external IP from the router and enable port
- forwarding.
+ forwarding of both the TCP and the UDP port, see listen_port. The forwarding
+ is renewed for as long as pica-node runs.
.TP
.I listen_port
Specifies the port number that
diff --git a/tests/test_client.c b/tests/test_client.c
index 0bf7fbc..320e0bb 100644
--- a/tests/test_client.c
+++ b/tests/test_client.c
@@ -239,6 +239,11 @@ void udp_address_cb(struct PICA_c2n *c2n, int status, int type, void *addr_bin,
printf("udp_address_cb: failed, status %i\n", status);
}
+void direct_c2c_established_cb(const unsigned char *peer_id, const char *ciphersuitename)
+{
+ printf("direct c2c connection established, %s\n", ciphersuitename);
+}
+
struct PICA_client_callbacks cbs =
{
newmsg_cb,
@@ -261,6 +266,7 @@ struct PICA_client_callbacks cbs =
c2n_closed_cb,
listener_error,
multilogin_cb,
+ .direct_c2c_established_cb = direct_c2c_established_cb,
.tcp_address_cb = tcp_address_cb,
.udp_address_cb = udp_address_cb
};
@@ -364,7 +370,7 @@ int main(int argc, char** argv)
if (argc < 4 || !nodeaddr || !nodeport || !certfile)
{
puts("usage: test_client -a node address -p node port -c cert_filename [-i peer id]\n\
- -d local address for direct incoming c2c connections\n\
+ -d local address for direct incoming c2c connections, \"auto\" for automatic configuration\n\
-e external port for incoming direct connections\n\
-l internal port to listen for incoming direct connections\n\
-t enable connect-only mode for direct c2c connections\n\
@@ -405,7 +411,33 @@ cert_filename should point to file that contains client certificate, private key
printf("new listener on %s port %i external announced port %i\n", localdirectaddr, intp, extp);
- ret = PICA_new_listener(acc, localdirectaddr, extp, intp, &l);
+ ret = PICA_new_listener(acc, intp, &l);
+
+ /* "auto" leaves the announced addresses to the listener */
+ if (ret == PICA_OK && strcmp(localdirectaddr, "auto") != 0)
+ {
+ /* a comma separated list, announced in its order */
+ const char *addrs[PICA_DIRECTC2C_MAX_ADDRS];
+ int ports[PICA_DIRECTC2C_MAX_ADDRS];
+ char *list = strdup(localdirectaddr), *a;
+ int n = 0;
+
+ for (a = strtok(list, ","); a && n < PICA_DIRECTC2C_MAX_ADDRS; a = strtok(NULL, ","))
+ {
+ addrs[n] = a;
+ ports[n] = extp;
+ n++;
+ }
+
+ ret = PICA_listener_set_addrlist(l, addrs, ports, n);
+ free(list);
+
+ if (ret != PICA_OK)
+ {
+ fprintf(stderr, "failed to set the listener's address, error code: %i\n", ret);
+ PICA_close_listener(l);
+ }
+ }
if (ret != PICA_OK)
{