ascii-chat
Binary v0.16.114-28-gf5913657f
Library lib/v0.3.2-3302-gf5913657f
Video chat in your terminal
Loading...
Searching...
No Matches
session.h File Reference

Go to the source code of this file.

Data Structures

struct  host_liveness_t
 When code needs to work with host liveness, it keeps last_ping_sent_ms, last_pong_received_ms, consecutive_failures, max_failures here instead of scattering it across globals. Initialization establishes the handles and sizes; teardown must release any allocation, lock, thread, or callback context recorded in those fields. More...
struct  discovery_session_t
 Discovery session context. More...
struct  discovery_config_t
 Configuration for discovery session. More...

Macros

#define DISCOVERY_SESSION_ACDS_ADDRESS_BUFFER_SIZE   64
#define DISCOVERY_SESSION_ACDS_URL_BUFFER_SIZE   512

Typedefs

typedef bool(* discovery_should_exit_fn) (void *user_data)
 Callback to check if session should exit.

Enumerations

enum  discovery_state_t {
  DISCOVERY_STATE_INIT , DISCOVERY_STATE_CONNECTING_ACDS , DISCOVERY_STATE_CREATING_SESSION , DISCOVERY_STATE_JOINING_SESSION ,
  DISCOVERY_STATE_WAITING_PEER , DISCOVERY_STATE_NEGOTIATING , DISCOVERY_STATE_STARTING_HOST , DISCOVERY_STATE_CONNECTING_HOST ,
  DISCOVERY_STATE_ACTIVE , DISCOVERY_STATE_MIGRATING , DISCOVERY_STATE_FAILED , DISCOVERY_STATE_ENDED
}
 Discovery session state. More...

Functions

discovery_session_t * discovery_session_create (const discovery_config_t *config)
 Configuration for discovery session.
asciichat_error_t discovery_session_destroy (discovery_session_t *session)
 Destroy discovery session and free resources.
asciichat_error_t discovery_session_start (discovery_session_t *session)
 Start the discovery session.
asciichat_error_t discovery_session_process (discovery_session_t *session, int64_t timeout_ns)
 Process session events (call in main loop).
void discovery_session_stop (discovery_session_t *session)
 Stop the discovery session.
discovery_state_t discovery_session_get_state (const discovery_session_t *session)
 Get current session state.
bool discovery_session_is_active (const discovery_session_t *session)
 Check if session is active (call in progress).
const char * discovery_session_get_string (const discovery_session_t *session)
 Get session string.
bool discovery_session_is_host (const discovery_session_t *session)
 Check if we are the host.
session_host_t * discovery_session_get_host (discovery_session_t *session)
 Get host context (if we are host).
session_participant_t * discovery_session_get_participant (discovery_session_t *session)
 Get participant context (if we are participant).
asciichat_error_t discovery_session_check_host_alive (discovery_session_t *session)
 Detect host disconnect (check connection status).
void discovery_session_host_pong (discovery_session_t *session)
asciichat_error_t discovery_session_handle_host_disconnect (discovery_session_t *session, uint32_t disconnect_reason)
 Report host disconnect and await the ACDS recovery decision.
asciichat_error_t discovery_session_apply_handoff (discovery_session_t *session)
 Replace the old role after a committed handoff and media-worker shutdown. Releases borrowed-role resources, resets liveness, and initializes the committed successor connection. Callers must stop media workers before entering this function.

Macro Definition Documentation

◆ DISCOVERY_SESSION_ACDS_ADDRESS_BUFFER_SIZE

#define DISCOVERY_SESSION_ACDS_ADDRESS_BUFFER_SIZE   64

Definition at line 4 of file src/discovery/session.h.

◆ DISCOVERY_SESSION_ACDS_URL_BUFFER_SIZE

#define DISCOVERY_SESSION_ACDS_URL_BUFFER_SIZE   512

Definition at line 5 of file src/discovery/session.h.

Typedef Documentation

◆ discovery_should_exit_fn

typedef bool(* discovery_should_exit_fn) (void *user_data)

Callback to check if session should exit.

Called periodically during blocking operations (e.g., ACDS connect, join). Should return true to gracefully cancel the current operation.

Parameters
user_dataOpaque pointer provided by caller
Returns
true to cancel operation, false to continue

Definition at line 80 of file src/discovery/session.h.

Enumeration Type Documentation

◆ discovery_state_t

Discovery session state.

Enumerator
DISCOVERY_STATE_INIT 

Initial state.

DISCOVERY_STATE_CONNECTING_ACDS 

Connecting to ACDS.

DISCOVERY_STATE_CREATING_SESSION 

Creating new session.

DISCOVERY_STATE_JOINING_SESSION 

Joining existing session.

DISCOVERY_STATE_WAITING_PEER 

Waiting for peer to join (initiator).

DISCOVERY_STATE_NEGOTIATING 

NAT negotiation in progress.

DISCOVERY_STATE_STARTING_HOST 

Starting as host.

DISCOVERY_STATE_CONNECTING_HOST 

Connecting to host as participant.

DISCOVERY_STATE_ACTIVE 

Session active (call in progress).

DISCOVERY_STATE_MIGRATING 

Host migration in progress.

DISCOVERY_STATE_FAILED 

Session failed.

DISCOVERY_STATE_ENDED 

Session ended.

Definition at line 85 of file src/discovery/session.h.

