Raw ↗
+ +
a18b27f fix(windows): resolve Win32 Winsock, signal, and CLI test compatibility
saifmukhtar · 2026-11-24
1 /*
2 * SPDX-License-Identifier: AGPL-3.0-or-later WITH Classpath-exception-2.0
3 * Copyright (c) 2026 Saif Mukhtar
4 *
5 * OpenAVX - Open Audio-Video eXchange
6 * test/openavx_socket_resilience_audit_test.c - Socket resilience and signal safety tests
7 *
8 * Checks SIGPIPE suppression, reconnect timeouts, mutex contention,
9 * strtok_r thread safety, and graceful socket shutdown.
10 */
11  
12 #define _GNU_SOURCE
13 #define _POSIX_C_SOURCE 200809L
14 #define _DEFAULT_SOURCE
15  
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <stdint.h>
19 #include <stdbool.h>
20 #include <string.h>
21 #include <signal.h>
22 #include <unistd.h>
23 #include <errno.h>
24 #include <assert.h>
25 #include <pthread.h>
26 #include <sys/socket.h>
27 #include <sys/uio.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
30 #include <time.h>
31  
32 #include "openavx.h"
33 #include "avx_internal.h"
34 #include "avx_platform.h"
35 #include "avx_web.h"
36 #include "avx_rtsp.h"
37  
38 static double get_time_ms(void) {
39 struct timespec ts;
40 clock_gettime(CLOCK_MONOTONIC, &ts);
41 return (double)ts.tv_sec * 1000.0 + (double)ts.tv_nsec / 1000000.0;
42 }
43  
44 /* ========================================================================= */
45 /* TEST 1: SIGPIPE Behavior on writev() vs sendmsg(MSG_NOSIGNAL) */
46 /* ========================================================================= */
47  
48 #ifndef _WIN32
49 static volatile sig_atomic_t g_sigpipe_delivered = 0;
50  
51 static void audit_sigpipe_handler(int sig) {
52 if (sig == SIGPIPE) {
53 g_sigpipe_delivered++;
54 }
55 }
56 #endif
57  
58 static void test_audit_proof_sigpipe_vulnerability(void) {
59 printf("\n[*] 1. SIGPIPE handling: writev() vs sendmsg(..., MSG_NOSIGNAL)\n");
60  
61 #ifndef _WIN32
62 /* Install temporary SIGPIPE signal handler to count signals instead of dying */
63 struct sigaction sa, old_sa;
64 memset(&sa, 0, sizeof(sa));
65 sa.sa_handler = audit_sigpipe_handler;
66 sigemptyset(&sa.sa_mask);
67 sigaction(SIGPIPE, &sa, &old_sa);
68  
69 /* 1. Direct kernel check: Compare bare writev() vs sendmsg(..., MSG_NOSIGNAL) */
70 int sv[2];
71 assert(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
72  
73 /* Client closes connection abruptly */
74 close(sv[1]);
75  
76 char hdr[] = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
77 char body[] = "<html><body>OpenAVX Preview</body></html>";
78 struct iovec iov[2];
79 iov[0].iov_base = hdr;
80 iov[0].iov_len = strlen(hdr);
81 iov[1].iov_base = body;
82 iov[1].iov_len = strlen(body);
83  
84 /* Baseline: POSIX writev() without MSG_NOSIGNAL */
85 g_sigpipe_delivered = 0;
86 ssize_t ret_writev = writev(sv[0], iov, 2);
87 int err_writev = errno;
88 int sigs_writev = (int)g_sigpipe_delivered;
89  
90 printf(" [*] Baseline writev(): ret=%zd, errno=%d (%s), SIGPIPE=%d\n",
91 ret_writev, err_writev, strerror(err_writev), sigs_writev);
92  
93 /* Test: sendmsg() with MSG_NOSIGNAL on the same broken socket */
94 struct msghdr msg;
95 memset(&msg, 0, sizeof(msg));
96 msg.msg_iov = iov;
97 msg.msg_iovlen = 2;
98  
99 g_sigpipe_delivered = 0;
100 ssize_t ret_sendmsg = sendmsg(sv[0], &msg, MSG_NOSIGNAL);
101 int err_sendmsg = errno;
102 int sigs_sendmsg = (int)g_sigpipe_delivered;
103  
104 printf(" [*] sendmsg(MSG_NOSIGNAL): ret=%zd, errno=%d (%s), SIGPIPE=%d\n",
105 ret_sendmsg, err_sendmsg, strerror(err_sendmsg), sigs_sendmsg);
106  
107 assert(sigs_sendmsg == 0 && ret_sendmsg < 0 && err_sendmsg == EPIPE);
108 printf(" [+] PASS: sendmsg(..., MSG_NOSIGNAL) returns EPIPE with 0 SIGPIPE\n");
109  
110 close(sv[0]);
111 sigaction(SIGPIPE, &old_sa, NULL);
112 #else
113 printf(" [*] Windows sockets do not deliver SIGPIPE signals; skipping POSIX signal check\n");
114 #endif
115  
116 /* 2. Web Gateway Preview check */
117 avx_web_server_config_t wcfg = {
118 .port = 0,
119 .codec = AVX_RTSP_CODEC_H264,
120 .stream_name = "AuditTestStream"
121 };
122 avx_web_server_t *srv = avx_web_server_create(&wcfg);
123 assert(srv != NULL);
124 uint16_t port = avx_web_server_get_port(srv);
125 printf(" [+] Web preview server bound to port %u\n", port);
126 avx_web_server_destroy(srv);
127 }
128  
129 /* ========================================================================= */
130 /* TEST 2: Reconnect Timeout Budget in oavx_stream_receive */
131 /* ========================================================================= */
132  
133 static void test_audit_proof_reconnect_blocking_budget(void) {
134 printf("\n[*] 2. Reconnect timeout budget on unreachable endpoint\n");
135  
136 oavx_context_t *ctx = oavx_context_create();
137 assert(ctx != NULL);
138  
139 /* Target RFC 5737 TEST-NET-2 non-routable IP (198.51.100.1:7960) */
140 oavx_stream_config_t cfg;
141 memset(&cfg, 0, sizeof(cfg));
142 cfg.direction = OAVX_DIR_RECEIVE;
143 cfg.name = "UnreachableStream";
144 cfg.endpoint = "198.51.100.1:7960";
145 cfg.bandwidth = OAVX_BANDWIDTH_HIGHEST;
146 cfg.color_format = OAVX_COLOR_FORMAT_FASTEST;
147  
148 double t_open_0 = get_time_ms();
149 oavx_stream_t *rx = oavx_stream_open(ctx, &cfg);
150 double t_open = get_time_ms() - t_open_0;
151 assert(rx != NULL);
152 printf(" [+] oavx_stream_open(%s) returned in %.2f ms\n", cfg.endpoint, t_open);
153  
154 /* Call oavx_stream_receive requesting a 40ms frame budget */
155 oavx_video_frame_t vframe = {0};
156 oavx_audio_frame_t aframe = {0};
157 oavx_metadata_frame_t mframe = {0};
158  
159 double t_recv_0 = get_time_ms();
160 oavx_frame_type_t ft = oavx_stream_receive(rx, &vframe, &aframe, &mframe, 40);
161 double t_recv = get_time_ms() - t_recv_0;
162  
163 printf(" [+] oavx_stream_receive(timeout=40 ms) returned type %d in %.2f ms\n", (int)ft, t_recv);
164  
165 if (t_recv >= 2500.0) {
166 printf(" [!] Warning: connect blocked for %.2f ms (> 2500 ms)\n", t_recv);
167 }
168  
169 oavx_stream_close(rx);
170 oavx_context_destroy(ctx);
171 }
172  
173 /* ========================================================================= */
174 /* TEST 3: Concurrent Telemetry Wait Time During Connection Attempt */
175 /* ========================================================================= */
176  
177 typedef struct {
178 oavx_stream_t *stream;
179 volatile bool ready;
180 double contention_wait_ms;
181 } contention_arg_t;
182  
183 static void* contention_worker_thread(void *arg) {
184 contention_arg_t *c = (contention_arg_t*)arg;
185 c->ready = true;
186  
187 /* Sleep briefly so Thread 1 enters oavx_stream_receive first */
188 avx_sleep_ms(200);
189  
190 oavx_telemetry_t telem;
191 double t0 = get_time_ms();
192 oavx_stream_get_telemetry(c->stream, &telem);
193 c->contention_wait_ms = get_time_ms() - t0;
194  
195 return NULL;
196 }
197  
198 static void test_audit_proof_mutex_contention(void) {
199 printf("\n[*] 3. Mutex contention on concurrent telemetry query\n");
200  
201 oavx_context_t *ctx = oavx_context_create();
202 assert(ctx != NULL);
203  
204 oavx_stream_config_t cfg;
205 memset(&cfg, 0, sizeof(cfg));
206 cfg.direction = OAVX_DIR_RECEIVE;
207 cfg.name = "ContentionStream";
208 cfg.endpoint = "198.51.100.1:7960";
209  
210 oavx_stream_t *rx = oavx_stream_open(ctx, &cfg);
211 assert(rx != NULL);
212  
213 contention_arg_t carg = {
214 .stream = rx,
215 .ready = false,
216 .contention_wait_ms = 0.0
217 };
218  
219 pthread_t th;
220 pthread_create(&th, NULL, contention_worker_thread, &carg);
221 while (!carg.ready) avx_sleep_ms(5);
222  
223 oavx_video_frame_t vframe = {0};
224 oavx_audio_frame_t aframe = {0};
225 oavx_metadata_frame_t mframe = {0};
226 oavx_stream_receive(rx, &vframe, &aframe, &mframe, 40);
227  
228 pthread_join(th, NULL);
229  
230 printf(" [+] Thread 2 telemetry wait time: %.2f ms\n", carg.contention_wait_ms);
231 if (carg.contention_wait_ms >= 1000.0) {
232 printf(" [!] Warning: telemetry query stalled for %.2f ms\n", carg.contention_wait_ms);
233 }
234  
235 oavx_stream_close(rx);
236 oavx_context_destroy(ctx);
237 }
238  
239 /* ========================================================================= */
240 /* TEST 4: Thread Safety of strtok_r() vs Non-Reentrant strtok() */
241 /* ========================================================================= */
242  
243 typedef struct {
244 volatile bool running;
245 } strtok_race_arg_t;
246  
247 static void* strtok_interferer_thread(void *arg) {
248 strtok_race_arg_t *r = (strtok_race_arg_t*)arg;
249 char dummy[64];
250 while (r->running) {
251 snprintf(dummy, sizeof(dummy), "UNRELATED_ALPHA UNRELATED_BETA UNRELATED_GAMMA");
252 char *tok1 = strtok(dummy, " ");
253 char *tok2 = strtok(NULL, " ");
254 (void)tok1;
255 (void)tok2;
256 }
257 return NULL;
258 }
259  
260 static void test_audit_proof_strtok_concurrency_race(void) {
261 printf("\n[*] 4. Discovery line parsing: strtok() vs reentrant strtok_r()\n");
262  
263 /* 4A: Baseline check showing global strtok() races across threads */
264 strtok_race_arg_t rarg = { .running = true };
265 pthread_t th;
266 pthread_create(&th, NULL, strtok_interferer_thread, &rarg);
267  
268 int test_iterations = 10000;
269 int corrupted_strtok = 0;
270  
271 for (int iter = 0; iter < test_iterations; ++iter) {
272 char resp[128];
273 snprintf(resp, sizeof(resp), "SOURCES\nCAM1|127.0.0.1:7960\nCAM2|127.0.0.1:7961\n");
274  
275 char *line = strtok(resp, "\r\n");
276 if (!line || strcmp(line, "SOURCES") != 0) {
277 corrupted_strtok++;
278 continue;
279 }
280  
281 line = strtok(NULL, "\r\n");
282 if (!line || strncmp(line, "CAM1", 4) != 0) {
283 corrupted_strtok++;
284 }
285 }
286  
287 rarg.running = false;
288 pthread_join(th, NULL);
289  
290 printf(" [*] strtok() (%d iters): %d corruptions\n", test_iterations, corrupted_strtok);
291  
292 /* 4B: Test reentrant strtok_r() under same concurrent background thread */
293 rarg.running = true;
294 pthread_create(&th, NULL, strtok_interferer_thread, &rarg);
295  
296 int corrupted_strtok_r = 0;
297 for (int iter = 0; iter < test_iterations; ++iter) {
298 char resp[128];
299 snprintf(resp, sizeof(resp), "SOURCES\nCAM1|127.0.0.1:7960\nCAM2|127.0.0.1:7961\n");
300  
301 char *saveptr = NULL;
302 char *line = strtok_r(resp, "\r\n", &saveptr);
303 if (!line || strcmp(line, "SOURCES") != 0) {
304 corrupted_strtok_r++;
305 continue;
306 }
307  
308 line = strtok_r(NULL, "\r\n", &saveptr);
309 if (!line || strncmp(line, "CAM1", 4) != 0) {
310 corrupted_strtok_r++;
311 }
312 }
313  
314 rarg.running = false;
315 pthread_join(th, NULL);
316  
317 assert(corrupted_strtok_r == 0);
318 printf(" [+] PASS: strtok_r() (%d iters): 0 corruptions\n", test_iterations);
319 }
320  
321 /* ========================================================================= */
322 /* TEST 5: Socket Graceful Shutdown Semantics */
323 /* ========================================================================= */
324  
325 static void test_audit_proof_socket_teardown_semantics(void) {
326 printf("\n[*] 5. Socket shutdown(SHUT_RDWR) before close()\n");
327  
328 int sv[2];
329 assert(socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == 0);
330  
331 /* Calling shutdown(SHUT_RDWR) aborts pending send/recv calls with EPIPE/ECONNRESET
332 * before closing and recycling the file descriptor. */
333 int shutdown_res = shutdown(sv[0], SHUT_RDWR);
334 assert(shutdown_res == 0);
335  
336 char buf[16] = "test";
337 ssize_t s = send(sv[0], buf, sizeof(buf), MSG_NOSIGNAL);
338 #ifdef _WIN32
339 int err = WSAGetLastError();
340 assert(s < 0 && (err == WSAESHUTDOWN || err == WSAECONNRESET || err == WSAECONNABORTED));
341 printf(" [+] PASS: send() after shutdown(SHUT_RDWR) failed with WSAGetLastError=%d\n", err);
342 closesocket(sv[0]);
343 closesocket(sv[1]);
344 #else
345 assert(s < 0 && (errno == EPIPE || errno == ECONNRESET));
346 printf(" [+] PASS: send() after shutdown(SHUT_RDWR) failed with errno=%d (%s)\n",
347 errno, strerror(errno));
348  
349 close(sv[0]);
350 close(sv[1]);
351 #endif
352 }
353  
354 /* ========================================================================= */
355 /* MAIN ENTRY POINT */
356 /* ========================================================================= */
357  
358 int main(void) {
359 printf("=== OpenAVX Socket Resilience Tests ===\n");
360  
361 test_audit_proof_sigpipe_vulnerability();
362 test_audit_proof_strtok_concurrency_race();
363 test_audit_proof_socket_teardown_semantics();
364 test_audit_proof_reconnect_blocking_budget();
365 test_audit_proof_mutex_contention();
366  
367 printf("\n[PASS] openavx_socket_resilience_audit_test\n\n");
368 return 0;
369 }