ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
upnp.c
Go to the documentation of this file.
1
2/* Storage capacities in elements; text buffers include the terminating NUL. */
3#define NETWORK_NAT_UPNP_CLIENT_BUFFER_SIZE 40
4#define UPNP_MAPPING_DESCRIPTION_BUFFER_SIZE 80
5#define NETWORK_NAT_UPNP_LEASE_BUFFER_SIZE 16
6#define NETWORK_NAT_UPNP_LAN_ADDRESS_BUFFER_SIZE 16
7#define NETWORK_NAT_UPNP_EXTERNAL_ADDRESS_BUFFER_SIZE 16
8
10#include <ascii-chat/otel.h>
15#include <stdlib.h>
16#include <string.h>
17
19#include <ascii-chat/common.h>
20#include <ascii-chat/log/log.h>
22
23#ifdef HAVE_MINIUPNPC
24#include <miniupnpc.h>
25#include <upnpcommands.h>
26#include <upnperrors.h>
27#ifdef __APPLE__
28#include <natpmp.h>
29#endif
30#endif
31
32#define MAPPING_LEASE_SECONDS 3600U
33#define MAPPING_RETRY_NS (30ULL * NS_PER_SEC_INT)
34
35#ifdef HAVE_MINIUPNPC
36static const char *mapping_protocol(const nat_upnp_context_t *ctx) {
37 return ctx->protocol == NAT_UPNP_UDP ? "UDP" : "TCP";
38}
39
40static void mapping_set_lease(nat_upnp_context_t *ctx, uint32_t seconds) {
41 uint64_t now = time_get_ns();
42 ctx->lease_seconds = seconds;
43 ctx->expires_at_ns = now + (uint64_t)seconds * NS_PER_SEC_INT;
44 ctx->refresh_at_ns = now + (uint64_t)seconds * NS_PER_SEC_INT / 2;
45 ctx->is_mapped = true;
46}
47
48static asciichat_error_t upnp_map(nat_upnp_context_t *ctx) {
49 char internal_port[PORT_STRING_BUFFER_SIZE], external_port[6];
50 safe_snprintf(internal_port, sizeof(internal_port), "%u", ctx->internal_port);
51 safe_snprintf(external_port, sizeof(external_port), "%u", ctx->mapped_port);
52 int result = UPNP_AddPortMapping(ctx->control_url, ctx->service_type, external_port, internal_port, ctx->internal_ip, ctx->description, mapping_protocol(ctx), NULL, "3600");
53 if (result != UPNPCOMMAND_SUCCESS) {
54 return SET_ERRNO(ERROR_NETWORK, "UPnP: mapping request failed: %s", strupnperror(result));
55 }
56 // Some gateways silently shorten the requested lease. Read it back on every renewal.
57 char client[NETWORK_NAT_UPNP_CLIENT_BUFFER_SIZE] = {0}, port[6] = {0}, description[UPNP_MAPPING_DESCRIPTION_BUFFER_SIZE] = {0}, enabled[4] = {0}, lease[NETWORK_NAT_UPNP_LEASE_BUFFER_SIZE] = {0};
58 result = UPNP_GetSpecificPortMappingEntry(ctx->control_url, ctx->service_type, external_port, mapping_protocol(ctx), NULL, client, port, description, enabled, lease);
59 uint32_t seconds = 60;
60 if (result == UPNPCOMMAND_SUCCESS && lease[0] >= '0' && lease[0] <= '9') {
61 char *end = NULL;
62 unsigned long granted = strtoul(lease, &end, 10);
63 if (*end == '\0' && granted <= MAPPING_LEASE_SECONDS) {
64 // A permanent mapping can still be refreshed periodically.
65 seconds = granted ? (uint32_t)granted : MAPPING_LEASE_SECONDS;
66 } else if (*end == '\0' && granted > MAPPING_LEASE_SECONDS) {
67 seconds = MAPPING_LEASE_SECONDS;
68 }
69 }
70 mapping_set_lease(ctx, seconds);
71 return ASCIICHAT_OK;
72}
73
74static asciichat_error_t upnp_try_map_port(nat_upnp_context_t *ctx) {
75 struct UPNPUrls urls = {0};
76 struct IGDdatas data = {0};
77 char lan_address[NETWORK_NAT_UPNP_LAN_ADDRESS_BUFFER_SIZE] = {0};
78 char external_address[NETWORK_NAT_UPNP_EXTERNAL_ADDRESS_BUFFER_SIZE] = {0};
79 struct UPNPDev *devices = upnpDiscover(2000, NULL, NULL, 0, 0, 2, NULL);
80 if (!devices) {
81 return SET_ERRNO(ERROR_NETWORK, "UPnP: no gateway discovered (unsupported or disabled)");
82 }
83#ifdef MINIUPNPC_GETVALIDIGD_7ARG
84 int result = UPNP_GetValidIGD(devices, &urls, &data, lan_address, sizeof(lan_address), external_address, sizeof(external_address));
85#else
86 int result = UPNP_GetValidIGD(devices, &urls, &data, lan_address, sizeof(lan_address));
87#endif
89 bool connected = result == 1;
90 bool private_wan = false;
91#ifdef UPNP_PRIVATEIP_IGD
92 // A connected gateway behind another NAT can still map its own listener.
93 private_wan = result == UPNP_PRIVATEIP_IGD;
94 connected = connected || private_wan;
95#endif
96 if (!connected || !urls.controlURL || !lan_address[0] || strncmp(lan_address, "127.", 4) == 0 || strcmp(lan_address, "0.0.0.0") == 0) {
97 SET_ERRNO(ERROR_NETWORK, "UPnP: no connected gateway with a usable LAN address (IGD result %d)", result);
98 goto cleanup;
99 }
100 result = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, external_address);
101 if (result != UPNPCOMMAND_SUCCESS || !external_address[0]) {
102 SET_ERRNO(ERROR_NETWORK, "UPnP: could not obtain gateway external address");
103 goto cleanup;
104 }
105 SAFE_STRNCPY(ctx->internal_ip, lan_address, sizeof(ctx->internal_ip));
106 SAFE_STRNCPY(ctx->external_ip, external_address, sizeof(ctx->external_ip));
107 SAFE_STRNCPY(ctx->service_type, data.first.servicetype, sizeof(ctx->service_type));
108 SAFE_STRNCPY(ctx->device_description, urls.controlURL, sizeof(ctx->device_description));
109 SAFE_STRDUP(ctx->control_url, urls.controlURL);
110 if (!ctx->control_url) {
111 error = SET_ERRNO(ERROR_MEMORY, "UPnP: could not retain gateway control URL");
112 goto cleanup;
113 }
114 error = upnp_map(ctx);
115 if (error == ASCIICHAT_OK) {
116 ctx->external_is_private = private_wan;
117 }
118cleanup:
119 freeUPNPDevlist(devices);
120 FreeUPNPUrls(&urls);
121 if (error != ASCIICHAT_OK) {
123 ctx->control_url = NULL;
124 }
125 return error;
126}
127#else
128static asciichat_error_t upnp_try_map_port(nat_upnp_context_t *ctx) {
129 (void)ctx;
130 return SET_ERRNO(ERROR_NETWORK, "UPnP: support unavailable in this build");
131}
132#endif
133
134#if defined(__APPLE__) && defined(HAVE_MINIUPNPC)
135// libnatpmp returns TRYAGAIN while waiting and scheduling retransmissions.
136static asciichat_error_t natpmp_wait(natpmp_t *pmp, natpmpresp_t *response, uint16_t type) {
137 uint64_t deadline = time_get_ns() + 2ULL * NS_PER_SEC_INT;
138 do {
139 int result = readnatpmpresponseorretry(pmp, response);
140 if (result == 0) {
141 if (response->type == type && response->resultcode == 0) {
142 return ASCIICHAT_OK;
143 }
144 return SET_ERRNO(ERROR_NETWORK, "NAT-PMP: unexpected response");
145 }
146 if (result != NATPMP_TRYAGAIN) {
147 return SET_ERRNO(ERROR_NETWORK, "NAT-PMP: gateway request failed (%d)", result);
148 }
150 } while (time_get_ns() < deadline);
151 return SET_ERRNO(ERROR_NETWORK, "NAT-PMP: gateway response timed out");
152}
153
154static asciichat_error_t natpmp_map(nat_upnp_context_t *ctx, uint32_t lifetime, bool discover) {
155 natpmp_t pmp;
156 natpmpresp_t response = {0};
157 if (initnatpmp(&pmp, discover ? 0 : 1, ctx->gateway) < 0) {
158 return SET_ERRNO(ERROR_NETWORK, "NAT-PMP: could not initialize gateway connection");
159 }
161 if (discover) {
162 if (sendpublicaddressrequest(&pmp) < 0) {
163 SET_ERRNO(ERROR_NETWORK, "NAT-PMP: public address request failed");
164 goto cleanup;
165 }
166 error = natpmp_wait(&pmp, &response, NATPMP_RESPTYPE_PUBLICADDRESS);
167 if (error != ASCIICHAT_OK) {
168 goto cleanup;
169 }
170 const unsigned char *ip = (const unsigned char *)&response.pnu.publicaddress.addr;
171 safe_snprintf(ctx->external_ip, sizeof(ctx->external_ip), "%u.%u.%u.%u", ip[0], ip[1], ip[2], ip[3]);
172 ctx->gateway = pmp.gateway;
173 }
174 if (sendnewportmappingrequest(&pmp, ctx->protocol == NAT_UPNP_UDP ? NATPMP_PROTOCOL_UDP : NATPMP_PROTOCOL_TCP, ctx->internal_port, ctx->mapped_port, lifetime) < 0) {
175 error = SET_ERRNO(ERROR_NETWORK, "NAT-PMP: mapping request failed");
176 goto cleanup;
177 }
178 error = natpmp_wait(&pmp, &response, ctx->protocol == NAT_UPNP_UDP ? NATPMP_RESPTYPE_UDPPORTMAPPING : NATPMP_RESPTYPE_TCPPORTMAPPING);
179 if (error == ASCIICHAT_OK && lifetime != 0) {
180 if (!response.pnu.newportmapping.lifetime || !response.pnu.newportmapping.mappedpublicport || response.pnu.newportmapping.privateport != ctx->internal_port) {
181 error = SET_ERRNO(ERROR_NETWORK, "NAT-PMP: invalid granted mapping");
182 goto cleanup;
183 }
184 ctx->mapped_port = response.pnu.newportmapping.mappedpublicport;
185 ctx->is_natpmp = true;
186 mapping_set_lease(ctx, response.pnu.newportmapping.lifetime);
187 }
188cleanup:
189 closenatpmp(&pmp);
190 return error;
191}
192#endif
193
194asciichat_error_t nat_upnp_open(uint16_t internal_port, const char *description, nat_upnp_context_t **ctx) {
195 return nat_upnp_open_protocol(internal_port, description, NAT_UPNP_TCP, ctx);
196}
197
198asciichat_error_t nat_upnp_open_protocol(uint16_t internal_port, const char *description, nat_upnp_protocol_t protocol, nat_upnp_context_t **ctx) {
199 ASCII_OTEL_SCOPE(NAT_MAP);
200 ASCII_OTEL_ATTR_STRING("network.transport", protocol == NAT_UPNP_UDP ? "udp" : "tcp");
201 ASCII_OTEL_ATTR_INT("network.local.port", internal_port);
202 if (!ctx) {
203 return SET_ERRNO(ERROR_INVALID_PARAM, "NAT: missing mapping output");
204 }
205 *ctx = NULL;
206 if (!internal_port || !description || (protocol != NAT_UPNP_TCP && protocol != NAT_UPNP_UDP)) {
207 return SET_ERRNO(ERROR_INVALID_PARAM, "NAT: a listening port and description are required");
208 }
210 if (!*ctx) {
211 return SET_ERRNO(ERROR_MEMORY, "NAT: could not allocate mapping context");
212 }
213 (*ctx)->protocol = protocol;
214 (*ctx)->internal_port = internal_port;
215 (*ctx)->mapped_port = internal_port;
216 SAFE_STRNCPY((*ctx)->description, description, sizeof((*ctx)->description));
217 log_info("UPnP: discovering a gateway for %s port %u", protocol == NAT_UPNP_UDP ? "UDP" : "TCP", internal_port);
219 asciichat_error_t result = upnp_try_map_port(*ctx);
220#if defined(__APPLE__) && defined(HAVE_MINIUPNPC)
221 if (result != ASCIICHAT_OK) {
222 log_debug("UPnP unavailable; trying NAT-PMP");
223 result = natpmp_map(*ctx, MAPPING_LEASE_SECONDS, true);
224 }
225#endif
226 if (result == ASCIICHAT_OK) {
227 ascii_otel_metric(ASCII_OTEL_METRIC_NAT_MAP_SUCCESS, 1);
229 log_info("NAT: mapping created for %s:%u (external reachability unverified)", (*ctx)->external_ip, (*ctx)->mapped_port);
230 return ASCIICHAT_OK;
231 }
232 ascii_otel_metric(ASCII_OTEL_METRIC_NAT_MAP_FAILURE, 1);
233 LOG_ERRNO_IF_SET("Automatic router mapping unavailable");
234 SAFE_FREE((*ctx)->control_url);
235 SAFE_FREE(*ctx);
236 *ctx = NULL;
237 return SET_ERRNO(ERROR_NETWORK, "NAT: automatic mapping unavailable; direct connectivity may still work");
238}
239
241 ASCII_OTEL_SCOPE(NAT_CLOSE);
242
243 if (!ctx || !*ctx) {
244 return;
245 }
246 if ((*ctx)->is_mapped) {
248#if defined(__APPLE__) && defined(HAVE_MINIUPNPC)
249 if ((*ctx)->is_natpmp) {
250 error = natpmp_map(*ctx, 0, false);
251 } else
252#endif
253 {
254#ifdef HAVE_MINIUPNPC
255 char port[PORT_STRING_BUFFER_SIZE];
256 safe_snprintf(port, sizeof(port), "%u", (*ctx)->mapped_port);
257 int result = UPNP_DeletePortMapping((*ctx)->control_url, (*ctx)->service_type, port, mapping_protocol(*ctx), NULL);
258 // Fios gateways require an explicit wildcard when deleting an unrestricted mapping.
259 if (result == 402) {
260 result = UPNP_DeletePortMapping((*ctx)->control_url, (*ctx)->service_type, port, mapping_protocol(*ctx), "*");
261 }
262 if (result != UPNPCOMMAND_SUCCESS && result != 714) {
263 log_debug("UPnP: deletion failed: %s (%d)", strupnperror(result), result);
264 }
265 // An already expired mapping needs no further cleanup.
266 error = (result == UPNPCOMMAND_SUCCESS || result == 714) ? ASCIICHAT_OK : ERROR_NETWORK;
267#endif
268 }
269 if (error != ASCIICHAT_OK) {
270 log_warn("NAT: could not remove mapping for port %u; its lease will expire", (*ctx)->mapped_port);
271 } else {
272 log_info("NAT: removed mapping for port %u", (*ctx)->mapped_port);
273 }
274 }
275 SAFE_FREE((*ctx)->control_url);
276 SAFE_FREE(*ctx);
277 *ctx = NULL;
278}
279
281 return ctx && ctx->is_mapped && ctx->external_ip[0] && time_get_ns() < ctx->expires_at_ns;
282}
283
284bool nat_upnp_matches_bind_address(const nat_upnp_context_t *ctx, const char *bind_address) {
285 if (!ctx) {
286 return false;
287 }
288 return !bind_address || !bind_address[0] || strcmp(bind_address, "0.0.0.0") == 0 || (ctx->internal_ip[0] && strcmp(bind_address, ctx->internal_ip) == 0);
289}
290
291asciichat_error_t nat_upnp_get_endpoint(const nat_upnp_context_t *ctx, char *ip, size_t ip_len, uint16_t *port) {
292 if (!ctx || !ip || !port || ip_len < sizeof(ctx->external_ip)) {
293 return SET_ERRNO(ERROR_INVALID_PARAM, "NAT: invalid endpoint output");
294 }
295 if (!nat_upnp_is_active(ctx)) {
296 return SET_ERRNO(ERROR_NETWORK, "NAT: no unexpired mapping to advertise");
297 }
298 SAFE_STRNCPY(ip, ctx->external_ip, ip_len);
299 *port = ctx->mapped_port;
300 return ASCIICHAT_OK;
301}
302
304 ASCII_OTEL_SCOPE(NAT_REFRESH);
305
306 if (!ctx || !ctx->is_mapped) {
307 return SET_ERRNO(ERROR_INVALID_PARAM, "NAT: cannot refresh without a mapping");
308 }
310#if defined(__APPLE__) && defined(HAVE_MINIUPNPC)
311 if (ctx->is_natpmp) {
312 result = natpmp_map(ctx, MAPPING_LEASE_SECONDS, false);
313 } else
314#endif
315 {
316#ifdef HAVE_MINIUPNPC
317 result = upnp_map(ctx);
318#endif
319 }
320 if (result != ASCIICHAT_OK) {
321 ctx->refresh_at_ns = time_get_ns() + MAPPING_RETRY_NS;
322 log_warn("NAT: mapping renewal failed; %s; retrying in 30 seconds", nat_upnp_is_active(ctx) ? "previous lease has not expired" : "mapping lease expired");
323 return result;
324 }
325 log_info("NAT: mapping renewed for %s:%u", ctx->external_ip, ctx->mapped_port);
326 return ASCIICHAT_OK;
327}
328
329asciichat_error_t nat_upnp_get_address(const nat_upnp_context_t *ctx, char *addr, size_t addr_len) {
330 if (!ctx || !addr || addr_len < 22) {
331 return SET_ERRNO(ERROR_INVALID_PARAM, "NAT: invalid arguments for get_address");
332 }
333 if (!nat_upnp_is_active(ctx)) {
334 return SET_ERRNO(ERROR_NETWORK, "NAT: no unexpired mapping to advertise");
335 }
336 int written = safe_snprintf(addr, addr_len, "%s:%u", ctx->external_ip, ctx->mapped_port);
337 if (written < 0 || (size_t)written >= addr_len) {
338 return SET_ERRNO(ERROR_INVALID_PARAM, "NAT: address buffer too small");
339 }
340 return ASCIICHAT_OK;
341}
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_errno_scope_t errno_scope_begin(void)
#define SET_ERRNO(code,...)
@ ASCIICHAT_ERRNO_HANDLED
#define LOG_ERRNO_IF_SET(message)
Application limits and constraints.
bool enabled
Is filtering active?
Definition grep.c:62
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_CALLOC(count, size, cast)
unsigned long long uint64_t
#define SAFE_STRDUP(dst, src)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_NETWORK
Definition error_codes.h:76
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define PORT_STRING_BUFFER_SIZE
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_info(...)
Log an INFO message.
Definition log/log.h:602
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define NS_PER_SEC_INT
Definition time.h:173
#define NS_PER_MS_INT
Definition time.h:172
void time_sleep_ns(uint64_t ns)
Configuration for adaptive sleep behavior.
Definition time.c:107
⚙️ Common definitions, error codes, macros, and types shared throughout the application
📝 Logging API with multiple log levels and terminal output control
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:159
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:77
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:72
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:71
🔤 String Manipulation and Shell Escaping Utilities
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
uint16_t internal_port
Internal port we're binding to.
Definition upnp.h:37
nat_upnp_protocol_t protocol
Transport of this mapping.
Definition upnp.h:50
char description[128]
Mapping description reused on renewal.
Definition upnp.h:44
uint16_t mapped_port
External port that was mapped (may differ from internal).
Definition upnp.h:36
char * control_url
Owned UPnP control URL.
Definition upnp.h:42
uint32_t gateway
NAT-PMP gateway, in network byte order.
Definition upnp.h:45
bool is_natpmp
true if NAT-PMP was used, false if UPnP
Definition upnp.h:40
bool is_mapped
true if port mapping is currently active
Definition upnp.h:49
bool external_is_private
Gateway reported an upstream NAT; mapping remains locally usable.
Definition upnp.h:51
uint32_t lease_seconds
Granted/requested lease duration.
Definition upnp.h:46
uint64_t refresh_at_ns
Next renewal or retry deadline.
Definition upnp.h:48
uint64_t expires_at_ns
Monotonic lease expiry.
Definition upnp.h:47
char internal_ip[16]
LAN address used by the gateway to reach us.
Definition upnp.h:41
char device_description[256]
Archer C7").
Definition upnp.h:38
char service_type[128]
UPnP service used to create the mapping.
Definition upnp.h:43
char external_ip[16]
Detected external/public IP (e.g., "203.0.113.42").
Definition upnp.h:35
⏱️ High-precision timing utilities using sokol_time.h and uthash
asciichat_error_t nat_upnp_refresh(nat_upnp_context_t *ctx)
Refresh port mapping (e.g., for long-running servers).
Definition upnp.c:303
#define MAPPING_LEASE_SECONDS
Definition upnp.c:32
asciichat_error_t nat_upnp_get_endpoint(const nat_upnp_context_t *ctx, char *ip, size_t ip_len, uint16_t *port)
Copy the unexpired mapped IP and external port for discovery advertisement.
Definition upnp.c:291
#define NETWORK_NAT_UPNP_LAN_ADDRESS_BUFFER_SIZE
Definition upnp.c:6
bool nat_upnp_matches_bind_address(const nat_upnp_context_t *ctx, const char *bind_address)
Whether the mapping targets a specific IPv4 bind address, or any wildcard listener.
Definition upnp.c:284
#define UPNP_MAPPING_DESCRIPTION_BUFFER_SIZE
Definition upnp.c:4
bool nat_upnp_is_active(const nat_upnp_context_t *ctx)
Check if port mapping is still active.
Definition upnp.c:280
void nat_upnp_close(nat_upnp_context_t **ctx)
Close port mapping and clean up.
Definition upnp.c:240
asciichat_error_t nat_upnp_open(uint16_t internal_port, const char *description, nat_upnp_context_t **ctx)
Discover and open port via UPnP.
Definition upnp.c:194
#define NETWORK_NAT_UPNP_CLIENT_BUFFER_SIZE
Definition upnp.c:3
asciichat_error_t nat_upnp_get_address(const nat_upnp_context_t *ctx, char *addr, size_t addr_len)
Get the public address (IP:port) for advertising to clients.
Definition upnp.c:329
#define MAPPING_RETRY_NS
Definition upnp.c:33
#define NETWORK_NAT_UPNP_LEASE_BUFFER_SIZE
Definition upnp.c:5
#define NETWORK_NAT_UPNP_EXTERNAL_ADDRESS_BUFFER_SIZE
Definition upnp.c:7
asciichat_error_t nat_upnp_open_protocol(uint16_t internal_port, const char *description, nat_upnp_protocol_t protocol, nat_upnp_context_t **ctx)
Open an owned TCP or UDP mapping; close with nat_upnp_close().
Definition upnp.c:198
UPnP/NAT-PMP port mapping for TCP and UDP connectivity.
struct nat_upnp_context nat_upnp_context_t
Handle to UPnP context.
nat_upnp_protocol_t
Definition upnp.h:31
@ NAT_UPNP_TCP
Definition upnp.h:31
@ NAT_UPNP_UDP
Definition upnp.h:31