ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
discovery.c File Reference

Parallel mDNS and ACDS session discovery implementation. More...

Go to the source code of this file.

Data Structures

struct  discovery_thread_state_t
 Context for ACDS discovery thread. More...
struct  mdns_query_state_t
 Internal state for collecting discovered services. More...
struct  mdns_thread_context_t
 Context for mDNS discovery thread. More...
struct  acds_thread_context_t
 Context for ACDS discovery thread. More...

Functions

void pubkey_to_hex (const uint8_t pubkey[32], char hex_out[(32 *2+1)])
 Convert Ed25519 public key to hex string.
asciichat_error_t hex_to_pubkey (const char *hex_str, uint8_t pubkey_out[32])
 Convert hex string to Ed25519 public key.
ui_mdns_server_t * discovery_mdns_query (int timeout_ms, int max_servers, bool quiet, int *out_count)
 Public mDNS query function used by both parallel discovery and TUI wrapper.
void discovery_mdns_destroy (ui_mdns_server_t *servers)
 Free memory from mDNS discovery results.
void discovery_config_init_defaults (discovery_config_t *config)
 Initialize discovery config with defaults.
asciichat_error_t discover_session_parallel (const char *session_string, const discovery_config_t *config, discovery_result_t *result)
 Look up session in parallel on mDNS and ACDS.

Detailed Description

Parallel mDNS and ACDS session discovery implementation.

This module provides automated discovery of ascii-chat servers via parallel mDNS (local LAN) and ACDS (internet) lookups.

Architecture:

  • mDNS discovery: discovery_mdns_query() - core implementation (this module)
  • ACDS discovery: ACDS client implementation for centralized lookup
  • Parallel coordination: Concurrent threads with "race to success" semantics
  • UI wrapper: lan_discovery.c calls discovery_mdns_query() for interactive selection

Definition in file discovery.c.

Function Documentation

◆ discover_session_parallel()

asciichat_error_t discover_session_parallel ( const char * session_string,
const discovery_config_t * config,
discovery_result_t * result )

Look up session in parallel on mDNS and ACDS.

Spawns two concurrent threads to search both mDNS (local LAN) and ACDS (internet). Returns immediately when either finds the session, cancelling the other search.

Verification Logic:

If config->expected_pubkey is set:

  • mDNS result: Verify TXT record contains matching host_pubkey
  • ACDS result: Verify SESSION_LOOKUP response contains matching host_pubkey
  • If both find result: Verify they have same pubkey (cross-check)
  • On mismatch: Return ERROR_CRYPTO_VERIFY_FAILED

If config->expected_pubkey is NULL but config->insecure_mode is true:

  • Skip all verification, accept first result found
  • WARNING: Vulnerable to MITM attacks!

If config->expected_pubkey is NULL and config->insecure_mode is false:

  • Search mDNS only (ACDS thread not started)
  • Use TOFU (Trust On First Use): accept first mDNS result found

Thread Lifecycle:

  • Both threads start immediately
  • Whichever completes first signals success via condition variable
  • Other thread is joined (cleaned up)
  • Function returns with result
Parameters
session_stringSession string to find (e.g., "swift-river-mountain")
configDiscovery configuration
resultDiscovery result (output)
Returns
ASCIICHAT_OK on success, error code on failure
Note
This function BLOCKS until one discovery method succeeds or both timeout
Not thread-safe for concurrent calls - use only one discovery at a time

Definition at line 533 of file discovery.c.

