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 File Reference

Router mapping lifecycle for TCP listeners and UDP transports. More...

Go to the source code of this file.

Macros

#define NETWORK_NAT_UPNP_CLIENT_BUFFER_SIZE   40
#define UPNP_MAPPING_DESCRIPTION_BUFFER_SIZE   80
#define NETWORK_NAT_UPNP_LEASE_BUFFER_SIZE   16
#define NETWORK_NAT_UPNP_LAN_ADDRESS_BUFFER_SIZE   16
#define NETWORK_NAT_UPNP_EXTERNAL_ADDRESS_BUFFER_SIZE   16
#define MAPPING_LEASE_SECONDS   3600U
#define MAPPING_RETRY_NS   (30ULL * NS_PER_SEC_INT)

Functions

asciichat_error_t nat_upnp_open (uint16_t internal_port, const char *description, nat_upnp_context_t **ctx)
 Discover and open port via UPnP.
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().
void nat_upnp_close (nat_upnp_context_t **ctx)
 Close port mapping and clean up.
bool nat_upnp_is_active (const nat_upnp_context_t *ctx)
 Check if port mapping is still active.
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.
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.
asciichat_error_t nat_upnp_refresh (nat_upnp_context_t *ctx)
 Refresh port mapping (e.g., for long-running servers).
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.

Detailed Description

Router mapping lifecycle for TCP listeners and UDP transports.

Definition in file upnp.c.

Macro Definition Documentation

◆ MAPPING_LEASE_SECONDS

#define MAPPING_LEASE_SECONDS   3600U

Definition at line 32 of file upnp.c.

Referenced by nat_upnp_open_protocol(), and nat_upnp_refresh().

◆ MAPPING_RETRY_NS

#define MAPPING_RETRY_NS   (30ULL * NS_PER_SEC_INT)

Definition at line 33 of file upnp.c.

Referenced by nat_upnp_refresh().

◆ NETWORK_NAT_UPNP_CLIENT_BUFFER_SIZE

#define NETWORK_NAT_UPNP_CLIENT_BUFFER_SIZE   40

Definition at line 3 of file upnp.c.

◆ NETWORK_NAT_UPNP_EXTERNAL_ADDRESS_BUFFER_SIZE

#define NETWORK_NAT_UPNP_EXTERNAL_ADDRESS_BUFFER_SIZE   16

Definition at line 7 of file upnp.c.

◆ NETWORK_NAT_UPNP_LAN_ADDRESS_BUFFER_SIZE

#define NETWORK_NAT_UPNP_LAN_ADDRESS_BUFFER_SIZE   16

Definition at line 6 of file upnp.c.

◆ NETWORK_NAT_UPNP_LEASE_BUFFER_SIZE

#define NETWORK_NAT_UPNP_LEASE_BUFFER_SIZE   16

Definition at line 5 of file upnp.c.

◆ UPNP_MAPPING_DESCRIPTION_BUFFER_SIZE

#define UPNP_MAPPING_DESCRIPTION_BUFFER_SIZE   80

Definition at line 4 of file upnp.c.

Function Documentation

◆ nat_upnp_close()

void nat_upnp_close ( nat_upnp_context_t ** ctx)

Close port mapping and clean up.

Removes the port mapping from the gateway and frees resources. Safe to call with NULL.

Parameters
ctxContext handle (will be set to NULL on return)

Definition at line 240 of file upnp.c.

240 {
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}
#define SAFE_FREE(ptr)
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_NETWORK
Definition error_codes.h:76
@ ASCIICHAT_OK
Definition error_codes.h:50
#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 ASCII_OTEL_SCOPE(id)
Definition otel.h:77

References ASCII_OTEL_SCOPE, ASCIICHAT_OK, ERROR_NETWORK, log_debug, log_info, log_warn, PORT_STRING_BUFFER_SIZE, and SAFE_FREE.

Referenced by mcp_http_run(), and session_server_like_run().

◆ nat_upnp_get_address()

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.

Useful for ACDS registration where we need to advertise the public endpoint for P2P connections.

Parameters
ctxContext handle
[out]addrBuffer to write "IP:port" format (must be at least 22 bytes)
addr_lenSize of addr buffer
Returns
ASCIICHAT_OK if successfully written
ERROR_INVALID_PARAM if addr is too small

Definition at line 329 of file upnp.c.

329 {
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}
#define SET_ERRNO(code,...)
@ ERROR_INVALID_PARAM
uint16_t mapped_port
External port that was mapped (may differ from internal).
Definition upnp.h:36
char external_ip[16]
Detected external/public IP (e.g., "203.0.113.42").
Definition upnp.h:35
bool nat_upnp_is_active(const nat_upnp_context_t *ctx)
Check if port mapping is still active.
Definition upnp.c:280

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, nat_upnp_context::external_ip, nat_upnp_context::mapped_port, nat_upnp_is_active(), and SET_ERRNO.

Referenced by session_server_like_run().

◆ nat_upnp_get_endpoint()

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 at line 291 of file upnp.c.

291 {
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}
#define SAFE_STRNCPY(dst, src, size)

References ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, nat_upnp_context::external_ip, nat_upnp_context::mapped_port, nat_upnp_is_active(), SAFE_STRNCPY, and SET_ERRNO.