85 {
discovery_state_t
Discovery session state.
@ DISCOVERY_STATE_ENDED
Session ended.
@ DISCOVERY_STATE_JOINING_SESSION
Joining existing session.
@ DISCOVERY_STATE_INIT
Initial state.
@ DISCOVERY_STATE_ACTIVE
Session active (call in progress).
@ DISCOVERY_STATE_MIGRATING
Host migration in progress.
@ DISCOVERY_STATE_NEGOTIATING
NAT negotiation in progress.
@ DISCOVERY_STATE_CONNECTING_HOST
Connecting to host as participant.
@ DISCOVERY_STATE_CREATING_SESSION
Creating new session.
@ DISCOVERY_STATE_CONNECTING_ACDS
Connecting to ACDS.
@ DISCOVERY_STATE_WAITING_PEER
Waiting for peer to join (initiator).
@ DISCOVERY_STATE_FAILED
Session failed.
@ DISCOVERY_STATE_STARTING_HOST
Starting as host.

Function Documentation

◆ discovery_session_apply_handoff()

asciichat_error_t discovery_session_apply_handoff ( discovery_session_t * session)

Replace the old role after a committed handoff and media-worker shutdown. Releases borrowed-role resources, resets liveness, and initializes the committed successor connection. Callers must stop media workers before entering this function.

Apply a committed role change after media workers have stopped.

Returns
ASCIICHAT_OK if no handoff is pending or initialization succeeds.

Definition at line 1353 of file src/discovery/session.c.

1353 {
1354 if (!session || !session->handoff_pending)
1355 return ASCIICHAT_OK;
1356 session->handoff_pending = false;
1357 if (session->participant_ctx) {
1359 session->participant_ctx = NULL;
1360 }
1361 if (session->peer_manager) {
1363 session->peer_manager = NULL;
1364 }
1365 session->is_host =
1366 !memcmp(session->host_id, session->participant_id, SESSION_ID_SIZE);
1367 if (!session->is_host && session->host_ctx) {
1369 session->host_ctx = NULL;
1370 }
1371 session->webrtc_transport_ready = false;
1372 session->webrtc_connection_initiated = false;
1373 session->webrtc_retry_attempt = 0;
1374 session->webrtc_disconnected_since_ms = 0;
1375 session->liveness.ping_in_flight = false;
1376 session->liveness.consecutive_failures = 0;
1377 session->liveness.last_ping_sent_ms = session_get_current_time_ms();
1379 if (session->session_type == SESSION_TYPE_WEBRTC) {
1380 asciichat_error_t result = initialize_webrtc_peer_manager(session);
1381 if (result != ASCIICHAT_OK)
1382 return result;
1383 }
1384 ascii_otel_metric(ASCII_OTEL_METRIC_HOST_CHANGES_APPLIED, 1);
1385 session->host_loss_detected_ms = 0;
1386
1387 set_state(session, session->is_host ? DISCOVERY_STATE_STARTING_HOST
1389 return ASCIICHAT_OK;
1390}
void atomic_store_u64(atomic_t *a, uint64_t value)
Atomically store a uint64_t value.
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ASCIICHAT_OK
Definition error_codes.h:50
#define SESSION_ID_SIZE
@ SESSION_TYPE_WEBRTC
WebRTC P2P mesh with STUN/TURN relay.
Definition acds.h:151
asciichat_error_t session_host_destroy(session_host_t *host)
Destroy session host and free resources.
Definition host.c:289
void session_participant_destroy(session_participant_t *p)
Destroy session participant and free resources.
void webrtc_peer_manager_destroy(webrtc_peer_manager_t *manager)
Destroy peer manager and close all connections.
void ascii_otel_metric(ascii_otel_metric_t metric, double value)
Definition otel.c:175
uint64_t webrtc_disconnected_since_ms
Start of a transient peer disconnection.
uint8_t session_type
0 = DIRECT_TCP, 1 = WEBRTC
uint8_t participant_id[SESSION_ID_SIZE]
session_participant_t * participant_ctx
struct webrtc_peer_manager * peer_manager
The useful part of discovery session is in state, error, waiting_peer_start_ns, is_initiator: togethe...
uint8_t host_id[SESSION_ID_SIZE]
uint32_t consecutive_failures
Number of consecutive ping failures.
atomic_t last_pong_received_ms
Timestamp of last pong received (monotonic).
uint64_t last_ping_sent_ms
Timestamp of last ping sent (monotonic).
bool ping_in_flight
True if waiting for pong.

References ascii_otel_metric(), ASCIICHAT_OK, atomic_store_u64(), host_liveness_t::consecutive_failures, DISCOVERY_STATE_CONNECTING_HOST, DISCOVERY_STATE_STARTING_HOST, discovery_session_t::handoff_pending, discovery_session_t::host_ctx, discovery_session_t::host_id, discovery_session_t::host_loss_detected_ms, discovery_session_t::is_host, host_liveness_t::last_ping_sent_ms, host_liveness_t::last_pong_received_ms, discovery_session_t::liveness, discovery_session_t::participant_ctx, discovery_session_t::participant_id, discovery_session_t::peer_manager, host_liveness_t::ping_in_flight, session_host_destroy(), SESSION_ID_SIZE, session_participant_destroy(), discovery_session_t::session_type, SESSION_TYPE_WEBRTC, discovery_session_t::webrtc_connection_initiated, discovery_session_t::webrtc_disconnected_since_ms, webrtc_peer_manager_destroy(), discovery_session_t::webrtc_retry_attempt, and discovery_session_t::webrtc_transport_ready.

◆ discovery_session_check_host_alive()

asciichat_error_t discovery_session_check_host_alive ( discovery_session_t * session)

Detect host disconnect (check connection status).

Parameters
sessionSession context
Returns
ASCIICHAT_OK if host alive, error if disconnected

Detect host disconnect (check connection status).

Returns
ASCIICHAT_OK for a live host, or a network error after loss is detected.

Definition at line 2580 of file src/discovery/session.c.

2580 {
2581 if (!session || session->is_host) {
2582 // We are the host, so "host" is always alive
2583 return ASCIICHAT_OK;
2584 }
2585
2586 // For WebRTC sessions, check the WebRTC transport instead of participant_ctx
2587 if (session->session_type == SESSION_TYPE_WEBRTC) {
2588 // If we have a WebRTC transport and it's marked as ready, host is alive
2589 if (session->webrtc_transport_ready) {
2590 return ASCIICHAT_OK;
2591 }
2592 // WebRTC transport not ready yet - might still be connecting
2593 return ERROR_NETWORK;
2594 }
2595
2596 // For TCP sessions, check participant context
2597 // If we don't have a participant context yet, we're not connected
2598 if (!session->participant_ctx) {
2599 return ERROR_NETWORK;
2600 }
2601
2602 // Check migration state - if we're already migrating, host is definitely not
2603 // alive
2604 if (session->state == DISCOVERY_STATE_MIGRATING) {
2605 return ERROR_NETWORK; // Already detected disconnect
2606 }
2607
2608 uint64_t now_ms = session_get_current_time_ms();
2609
2610 if (session->liveness.ping_in_flight &&
2612 session->liveness.last_ping_sent_ms) {
2613 session->liveness.ping_in_flight = false;
2614 session->liveness.consecutive_failures = 0;
2615 }
2616 // Check if we have a ping in flight that timed out
2617 if (session->liveness.ping_in_flight) {
2618 uint64_t ping_age_ms = now_ms - session->liveness.last_ping_sent_ms;
2619 if (ping_age_ms > session->liveness.timeout_ms) {
2620 // Ping timed out
2621 session->liveness.consecutive_failures++;
2622 session->liveness.ping_in_flight = false;
2623 log_warn("Host ping timeout (attempt %u/%u, age=%llu ms)",
2625 session->liveness.max_failures, (unsigned long long)ping_age_ms);
2626
2627 // Check if we've exceeded failure threshold
2628 if (session->liveness.consecutive_failures >=
2629 session->liveness.max_failures) {
2630 log_error("Host declared dead after %u consecutive ping failures",
2632 return ERROR_NETWORK;
2633 }
2634 }
2635 }
2636
2637 // Check if it's time to send a new ping
2638 uint64_t time_since_last_ping = now_ms - session->liveness.last_ping_sent_ms;
2639 if (!session->liveness.ping_in_flight &&
2640 time_since_last_ping >= session->liveness.ping_interval_ms) {
2641 // Send ping to host via participant connection
2642 acip_transport_t *transport =
2644 if (!transport || !acip_transport_is_connected(transport))
2645 return SET_ERRNO(ERROR_NETWORK, "Host transport disconnected");
2646 asciichat_error_t result = acip_send_ping(transport);
2647 if (result == ASCIICHAT_OK) {
2648 session->liveness.last_ping_sent_ms = now_ms;
2649 session->liveness.ping_in_flight = true;
2650 log_debug("Sent ping to host (attempt %u/%u)",
2651 session->liveness.consecutive_failures + 1,
2652 session->liveness.max_failures);
2653 } else {
2654 log_warn("Failed to send ping to host: %d", result);
2655 session->liveness.consecutive_failures++;
2656 if (session->liveness.consecutive_failures >=
2657 session->liveness.max_failures) {
2658 log_error("Host declared dead after %u consecutive send failures",
2660 return ERROR_NETWORK;
2661 }
2662 }
2663 }
2664
2665 return ASCIICHAT_OK;
2666}
#define SET_ERRNO(code,...)
uint64_t atomic_load_u64(const atomic_t *a)
Atomically load a uint64_t value.
unsigned long long uint64_t
@ ERROR_NETWORK
Definition error_codes.h:77
#define log_warn(...)
Log a WARN message.
Definition log/log.h:591
#define log_error(...)
Log an ERROR message.
Definition log/log.h:604
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
acip_transport_t * session_participant_get_transport(session_participant_t *p)
Get the current transport for the participant.
struct acip_transport acip_transport_t
Forward declaration of ACIP transport.
Definition host.h:508
asciichat_error_t acip_send_ping(acip_transport_t *transport)
Send ping packet.
Definition send.c:372
uint32_t max_failures
Threshold for triggering migration (default: 3).
uint64_t ping_interval_ms
Time between pings (default: 3000ms).
uint64_t timeout_ms
Timeout for ping response (default: 10000ms).

References acip_send_ping(), ASCIICHAT_OK, atomic_load_u64(), host_liveness_t::consecutive_failures, DISCOVERY_STATE_MIGRATING, ERROR_NETWORK, discovery_session_t::is_host, host_liveness_t::last_ping_sent_ms, host_liveness_t::last_pong_received_ms, discovery_session_t::liveness, log_debug, log_error, log_warn, host_liveness_t::max_failures, discovery_session_t::participant_ctx, host_liveness_t::ping_in_flight, host_liveness_t::ping_interval_ms, session_participant_get_transport(), discovery_session_t::session_type, SESSION_TYPE_WEBRTC, SET_ERRNO, discovery_session_t::state, host_liveness_t::timeout_ms, and discovery_session_t::webrtc_transport_ready.

◆ discovery_session_create()

discovery_session_t * discovery_session_create ( const discovery_config_t * config)

Configuration for discovery session.

Create a new discovery session

Parameters
configSession configuration
Returns
New session or NULL on error

Definition at line 81 of file src/discovery/session.c.

81 {
82 if (!config) {
83 SET_ERRNO(ERROR_INVALID_PARAM, "config is NULL");
84 return NULL;
85 }
86
87 discovery_session_t *session =
89 if (!session) {
90 SET_ERRNO(ERROR_MEMORY, "Failed to allocate discovery session");
91 return NULL;
92 }
93
94 session->state = DISCOVERY_STATE_INIT;
95 session->handoff_generation = 1; // Match consensus_handoff_init().
96 session->acds_transport = NULL;
97 session->peer_manager = NULL;
98 session->webrtc_transport_ready = false;
99 session->webrtc_connection_initiated = false;
100 session->webrtc_retry_attempt = 0;
101 session->webrtc_last_attempt_time_ms = 0;
102 session->webrtc_disconnected_since_ms = 0;
103 session->stun_servers = NULL;
104 session->stun_count = 0;
105 session->turn_servers = NULL;
106 session->turn_count = 0;
107
108 // Initialize host liveness detection
109 session->liveness.last_ping_sent_ms = 0;
111 session->liveness.consecutive_failures = 0;
112 session->liveness.max_failures = 3;
113 session->liveness.ping_interval_ms =
114 3 * MS_PER_SEC_INT; // Ping every 3 seconds
115 session->liveness.timeout_ms = 10 * MS_PER_SEC_INT; // 10 second timeout
116 session->liveness.ping_in_flight = false;
117
118 log_info("After CALLOC - participant_ctx=%p, host_ctx=%p",
119 session->participant_ctx, session->host_ctx);
120
121 // Explicit identity credentials apply to signaling as well as media
122 // authentication.
123 const options_t *opts = options_get();
124 bool explicit_identity = opts && opts->encrypt_key[0];
126 asciichat_error_t id_result;
127 if (explicit_identity) {
128 SAFE_STRNCPY(identity_path, opts->encrypt_key, sizeof(identity_path));
129 id_result = ASCIICHAT_OK;
130 } else {
131 id_result =
132 acds_identity_default_path(identity_path, sizeof(identity_path));
133 }
134 if (id_result == ASCIICHAT_OK) {
135 asciichat_errno_scope_t load_scope = {0};
136 bool suppressed = false;
137 if (!explicit_identity) {
138 load_scope = errno_scope_begin();
139 suppressed = errno_notifications_suppress(true);
140 }
141 if (!explicit_identity &&
142 platform_access(identity_path, PLATFORM_ACCESS_EXISTS) != 0)
143 id_result = ERROR_CONFIG;
144 else
145 id_result = acds_identity_load(identity_path, session->identity_pubkey,
146 session->identity_seckey);
147 if (!explicit_identity) {
150 }
151 if (id_result != ASCIICHAT_OK && !explicit_identity) {
152 // File doesn't exist or is corrupted - generate new key
153 log_info("Identity key not found, generating new key");
154 id_result = acds_identity_generate(session->identity_pubkey,
155 session->identity_seckey);
156 if (id_result == ASCIICHAT_OK) {
157 // Save for future use
158 acds_identity_save(identity_path, session->identity_pubkey,
159 session->identity_seckey);
160 }
161 }
162 }
163
164 if (id_result != ASCIICHAT_OK && explicit_identity) {
165 SAFE_FREE(session);
166 return NULL;
167 }
168 if (id_result != ASCIICHAT_OK) {
169 NOTICE(DANGER, "DISCOVERY IDENTITY UNAVAILABLE",
170 "Failed to load/generate identity key, using zero key");
171 memset(session->identity_pubkey, 0, sizeof(session->identity_pubkey));
172 memset(session->identity_seckey, 0, sizeof(session->identity_seckey));
173 } else {
174 char fingerprint[HEX_STRING_SIZE_32];
175 acds_identity_fingerprint(session->identity_pubkey, fingerprint);
176 log_info("Using identity key with fingerprint: %.16s...", fingerprint);
177 }
178
179 // Load multiple identity keys from options (multi-key protocol support)
180 if (opts && opts->num_identity_keys > 0) {
181 // Load all identity keys from options
182 for (size_t i = 0; i < opts->num_identity_keys && i < MAX_SESSION_KEYS;
183 i++) {
184 uint8_t pubkey[ED25519_PUBLIC_KEY_SIZE] = {0};
185 uint8_t seckey[ED25519_PRIVATE_KEY_SIZE] = {0};
186 asciichat_error_t key_result =
187 acds_identity_load(opts->identity_keys[i], pubkey, seckey);
188 if (key_result == ASCIICHAT_OK) {
189 memcpy(session->identity_pubkeys[session->num_identity_keys], pubkey,
190 sizeof(pubkey));
191 memcpy(session->identity_seckeys[session->num_identity_keys++], seckey,
192 sizeof(seckey));
193 sodium_memzero(seckey, sizeof(seckey));
194 char fingerprint[HEX_STRING_SIZE_32];
195 acds_identity_fingerprint(pubkey, fingerprint);
196 log_info("Loaded identity key #%zu with fingerprint: %.16s...", i + 1,
197 fingerprint);
198 } else {
199 log_warn("Failed to load identity key #%zu from %s", i + 1,
200 opts->identity_keys[i]);
201 }
202 }
203 if (session->num_identity_keys != opts->num_identity_keys) {
204 sodium_memzero(session->identity_seckey,
205 sizeof(session->identity_seckey));
206 sodium_memzero(session->identity_seckeys,
207 sizeof(session->identity_seckeys));
208 SAFE_FREE(session);
210 "Could not load the complete discovery identity key set");
211 return NULL;
212 }
213 memcpy(session->identity_pubkey, session->identity_pubkeys[0],
214 sizeof(session->identity_pubkey));
215 memcpy(session->identity_seckey, session->identity_seckeys[0],
216 sizeof(session->identity_seckey));
217 log_info("Loaded %zu identity key(s) for multi-key protocol",
218 session->num_identity_keys);
219 } else {
220 // Single-key mode: use only the primary identity key
221 memcpy(session->identity_pubkeys[0], session->identity_pubkey,
223 memcpy(session->identity_seckeys[0], session->identity_seckey,
224 sizeof(session->identity_seckey));
225 session->num_identity_keys = 1;
226 }
227
228 // ACDS connection info
229 if (config->acds_url && config->acds_url[0]) {
230 SAFE_STRNCPY(session->acds_url, config->acds_url,
231 sizeof(session->acds_url));
232 }
233 if (config->acds_address && config->acds_address[0]) {
234 SAFE_STRNCPY(session->acds_address, config->acds_address,
235 sizeof(session->acds_address));
236 } else {
237 SAFE_STRNCPY(session->acds_address, "127.0.0.1",
238 sizeof(session->acds_address));
239 }
240 session->acds_port =
241 config->acds_port > 0 ? config->acds_port : ACIP_DISCOVERY_DEFAULT_PORT;
242
243 // Session string (if joining)
244 if (config->session_string && config->session_string[0]) {
246 sizeof(session->session_string));
247 session->is_initiator = false;
248 } else {
249 session->is_initiator = true;
250 }
251 if (config->password && config->password[0]) {
252 SAFE_STRNCPY(session->password, config->password,
253 sizeof(session->password));
254 }
255
256 // Callbacks
257 session->on_state_change = config->on_state_change;
258 session->on_session_ready = config->on_session_ready;
259 session->on_error = config->on_error;
260 session->callback_user_data = config->callback_user_data;
262 session->exit_callback_data = config->exit_callback_data;
263
264 // Initialize mutex for NAT quality protection
265 if (mutex_init(&session->nat_quality_mutex, "discovery_nat_quality") != 0) {
266 log_warn("Failed to initialize NAT quality mutex");
267 }
268
269 log_debug("Discovery session created (initiator=%d, acds=%s:%u)",
270 session->is_initiator, session->acds_address, session->acds_port);
271
273 "discovery.last_pong_received_ms", NULL);
274 return session;
275}
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
int platform_access(const char *pathname, int mode)
Definition filesystem.c:95
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_FREE(ptr)
#define SAFE_CALLOC(count, size, cast)
unsigned char uint8_t
#define NAMED_REGISTER_ATOMIC(a, name, parent_ptr)
Register an atomic_t with automatic format specifier.
@ ERROR_MEMORY
Definition error_codes.h:55
@ ERROR_CONFIG
Definition error_codes.h:56
@ ERROR_CRYPTO
@ ERROR_INVALID_PARAM
#define MAX_SESSION_KEYS
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define ACIP_DISCOVERY_DEFAULT_PORT
Discovery server default port (use OPT_ACDS_PORT_INT_DEFAULT from options.h).
Definition acds.h:1102
#define MS_PER_SEC_INT
Definition time.h:180
struct options_state options_t
Immutable, RCU-published snapshot of the application's runtime configuration.
const options_t * options_get(void)
Get pointer to current options struct (lock-free, thread-safe).
Definition rcu.c:513
asciichat_error_t acds_identity_load(const char *path, uint8_t public_key[32], uint8_t secret_key[64])
Load identity from file.
Definition identity.c:40
void acds_identity_fingerprint(const uint8_t public_key[32], char fingerprint[(32 *2+1)])
Compute SHA256 fingerprint of public key.
Definition identity.c:150
asciichat_error_t acds_identity_default_path(char *path_out, size_t path_size)
Get default identity file path for current platform.
Definition identity.c:172
asciichat_error_t acds_identity_save(const char *path, const uint8_t public_key[32], const uint8_t secret_key[64])
Save identity to file.
Definition identity.c:100
asciichat_error_t acds_identity_generate(uint8_t public_key[32], uint8_t secret_key[64])
Generate new Ed25519 keypair.
Definition identity.c:23
#define NOTICE(severity, title,...)
Definition notice.h:86
#define ED25519_PUBLIC_KEY_SIZE
Ed25519 public key size in bytes.
Definition sizes.h:38
#define HEX_STRING_SIZE_32
Hex string size for 32-byte values (64 hex chars + null terminator).
Definition sizes.h:163
#define ED25519_PRIVATE_KEY_SIZE
Ed25519 private key size (seed + public) in bytes.
Definition sizes.h:40
#define DISCOVERY_SESSION_IDENTITY_PATH_BUFFER_SIZE
When code needs to work with asciichat errno snapshot, it keeps total, copied here instead of scatter...
const char * acds_address
ACDS address (default: "127.0.0.1").
void(* on_error)(asciichat_error_t error, const char *message, void *user_data)
uint16_t acds_port
ACDS port (default: 27225).
const char * password
Session password (optional).
discovery_should_exit_fn should_exit_callback
void(* on_state_change)(discovery_state_t new_state, void *user_data)
const char * session_string
Session string to join (or NULL to create).
void(* on_session_ready)(const char *session_string, void *user_data)
Discovery session context.
uint8_t identity_pubkeys[MAX_SESSION_KEYS][ED25519_PUBLIC_KEY_SIZE]
uint8_t identity_pubkey[ED25519_PUBLIC_KEY_SIZE]
uint8_t identity_seckey[ED25519_PRIVATE_KEY_SIZE]
char password[ACIP_PASSWORD_SIZE]
uint8_t identity_seckeys[MAX_SESSION_KEYS][ED25519_PRIVATE_KEY_SIZE]
turn_server_t * turn_servers
TURN servers from ACDS.
size_t stun_count
Number of STUN servers.
void(* on_error)(asciichat_error_t error, const char *message, void *user_data)
size_t num_identity_keys
Number of identity keys loaded.
stun_server_t * stun_servers
STUN servers from ACDS.
void(* on_session_ready)(const char *session_string, void *user_data)
char session_string[SESSION_STRING_BUFFER_SIZE]
discovery_should_exit_fn should_exit_callback
size_t turn_count
Number of TURN servers.
acip_transport_t * acds_transport
Persistent transport for ACDS communication.
void(* on_state_change)(discovery_state_t new_state, void *user_data)
size_t num_identity_keys
Number of identity keys loaded (0 means single-key mode using encrypt_key).
Definition options.h:1183
char identity_keys[32][256]
All identity keys (populated when –key is used multiple times).
Definition options.h:1182
char encrypt_key[256]
SSH/GPG key file path (first –key flag, kept for compatibility).
Definition options.h:1172

References discovery_config_t::acds_address, discovery_session_t::acds_address, acds_identity_default_path(), acds_identity_fingerprint(), acds_identity_generate(), acds_identity_load(), acds_identity_save(), discovery_config_t::acds_port, discovery_session_t::acds_port, discovery_session_t::acds_transport, discovery_config_t::acds_url, discovery_session_t::acds_url, ACIP_DISCOVERY_DEFAULT_PORT, ASCIICHAT_ERRNO_HANDLED, ASCIICHAT_OK, atomic_store_u64(), discovery_config_t::callback_user_data, discovery_session_t::callback_user_data, host_liveness_t::consecutive_failures, DISCOVERY_SESSION_IDENTITY_PATH_BUFFER_SIZE, DISCOVERY_STATE_INIT, ED25519_PRIVATE_KEY_SIZE, ED25519_PUBLIC_KEY_SIZE, options_state::encrypt_key, errno_notifications_suppress(), errno_scope_begin(), errno_scope_end(), ERROR_CONFIG, ERROR_CRYPTO, ERROR_INVALID_PARAM, ERROR_MEMORY, discovery_config_t::exit_callback_data, discovery_session_t::exit_callback_data, discovery_session_t::handoff_generation, HEX_STRING_SIZE_32, discovery_session_t::host_ctx, options_state::identity_keys, discovery_session_t::identity_pubkey, discovery_session_t::identity_pubkeys, discovery_session_t::identity_seckey, discovery_session_t::identity_seckeys, discovery_session_t::is_initiator, host_liveness_t::last_ping_sent_ms, host_liveness_t::last_pong_received_ms, discovery_session_t::liveness, log_debug, log_info, log_warn, host_liveness_t::max_failures, MAX_SESSION_KEYS, MS_PER_SEC_INT, NAMED_REGISTER_ATOMIC, discovery_session_t::nat_quality_mutex, NOTICE, discovery_session_t::num_identity_keys, options_state::num_identity_keys, discovery_config_t::on_error, discovery_session_t::on_error, discovery_config_t::on_session_ready, discovery_session_t::on_session_ready, discovery_config_t::on_state_change, discovery_session_t::on_state_change, options_get(), discovery_session_t::participant_ctx, discovery_config_t::password, discovery_session_t::password, discovery_session_t::peer_manager, host_liveness_t::ping_in_flight, host_liveness_t::ping_interval_ms, platform_access(), SAFE_CALLOC, SAFE_FREE, SAFE_STRNCPY, discovery_config_t::session_string, discovery_session_t::session_string, SET_ERRNO, discovery_config_t::should_exit_callback, discovery_session_t::should_exit_callback, discovery_session_t::state, discovery_session_t::stun_count, discovery_session_t::stun_servers, host_liveness_t::timeout_ms, discovery_session_t::turn_count, discovery_session_t::turn_servers, discovery_session_t::webrtc_connection_initiated, discovery_session_t::webrtc_disconnected_since_ms, discovery_session_t::webrtc_last_attempt_time_ms, discovery_session_t::webrtc_retry_attempt, and discovery_session_t::webrtc_transport_ready.

Referenced by discovery_main().

◆ discovery_session_destroy()

asciichat_error_t discovery_session_destroy ( discovery_session_t * session)

Destroy discovery session and free resources.

Parameters
sessionSession to destroy

Definition at line 329 of file src/discovery/session.c.

329 {
330 ASCII_OTEL_SCOPE(DISCOVERY_SHUTDOWN);
331 if (!session) {
332 return SET_ERRNO(ERROR_INVALID_PARAM, "session is NULL");
333 }
334
335 asciichat_error_t result = release_participant_transport(session);
336 if (result != ASCIICHAT_OK)
337 return result;
338 // The detector borrows the session and mutex; retain both on a timed join
339 // failure.
340 if (session->nat_detection_thread_started) {
341 asciichat_error_t join_result = thread_join_timeout(
342 &session->nat_detection_thread, NULL, 500 * NS_PER_MS_INT);
343 if (join_result != ASCIICHAT_OK)
344 return SET_ERRNO(ERROR_THREAD,
345 "NAT detection worker still owns discovery session");
346 session->nat_detection_thread_started = false;
347 }
348 release_host_control_transport(session);
349
350 // Close ACDS connection
351 if (session->acds_transport) {
353 session->acds_transport = NULL;
354 }
355
356 // Destroy host context if active
357 if (session->host_ctx) {
358 asciichat_error_t host_result = session_host_destroy(session->host_ctx);
359 if (host_result != ASCIICHAT_OK)
360 return host_result;
361 session->host_ctx = NULL;
362 }
363
364 // Destroy participant context if active
365 if (session->participant_ctx) {
367 session->participant_ctx = NULL;
368 }
369
370 // Clean up WebRTC peer manager (NEW)
371 if (session->peer_manager) {
373 session->peer_manager = NULL;
374 }
375
376 // Clean up STUN/TURN server arrays (NEW)
377 if (session->stun_servers) {
378 SAFE_FREE(session->stun_servers);
379 session->stun_servers = NULL;
380 session->stun_count = 0;
381 }
382
383 if (session->turn_servers) {
384 SAFE_FREE(session->turn_servers);
385 session->turn_servers = NULL;
386 session->turn_count = 0;
387 }
388
389 // Destroy NAT quality mutex
390 mutex_destroy(&session->nat_quality_mutex);
391
393 sodium_memzero(session->password, sizeof(session->password));
394 sodium_memzero(session->identity_seckey, sizeof(session->identity_seckey));
395 sodium_memzero(session->identity_seckeys, sizeof(session->identity_seckeys));
396 SAFE_FREE(session);
397 return ASCIICHAT_OK;
398}
#define NAMED_UNREGISTER(ptr)
Unregister a pointer.
@ ERROR_THREAD
#define NS_PER_MS_INT
Definition time.h:172
void network_connection_destroy(network_connection_t **owner)
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
platform_thread_t nat_detection_thread
network_connection_t * acds_connection

References discovery_session_t::acds_connection, discovery_session_t::acds_transport, ASCII_OTEL_SCOPE, ASCIICHAT_OK, ERROR_INVALID_PARAM, ERROR_THREAD, discovery_session_t::host_ctx, discovery_session_t::identity_seckey, discovery_session_t::identity_seckeys, host_liveness_t::last_pong_received_ms, discovery_session_t::liveness, NAMED_UNREGISTER, discovery_session_t::nat_detection_thread, discovery_session_t::nat_detection_thread_started, discovery_session_t::nat_quality_mutex, network_connection_destroy(), NS_PER_MS_INT, discovery_session_t::participant_ctx, discovery_session_t::password, discovery_session_t::peer_manager, SAFE_FREE, session_host_destroy(), session_participant_destroy(), SET_ERRNO, discovery_session_t::stun_count, discovery_session_t::stun_servers, discovery_session_t::turn_count, discovery_session_t::turn_servers, and webrtc_peer_manager_destroy().

Referenced by discovery_main().

◆ discovery_session_get_host()

session_host_t * discovery_session_get_host ( discovery_session_t * session)

Get host context (if we are host).

Parameters
sessionSession context
Returns
Host context or NULL

Definition at line 2550 of file src/discovery/session.c.

2550 {
2551 if (!session) {
2552 SET_ERRNO(ERROR_INVALID_PARAM, "null session");
2553 return NULL;
2554 }
2555 return session->host_ctx;
2556}

References ERROR_INVALID_PARAM, discovery_session_t::host_ctx, and SET_ERRNO.

◆ discovery_session_get_participant()

session_participant_t * discovery_session_get_participant ( discovery_session_t * session)

Get participant context (if we are participant).

Parameters
sessionSession context
Returns
Participant context or NULL

Definition at line 2559 of file src/discovery/session.c.

2559 {
2560 if (!session) {
2561 SET_ERRNO(ERROR_INVALID_PARAM, "null session");
2562 return NULL;
2563 }
2564 return session->participant_ctx;
2565}

References ERROR_INVALID_PARAM, discovery_session_t::participant_ctx, and SET_ERRNO.

◆ discovery_session_get_state()

discovery_state_t discovery_session_get_state ( const discovery_session_t * session)

Get current session state.

Parameters
sessionSession context
Returns
Current state

Definition at line 2518 of file src/discovery/session.c.

2518 {
2519 if (!session) {
2520 SET_ERRNO(ERROR_INVALID_PARAM, "null session");
2522 }
2523 return session->state;
2524}

References DISCOVERY_STATE_FAILED, ERROR_INVALID_PARAM, SET_ERRNO, and discovery_session_t::state.

◆ discovery_session_get_string()

const char * discovery_session_get_string ( const discovery_session_t * session)

Get session string.

Parameters
sessionSession context
Returns
Session string or NULL if not yet assigned

Definition at line 2534 of file src/discovery/session.c.

2534 {
2535 if (!session || session->session_string[0] == '\0') {
2536 SET_ERRNO(ERROR_INVALID_PARAM, "null session or session string is empty");
2537 return NULL;
2538 }
2539 return session->session_string;
2540}

References ERROR_INVALID_PARAM, discovery_session_t::session_string, and SET_ERRNO.

◆ discovery_session_handle_host_disconnect()

asciichat_error_t discovery_session_handle_host_disconnect ( discovery_session_t * session,
uint32_t disconnect_reason )

Report host disconnect and await the ACDS recovery decision.

Parameters
sessionSession context
disconnect_reasonReason code for disconnect
Returns
ASCIICHAT_OK if the host loss report was sent

Report host disconnect and await the ACDS recovery decision.

Returns
ASCIICHAT_OK if the report was sent; a send error also fails the session.

Definition at line 2676 of file src/discovery/session.c.

2677 {
2678 if (!session) {
2679 SET_ERRNO(ERROR_INVALID_PARAM, "session is NULL");
2680 return ERROR_INVALID_PARAM;
2681 }
2682
2683 log_warn("Host disconnect detected: reason=%u", disconnect_reason);
2684
2685 session->host_loss_detected_ms = session_get_current_time_ms();
2686
2687 // Notify ACDS of host loss (lightweight notification, no NAT data exchanged!)
2688 acip_host_lost_t host_lost = {0};
2689 memcpy(host_lost.session_id, session->session_id, SESSION_ID_SIZE);
2690 memcpy(host_lost.participant_id, session->participant_id, SESSION_ID_SIZE);
2691 memcpy(host_lost.last_host_id, session->host_id, SESSION_ID_SIZE);
2692 host_lost.disconnect_reason = disconnect_reason;
2693 host_lost.disconnect_time_ms = session->host_loss_detected_ms;
2694
2696 session->acds_transport, PACKET_TYPE_ACIP_HOST_LOST, &host_lost,
2697 sizeof(host_lost), 0);
2698 if (result != ASCIICHAT_OK) {
2699 set_error(session, result, "Could not report host loss to ACDS");
2700 return result;
2701 }
2702
2703 // A PLAN is advisory. Only ACDS COMMIT authorizes a role change after fresh
2704 // measurement and preparation. Continue dispatching while awaiting that
2705 // decision.
2706 set_state(session, DISCOVERY_STATE_MIGRATING);
2707
2708 return ASCIICHAT_OK;
2709}
acip_host_lost_t
Definition acds.h:961
@ PACKET_TYPE_ACIP_HOST_LOST
Host lost notification - lightweight (Participant -> ACDS).
Definition packet.h:503
asciichat_error_t packet_send_via_transport(acip_transport_t *transport, packet_type_t type, const void *payload, size_t payload_len, uint32_t client_id)
Definition send.c:183
uint8_t session_id[SESSION_ID_SIZE]

References discovery_session_t::acds_transport, acip_host_lost_t, ASCIICHAT_OK, DISCOVERY_STATE_MIGRATING, ERROR_INVALID_PARAM, discovery_session_t::host_id, discovery_session_t::host_loss_detected_ms, log_warn, packet_send_via_transport(), PACKET_TYPE_ACIP_HOST_LOST, discovery_session_t::participant_id, discovery_session_t::session_id, SESSION_ID_SIZE, and SET_ERRNO.

◆ discovery_session_host_pong()

void discovery_session_host_pong ( discovery_session_t * session)

Record a host reply using the same clock as liveness deadlines.

Definition at line 2567 of file src/discovery/session.c.

2567 {
2568 if (session)
2570 session_get_current_time_ms());
2571}

