ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
lib/network/network.c
Go to the documentation of this file.
1
7
9#include <ascii-chat/common.h>
11#include <libplatform/socket.h>
12#include <stdint.h>
13#include <errno.h>
14#include <stdbool.h>
15#include <stdio.h>
16#include <stdlib.h>
17#include <string.h>
18#include <libplatform/atomic.h>
19#ifndef _WIN32
20#include <sys/time.h>
21#endif
22
23/* ============================================================================
24 * Core Network I/O Operations
25 * ============================================================================
26 * This module provides the fundamental network I/O operations including
27 * socket management, timeouts, and basic send/receive operations.
28 */
29
30// Use network_network_is_test_environment() from network.h
31
37static int network_handle_send_error(int error) {
38 if (error == EAGAIN || error == EWOULDBLOCK) {
39 return 1; // Retry
40 }
41 if (error == EPIPE) {
42 SET_ERRNO_SYS(ERROR_NETWORK, "Connection closed by peer during send");
43 return 0; // Fatal
44 }
45 SET_ERRNO_SYS(ERROR_NETWORK, "send_with_timeout failed: %s", socket_get_error_string());
46 return 0; // Fatal
47}
48
54static int network_handle_recv_error(int error) {
55 // Check for "would block" - retry operation
56 if (socket_is_would_block_error(error)) {
57 return 1; // Retry
58 }
59
60 // Check for signal interruption - recoverable, retry
61 if (error == EINTR) {
62 log_debug("recv interrupted by signal, retrying");
63 return 1; // Retry
64 }
65
66 // Check for invalid/closed socket - fatal
68 SET_ERRNO_SYS(ERROR_NETWORK, "Socket is not a socket (closed by another thread)");
69 return 0; // Fatal
70 }
71
72 SET_ERRNO_SYS(ERROR_NETWORK, "recv_with_timeout failed: %s", socket_get_error_string());
73 return 0; // Fatal
74}
75
81static int network_handle_select_error(int result) {
82 if (result == 0) {
83 // Timeout - this is expected behavior for server waiting for connections
84 errno_set_with_system_error(ERROR_NETWORK_TIMEOUT, __FILE__, __LINE__, __func__, ETIMEDOUT);
85 return 0; // Not an error, but don't retry
86 }
87
88 // Get error code (cross-platform)
89 int error = socket_get_last_error();
90
91 // Check for signal interruption - recoverable, retry
92 if (error == EINTR) {
93 log_debug("select interrupted by signal, retrying");
94 return 1; // Retry
95 }
96
98 return 0; // Fatal
99}
100
109ssize_t send_with_timeout(socket_t sockfd, const void *data, size_t len, uint64_t timeout_ns) {
110 if (sockfd == INVALID_SOCKET_VALUE) {
111 errno = EBADF;
112 return -1;
113 }
114
115 size_t total_sent = 0;
116 const char *data_ptr = (const char *)data;
117
118 while (total_sent < len) {
119 // Calculate chunk size
120 size_t bytes_to_send = len - total_sent;
121 const size_t MAX_CHUNK_SIZE = 65536; // 64KB chunks for reliable TCP transmission
122 if (bytes_to_send > MAX_CHUNK_SIZE) {
123 bytes_to_send = MAX_CHUNK_SIZE;
124 }
125
126 // Set up poll for write timeout (in nanoseconds)
127 struct pollfd pfd;
128 pfd.fd = sockfd;
129 pfd.events = POLLOUT;
130 pfd.revents = 0;
131
132 int64_t effective_timeout_ns = network_is_test_environment() ? (100LL * NS_PER_MS_INT) : (int64_t)timeout_ns;
133 int result = socket_poll(&pfd, 1, effective_timeout_ns);
134 if (result <= 0) {
135 if (result == 0) {
136 SET_ERRNO_SYS(ERROR_NETWORK_TIMEOUT, "timed out after %llu nanoseconds", (unsigned long long)timeout_ns);
137 return -1;
138 }
139 if (network_handle_select_error(result)) {
140 continue; // Retry
141 }
142 return -1; // Fatal error
143 }
144
145 // Check if socket is ready for writing
146 if (!(pfd.revents & POLLOUT)) {
147 SET_ERRNO_SYS(ERROR_NETWORK_TIMEOUT, "socket not ready for writing after poll");
148 return -1;
149 }
150
151 // Use platform-specific send
152 ssize_t sent = socket_send(sockfd, data_ptr + total_sent, bytes_to_send, 0);
153
154 if (sent < 0) {
155 int error = errno;
156 if (network_handle_send_error(error)) {
157 continue; // Retry
158 }
159 return -1; // Fatal error
160 }
161
162 if (sent > 0) {
163 total_sent += (size_t)sent;
164 }
165 }
166
167 return (ssize_t)total_sent;
168}
169
178ssize_t recv_with_timeout(socket_t sockfd, void *buf, size_t len, uint64_t timeout_ns) {
179 if (sockfd == INVALID_SOCKET_VALUE) {
180 errno = EBADF;
181 return -1;
182 }
183
184 ssize_t total_received = 0;
185 char *data = (char *)buf;
186 uint64_t receive_start = time_get_ns();
187
188 while (total_received < (ssize_t)len) {
189 // Set up poll for read timeout (in nanoseconds)
190 struct pollfd pfd;
191 pfd.fd = sockfd;
192 pfd.events = POLLIN;
193 pfd.revents = 0;
194
195 // Use provided timeout for recv() calls - don't artificially limit data packets in test mode
196 // Timeouts should only apply to initial handshake, not to receiving data on active connections
197 uint64_t elapsed = time_get_ns() - receive_start;
198 if (elapsed >= timeout_ns) {
199 SET_ERRNO(total_received ? ERROR_NETWORK : ERROR_NETWORK_TIMEOUT, "Receive deadline expired");
200 return -1;
201 }
202 int result = socket_poll(&pfd, 1, (int64_t)(timeout_ns - elapsed));
203 if (result <= 0) {
204 if (result == 0) {
205 /* A read timeout is the ordinary idle state for signaling sockets.
206 * Do not emit an error on every polling interval. */
207 errno_set_with_system_error(ERROR_NETWORK_TIMEOUT, __FILE__, __LINE__, __func__, ETIMEDOUT);
208 if (total_received > 0)
209 SET_ERRNO(ERROR_NETWORK, "Receive timed out after consuming %zd/%zu bytes", total_received, len);
210 return -1;
211 }
212 if (network_handle_select_error(result)) {
213 continue; // Retry
214 }
215 return -1; // Fatal error
216 }
217
218 // Poll can return readiness for a hangup or socket error without POLLIN.
219 // Treat those as terminal network errors so callers tear down the dead
220 // connection instead of retrying it as an idle timeout in a tight loop.
221 // Linux zerocopy completions also raise POLLERR with SO_ERROR == 0.
222 // The serialized sender owns the error queue and will consume those events.
223 if ((pfd.revents & POLLERR) && !(pfd.revents & (POLLHUP | POLLNVAL))) {
224 int socket_error = 0;
225 socklen_t error_len = sizeof(socket_error);
226 if (socket_getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &socket_error, &error_len) == 0 && !socket_error) {
227 pfd.revents &= (short)~POLLERR;
228 if (!(pfd.revents & POLLIN)) {
229 platform_sleep_ns(NS_PER_MS_INT);
230 continue;
231 }
232 }
233 }
234 if (pfd.revents & (POLLERR | POLLNVAL)) {
235 SET_ERRNO(ERROR_NETWORK, "poll reported socket flags 0x%x", pfd.revents);
236 return -1;
237 }
238 // A drained asynchronous writer may close while readable bytes remain.
239 // Consume POLLIN before treating POLLHUP as EOF (notably WSAPoll).
240 if ((pfd.revents & POLLHUP) && !(pfd.revents & POLLIN))
241 return total_received;
242
243 // Other readiness flags without POLLIN are an ordinary no-data result.
244 if (!(pfd.revents & POLLIN)) {
245 errno_set_with_system_error(ERROR_NETWORK_TIMEOUT, __FILE__, __LINE__, __func__, ETIMEDOUT);
246 if (total_received > 0)
247 SET_ERRNO(ERROR_NETWORK, "Receive stalled after consuming %zd/%zu bytes", total_received, len);
248 return -1;
249 }
250
251 // Calculate how much we still need to receive
252 size_t bytes_to_recv = len - (size_t)total_received;
253 ssize_t received = socket_recv(sockfd, data + total_received, bytes_to_recv, 0);
254
255 if (received < 0) {
256 int error = errno;
257 if (network_handle_recv_error(error)) {
258 continue; // Retry
259 }
260 return -1; // Fatal error
261 }
262
263 if (received == 0) {
264 // Connection closed by peer
265 log_debug("Connection closed by peer during recv");
266 return total_received; // Return what we got so far
267 }
268
269 total_received += received;
270 }
271
272 return total_received;
273}
274
283int accept_with_timeout(socket_t listenfd, struct sockaddr *addr, socklen_t *addrlen, uint64_t timeout_ns) {
284 // Set up poll for accept timeout (in nanoseconds)
285 struct pollfd pfd;
286 pfd.fd = listenfd;
287 pfd.events = POLLIN;
288 pfd.revents = 0;
289
290 int result = socket_poll(&pfd, 1, (int64_t)timeout_ns);
291
292 if (result <= 0) {
293 if (result == 0) {
294 // Timeout is expected behavior for server waiting for connections
295 errno_set_with_system_error(ERROR_NETWORK_TIMEOUT, __FILE__, __LINE__, __func__, ETIMEDOUT);
296 return -1;
297 }
298
299 if (network_handle_select_error(result)) {
300 return -1; // Don't retry for accept
301 }
302 return -1;
303 }
304
305 // Check if socket is ready
306 if (!(pfd.revents & POLLIN)) {
307 errno_set_with_system_error(ERROR_NETWORK_TIMEOUT, __FILE__, __LINE__, __func__, ETIMEDOUT);
308 return -1;
309 }
310
311 // Check if socket is still valid before attempting accept
312 if (listenfd == INVALID_SOCKET_VALUE) {
313 SET_ERRNO(ERROR_NETWORK, "listening socket is closed");
314 return -1;
315 }
316
317 socket_t accept_result = socket_accept(listenfd, addr, addrlen, "connection");
318
319 if (accept_result == INVALID_SOCKET_VALUE) {
320 // Check if this is a socket closed error (common during shutdown)
321 int error_code = socket_get_last_error();
322
323 if (socket_is_invalid_socket_error(error_code)) {
324 // During shutdown, don't log this as an error since it's expected behavior
325 SET_ERRNO(ERROR_NETWORK, "Network operation failed");
326 } else {
328 }
329 return -1;
330 }
331
332 return (int)accept_result;
333}
334
346 if (sockfd == INVALID_SOCKET_VALUE) {
347 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid socket file descriptor");
348 }
349
350 // Convert nanoseconds to milliseconds for socket-level timeout
351 // Note: socket-level timeouts have ~millisecond granularity on most platforms
352 uint64_t timeout_ms = timeout_ns / (1000 * 1000);
353 if (timeout_ms == 0 && timeout_ns > 0) {
354 timeout_ms = 1; // Ensure at least 1ms for non-zero timeouts
355 }
356
357 // Set both receive and send timeouts using struct timeval
358 struct timeval tv;
359 tv.tv_sec = (time_t)(timeout_ms / 1000);
360 tv.tv_usec = (long)((timeout_ms % 1000) * 1000);
361
362 // Set receive timeout
363 if (socket_setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) != 0) {
364 return SET_ERRNO_SYS(ERROR_NETWORK, "Failed to set socket receive timeout");
365 }
366
367 // Set send timeout
368 if (socket_setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)) != 0) {
369 return SET_ERRNO_SYS(ERROR_NETWORK, "Failed to set socket send timeout");
370 }
371
372 return ASCIICHAT_OK;
373}
374
381 if (sockfd == INVALID_SOCKET_VALUE) {
382 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid socket file descriptor");
383 }
384 int result = socket_set_keepalive_params(sockfd, true, KEEPALIVE_IDLE, KEEPALIVE_INTERVAL, KEEPALIVE_COUNT);
385 if (result != 0) {
386 return SET_ERRNO_SYS(ERROR_NETWORK, "Failed to set socket keepalive parameters");
387 }
388 return ASCIICHAT_OK;
389}
390
397 if (sockfd == INVALID_SOCKET_VALUE) {
398 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid socket file descriptor");
399 }
400 int result = socket_set_nonblocking(sockfd, true);
401 if (result != 0) {
402 return SET_ERRNO_SYS(ERROR_NETWORK, "Failed to set socket non-blocking mode");
403 }
404 return ASCIICHAT_OK;
405}
406
413 if (sockfd == INVALID_SOCKET_VALUE) {
414 return SET_ERRNO_SYS(ERROR_NETWORK, "Invalid socket file descriptor");
415 }
416
417 int failed_options = 0;
418
419 // Attempt to configure 1MB send buffer for optimal frame transmission
420 int send_buffer_size = 1024 * 1024;
421 if (socket_setsockopt(sockfd, SOL_SOCKET, SO_SNDBUF, &send_buffer_size, sizeof(send_buffer_size)) < 0) {
422 log_warn("Failed to set send buffer size to 1MB: %s", network_error_string());
423 failed_options++;
424 }
425
426 // Attempt to configure 1MB receive buffer for optimal frame reception
427 int recv_buffer_size = 1024 * 1024;
428 if (socket_setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, &recv_buffer_size, sizeof(recv_buffer_size)) < 0) {
429 log_warn("Failed to set receive buffer size to 1MB: %s", network_error_string());
430 failed_options++;
431 }
432
433 // Attempt to enable TCP_NODELAY to disable Nagle's algorithm for low-latency transmission
434 // This must be set even if buffer configuration fails, as it's essential for real-time video.
435 int tcp_nodelay = 1;
436 if (socket_setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, &tcp_nodelay, sizeof(tcp_nodelay)) < 0) {
437 log_warn("Failed to set TCP_NODELAY: %s", network_error_string());
438 failed_options++;
439 }
440
441 // Return error only if ALL options failed
442 if (failed_options >= 3) {
443 return SET_ERRNO_SYS(ERROR_NETWORK, "Failed to configure all socket options");
444 }
445
446 return ASCIICHAT_OK;
447}
448
454const char *network_error_string() {
456}
457
466bool connect_with_timeout(socket_t sockfd, const struct sockaddr *addr, socklen_t addrlen, int timeout_seconds) {
467 if (sockfd == INVALID_SOCKET_VALUE) {
468 errno = EBADF;
469 return false;
470 }
471
472 // Set socket to non-blocking for timeout control
473 if (set_socket_nonblocking(sockfd) != ASCIICHAT_OK) {
474 return false;
475 }
476
477 // Attempt connection
478 int result = connect(sockfd, addr, addrlen);
479
480 if (result == 0) {
481 // Connected immediately
482 if (socket_set_blocking(sockfd) != 0) {
483 return false;
484 }
485 return true;
486 }
487
488 // Check if connection is in progress (expected for non-blocking sockets)
489 int error = socket_get_last_error();
490 if (!socket_is_in_progress_error(error) && !socket_is_would_block_error(error)) {
491 log_warn("TCP connection could not start (socket error %d)", error);
492 return false;
493 }
494
495 // Use select to wait for connection with timeout
496 fd_set write_fds;
497 struct timeval timeout;
498
499 socket_fd_zero(&write_fds);
500 socket_fd_set(sockfd, &write_fds);
501
502 timeout.tv_sec = timeout_seconds;
503 timeout.tv_usec = 0;
504
505 result = socket_select(sockfd, NULL, &write_fds, NULL, &timeout);
506
507 if (result <= 0) {
508 log_warn("TCP connection wait failed (result %d, socket error %d)", result, result == 0 ? 0 : socket_get_last_error());
509 return false; // Timeout or error
510 }
511
512 if (!socket_fd_isset(sockfd, &write_fds)) {
513 return false; // Socket not ready
514 }
515
516 // Check if connection was successful
517 int error_code = 0;
518 socklen_t error_len = sizeof(error_code);
519
520 if (socket_getsockopt(sockfd, SOL_SOCKET, SO_ERROR, &error_code, &error_len) != 0) {
521 return false;
522 }
523
524 if (error_code != 0) {
525 log_warn("TCP connection failed (socket error %d)", error_code);
526 return false;
527 }
528
529 // Connection successful - restore blocking mode
530 if (socket_set_blocking(sockfd) != 0) {
531 log_warn("Failed to restore socket to blocking mode after connect");
532 // Continue anyway - non-blocking mode works but may cause issues with send/recv
533 }
534
535 return true;
536}
asciichat_error_t errno_set_with_system_error(asciichat_error_t code, const char *file, int line, const char *function, int sys_errno)
Synchronized per-thread pending error stacks and value snapshots. SET_ERRNO pushes,...
#define SET_ERRNO(code,...)
#define SET_ERRNO_SYS(code,...)
ssize_t socket_recv(socket_t sock, void *buf, size_t len, int flags)
int socket_poll(struct pollfd *fds, nfds_t nfds, int64_t timeout_ns)
bool socket_is_would_block_error(int error_code)
ssize_t socket_send(socket_t sock, const void *buf, size_t len, int flags)
bool socket_is_invalid_socket_error(int error_code)
int socket_get_last_error(void)
const char * socket_get_error_string(void)
Dedicated worker for all pending errno stacks and handled history. Signal handlers may only request a...
unsigned long long uint64_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_NETWORK_BIND
Definition error_codes.h:77
@ ERROR_NETWORK
Definition error_codes.h:76
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
@ ERROR_NETWORK_TIMEOUT
Definition error_codes.h:79
#define log_warn(...)
Log a WARN message.
Definition log/log.h:615
#define log_debug(...)
Log a DEBUG message.
Definition log/log.h:589
#define NS_PER_MS_INT
Definition time.h:172
asciichat_error_t set_socket_timeout(socket_t sockfd, uint64_t timeout_ns)
Set socket timeout.
asciichat_error_t set_socket_keepalive(socket_t sockfd)
Set socket keepalive.
ssize_t recv_with_timeout(socket_t sockfd, void *buf, size_t len, uint64_t timeout_ns)
Receive data with timeout.
#define KEEPALIVE_COUNT
Keepalive probe count (8 probes).
Definition network.h:207
#define KEEPALIVE_INTERVAL
Keepalive interval in seconds (10 seconds).
Definition network.h:198
asciichat_error_t set_socket_nonblocking(socket_t sockfd)
Set socket non-blocking.
#define network_is_test_environment()
Check if we're in a test environment.
Definition network.h:168
bool connect_with_timeout(socket_t sockfd, const struct sockaddr *addr, socklen_t addrlen, int timeout_seconds)
Connect with timeout.
int accept_with_timeout(socket_t listenfd, struct sockaddr *addr, socklen_t *addrlen, uint64_t timeout_ns)
Accept connection with timeout.
ssize_t send_with_timeout(socket_t sockfd, const void *data, size_t len, uint64_t timeout_ns)
Send data with timeout using chunked transmission.
const char * network_error_string()
Get human-readable error string for network errors.
asciichat_error_t socket_configure_buffers(socket_t sockfd)
Configure socket buffers and TCP_NODELAY for optimal performance.
#define KEEPALIVE_IDLE
Keepalive idle time in seconds (60 seconds).
Definition network.h:189
int socket_t
⚙️ Common definitions, error codes, macros, and types shared throughout the application
🌐 Core network I/O operations with timeout support
🔤 String Manipulation and Shell Escaping Utilities