diff options
| author | Anton <anton@picapica.im> | 2026-11-15 21:25:50 +0400 |
|---|---|---|
| committer | Anton <anton@picapica.im> | 2026-11-15 21:25:50 +0400 |
| commit | 0f9e20bdd1159b65013dcc27bf1a6fb30c5cb115 (patch) | |
| tree | 97f0e973ac7dd58b84f52af4a079568b1900d06f | |
| parent | bd0bc3949a8fed3a2bd87b39cbeecd0b5cfcafd1 (diff) | |
| download | pica-pica-0f9e20bdd1159b65013dcc27bf1a6fb30c5cb115.tar.gz pica-pica-0f9e20bdd1159b65013dcc27bf1a6fb30c5cb115.zip | |
proto update: add get my addr and get my UDP addr messages
| -rw-r--r-- | PICA_client.c | 191 | ||||
| -rw-r--r-- | PICA_client.h | 70 | ||||
| -rw-r--r-- | PICA_node.c | 272 | ||||
| -rw-r--r-- | PICA_node.h | 11 | ||||
| -rw-r--r-- | PICA_proto.h | 26 | ||||
| -rw-r--r-- | doc/proto-doc-latest.txt | 100 | ||||
| -rw-r--r-- | pica-node.conf | 3 | ||||
| -rw-r--r-- | pica-node.conf.5 | 9 | ||||
| -rw-r--r-- | tests/test_client.c | 56 |
9 files changed, 729 insertions, 9 deletions
diff --git a/PICA_client.c b/PICA_client.c index d26287f..c994089 100644 --- a/PICA_client.c +++ b/PICA_client.c @@ -87,6 +87,9 @@ static unsigned int procmsg_CALL_AUDIO_PACKET(unsigned char*, unsigned int, void static unsigned int procmsg_CALL_VIDEO_PACKET(unsigned char*, unsigned int, void*); static unsigned int procmsg_MEDIA_PINGREQ(unsigned char*, unsigned int, void*); static unsigned int procmsg_MEDIA_PINGREP(unsigned char*, unsigned int, void*); +static unsigned int procmsg_MYTCPADDR(unsigned char*, unsigned int, void*); +static unsigned int procmsg_MYUDPADDRTOKEN(unsigned char*, unsigned int, void*); +static unsigned int procmsg_MYUDPADDR(unsigned char*, unsigned int, void*); static struct PICA_proto_msg* c2n_writebuf_push(struct PICA_c2n *ci, unsigned int msgid, unsigned int size); static struct PICA_proto_msg* c2c_writebuf_push(struct PICA_c2c *chn, unsigned int msgid, unsigned int size); @@ -112,7 +115,11 @@ const struct PICA_msginfo c2n_messages[] = {PICA_PROTO_PINGREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREQ_SIZE, procmsg_PINGREQ}, {PICA_PROTO_INITRESPOK, PICA_MSG_FIXED_SIZE, PICA_PROTO_INITRESPOK_SIZE, procmsg_INITRESP}, {PICA_PROTO_VERDIFFER, PICA_MSG_FIXED_SIZE, PICA_PROTO_VERDIFFER_SIZE, procmsg_INITRESP}, - {PICA_PROTO_MULTILOGIN, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MULTILOGIN} + {PICA_PROTO_MULTILOGIN, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MULTILOGIN}, + {PICA_PROTO_MYTCPADDR_IPV4, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYTCPADDR_IPV4_SIZE, procmsg_MYTCPADDR}, + {PICA_PROTO_MYTCPADDR_IPV6, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYTCPADDR_IPV6_SIZE, procmsg_MYTCPADDR}, + {PICA_PROTO_MYUDPADDRTOKEN, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYUDPADDRTOKEN_SIZE, procmsg_MYUDPADDRTOKEN}, + {PICA_PROTO_MYUDPADDR, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT8, procmsg_MYUDPADDR} }; const struct PICA_msginfo c2c_messages[] = @@ -1052,6 +1059,186 @@ unsigned int procmsg_PINGREQ(unsigned char* buf, unsigned int nb, void* p) return 1; } +/* Reads the address and the port following it, both in network byte order, + * for one of the "my address" callbacks. addr_str has to have room for + * INET6_ADDRSTRLEN characters. + */ +static int myaddr_parse(int af, const unsigned char *addr, char *addr_str, uint16_t *port) +{ + if (!inet_ntop(af, addr, addr_str, INET6_ADDRSTRLEN)) + return 0; + + memcpy(port, addr + (af == AF_INET6 ? 16 : 4), 2); + *port = ntohs(*port); + + return 1; +} + +static unsigned int procmsg_MYTCPADDR(unsigned char* buf, unsigned int nb, void* p) +{ + PICA_TRACEFUNC + struct PICA_c2n *c2n = (struct PICA_c2n *)p; + char addr_str[INET6_ADDRSTRLEN]; + uint16_t port; + + /* not something we asked for */ + if (!c2n->tcpaddr_requested) + return 1; + + c2n->tcpaddr_requested = 0; + + /* the message size is fixed for each of the two types, see c2n_messages[] */ + if (!myaddr_parse(buf[0] == PICA_PROTO_MYTCPADDR_IPV6 ? AF_INET6 : AF_INET, buf + 2, addr_str, &port)) + return 0; + + if (callbacks.tcp_address_cb) + callbacks.tcp_address_cb(c2n, buf[0], buf + 2, addr_str, port); + + return 1; +} + +static void udpaddr_send_probe(struct PICA_c2n *c2n) +{ + unsigned char probe[PICA_PROTO_MYUDPADDRPROBE_SIZE]; + + probe[0] = probe[1] = PICA_PROTO_MYUDPADDRPROBE; + memcpy(probe + 2, c2n->udpaddr_token, PICA_PROTO_MYUDPADDR_TOKENSIZE); + + /* The node's UDP port has the same number as the TCP port the c2n + * connection was made to. A failed send is treated like a lost datagram. + */ + sendto(c2n->udpaddr_sck, (const char*)probe, sizeof(probe), 0, + (const struct sockaddr*)&c2n->srv_addr, sizeof(c2n->srv_addr)); + + c2n->udpaddr_last_probe = time(0); + c2n->udpaddr_probes_sent++; +} + +static unsigned int procmsg_MYUDPADDRTOKEN(unsigned char* buf, unsigned int nb, void* p) +{ + PICA_TRACEFUNC + struct PICA_c2n *c2n = (struct PICA_c2n *)p; + + /* not something we asked for, or the answer to a request already given up on */ + if (c2n->udpaddr_state == PICA_UDPADDR_STATE_IDLE) + return 1; + + /* A token arriving while an earlier one is being sent belongs to a + * request that restarted this one - the node has dropped the earlier + * token by now, so the new one is the one to use. + */ + memcpy(c2n->udpaddr_token, buf + 2, PICA_PROTO_MYUDPADDR_TOKENSIZE); + c2n->udpaddr_state = PICA_UDPADDR_STATE_PROBING; + c2n->udpaddr_probes_sent = 0; + + udpaddr_send_probe(c2n); + + return 1; +} + +static unsigned int procmsg_MYUDPADDR(unsigned char* buf, unsigned int nb, void* p) +{ + PICA_TRACEFUNC + struct PICA_c2n *c2n = (struct PICA_c2n *)p; + char addr_str[INET6_ADDRSTRLEN]; + uint16_t port; + int af; + + if (c2n->udpaddr_state != PICA_UDPADDR_STATE_PROBING) + return 1; + + /* buf[2] is the length of the address that starts with its type at buf[3] */ + if (nb < 4) + return 0; + + if (buf[3] == PICA_PROTO_MYUDPADDR_IPV4 && buf[2] == PICA_PROTO_MYUDPADDR_IPV4_SIZE) + af = AF_INET; + else if (buf[3] == PICA_PROTO_MYUDPADDR_IPV6 && buf[2] == PICA_PROTO_MYUDPADDR_IPV6_SIZE) + af = AF_INET6; + else + return 0; + + if (!myaddr_parse(af, buf + 4, addr_str, &port)) + return 0; + + /* before the callback, which is free to make another request */ + c2n->udpaddr_state = PICA_UDPADDR_STATE_IDLE; + + if (callbacks.udp_address_cb) + callbacks.udp_address_cb(c2n, PICA_OK, buf[3], buf + 4, addr_str, port); + + return 1; +} + +/* resends the datagram of a request in progress, and gives up on one that + * was not answered in time + */ +static void process_udpaddr(struct PICA_c2n *c2n) +{ + time_t now; + + if (c2n->udpaddr_state == PICA_UDPADDR_STATE_IDLE) + return; + + now = time(0); + + if (now - c2n->udpaddr_started > PICA_UDPADDR_TIMEOUT || now < c2n->udpaddr_started) + { + c2n->udpaddr_state = PICA_UDPADDR_STATE_IDLE; + + if (callbacks.udp_address_cb) + callbacks.udp_address_cb(c2n, PICA_ERRTIMEDOUT, 0, NULL, NULL, 0); + + return; + } + + if (c2n->udpaddr_state == PICA_UDPADDR_STATE_PROBING + && c2n->udpaddr_probes_sent < PICA_UDPADDR_PROBES + && now != c2n->udpaddr_last_probe) + udpaddr_send_probe(c2n); +} + +int PICA_request_tcp_address(struct PICA_c2n *c2n) +{ + struct PICA_proto_msg *mp; + + if (!c2n || c2n->state != PICA_C2N_STATE_CONNECTED) + return PICA_ERRINVARG; + + mp = c2n_writebuf_push(c2n, PICA_PROTO_MYTCPADDRREQ, PICA_PROTO_MYTCPADDRREQ_SIZE); + + if (!mp) + return PICA_ERRNOMEM; + + RAND_pseudo_bytes(mp->tail, 2); + + c2n->tcpaddr_requested = 1; + + return PICA_OK; +} + +int PICA_request_udp_address(struct PICA_c2n *c2n, SOCKET udp_sck) +{ + struct PICA_proto_msg *mp; + + if (!c2n || c2n->state != PICA_C2N_STATE_CONNECTED || udp_sck == (SOCKET)-1) + return PICA_ERRINVARG; + + mp = c2n_writebuf_push(c2n, PICA_PROTO_MYUDPADDRREQ, PICA_PROTO_MYUDPADDRREQ_SIZE); + + if (!mp) + return PICA_ERRNOMEM; + + RAND_pseudo_bytes(mp->tail, 2); + + c2n->udpaddr_sck = udp_sck; + c2n->udpaddr_started = time(0); + c2n->udpaddr_probes_sent = 0; + c2n->udpaddr_state = PICA_UDPADDR_STATE_WAITINGTOKEN; + + return PICA_OK; +} + int PICA_deny_file(struct PICA_c2c *chan) { struct PICA_proto_msg *mp; @@ -3391,6 +3578,8 @@ int PICA_event_loop(struct PICA_c2n **connections, int timeout) //processing media connections of calls in progress PICA_media_process(*ic2n, &rfds); + + process_udpaddr(*ic2n); } ic2n++; } diff --git a/PICA_client.h b/PICA_client.h index 2c0b95f..fe6ab5e 100644 --- a/PICA_client.h +++ b/PICA_client.h @@ -20,6 +20,7 @@ #include <time.h> #include "PICA_id.h" +#include "PICA_proto.h" #ifdef WIN32 @@ -142,6 +143,12 @@ typedef u_short in_port_t; #define PICA_C2C_ACTIVATE_TIMEOUT 30 +/* PICA_request_udp_address(): how long the node's answer is waited for, and + * how many datagrams are sent to the node, one per second, until it comes. + */ +#define PICA_UDPADDR_TIMEOUT 10 +#define PICA_UDPADDR_PROBES 3 + /* How long an incoming direct connection may take to finish its TLS handshake * before it is reaped, and how many half-open incoming connections may sit in * a listener at once - both bound a peer's ability to tie up the listener. @@ -186,6 +193,15 @@ enum PICA_c2n_state PICA_C2N_STATE_CONNECTED }; +enum PICA_udpaddr_state +{ + PICA_UDPADDR_STATE_IDLE = 0, + /* request sent, waiting for the node to issue a token */ + PICA_UDPADDR_STATE_WAITINGTOKEN, + /* sending the token to the node's UDP port, waiting for the address */ + PICA_UDPADDR_STATE_PROBING +}; + enum PICA_directc2c_config { PICA_DIRECTC2C_CFG_DISABLED, @@ -221,6 +237,16 @@ struct PICA_c2n unsigned char node_ver_major, node_ver_minor; int disconnect_on_empty_write_buf; int want_write; + + int tcpaddr_requested; + + /* request made by PICA_request_udp_address() */ + enum PICA_udpaddr_state udpaddr_state; + SOCKET udpaddr_sck; + unsigned char udpaddr_token[PICA_PROTO_MYUDPADDR_TOKENSIZE]; + time_t udpaddr_started; + time_t udpaddr_last_probe; + int udpaddr_probes_sent; }; enum PICA_c2c_state @@ -464,6 +490,32 @@ struct PICA_client_callbacks */ void (*call_media_transport_cb)(const unsigned char *peer_id, int transport, const char *ciphersuitename, unsigned int max_payload); + + /* The callbacks below are optional and can be left NULL. */ + + /** + * The node's answer to PICA_request_tcp_address(): the address and port + * the c2n connection comes from, as the node sees them. + * \param type address type, PICA_PROTO_MYTCPADDR_{IPV4,IPV6} + * \param addr_bin address in binary form, network byte order + * \param addr_str address in string format, zero-terminated + * \param port port number, in host byte order + */ + void (*tcp_address_cb)(struct PICA_c2n *c2n, int type, void *addr_bin, const char *addr_str, uint16_t port); + + /** + * The outcome of PICA_request_udp_address(). + * \param status PICA_OK - the node saw a datagram from the socket coming + * from the address described by the remaining arguments, which have the + * same meaning as in tcp_address_cb, except that type is + * PICA_PROTO_MYUDPADDR_{IPV4,IPV6}. PICA_ERRTIMEDOUT - no answer; the + * node does not offer this, or UDP does not get through to it. The + * remaining arguments are zero then. + * + * The address is what the node saw, and is not authenticated: it is only + * good as a place for a peer to try, never as a proof of who is there. + */ + void (*udp_address_cb)(struct PICA_c2n *c2n, int status, int type, void *addr_bin, const char *addr_str, uint16_t port); }; @@ -512,6 +564,24 @@ int PICA_open_acc(const char *cert_file, // timeout - timeout in milliseconds int PICA_event_loop(struct PICA_c2n **connections, int timeout); +/** + * Asks the node which address and TCP port the c2n connection comes from. + * The answer is delivered to tcp_address_cb. + */ +int PICA_request_tcp_address(struct PICA_c2n *c2n); +/** + * Asks the node which address and port the datagrams sent from udp_sck come + * from, i.e. what the NAT in front of this host maps that socket to. The + * outcome is delivered to udp_address_cb. + * \param udp_sck bound, unconnected IPv4 UDP socket - the one the address is + * wanted for. It is only sent from, and has to stay open until the callback + * is called. The mapping learned is only useful with this same socket. + * + * One request per c2n connection can be in progress; another call restarts + * it. A node serves only a few of these in a row from one client. + */ +int PICA_request_udp_address(struct PICA_c2n *c2n, SOCKET udp_sck); + int PICA_send_msg(struct PICA_c2c *chn, char *buf, unsigned int len); //filename - ASCII or UTF-8 encoded string diff --git a/PICA_node.c b/PICA_node.c index f04df00..2eb97d6 100644 --- a/PICA_node.c +++ b/PICA_node.c @@ -60,6 +60,17 @@ typedef u_short uint16_t; #define NOREPLY_TIMEOUT 15 #define KEEPALIVE_TIMEOUT 60 +//"Get my UDP address": how long an issued token is accepted from the UDP socket +#define UDPADDR_TOKEN_TIMEOUT 10 //sec +//A client is served this many MYUDPADDRREQ messages in a row, and one more +//for every UDPADDR_REQ_PERIOD seconds after that +#define UDPADDR_REQ_BURST 4 +#define UDPADDR_REQ_PERIOD 5 //sec +#define UDPADDR_TOKEN_BUCKETS 1024 +//datagrams taken from the UDP socket per event, so that a flood of them does +//not keep the event loop away from the connections +#define UDP_READ_BATCH 64 + time_t skynet_refresh_tmst; time_t TMO_CCLINK_WAITACTIVE = 15; //CONF @@ -68,6 +79,12 @@ char *my_addr;//TEMP CONF FIXME static struct event_base *pica_event_base; SOCKET listen_comm_sck;//* +//UDP socket on the port with the same number as listen_comm_sck, -1 if it +//could not be opened. Nothing is ever sent from it. +SOCKET listen_udp_sck = -1; + +//clients with an issued "get my UDP address" token, hashed by the token +static struct client *udpaddr_tokens[UDPADDR_TOKEN_BUCKETS]; static int stop_node_loop = 0; @@ -119,6 +136,8 @@ unsigned int procmsg_PINGREP_node(unsigned char* buf, unsigned int size, void* p unsigned int procmsg_dummy_multi_c2n(unsigned char* buf, unsigned int size, void* ptr); unsigned int procmsg_MULTILOGIN_client(unsigned char* buf, unsigned int size, void* ptr); unsigned int procmsg_MULTILOGIN_node(unsigned char* buf, unsigned int size, void* ptr); +unsigned int procmsg_MYTCPADDRREQ(unsigned char* buf, unsigned int size, void* ptr); +unsigned int procmsg_MYUDPADDRREQ(unsigned char* buf, unsigned int size, void* ptr); struct cclink* cclink_list_add(struct client *clr, struct client *cle); struct cclink* cclink_list_search(const unsigned char *caller_id, const unsigned char *callee_id); @@ -164,6 +183,7 @@ void process_n2n_read(evutil_socket_t s, short event, void *arg); void process_n2n_write(evutil_socket_t s, short event, void *arg); void process_c2c_read(evutil_socket_t s, short event, void *arg); void process_c2c_write(evutil_socket_t s, short event, void *arg); +void process_udp_read(evutil_socket_t s, short event, void *arg); void process_nodewait(); #define MSGINFO_MSGSNUM(arr) (sizeof(arr)/sizeof(struct PICA_msginfo)) @@ -176,7 +196,9 @@ struct PICA_msginfo _msginfo_comm[] = {PICA_PROTO_CLNODELISTREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_CLNODELISTREQ_SIZE, procmsg_NODELISTREQ}, {PICA_PROTO_PINGREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREQ_SIZE, procmsg_PINGREQ_client}, {PICA_PROTO_PINGREP, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREP_SIZE, procmsg_PINGREP_client}, - {PICA_PROTO_MULTILOGIN, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MULTILOGIN_client} + {PICA_PROTO_MULTILOGIN, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MULTILOGIN_client}, + {PICA_PROTO_MYTCPADDRREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYTCPADDRREQ_SIZE, procmsg_MYTCPADDRREQ}, + {PICA_PROTO_MYUDPADDRREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYUDPADDRREQ_SIZE, procmsg_MYUDPADDRREQ} }; struct PICA_msginfo _msginfo_node[] = @@ -214,7 +236,9 @@ struct PICA_msginfo _msginfo_multi[] = {PICA_PROTO_CLNODELISTREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_CLNODELISTREQ_SIZE, procmsg_NODELISTREQ}, {PICA_PROTO_PINGREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREQ_SIZE, procmsg_PINGREQ_client}, {PICA_PROTO_PINGREP, PICA_MSG_FIXED_SIZE, PICA_PROTO_PINGREP_SIZE, procmsg_PINGREP_client}, - {PICA_PROTO_MULTILOGIN, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MULTILOGIN_client} + {PICA_PROTO_MULTILOGIN, PICA_MSG_VAR_SIZE, PICA_MSG_VARSIZE_INT16, procmsg_MULTILOGIN_client}, + {PICA_PROTO_MYTCPADDRREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYTCPADDRREQ_SIZE, procmsg_MYTCPADDRREQ}, + {PICA_PROTO_MYUDPADDRREQ, PICA_MSG_FIXED_SIZE, PICA_PROTO_MYUDPADDRREQ_SIZE, procmsg_MYUDPADDRREQ} }; static int process_async_ssl_readwrite(SSL *ssl, int ret) @@ -659,6 +683,136 @@ unsigned int procmsg_PINGREP_client(unsigned char* buf, unsigned int size, void* return 1; } +unsigned int procmsg_MYTCPADDRREQ(unsigned char* buf, unsigned int size, void* ptr) +{ + struct client *c = (struct client*)ptr; + struct PICA_proto_msg *mp; + + PICA_debug3("MYTCPADDRREQ"); + + //IPv6 + if ((mp = client_wbuf_push(c, PICA_PROTO_MYTCPADDR_IPV4, PICA_PROTO_MYTCPADDR_IPV4_SIZE))) + { + memcpy(mp->tail, &c->addr.sin_addr.s_addr, 4); + memcpy(mp->tail + 4, &c->addr.sin_port, 2); + } + else + return 0; + + return 1; +} + +static unsigned int udpaddr_token_bucket(const unsigned char *token) +{ + //tokens are random and are generated by the node itself, so any part of + //one is as good a hash as any other, and a client has no say in which + //bucket it ends up in + return (token[0] | (token[1] << 8)) % UDPADDR_TOKEN_BUCKETS; +} + +static void client_udpaddr_token_drop(struct client *c) +{ + struct client **pp; + + if (!c->udpaddr_token_issued) + return; + + pp = &udpaddr_tokens[udpaddr_token_bucket(c->udpaddr_token)]; + + while(*pp && *pp != c) + pp = &(*pp)->udpaddr_token_next; + + if (*pp) + *pp = c->udpaddr_token_next; + + c->udpaddr_token_next = NULL; + c->udpaddr_token_issued = 0; +} + +static struct client *udpaddr_token_search(const unsigned char *token) +{ + struct client *c = udpaddr_tokens[udpaddr_token_bucket(token)]; + + while(c && CRYPTO_memcmp(c->udpaddr_token, token, PICA_PROTO_MYUDPADDR_TOKENSIZE) != 0) + c = c->udpaddr_token_next; + + return c; +} + +static int client_udpaddr_req_allowed(struct client *c) +{ + time_t now = time(0); + time_t periods; + + if (now < c->udpaddr_req_tmst)//the clock was set back + c->udpaddr_req_tmst = now; + + periods = (now - c->udpaddr_req_tmst) / UDPADDR_REQ_PERIOD; + + if (periods >= (time_t)(UDPADDR_REQ_BURST - c->udpaddr_req_allowance)) + { + c->udpaddr_req_allowance = UDPADDR_REQ_BURST; + c->udpaddr_req_tmst = now; + } + else + { + c->udpaddr_req_allowance += periods; + c->udpaddr_req_tmst += periods * UDPADDR_REQ_PERIOD; + } + + if (!c->udpaddr_req_allowance) + return 0; + + c->udpaddr_req_allowance--; + + return 1; +} + +//The reply to this message is a token, which the client then sends to the UDP +//socket - see process_udp_read() for what makes that exchange safe to offer. +unsigned int procmsg_MYUDPADDRREQ(unsigned char* buf, unsigned int size, void* ptr) +{ + struct client *c = (struct client*)ptr; + struct PICA_proto_msg *mp; + unsigned char token[PICA_PROTO_MYUDPADDR_TOKENSIZE]; + + PICA_debug3("MYUDPADDRREQ"); + + //A request that is not served is ignored rather than answered: the client + //has to cope with its datagrams being lost anyway, and gives up by timeout. + if (listen_udp_sck == -1) + return 1; + + if (!client_udpaddr_req_allowed(c)) + { + PICA_debug2("too many MYUDPADDRREQ from client %p, ignoring", (void*)c); + return 1; + } + + if (RAND_bytes(token, sizeof token) != 1) + { + PICA_error("RAND_bytes() failed, unable to issue a token for MYUDPADDRREQ"); + return 1; + } + + if (!(mp = client_wbuf_push(c, PICA_PROTO_MYUDPADDRTOKEN, PICA_PROTO_MYUDPADDRTOKEN_SIZE))) + return 0; + + memcpy(mp->tail, token, sizeof token); + + //one outstanding token per connection, a new request replaces the old one + client_udpaddr_token_drop(c); + + memcpy(c->udpaddr_token, token, sizeof token); + c->udpaddr_token_tmst = time(0); + c->udpaddr_token_issued = 1; + + c->udpaddr_token_next = udpaddr_tokens[udpaddr_token_bucket(token)]; + udpaddr_tokens[udpaddr_token_bucket(token)] = c; + + return 1; +} + unsigned int procmsg_MULTILOGIN_client(unsigned char* buf, unsigned int size, void* ptr) { struct client *other, *me = (struct client*)ptr; @@ -1802,6 +1956,33 @@ int PICA_node_init() event_add(listener_event, /*&tv*/ NULL); + //The UDP socket clients use to learn the address their NAT gives them, on + //the port with the same number as the TCP one. A node works without it. + listen_udp_sck = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + + if (listen_udp_sck != -1 && bind(listen_udp_sck, (struct sockaddr*)&sd, sizeof(sd)) == -1) + { + CLOSE(listen_udp_sck); + listen_udp_sck = -1; + } + + if (listen_udp_sck != -1) + { + struct event *udp_event; + + IOCTLSETNONBLOCKINGSOCKET(listen_udp_sck, 1); + + udp_event = event_new(pica_event_base, listen_udp_sck, EV_READ|EV_PERSIST, process_udp_read, NULL); + + if (!udp_event) + PICA_fatal("failed to allocate UDP socket event"); + + event_add(udp_event, NULL); + } + else + PICA_error("unable to open UDP port %u, clients will not be able to learn their UDP addresses from this node - %s", + (unsigned int)ntohs(sd.sin_port), strerror(errno)); + timeout_event = event_new(pica_event_base, -1, EV_TIMEOUT|EV_PERSIST, process_timeout_event, NULL); event_add(timeout_event, &tv); @@ -2169,6 +2350,9 @@ struct client *client_list_addnew(struct newconn *nc) ci->tmst = time(0); + ci->udpaddr_req_allowance = UDPADDR_REQ_BURST; + ci->udpaddr_req_tmst = ci->tmst; + ci->ev_read = event_new(pica_event_base, ci->sck_comm, EV_READ | EV_PERSIST, process_c2n_read, ci); ci->ev_write = event_new(pica_event_base, ci->sck_comm, EV_WRITE, process_c2n_write, ci); @@ -2253,6 +2437,8 @@ void client_list_delete(struct client* ci) cclink_list_delete_by_client(ci); + client_udpaddr_token_drop(ci); + if (ci->r_buf) free(ci->r_buf); @@ -2785,6 +2971,88 @@ void process_listen_read(evutil_socket_t listener, short event, void *arg) //IPv6 } +//Tells a client the address and port its datagram came from - the address its +//NAT gave to the socket the datagram was sent from. +// +//Anyone can send anything to this socket, with any source address, so: +// - nothing is ever sent from it. The answer goes over the c2n connection of +// the client that asked, which leaves nothing to reflect or amplify; +// - a datagram is acted upon only if it carries a token this node issued over +// an authenticated c2n connection moments ago. The token is random, so it +// cannot be guessed, and is good for one datagram, so a client is sent one +// answer per request it made itself and duplicates are dropped; +// - a datagram that is not acted upon costs a table lookup and leaves no +// state behind, and it is not logged. +//The source address itself cannot be verified, and does not need to be: it +//is only reported back to the client the token belongs to. +void process_udp_read(evutil_socket_t s, short event, void *arg) +{ + //one octet more than a valid datagram has, so that a longer one does not + //pass for a valid one after being truncated + unsigned char buf[PICA_PROTO_MYUDPADDRPROBE_SIZE + 1]; + int i; + + for (i = 0; i < UDP_READ_BATCH; i++) + { + struct sockaddr_in from; +#ifdef WIN32 + int fromlen = sizeof(from); +#else + socklen_t fromlen = sizeof(from); +#endif + struct client *c; + struct PICA_proto_msg *mp; + time_t now; + int ret; + + ret = recvfrom(s, (char*)buf, sizeof(buf), 0, (struct sockaddr*)&from, &fromlen); + + if (ret == -1) + { +#ifdef WIN32 + if (WSAGetLastError() == WSAEWOULDBLOCK) + break; +#else + if (errno == EAGAIN || errno == EWOULDBLOCK) + break; +#endif + //anything else is about the one datagram, e.g. it did not fit + //into the buffer on Windows + continue; + } + + if (ret != PICA_PROTO_MYUDPADDRPROBE_SIZE || buf[0] != PICA_PROTO_MYUDPADDRPROBE || buf[1] != PICA_PROTO_MYUDPADDRPROBE) + continue; + + if (fromlen < sizeof(from) || from.sin_family != AF_INET) + continue; + + c = udpaddr_token_search(buf + 2); + + if (!c) + continue; + + now = time(0); + ret = (now >= c->udpaddr_token_tmst && now - c->udpaddr_token_tmst <= UDPADDR_TOKEN_TIMEOUT); + + client_udpaddr_token_drop(c); + + if (!ret) + continue; + + PICA_debug3("MYUDPADDRPROBE for client %p from %.16s:%hu", (void*)c, inet_ntoa(from.sin_addr), ntohs(from.sin_port)); + + //IPv6 + if ((mp = client_wbuf_push(c, PICA_PROTO_MYUDPADDR, 2 + PICA_MSG_VARSIZE_INT8 + PICA_PROTO_MYUDPADDR_IPV4_SIZE))) + { + mp->tail[0] = PICA_PROTO_MYUDPADDR_IPV4_SIZE; + mp->tail[1] = PICA_PROTO_MYUDPADDR_IPV4; + memcpy(mp->tail + 2, &from.sin_addr.s_addr, 4); + memcpy(mp->tail + 6, &from.sin_port, 2); + } + } +} + void process_newconn_write(struct newconn *nc) { int ret; diff --git a/PICA_node.h b/PICA_node.h index 2dbb088..82ddb32 100644 --- a/PICA_node.h +++ b/PICA_node.h @@ -52,6 +52,7 @@ #include <time.h> #include "PICA_nodeaddrlist.h" #include "PICA_id.h" +#include "PICA_proto.h" #include <event2/event.h> @@ -142,6 +143,16 @@ struct client int disconnect_ticking;//on sending message TO client this var is set to 1, on receiving some message FROM client this var is reset to 0 struct event *ev_read; struct event *ev_write; + + //Pending "get my UDP address" request. The token is what ties a datagram + //arriving at the UDP socket to this connection, see process_udp_read() + unsigned char udpaddr_token[PICA_PROTO_MYUDPADDR_TOKENSIZE]; + int udpaddr_token_issued; + time_t udpaddr_token_tmst; + struct client *udpaddr_token_next;//next client in the same bucket of udpaddr_tokens[] + //how many more MYUDPADDRREQ messages are served right now, see client_udpaddr_req_allowed() + unsigned int udpaddr_req_allowance; + time_t udpaddr_req_tmst; }; struct cclink //структура, описывающая соединение двух клиентов между собой через сервер diff --git a/PICA_proto.h b/PICA_proto.h index 78a5c7a..cdf0eef 100644 --- a/PICA_proto.h +++ b/PICA_proto.h @@ -21,7 +21,7 @@ #define PICA_PROTO_VER_HIGH 0 -#define PICA_PROTO_VER_LOW 5 +#define PICA_PROTO_VER_LOW 6 #define PICA_C2CPROTO_VER_HIGH 0 #define PICA_C2CPROTO_VER_LOW 2 @@ -44,6 +44,19 @@ #define PICA_PROTO_CLNODELISTREQ 0x09 #define PICA_PROTO_CLNODELIST 0x0A +#define PICA_PROTO_MYTCPADDRREQ 0x0F +#define PICA_PROTO_MYTCPADDR_IPV4 0xA0 +#define PICA_PROTO_MYTCPADDR_IPV6 0xA1 +#define PICA_PROTO_MYUDPADDRREQ 0x10 +#define PICA_PROTO_MYUDPADDRTOKEN 0x11 +#define PICA_PROTO_MYUDPADDR 0x12 +// type octet of the address carried by PICA_PROTO_MYUDPADDR +#define PICA_PROTO_MYUDPADDR_IPV4 0xA0 +#define PICA_PROTO_MYUDPADDR_IPV6 0xA1 +// The only message that is sent to a node as a UDP datagram, outside of any +// connection. It carries the token from PICA_PROTO_MYUDPADDRTOKEN. +#define PICA_PROTO_MYUDPADDRPROBE 0x10 + #define PICA_PROTO_CONNID 0x20 #define PICA_PROTO_C2CCONNREQ 0xCC @@ -113,6 +126,17 @@ #define PICA_PROTO_CONNDENY_SIZE 30 #define PICA_PROTO_CLNODELISTREQ_SIZE 4 +#define PICA_PROTO_MYTCPADDRREQ_SIZE 4 +#define PICA_PROTO_MYTCPADDR_IPV4_SIZE 8 +#define PICA_PROTO_MYTCPADDR_IPV6_SIZE 20 +#define PICA_PROTO_MYUDPADDRREQ_SIZE 4 +#define PICA_PROTO_MYUDPADDR_TOKENSIZE 16 +#define PICA_PROTO_MYUDPADDRTOKEN_SIZE (2 + PICA_PROTO_MYUDPADDR_TOKENSIZE) +#define PICA_PROTO_MYUDPADDRPROBE_SIZE (2 + PICA_PROTO_MYUDPADDR_TOKENSIZE) +// address carried by PICA_PROTO_MYUDPADDR: type octet, address, port +#define PICA_PROTO_MYUDPADDR_IPV4_SIZE 7 +#define PICA_PROTO_MYUDPADDR_IPV6_SIZE 19 + #define PICA_PROTO_CONNID_SIZE 58 #define PICA_PROTO_C2CCONNREQ_SIZE 4 diff --git a/doc/proto-doc-latest.txt b/doc/proto-doc-latest.txt index 8eab376..4644794 100644 --- a/doc/proto-doc-latest.txt +++ b/doc/proto-doc-latest.txt @@ -13,6 +13,8 @@ octets. It is used as a user identifier. Connections. There are 5 types of connections between Pica Pica nodes and clients. +Apart from them, a node accepts single UDP datagrams from clients, see the "Get +my UDP address" messages. -client to node (c2n) - a control connection from client to node @@ -210,6 +212,104 @@ of the sending client. The signature is calculated from the sender's concatenated UH, timestamp and node address = Sign(UH|timestamp|node address) ==================================================== +Get my TCP address. + +Sent by a client. Requests the node to respond with the client +address and TCP port as seen by the node. The response should +be one packet of the type A0 or A1 corresponding to protocol used for this +TCP connection - IPv4 or IPv6 + +[0x0F 0x0F][2 pseudo-random octets] + +4 octets +==================================================== +My TCP address. +Sent by the node in reply to 0x0F. + +[0xA0 0xA0][IP address - 4 octets, network byte order][port number - 2 octets, network byte order] + +8 octets + +or + +[0xA1 0xA1][IPv6 address - 16 octets, network byte order][port number - 2 octets, network byte order] + +20 octets + +A client must ignore this message unless it is waiting for it. +==================================================== +Get my UDP address. +Sent by a client. + +[0x10 0x10][2 pseudo-random octets] + +4 octets + +Requests a token that lets the client learn the address and port its UDP +datagrams arrive at the node from, i.e. what the NAT in front of the client +maps one of its UDP sockets to. The exchange is: + + c2n client -> node 0x10 request + c2n node -> client 0x11 token + UDP client -> node 0x10 the token, from the socket in question + c2n node -> client 0x12 source address and port of that datagram + +A node serves only a limited number of these requests in a row from one +client, and may not serve them at all (e.g. it has no UDP port open); a request +that is not served is not answered. The client gives up by timeout. +==================================================== +UDP address token. +Sent by the node in reply to 0x10. + +[0x11 0x11][token, 16 octets] + +18 octets + +token - random octets from a cryptographically secure generator, chosen by the +node. It is valid for a short time (10 seconds) and for one datagram. A client +has at most one valid token: a new 0x10 request invalidates the token issued +for the previous one. +==================================================== +UDP address probe. +Sent by a client to the node as a UDP datagram, not over a connection. + +[0x10 0x10][token, 16 octets] + +18 octets, the whole datagram + +Sent to the UDP port with the same number as the TCP port the c2n connection +was made to, from the socket whose external address the client wants to learn. +Datagrams can be lost, so the client sends it a few times, about a second +apart, until 0x12 arrives. + +The node never answers over UDP, whatever it receives. A datagram that is not +exactly 18 octets long, or does not carry a currently valid token, is silently +dropped. When a valid token arrives, the node invalidates it and sends 0x12 +over the c2n connection the token was issued on. Copies of the datagram that +arrive afterwards are therefore dropped as well. +==================================================== +My UDP address. +Sent by the node over the c2n connection. + +[0x12 0x12][length, 1 octet][address] + +address - the source address and port of the datagram that carried the token, +in network byte order: +[0xA0][IP address - 4 octets][port number - 2 octets], length 7, or +[0xA1][IPv6 address - 16 octets][port number - 2 octets], length 19. + +A client must ignore this message unless it is waiting for it. + +Security considerations. +The token only ties a datagram to an authenticated c2n connection. The source +address the node reports cannot be authenticated - it is not known to the +client, and is rewritten on the way by design - so somebody able to observe the +datagram can send a copy of it from another address, and have that address +reported if the copy arrives first. The reported address must therefore be +treated only as a place where the client might be reachable, never as proof of +who is reachable there: a connection made to it has to authenticate the peer +on its own, as directc2c and mediac2c connections do. +==================================================== The message below is transmitted over the connection between a node and a client which is used for data transfer. diff --git a/pica-node.conf b/pica-node.conf index 49fbcdc..5be5905 100644 --- a/pica-node.conf +++ b/pica-node.conf @@ -16,6 +16,9 @@ #announced_addr = "autoconfigure"; #TCP port for incoming connections that pica-node listens on. Default is 2299 +#The UDP port with the same number is opened as well: clients send a datagram to it to learn +#which address and port their NAT gives them. pica-node never sends anything from that port, +#it only needs to be reachable. # #listen_port = "2299"; diff --git a/pica-node.conf.5 b/pica-node.conf.5 index 28ed94c..e1a84f8 100644 --- a/pica-node.conf.5 +++ b/pica-node.conf.5 @@ -28,7 +28,14 @@ future releases). If the computer running pica-node is behind the NAT, external .I listen_port Specifies the port number that .BR pica-node (8) -listens on. The default is 2299 +listens on. The default is 2299. +The number is used for the TCP port that accepts connections, and for a UDP +port that clients send a datagram to in order to learn which address and port +their NAT gives them. +.BR pica-node (8) +never sends anything from the UDP port, but it has to be reachable for +incoming datagrams, so both have to be allowed through a firewall or forwarded +by a router. .TP .I nodes_db_file Specifies the nodes database file. This is the SQLite 3 database. It stores diff --git a/tests/test_client.c b/tests/test_client.c index d9ae35d..0bf7fbc 100644 --- a/tests/test_client.c +++ b/tests/test_client.c @@ -42,6 +42,10 @@ int random_message_mode = 0; int delivery_acks_count = 0; int rmm_wait_for_reply = 0; +/* -u: 1 - ask the node for our TCP and UDP addresses once connected, 2 - asked */ +int request_addresses = 0; +int udp_sck = -1; + unsigned char buf[64 * 1024]; int accept_cb(const unsigned char *id) @@ -90,7 +94,7 @@ void msgok_cb(const unsigned char *peer_id) puts("[V]"); } //создание канала с собеседником -void c2c_established_cb(const unsigned char *peer_id) +void c2c_established_cb(const unsigned char *peer_id, const char *ciphersuitename) { c2c_active = 1; c2c_in_progress = 0; @@ -217,11 +221,24 @@ void listener_error(struct PICA_listener *lst, int errorcode) l = NULL; } -void multilogin_cb(time_t timestamp, void *addr_bin, const char *addr_str, uint16_t port) +void multilogin_cb(uint64_t timestamp, void *addr_bin, const char *addr_str, uint16_t port) { printf("received MULTILOGIN\n"); } +void tcp_address_cb(struct PICA_c2n *c2n, int type, void *addr_bin, const char *addr_str, uint16_t port) +{ + printf("tcp_address_cb: type 0x%X address %s port %u\n", type, addr_str, port); +} + +void udp_address_cb(struct PICA_c2n *c2n, int status, int type, void *addr_bin, const char *addr_str, uint16_t port) +{ + if (status == PICA_OK) + printf("udp_address_cb: type 0x%X address %s port %u\n", type, addr_str, port); + else + printf("udp_address_cb: failed, status %i\n", status); +} + struct PICA_client_callbacks cbs = { newmsg_cb, @@ -243,7 +260,9 @@ struct PICA_client_callbacks cbs = c2n_failed_cb, c2n_closed_cb, listener_error, - multilogin_cb + multilogin_cb, + .tcp_address_cb = tcp_address_cb, + .udp_address_cb = udp_address_cb }; int main(int argc, char** argv) @@ -264,7 +283,7 @@ int main(int argc, char** argv) int multilogin = PICA_MULTILOGIN_PROHIBIT; - while ((opt = getopt(argc, argv, "a:p:c:i:d:e:l:f:tmrM:")) != -1) + while ((opt = getopt(argc, argv, "a:p:c:i:d:e:l:f:tmruM:")) != -1) { switch(opt) { @@ -312,6 +331,10 @@ int main(int argc, char** argv) random_message_mode = 1; break; + case 'u': + request_addresses = 1; + break; + case 'M': if (strcmp(optarg, "prohibit") == 0) multilogin = PICA_MULTILOGIN_PROHIBIT; @@ -348,6 +371,7 @@ int main(int argc, char** argv) -m start in echo mode, received messages are sent back, input from stdin is not accepted\n\ -r send random test messages and exit, expects other side to be run in echo mode\n\ -M multilogin policy, one from \"prohibit\", \"replace\", \"sync\"\n\ + -u ask the node for the TCP and UDP addresses it sees this client coming from\n\ cert_filename should point to file that contains client certificate, private key and Diffie-Hellman parameters in PEM format"); return 0; } @@ -412,6 +436,30 @@ cert_filename should point to file that contains client certificate, private key while(PICA_event_loop(c2ns, 500) == PICA_OK && c != NULL) { //puts("event loop..."); + if (request_addresses == 1 && connected_to_node == 1) + { + struct sockaddr_in any; + + request_addresses = 2; + + ret = PICA_request_tcp_address(c); + printf("PICA_request_tcp_address: ret=%i\n", ret); + + memset(&any, 0, sizeof(any)); + any.sin_family = AF_INET; + + udp_sck = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + + if (udp_sck == -1 || bind(udp_sck, (struct sockaddr*)&any, sizeof(any)) == -1) + { + perror("failed to open UDP socket"); + return 1; + } + + ret = PICA_request_udp_address(c, udp_sck); + printf("PICA_request_udp_address: ret=%i\n", ret); + } + if (peerid && connected_to_node == 1 && c2c_active == 0 && c2c_in_progress == 0) { if (PICA_id_from_base64(peerid, peer_id) == NULL) |