◆ nat_upnp_is_active()

bool nat_upnp_is_active ( const nat_upnp_context_t * ctx)

Check if port mapping is still active.

Checks the locally tracked lease; does not probe Internet reachability.

Parameters
ctxContext handle
Returns
true if the locally tracked mapping lease has not expired

Definition at line 280 of file upnp.c.

280 {
281 return ctx && ctx->is_mapped && ctx->external_ip[0] && time_get_ns() < ctx->expires_at_ns;
282}
bool is_mapped
true if port mapping is currently active
Definition upnp.h:49
uint64_t expires_at_ns
Monotonic lease expiry.
Definition upnp.h:47

References nat_upnp_context::expires_at_ns, nat_upnp_context::external_ip, and nat_upnp_context::is_mapped.

Referenced by nat_upnp_get_address(), nat_upnp_get_endpoint(), nat_upnp_refresh(), and session_server_like_run().

◆ nat_upnp_matches_bind_address()

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 at line 284 of file upnp.c.

284 {
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}
char internal_ip[16]
LAN address used by the gateway to reach us.
Definition upnp.h:41

References nat_upnp_context::internal_ip.

Referenced by session_server_like_run().

◆ nat_upnp_open()

asciichat_error_t nat_upnp_open ( uint16_t internal_port,
const char * description,
nat_upnp_context_t ** ctx )

Discover and open port via UPnP.

Attempts to find an UPnP-enabled gateway and request port mapping. On success, fills in external_ip and mapped_port.

Parameters
internal_portLocal TCP port to map (e.g., 27224 for ACDS)
descriptionDescription for port mapping (e.g., "ascii-chat Server")
[out]ctxContext handle (must be freed with nat_upnp_close())
Returns
ASCIICHAT_OK if port was successfully mapped
ERROR_NETWORK_* if discovery or mapping failed (does not determine listener reachability)

Example:

nat_upnp_context_t *ctx = NULL;
asciichat_error_t result = nat_upnp_open(27224, "ascii-chat Server", &ctx);
if (result == ASCIICHAT_OK && ctx) {
printf("Public IP: %s\n", ctx->external_ip);
// Advertise ctx->external_ip:ctx->mapped_port to ACDS
}
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
struct nat_upnp_context nat_upnp_context_t
Handle to UPnP context.

Definition at line 194 of file upnp.c.

194 {
195 return nat_upnp_open_protocol(internal_port, description, NAT_UPNP_TCP, ctx);
196}
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
@ NAT_UPNP_TCP
Definition upnp.h:31

References nat_upnp_open_protocol(), and NAT_UPNP_TCP.

Referenced by mcp_http_run(), and session_server_like_run().

◆ nat_upnp_open_protocol()

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 at line 198 of file upnp.c.

198 {
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}
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
asciichat_errno_scope_t errno_scope_begin(void)
@ ASCIICHAT_ERRNO_HANDLED
#define LOG_ERRNO_IF_SET(message)
#define SAFE_CALLOC(count, size, cast)
@ ERROR_MEMORY
Definition error_codes.h:55
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:159
#define ASCII_OTEL_ATTR_INT(key, value)
Definition otel.h:72
#define ASCII_OTEL_ATTR_STRING(key, value)
Definition otel.h:71
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
#define MAPPING_LEASE_SECONDS
Definition upnp.c:32
@ NAT_UPNP_UDP
Definition upnp.h:31

References ASCII_OTEL_ATTR_INT, ASCII_OTEL_ATTR_STRING, ascii_otel_metric(), ASCII_OTEL_SCOPE, ASCIICHAT_ERRNO_HANDLED, ASCIICHAT_OK, errno_scope_begin(), errno_scope_end(), ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_NETWORK, log_debug, LOG_ERRNO_IF_SET, log_info, MAPPING_LEASE_SECONDS, NAT_UPNP_TCP, NAT_UPNP_UDP, SAFE_CALLOC, SAFE_FREE, SAFE_STRNCPY, and SET_ERRNO.

Referenced by nat_upnp_open().

◆ nat_upnp_refresh()

asciichat_error_t nat_upnp_refresh ( nat_upnp_context_t * ctx)

Refresh port mapping (e.g., for long-running servers).

Call from one owning thread when refresh_at_ns is reached. Renewal is scheduled halfway through the lease; failures schedule a bounded retry.

Parameters
ctxContext handle
Returns
ASCIICHAT_OK if refresh succeeded

Definition at line 303 of file upnp.c.

303 {
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}
bool is_natpmp
true if NAT-PMP was used, false if UPnP
Definition upnp.h:40
uint64_t refresh_at_ns
Next renewal or retry deadline.
Definition upnp.h:48
#define MAPPING_RETRY_NS
Definition upnp.c:33

References ASCII_OTEL_SCOPE, ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_NETWORK, nat_upnp_context::external_ip, nat_upnp_context::is_mapped, nat_upnp_context::is_natpmp, log_info, log_warn, nat_upnp_context::mapped_port, MAPPING_LEASE_SECONDS, MAPPING_RETRY_NS, nat_upnp_is_active(), nat_upnp_context::refresh_at_ns, and SET_ERRNO.

Referenced by mcp_http_run().