533 {
534 if (!session_string || !config || !result) {
535 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid parameters");
536 return ERROR_INVALID_PARAM;
537 }
538
539 // Validate session string format
540 if (!is_session_string(session_string)) {
541 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid session string format");
542 return ERROR_INVALID_PARAM;
543 }
544
545 memset(result, 0, sizeof(*result));
546 log_info("Discovery: Looking up session '%s'", session_string);
547
548 // Initialize thread state
550 memset(&state, 0, sizeof(state));
551 state.result = result;
552 mutex_init(&state.lock, "mdns_resolve");
553 cond_init(&state.signal, "mdns_signal");
554
555 // Determine which discovery methods to use
556 bool use_mdns = true;
557 bool use_acds = config->expected_pubkey != NULL || config->insecure_mode;
558 if (config->insecure_mode && !config->expected_pubkey)
559 NOTICE(DANGER, "DISCOVERY HOST VERIFICATION DISABLED",
560 "Insecure discovery is enabled without an expected host key.\n"
561 "The discovered host identity cannot be verified; this is vulnerable to man-in-the-middle attacks.");
562
563 if (!use_acds) {
564 log_debug("Discovery: mDNS-only mode (no --server-key and no --acds-insecure)");
565 }
566
567 // Spawn mDNS thread
568 platform_thread_t mdns_thread;
569 thread_init(&mdns_thread);
570
571 if (use_mdns) {
572 mdns_thread_context_t *mdns_ctx = SAFE_MALLOC(sizeof(*mdns_ctx), mdns_thread_context_t *);
573 if (!mdns_ctx) {
574 SET_ERRNO(ERROR_MEMORY, "Failed to allocate mDNS context");
575 mutex_destroy(&state.lock);
576 cond_destroy(&state.signal);
577 return ERROR_MEMORY;
578 }
579
580 mdns_ctx->session_string = session_string;
581 mdns_ctx->state = &state;
582 mdns_ctx->expected_pubkey = config->expected_pubkey;
583
584 int thread_err = platform_thread_create(&mdns_thread, "mdns", mdns_thread_fn, mdns_ctx);
585 if (thread_err != 0) {
586 log_warn("Discovery: Failed to spawn mDNS thread");
587 SAFE_FREE(mdns_ctx);
588 use_mdns = false;
589 }
590 }
591
592 // Spawn ACDS thread
593 platform_thread_t acds_thread;
594 thread_init(&acds_thread);
595
596 if (use_acds) {
597 acds_thread_context_t *acds_ctx = SAFE_MALLOC(sizeof(*acds_ctx), acds_thread_context_t *);
598 if (!acds_ctx) {
599 SET_ERRNO(ERROR_MEMORY, "Failed to allocate ACDS context");
600 if (use_mdns && thread_is_initialized(&mdns_thread)) {
601 thread_join(&mdns_thread, NULL);
602 }
603 mutex_destroy(&state.lock);
604 cond_destroy(&state.signal);
605 return ERROR_MEMORY;
606 }
607
608 acds_ctx->session_string = session_string;
609 acds_ctx->state = &state;
610 acds_ctx->config = config;
611
612 int thread_err = platform_thread_create(&acds_thread, "acds_client", acds_thread_fn, acds_ctx);
613 if (thread_err != 0) {
614 log_warn("Discovery: Failed to spawn ACDS thread");
615 SAFE_FREE(acds_ctx);
616 use_acds = false;
617 }
618 }
619
620 // Wait for result (mDNS timeout 2s + ACDS timeout 5s max)
621 uint32_t wait_timeout_ms = config->acds_timeout_ms + 1000;
622 mutex_lock(&state.lock);
623 {
624 uint32_t elapsed_ms = 0;
625 while (!state.found && elapsed_ms < wait_timeout_ms) {
626 // Check if both threads are done
627 if (state.mdns_done && state.acds_done) {
628 break;
629 }
630
631 // Wait with timeout
632 cond_timedwait(&state.signal, &state.lock, 500 * NS_PER_MS_INT);
633 elapsed_ms += 500;
634 }
635 }
636 mutex_unlock(&state.lock);
637
638 // Join threads
639 if (use_mdns && thread_is_initialized(&mdns_thread)) {
640 thread_join(&mdns_thread, NULL);
641 }
642 if (use_acds && thread_is_initialized(&acds_thread)) {
643 thread_join(&acds_thread, NULL);
644 }
645
646 // Cleanup
647 mutex_destroy(&state.lock);
648 cond_destroy(&state.signal);
649
650 // Check result
651 if (!result->success) {
652 SET_ERRNO(ERROR_NOT_FOUND, "Session '%s' not found (mDNS/ACDS timeout)", session_string);
653 return ERROR_NOT_FOUND;
654 }
655
656 log_info("Discovery: Session '%s' discovered via %s", session_string, result->source == DISCOVERY_SOURCE_MDNS ? "mDNS" : "ACDS");
657
658 return ASCIICHAT_OK;
659}
#define SET_ERRNO(code,...)
bool is_session_string(const char *str)
Check if a string is a valid session string.
unsigned int uint32_t
#define SAFE_FREE(ptr)
#define SAFE_MALLOC(size, cast)
@ ERROR_NOT_FOUND
@ ERROR_MEMORY
Definition error_codes.h:55
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#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_MS_INT
Definition time.h:172
#define NOTICE(severity, title,...)
Definition notice.h:56
Context for ACDS discovery thread.
Definition discovery.c:373
discovery_thread_state_t * state
Shared discovery state.
Definition discovery.c:375
const discovery_config_t * config
Discovery configuration.
Definition discovery.c:376
const char * session_string
Session string to look up.
Definition discovery.c:374
uint32_t acds_timeout_ms
ACDS lookup timeout (default: 5000ms).
Definition discovery.h:132
bool insecure_mode
Allow no verification (–acds-insecure flag).
Definition discovery.h:124
const uint8_t * expected_pubkey
Expected server pubkey (NULL = no verification).
Definition discovery.h:123
enum discovery_result_t::@335075210033063074377072145063374373365157111022 source
Which discovery method found the server.
bool success
Discovery succeeded.
Definition discovery.h:93
Context for ACDS discovery thread.
Definition discovery.c:45
bool found
Whether a session was found.
Definition discovery.c:51
discovery_result_t * result
Shared discovery result.
Definition discovery.c:48
cond_t signal
Condition variable for signaling.
Definition discovery.c:47
bool mdns_done
Whether mDNS discovery completed.
Definition discovery.c:49
mutex_t lock
Mutex for thread-safe access.
Definition discovery.c:46
bool acds_done
Whether ACDS discovery completed.
Definition discovery.c:50
Context for mDNS discovery thread.
Definition discovery.c:296
discovery_thread_state_t * state
Shared discovery state.
Definition discovery.c:298
const uint8_t * expected_pubkey
Expected server public key (optional).
Definition discovery.c:299
const char * session_string
Session string to discover.
Definition discovery.c:297