References atomic_store_u64(), host_liveness_t::last_pong_received_ms, and discovery_session_t::liveness.

◆ discovery_session_is_active()

bool discovery_session_is_active ( const discovery_session_t * session)

Check if session is active (call in progress).

Parameters
sessionSession context
Returns
True if active

Definition at line 2526 of file src/discovery/session.c.

2526 {
2527 if (!session) {
2528 SET_ERRNO(ERROR_INVALID_PARAM, "null session");
2529 return false;
2530 }
2531 return session->state == DISCOVERY_STATE_ACTIVE;
2532}

References DISCOVERY_STATE_ACTIVE, ERROR_INVALID_PARAM, SET_ERRNO, and discovery_session_t::state.

◆ discovery_session_is_host()

bool discovery_session_is_host ( const discovery_session_t * session)

Check if we are the host.

Parameters
sessionSession context
Returns
True if we are hosting

Definition at line 2542 of file src/discovery/session.c.

2542 {
2543 if (!session) {
2544 SET_ERRNO(ERROR_INVALID_PARAM, "null session");
2545 return false;
2546 }
2547 return session->is_host;
2548}

References ERROR_INVALID_PARAM, discovery_session_t::is_host, and SET_ERRNO.

◆ discovery_session_process()

asciichat_error_t discovery_session_process ( discovery_session_t * session,
int64_t timeout_ns )

