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

Parallel IPv4/IPv6 connection with race-to-connect semantics. More...

Go to the source code of this file.

Data Structures

struct  parallel_connect_config_t

Typedefs

typedef bool(* parallel_connect_should_exit_fn) (void *user_data)
 When code needs to work with parallel connect config, it keeps hostname, port, timeout_ms, should_exit_callback 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.

Functions

asciichat_error_t parallel_connect (const parallel_connect_config_t *config, socket_t *out_socket)

Detailed Description

Parallel IPv4/IPv6 connection with race-to-connect semantics.

Attempts IPv4 and IPv6 connections in parallel and returns the first successful socket, closing the loser. Handles unreachable addresses gracefully without blocking on timeouts.

Definition in file parallel_connect.h.

Typedef Documentation

◆ parallel_connect_should_exit_fn

typedef bool(* parallel_connect_should_exit_fn) (void *user_data)

When code needs to work with parallel connect config, it keeps hostname, port, timeout_ms, should_exit_callback 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.

Callback type to check if connection should be abandoned

Called periodically by connection threads to allow graceful shutdown. Should return true if connection attempts should stop immediately.

Parameters
user_dataOpaque pointer provided by caller
Returns
true to abandon connection attempts, false to continue

Definition at line 35 of file parallel_connect.h.

Function Documentation

◆ parallel_connect()

asciichat_error_t parallel_connect ( const parallel_connect_config_t * config,
socket_t * out_socket )

Connect to hostname with parallel IPv4/IPv6 attempts

Resolves hostname and attempts IPv4 and IPv6 connections in parallel. Returns the first successful socket; the losing connection is closed. Each connection attempt is non-blocking with select() timeout.

Parameters
configConnection configuration
out_socketPointer to receive winning socket
Returns
ASCIICHAT_OK on success, ERROR_* on failure
Note
Caller is responsible for closing the returned socket
Timeout applies to each connection attempt independently

Definition at line 202 of file parallel_connect.c.