References discovery_thread_state_t::acds_done, discovery_config_t::acds_timeout_ms, ASCIICHAT_OK, acds_thread_context_t::config, ERROR_INVALID_PARAM, ERROR_MEMORY, ERROR_NOT_FOUND, discovery_config_t::expected_pubkey, mdns_thread_context_t::expected_pubkey, discovery_thread_state_t::found, discovery_config_t::insecure_mode, is_session_string(), discovery_thread_state_t::lock, log_debug, log_info, log_warn, discovery_thread_state_t::mdns_done, NOTICE, NS_PER_MS_INT, discovery_thread_state_t::result, SAFE_FREE, SAFE_MALLOC, acds_thread_context_t::session_string, mdns_thread_context_t::session_string, SET_ERRNO, discovery_thread_state_t::signal, discovery_result_t::source, acds_thread_context_t::state, mdns_thread_context_t::state, and discovery_result_t::success.

◆ discovery_config_init_defaults()

void discovery_config_init_defaults ( discovery_config_t * config)

Initialize discovery config with defaults.

Sets sensible defaults:

  • ACDS server: localhost:27225 (debug), discovery.ascii-chat.com (release)
  • Timeouts: mdns=2000ms, acds=5000ms
  • Verification: None (expected_pubkey=NULL)
  • Insecure mode: false
Parameters
configConfiguration to initialize

Definition at line 511 of file discovery.c.

511 {
512 if (!config)
513 return;
514
515 memset(config, 0, sizeof(*config));
516
517 // Check if debug or release build
518#ifdef NDEBUG
519 // Release: use internet ACDS
520 SAFE_STRNCPY(config->acds_server, "discovery.ascii-chat.com", sizeof(config->acds_server) - 1);
521#else
522 // Debug: use local ACDS
523 SAFE_STRNCPY(config->acds_server, "127.0.0.1", sizeof(config->acds_server) - 1);
524#endif
525
527 config->mdns_timeout_ms = 2 * MS_PER_SEC_INT;
528 config->acds_timeout_ms = 5 * MS_PER_SEC_INT;
529 config->insecure_mode = false;
530 config->expected_pubkey = NULL;
531}
#define SAFE_STRNCPY(dst, src, size)
#define MS_PER_SEC_INT
Definition time.h:180
#define OPT_ACDS_PORT_INT_DEFAULT
Default ACDS discovery service port (integer).
Definition options.h:593
uint32_t mdns_timeout_ms
mDNS search timeout (default: 2000ms)
Definition discovery.h:131
uint16_t acds_port
ACDS port (default: 27225).
char acds_server[256]
ACDS server address (e.g., "localhost" or "discovery.ascii-chat.com").
Definition discovery.h:127

References discovery_config_t::acds_port, discovery_config_t::acds_server, discovery_config_t::acds_timeout_ms, discovery_config_t::expected_pubkey, discovery_config_t::insecure_mode, discovery_config_t::mdns_timeout_ms, MS_PER_SEC_INT, OPT_ACDS_PORT_INT_DEFAULT, and SAFE_STRNCPY.