Process session events (call in main loop).

Handles incoming ACDS messages, negotiation, and state transitions.

Parameters
sessionSession context
timeout_nsMax time to wait for events in nanoseconds (0 = non-blocking)
Returns
ASCIICHAT_OK on success, error on failure

Definition at line 2422 of file src/discovery/session.c.

2423 {
2424 if (!session) {
2425 return SET_ERRNO(ERROR_INVALID_PARAM, "session is NULL");
2426 }
2427
2428 // Transport callbacks publish readiness; ownership changes and worker joins
2429 // execute here on the session's controlling thread.
2430 asciichat_error_t result =
2432 if (result != ASCIICHAT_OK)
2433 return result;
2434
2435 result = discovery_session_send_keepalive(session);
2436 if (result != ASCIICHAT_OK) {
2437 return result;
2438 }
2439
2440 if (session->state == DISCOVERY_STATE_ACTIVE ||
2442 session->state == DISCOVERY_STATE_MIGRATING) {
2443 result = discovery_handoff_sample(session);
2444 if (result != ASCIICHAT_OK)
2445 return result;
2446 }
2447
2448 // State handlers preserve deferred failures: recording a failed state does
2449 // not necessarily return an error until the next iteration processes that
2450 // state.
2451 switch (session->state) {
2453 return discovery_session_wait_for_peer(session, timeout_ns);
2455 return discovery_session_negotiate(session);
2457 return discovery_session_start_host(session);
2459 return session->session_type == SESSION_TYPE_WEBRTC
2460 ? discovery_session_connect_webrtc(session)
2461 : discovery_session_connect_tcp(session);
2463 return discovery_session_process_active(session, timeout_ns);
2465 return discovery_session_process_migration(session, timeout_ns);
2467 // Session has failed - return error on further processing
2468 return session->error != ASCIICHAT_OK ? session->error : ERROR_NETWORK;
2469
2471 // Session has ended gracefully - return OK
2472 return ASCIICHAT_OK;
2473
2478 // These states are handled during discovery_session_start(), not in the
2479 // process loop If we reach here, something went wrong - sleep and wait
2480 log_debug("State %d should be handled by discovery_session_start",
2481 session->state);
2482 discovery_sleep_ns(timeout_ns);
2483 break;
2484
2485 default:
2486 return SET_ERRNO(ERROR_INVALID_STATE, "Invalid session state: %d",
2487 session->state);
2488 }
2489
2490 return ASCIICHAT_OK;
2491}
@ ERROR_INVALID_STATE
asciichat_error_t webrtc_peer_manager_dispatch_ready(webrtc_peer_manager_t *manager)