203 {
204 ASCII_OTEL_SCOPE(PARALLEL_CONNECT);
205 if (!config || !out_socket) {
206 return SET_ERRNO(ERROR_INVALID_PARAM, "config or out_socket is NULL");
207 }
208
209 *out_socket = INVALID_SOCKET_VALUE;
210
211 char ascii_hostname[HOSTNAME_BUFFER_SIZE];
213 config->hostname, ascii_hostname, sizeof(ascii_hostname));
214 if (normalized != ASCIICHAT_OK)
215 return normalized;
216
217 // Resolve hostname
218 log_debug("PCONN: Resolving %s:%d", config->hostname, config->port);
219
220 struct addrinfo hints;
221 struct addrinfo *result = NULL;
222 memset(&hints, 0, sizeof(hints));
223 hints.ai_family = AF_UNSPEC;
224 hints.ai_socktype = SOCK_STREAM;
225
227 safe_snprintf(port_str, sizeof(port_str), "%d", config->port);
228
229 int gai_result;
230 {
231 ASCII_OTEL_SCOPE_AS(dns_scope, DNS_RESOLVE);
232 if (dns_scope.retained)
233 gotel_attr_string(&dns_scope.scope, "dns.question.name",
234 config->hostname);
235 gai_result = getaddrinfo(ascii_hostname, port_str, &hints, &result);
236 if (gai_result && dns_scope.retained)
237 gotel_error(&dns_scope.scope, "dns.error", "DNS lookup failed");
238 }
239 if (gai_result != 0) {
240 return SET_ERRNO(ERROR_NETWORK, "Failed to resolve %s: %s",
241 config->hostname, gai_strerror(gai_result));
242 }
243
244 // Find first IPv4 and IPv6 addresses
245 struct addrinfo *ipv4_addr = NULL;
246 struct addrinfo *ipv6_addr = NULL;
247
248 for (struct addrinfo *rp = result; rp != NULL; rp = rp->ai_next) {
249 if (rp->ai_family == AF_INET && !ipv4_addr) {
250 ipv4_addr = rp;
251 log_debug("PCONN: Found IPv4 address");
252 } else if (rp->ai_family == AF_INET6 && !ipv6_addr) {
253 ipv6_addr = rp;
254 log_debug("PCONN: Found IPv6 address");
255 }
256 if (ipv4_addr && ipv6_addr)
257 break;
258 }
259
260 // Need at least one address
261 if (!ipv4_addr && !ipv6_addr) {
262 freeaddrinfo(result);
263 return SET_ERRNO(ERROR_NETWORK, "No IPv4 or IPv6 addresses found for %s",
264 config->hostname);
265 }
266
267 // Shared state
268 mutex_t lock;
269 cond_t signal;
270 mutex_init(&lock, "parallel_connect");
271 cond_init(&signal, "parallel_connect");
272
273 volatile socket_t winner_socket = INVALID_SOCKET_VALUE;
274 volatile bool winner_found = false;
275
276 // An unavailable address family never starts a worker. Its cleanup must not
277 // close descriptor zero, which can subsequently be reused by the event loop.
278 connection_attempt_t ipv4_attempt = {.socket = INVALID_SOCKET_VALUE};
279 connection_attempt_t ipv6_attempt = {.socket = INVALID_SOCKET_VALUE};
280 platform_thread_t ipv4_thread;
281 platform_thread_t ipv6_thread;
282
283 thread_init(&ipv4_thread);
284 thread_init(&ipv6_thread);
285
286 // Start IPv4 attempt if available
287 if (ipv4_addr) {
288 ipv4_attempt.family = AF_INET;
289 ipv4_attempt.family_name = "IPv4";
290 ipv4_attempt.timeout_ms = config->timeout_ms;
291 ipv4_attempt.winner_socket = &winner_socket;
292 ipv4_attempt.winner_found = &winner_found;
293 ipv4_attempt.lock = &lock;
294 ipv4_attempt.signal = &signal;
295 ipv4_attempt.should_exit_callback = config->should_exit_callback;
296 ipv4_attempt.callback_data = config->callback_data;
297 memcpy(&ipv4_attempt.addr, ipv4_addr->ai_addr, ipv4_addr->ai_addrlen);
298 ipv4_attempt.addr_len = (socklen_t)ipv4_addr->ai_addrlen;
299
300 platform_thread_create(&ipv4_thread, "connect_ipv4",
301 attempt_connection_thread, &ipv4_attempt);
302 }
303
304 // Start IPv6 attempt if available
305 if (ipv6_addr) {
306 ipv6_attempt.family = AF_INET6;
307 ipv6_attempt.family_name = "IPv6";
308 ipv6_attempt.timeout_ms = config->timeout_ms;
309 ipv6_attempt.winner_socket = &winner_socket;
310 ipv6_attempt.winner_found = &winner_found;
311 ipv6_attempt.lock = &lock;
312 ipv6_attempt.signal = &signal;
313 ipv6_attempt.should_exit_callback = config->should_exit_callback;
314 ipv6_attempt.callback_data = config->callback_data;
315 memcpy(&ipv6_attempt.addr, ipv6_addr->ai_addr, ipv6_addr->ai_addrlen);
316 ipv6_attempt.addr_len = (socklen_t)ipv6_addr->ai_addrlen;
317
318 platform_thread_create(&ipv6_thread, "connect_ipv6",
319 attempt_connection_thread, &ipv6_attempt);
320 }
321
322 // Wait for winner or both to finish
323 uint32_t max_wait_ms = config->timeout_ms + 1000;
324 uint32_t elapsed_ms = 0;
325
326 mutex_lock(&lock);
327 while (!winner_found && elapsed_ms < max_wait_ms) {
328 cond_timedwait(&signal, &lock, 100 * NS_PER_MS_INT);
329 elapsed_ms += 100;
330
331 // Check if both are done
332 if (ipv4_addr && ipv6_addr) {
333 if (ipv4_attempt.done && ipv6_attempt.done) {
334 break;
335 }
336 } else if ((ipv4_addr && ipv4_attempt.done) ||
337 (ipv6_addr && ipv6_attempt.done)) {
338 break;
339 }
340 }
341 mutex_unlock(&lock);
342
343 // Join threads (must wait for both to complete before returning)
344 // The threads access shared state on our stack, so we cannot return until
345 // they're done
346 if (thread_is_initialized(&ipv4_thread)) {
347 thread_join(&ipv4_thread, NULL);
348 }
349 if (thread_is_initialized(&ipv6_thread)) {
350 thread_join(&ipv6_thread, NULL);
351 }
352
353 // Close any remaining sockets
354 if (ipv4_attempt.socket != INVALID_SOCKET_VALUE) {
355 socket_close(ipv4_attempt.socket);
356 }
357 if (ipv6_attempt.socket != INVALID_SOCKET_VALUE) {
358 socket_close(ipv6_attempt.socket);
359 }
360
361 // Cleanup
362 mutex_destroy(&lock);
363 cond_destroy(&signal);
364 freeaddrinfo(result);
365
366 // Check result
367 if (winner_socket == INVALID_SOCKET_VALUE) {
369 "Failed to connect to %s:%d (both IPv4 and IPv6 failed)",
370 config->hostname, config->port);
371 }
372
373 *out_socket = (socket_t)winner_socket;
374 log_info("PCONN: Successfully connected to %s:%d", config->hostname,
375 config->port);
376 return ASCIICHAT_OK;
377}
#define SET_ERRNO(code,...)
unsigned int uint32_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_NETWORK
Definition error_codes.h:77
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define HOSTNAME_BUFFER_SIZE
#define log_info(...)
Log an INFO message.
Definition log/log.h:578
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:565
#define NS_PER_MS_INT
Definition time.h:172
asciichat_error_t hostname_to_ascii(const char *hostname, char *output, size_t capacity)
Definition url.c:109
int socket_t
int socket_close(socket_t)
#define ASCII_OTEL_SCOPE_AS(variable, id)
Definition otel.h:106
#define ASCII_OTEL_SCOPE(id)
Definition otel.h:102
#define NETWORK_PARALLEL_CONNECT_PORT_BUFFER_SIZE
Per-thread connection attempt state for parallel IPv4/IPv6 racing.
volatile bool done
True if this attempt finished.
volatile bool * winner_found
Shared flag indicating a winner exists.
int family
Address family (AF_INET or AF_INET6).
socklen_t addr_len
Length of address structure.
void * callback_data
User data for callback.
mutex_t * lock
Shared mutex for coordination.
parallel_connect_should_exit_fn should_exit_callback
Optional exit callback for graceful shutdown.
const char * family_name
Human-readable family name ("IPv4"/"IPv6").
uint32_t timeout_ms
Connection timeout in milliseconds.
socket_t socket
Socket for this attempt.
cond_t * signal
Shared condition variable for signaling.
struct sockaddr_storage addr
Socket address to connect to.
volatile socket_t * winner_socket
Shared pointer to winning socket.
parallel_connect_should_exit_fn should_exit_callback

References connection_attempt_t::addr, connection_attempt_t::addr_len, ASCII_OTEL_SCOPE, ASCII_OTEL_SCOPE_AS, ASCIICHAT_OK, connection_attempt_t::callback_data, parallel_connect_config_t::callback_data, connection_attempt_t::done, ERROR_INVALID_PARAM, ERROR_NETWORK, connection_attempt_t::family, connection_attempt_t::family_name, parallel_connect_config_t::hostname, HOSTNAME_BUFFER_SIZE, hostname_to_ascii(), connection_attempt_t::lock, log_debug, log_info, NETWORK_PARALLEL_CONNECT_PORT_BUFFER_SIZE, NS_PER_MS_INT, parallel_connect_config_t::port, SET_ERRNO, connection_attempt_t::should_exit_callback, parallel_connect_config_t::should_exit_callback, connection_attempt_t::signal, connection_attempt_t::socket, socket_close(), connection_attempt_t::timeout_ms, parallel_connect_config_t::timeout_ms, connection_attempt_t::winner_found, and connection_attempt_t::winner_socket.