◆ discovery_mdns_destroy()

void discovery_mdns_destroy ( ui_mdns_server_t * servers)

Free memory from mDNS discovery results.

Definition at line 285 of file discovery.c.

285 {
286 SAFE_FREE(servers);
287}

References SAFE_FREE.

Referenced by ui_mdns_free_results().

◆ discovery_mdns_query()

ui_mdns_server_t * discovery_mdns_query ( int timeout_ms,
int max_servers,
bool quiet,
int * out_count )

Public mDNS query function used by both parallel discovery and TUI wrapper.

Discover ascii-chat servers on local network via mDNS.

Parameters
timeout_msQuery timeout in milliseconds
max_serversMaximum servers to discover
quietIf true, suppresses progress messages
out_countOutput: number of servers discovered
Returns
Array of discovered servers, or NULL on error. Use discovery_mdns_destroy() to free.

Definition at line 190 of file discovery.c.

190 {
191 if (!out_count) {
192 SET_ERRNO(ERROR_INVALID_PARAM, "out_count pointer is NULL");
193 return NULL;
194 }
195
196 *out_count = 0;
197
198 // Apply defaults
199 if (timeout_ms <= 0) {
200 timeout_ms = 2 * MS_PER_SEC_INT;
201 }
202 if (max_servers <= 0) {
203 max_servers = 20;
204 }
205
206 // Allocate state for collecting servers
207 mdns_query_state_t state;
208 memset(&state, 0, sizeof(state));
209 state.capacity = max_servers;
210 state.timeout_ms = timeout_ms;
211 state.start_time_ms = (int64_t)time_ns_to_ms(time_get_ns());
212
213 // Allocate server array
214 state.servers = SAFE_MALLOC((size_t)state.capacity * sizeof(ui_mdns_server_t), ui_mdns_server_t *);
215 if (!state.servers) {
216 SET_ERRNO(ERROR_MEMORY, "Failed to allocate mDNS discovery server array");
217 return NULL;
218 }
219 memset(state.servers, 0, state.capacity * sizeof(ui_mdns_server_t));
220
221 if (!quiet) {
222 log_info("mDNS: Searching for ascii-chat servers on local network (timeout: %dms)", state.timeout_ms);
223 printf("🔍 Searching for ascii-chat servers on LAN...\n");
224 }
225
226 // Discovery is retried in the live picker; failures remain in logs.
228 bool previous_notifications = errno_notifications_suppress(true);
229 // Initialize mDNS
231 if (!mdns) {
232 log_warn("mDNS: Failed to initialize mDNS - discovery unavailable");
233 errno_notifications_suppress(previous_notifications);
235 return state.servers;
236 }
237
238 // Start mDNS query for _ascii-chat._tcp services
239 asciichat_error_t query_result = asciichat_mdns_query(mdns, "_ascii-chat._tcp.local", discovery_mdns_callback, &state);
240
241 if (query_result != ASCIICHAT_OK) {
242 log_info("mDNS: Query failed - no servers found via service discovery");
244 errno_notifications_suppress(previous_notifications);
246 return state.servers;
247 }
248
249 // Poll for responses until timeout
250 int64_t deadline = state.start_time_ms + state.timeout_ms;
251 while (!state.query_complete && (int64_t)time_ns_to_ms(time_get_ns()) < deadline) {
252 int poll_timeout = (int)(deadline - (int64_t)time_ns_to_ms(time_get_ns()));
253 if (poll_timeout < 0) {
254 poll_timeout = 0;
255 }
256 if (poll_timeout > 100) {
257 poll_timeout = 100; // Check every 100ms
258 }
259 if (asciichat_mdns_update(mdns, poll_timeout) != ASCIICHAT_OK)
260 break;
261 }
262
263 // Cleanup mDNS
265 errno_notifications_suppress(previous_notifications);
267
268 if (!quiet) {
269 if (state.count > 0) {
270 printf("✅ Found %d ascii-chat server%s on LAN\n", state.count, state.count == 1 ? "" : "s");
271 log_info("mDNS: Found %d server(s)", state.count);
272 } else {
273 printf("❌ No ascii-chat servers found on LAN\n");
274 log_info("mDNS: No servers found");
275 }
276 }
277
278 *out_count = state.count;
279 return state.servers;
280}
void errno_scope_end(asciichat_errno_scope_t scope, asciichat_errno_outcome_t outcome)
bool errno_notifications_suppress(bool suppress)
asciichat_errno_scope_t errno_scope_begin(void)
@ ASCIICHAT_ERRNO_HANDLED
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
asciichat_error_t asciichat_mdns_update(asciichat_mdns_t *mdns, int timeout_ms)
Process pending mDNS events (must be called regularly).
void asciichat_mdns_destroy(asciichat_mdns_t *mdns)
Shutdown mDNS context and cleanup.
asciichat_mdns_t * asciichat_mdns_init(void)
Initialize mDNS context.
asciichat_error_t asciichat_mdns_query(asciichat_mdns_t *mdns, const char *service_type, asciichat_mdns_discovery_callback_fn callback, void *user_data)
Query for services on the local network.
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
Owns one mDNS browse or advertisement session, including its socket, event-loop registration,...
Internal state for collecting discovered services.
Definition discovery.c:107
ui_mdns_server_t * servers
Array of discovered servers.
Definition discovery.c:108
int count
Number of servers discovered so far.
Definition discovery.c:109
int64_t start_time_ms
When discovery started (for timeout).
Definition discovery.c:111
bool query_complete
Set when discovery completes.
Definition discovery.c:113
int capacity
Allocated capacity.
Definition discovery.c:110
int timeout_ms
Discovery timeout in milliseconds.
Definition discovery.c:112
Discovered server information from mDNS.
Definition tui/mdns.h:66