References ASCIICHAT_OK, DISCOVERY_STATE_ACTIVE, DISCOVERY_STATE_CONNECTING_ACDS, DISCOVERY_STATE_CONNECTING_HOST, DISCOVERY_STATE_CREATING_SESSION, DISCOVERY_STATE_ENDED, DISCOVERY_STATE_FAILED, DISCOVERY_STATE_INIT, DISCOVERY_STATE_JOINING_SESSION, DISCOVERY_STATE_MIGRATING, DISCOVERY_STATE_NEGOTIATING, DISCOVERY_STATE_STARTING_HOST, DISCOVERY_STATE_WAITING_PEER, discovery_session_t::error, ERROR_INVALID_PARAM, ERROR_INVALID_STATE, ERROR_NETWORK, log_debug, discovery_session_t::peer_manager, discovery_session_t::session_type, SESSION_TYPE_WEBRTC, SET_ERRNO, discovery_session_t::state, and webrtc_peer_manager_dispatch_ready().

◆ discovery_session_start()

asciichat_error_t discovery_session_start ( discovery_session_t * session)

Start the discovery session.

Connects to ACDS and either creates or joins a session.

Parameters
sessionSession context
Returns
ASCIICHAT_OK on success

Definition at line 1731 of file src/discovery/session.c.

