unet-cli: add DHT support
[project/unetd.git] / pex.h
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3 * Copyright (C) 2022 Felix Fietkau <nbd@nbd.name>
4 */
5 #ifndef __UNETD_PEX_H
6 #define __UNETD_PEX_H
7
8 #include <sys/socket.h>
9 #include <libubox/uloop.h>
10 #include "stun.h"
11
12 struct network;
13
14 struct network_pex_host {
15 struct list_head list;
16 uint64_t timeout;
17 uint64_t last_active;
18 uint64_t last_ping;
19 union network_endpoint endpoint;
20 };
21
22 struct network_pex {
23 struct uloop_fd fd;
24 struct list_head hosts;
25 struct uloop_timeout request_update_timer;
26 };
27
28 enum network_stun_state {
29 STUN_STATE_IDLE,
30 STUN_STATE_PEX_QUERY_WAIT,
31 STUN_STATE_STUN_QUERY_SEND,
32 STUN_STATE_STUN_QUERY_WAIT,
33 };
34
35 struct network_stun_server {
36 struct list_head list;
37
38 struct avl_node pending_node;
39 struct stun_request req;
40
41 const char *host;
42 uint8_t seq;
43 bool req_auth_port;
44 bool pending;
45 };
46
47 struct network_stun {
48 struct list_head servers;
49 struct avl_tree pending;
50
51 struct uloop_timeout timer;
52
53 enum network_stun_state state;
54 bool wgport_disabled;
55
56 uint16_t auth_port_ext;
57 uint16_t port_local;
58 uint16_t port_ext;
59
60 int retry;
61
62 struct uloop_fd socket;
63 };
64
65 enum pex_event {
66 PEX_EV_HANDSHAKE,
67 PEX_EV_ENDPOINT_CHANGE,
68 PEX_EV_QUERY,
69 PEX_EV_PING,
70 };
71
72 void network_pex_init(struct network *net);
73 int network_pex_open(struct network *net);
74 void network_pex_close(struct network *net);
75 void network_pex_free(struct network *net);
76
77 void network_pex_event(struct network *net, struct network_peer *peer,
78 enum pex_event ev);
79 void network_pex_create_host(struct network *net, union network_endpoint *ep,
80 unsigned int timeout);
81
82 void network_stun_init(struct network *net);
83 void network_stun_free(struct network *net);
84 void network_stun_server_add(struct network *net, const char *host);
85 void network_stun_rx_packet(struct network *net, const void *data, size_t len);
86 void network_stun_update_port(struct network *net, bool auth, uint16_t val);
87 void network_stun_start(struct network *net);
88
89 static inline bool network_pex_active(struct network_pex *pex)
90 {
91 return pex->fd.fd >= 0;
92 }
93
94 int global_pex_open(const char *unix_path);
95
96 #endif