References ASCIICHAT_ERRNO_HANDLED, asciichat_mdns_destroy(), asciichat_mdns_init(), asciichat_mdns_query(), asciichat_mdns_update(), ASCIICHAT_OK, mdns_query_state_t::capacity, mdns_query_state_t::count, errno_notifications_suppress(), errno_scope_begin(), errno_scope_end(), ERROR_INVALID_PARAM, ERROR_MEMORY, log_info, log_warn, MS_PER_SEC_INT, mdns_query_state_t::query_complete, SAFE_MALLOC, mdns_query_state_t::servers, SET_ERRNO, mdns_query_state_t::start_time_ms, and mdns_query_state_t::timeout_ms.

Referenced by ui_mdns_query().

◆ hex_to_pubkey()

asciichat_error_t hex_to_pubkey ( const char * hex_str,
uint8_t pubkey_out[32] )

Convert hex string to Ed25519 public key.

Converts 64-character hex string to 32-byte binary pubkey.

Parameters
hex_strHex string (64 characters)
pubkey_outOutput binary pubkey (32 bytes)
Returns
ASCIICHAT_OK on success, ERROR_INVALID_PARAM if invalid hex

Definition at line 67 of file discovery.c.

67 {
68 if (!hex_str || !pubkey_out) {
69 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid hex_str or pubkey_out pointer");
71 }
72
73 if (strlen(hex_str) != 64) {
74 SET_ERRNO(ERROR_INVALID_PARAM, "Hex string must be exactly 64 characters");
76 }
77
78 for (int i = 0; i < 32; i++) {
79 char hex_byte[3];
80 hex_byte[0] = hex_str[i * 2];
81 hex_byte[1] = hex_str[i * 2 + 1];
82 hex_byte[2] = '\0';
83
84 if (!isxdigit(hex_byte[0]) || !isxdigit(hex_byte[1])) {
85 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid hex character in string");
87 }
88
89 pubkey_out[i] = (uint8_t)strtol(hex_byte, NULL, 16);
90 }
91
92 return ASCIICHAT_OK;
93}
unsigned char uint8_t

References ASCIICHAT_OK, ED25519_PUBLIC_KEY_SIZE, ERROR_INVALID_PARAM, and SET_ERRNO.

◆ pubkey_to_hex()

void pubkey_to_hex ( const uint8_t pubkey[32],
char hex_out[(32 *2+1)] )

Convert Ed25519 public key to hex string.

Converts 32-byte binary pubkey to lowercase hex (64 characters).

Parameters
pubkeyBinary public key (32 bytes)
hex_outOutput hex string buffer (must be at least 65 bytes)

Definition at line 58 of file discovery.c.

58 {
59 if (!pubkey || !hex_out)
60 return;
61 for (int i = 0; i < 32; i++) {
62 safe_snprintf(hex_out + (i * 2), 3, "%02x", pubkey[i]);
63 }
64 hex_out[64] = '\0';
65}

References ED25519_PUBLIC_KEY_SIZE, and HEX_STRING_SIZE_32.