1731 {
1732 log_info("session=%p", session);
1733
1734 if (!session) {
1735 return SET_ERRNO(ERROR_INVALID_PARAM, "session is NULL");
1736 }
1737
1738 log_info("is_initiator=%d, session_string='%s'", session->is_initiator,
1739 session->session_string);
1740
1741 // Check if we should exit before starting blocking operations
1742 if (session->should_exit_callback &&
1743 session->should_exit_callback(session->exit_callback_data)) {
1744 log_info("Exiting early due to should_exit_callback (before ACDS connect)");
1745 return ASCIICHAT_OK; // Return success to allow clean shutdown
1746 }
1747
1748 log_info("Calling connect_to_acds...");
1749 // Connect to ACDS
1750 asciichat_error_t result = connect_to_acds(session);
1751 if (result != ASCIICHAT_OK) {
1752 log_error("connect_to_acds FAILED %s",
1753 asciichat_error_format(NULL, result));
1754 set_state(session, DISCOVERY_STATE_FAILED);
1755 return result;
1756 }
1757 log_info("connect_to_acds succeeded");
1758
1759 // Check again after connection
1760 if (session->should_exit_callback &&
1761 session->should_exit_callback(session->exit_callback_data)) {
1762 log_info("Exiting early due to should_exit_callback (after ACDS connect)");
1763 return ASCIICHAT_OK; // Return success to allow clean shutdown
1764 }
1765
1767
1768 // Perform crypto handshake with ACDS (same as client-server handshake)
1769 log_info("Performing crypto handshake with ACDS...");
1770 crypto_handshake_context_t *handshake_ctx =
1772
1773 result = crypto_handshake_init("discovery_client", handshake_ctx, false);
1774 if (result != ASCIICHAT_OK) {
1775 log_error("Handshake init failed - %s",
1776 asciichat_error_format(NULL, result));
1777 set_error(session, result, "Crypto handshake init failed");
1778 return result;
1779 }
1780
1781 bool has_identity = memcmp(session->identity_pubkey, (uint8_t[32]){0},
1783 // Store identity key in handshake context
1784 handshake_ctx->client_public_key.type =
1785 has_identity ? KEY_TYPE_ED25519 : KEY_TYPE_UNKNOWN;
1786 handshake_ctx->client_private_key.type =
1787 handshake_ctx->client_public_key.type;
1788 memcpy(handshake_ctx->client_public_key.key, session->identity_pubkey,
1790 memcpy(handshake_ctx->client_private_key.key.ed25519,
1792 memcpy(handshake_ctx->client_private_key.public_key, session->identity_pubkey,
1793 sizeof(session->identity_pubkey));
1794
1795 crypto_policy_t signaling_policy = {
1796 .transport_secure = strncmp(session->acds_url, "wss://", 6) == 0,
1797 .has_identity = has_identity,
1798 };
1799 uint8_t mode;
1800 result = crypto_policy_resolve(&signaling_policy, &mode);
1801 if (result == ASCIICHAT_OK)
1802 result = network_client_negotiate(session->acds_transport, handshake_ctx,
1804 if (result != ASCIICHAT_OK) {
1805 set_error(session, result, "Discovery handshake failed");
1806 return result;
1807 }
1808
1809 // Check again after handshake
1810 if (session->should_exit_callback &&
1811 session->should_exit_callback(session->exit_callback_data)) {
1812 log_info("Exiting early due to should_exit_callback (after handshake)");
1813 return ASCIICHAT_OK; // Return success to allow clean shutdown
1814 }
1815
1816 // Create or join session
1817 if (session->is_initiator) {
1818 log_info("Calling create_session - participant_ctx before=%p",
1819 session->participant_ctx);
1820 result = create_session(session);
1821 log_info("create_session returned - participant_ctx after=%p, result=%d",
1822 session->participant_ctx, result);
1823
1824 if (result == ASCIICHAT_OK) {
1825 // Initiator also needs to register itself as a participant so it can
1826 // receive PARTICIPANT_JOINED notifications when other peers join. This
1827 // makes the initiator discoverable to other participants.
1828 log_info(
1829 "Initiator: now registering self as participant in created session");
1830 result = join_session(session);
1831 log_info("Initiator: join_session result=%d", result);
1832 }
1833 return result;
1834 } else {
1835 log_info("Calling join_session - participant_ctx before=%p",
1836 session->participant_ctx);
1837 asciichat_error_t join_result = join_session(session);
1838 log_info(
1839 "join_session returned - participant_ctx after=%p, state=%d, result=%d",
1840 session->participant_ctx, session->state, join_result);
1841 return join_result;
1842 }
1843}
const char * asciichat_error_format(const char *message, asciichat_error_t code)
asciichat_error_t crypto_handshake_init(const char *name, crypto_handshake_context_t *ctx, bool is_server)
Initialize named crypto handshake context.
uint8_t key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:85
uint8_t ed25519[ED25519_PRIVATE_KEY_SIZE]
Definition key_types.h:116
key_type_t type
Definition key_types.h:114
uint8_t public_key[CRYPTO_PUBLIC_KEY_SIZE]
Definition key_types.h:124
key_type_t type
Definition key_types.h:84
union private_key_t::@040247167361101132173265304166142033301213115260 key
@ KEY_TYPE_UNKNOWN
Definition key_types.h:60
@ KEY_TYPE_ED25519
Definition key_types.h:61
#define NS_PER_SEC_INT
Definition time.h:173
crypto_handshake_context_t * network_connection_handshake(network_connection_t *c)
asciichat_error_t network_client_negotiate(acip_transport_t *transport, crypto_handshake_context_t *ctx, uint8_t mode, network_protocol_t protocol)
@ NETWORK_PROTOCOL_DISCOVERY
Definition negotiation.h:11
asciichat_error_t crypto_policy_resolve(const crypto_policy_t *policy, uint8_t *mode)
Definition policy.c:4
uint64_t receive_timeout_ns
Optional TCP receive timeout override; zero uses the normal polling timeout.
Cryptographic handshake context structure.
The useful part of crypto policy is in transport_secure, encrypt, no_encrypt, no_auth: together they ...
Definition policy.h:19

References discovery_session_t::acds_connection, discovery_session_t::acds_transport, discovery_session_t::acds_url, asciichat_error_format(), ASCIICHAT_OK, crypto_handshake_context_t::client_private_key, crypto_handshake_context_t::client_public_key, crypto_handshake_init(), crypto_policy_resolve(), DISCOVERY_STATE_FAILED, private_key_t::ed25519, ED25519_PRIVATE_KEY_SIZE, ED25519_PUBLIC_KEY_SIZE, ERROR_INVALID_PARAM, discovery_session_t::exit_callback_data, discovery_session_t::identity_pubkey, discovery_session_t::identity_seckey, discovery_session_t::is_initiator, private_key_t::key, public_key_t::key, KEY_TYPE_ED25519, KEY_TYPE_UNKNOWN, log_error, log_info, network_client_negotiate(), network_connection_handshake(), NETWORK_PROTOCOL_DISCOVERY, NS_PER_SEC_INT, discovery_session_t::participant_ctx, private_key_t::public_key, acip_transport::receive_timeout_ns, discovery_session_t::session_string, SET_ERRNO, discovery_session_t::should_exit_callback, discovery_session_t::state, private_key_t::type, and public_key_t::type.

◆ discovery_session_stop()

void discovery_session_stop ( discovery_session_t * session)

Stop the discovery session.

Parameters
sessionSession context

Definition at line 2493 of file src/discovery/session.c.

2493 {
2494 ASCII_OTEL_SCOPE(DISCOVERY_SHUTDOWN);
2495 if (!session) {
2496 SET_ERRNO(ERROR_INVALID_PARAM, "session is NULL");
2497 return;
2498 }
2499
2500 log_info("Stopping discovery session...");
2501
2502 // Send SESSION_LEAVE if connected
2503 if (session->acds_transport && session->session_id[0] != 0) {
2504 acip_session_leave_t leave_msg;
2505 memset(&leave_msg, 0, sizeof(leave_msg));
2506 memcpy(leave_msg.session_id, session->session_id, SESSION_ID_SIZE);
2507 memcpy(leave_msg.participant_id, session->participant_id, SESSION_ID_SIZE);
2508
2511 sizeof(leave_msg), 0);
2512 }
2513
2514 set_state(session, DISCOVERY_STATE_ENDED);
2515}
acip_session_leave_t
Definition acds.h:529
@ PACKET_TYPE_ACIP_SESSION_LEAVE
Leave session (Client -> Discovery Server).
Definition packet.h:457

References discovery_session_t::acds_transport, acip_session_leave_t, ASCII_OTEL_SCOPE, DISCOVERY_STATE_ENDED, ERROR_INVALID_PARAM, log_info, packet_send_via_transport(), PACKET_TYPE_ACIP_SESSION_LEAVE, discovery_session_t::participant_id, discovery_session_t::session_id, SESSION_ID_SIZE, and SET_ERRNO.

Referenced by discovery_main().