Raw ↗
+ +
6f7acc3 fix(socket): use SO_EXCLUSIVEADDRUSE on windows tcp listeners to prevent port hijacking
saifmukhtar · 2026-11-25
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 * src/avx_socket.c - Socket helpers, interface resolution, and pcap utilities
7 */
8  
9 #define _DEFAULT_SOURCE
10 #define _GNU_SOURCE
11 #include "avx_platform.h"
12 #include "avx_internal.h"
13 #include <string.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #if defined(AVX_OS_POSIX)
17 #include <netinet/tcp.h>
18 #include <sys/ioctl.h>
19 #include <ifaddrs.h>
20 #include <net/if.h>
21 #include <netdb.h>
22 #if defined(__linux__)
23 #include <linux/sockios.h>
24 #endif
25 #endif
26  
27 /* Resolves network interface name (e.g. eth0) or IP literal to active unicast IPv4/IPv6 address. */
28 bool avx_net_resolve_interface_or_ip(const char* iface_or_ip, char* out_ip, size_t out_len) {
29 if (!iface_or_ip || iface_or_ip[0] == '\0' || !out_ip || out_len == 0) return false;
30  
31 /* 1. Direct IPv4 literal validation */
32 struct in_addr dummy4;
33 if (inet_pton(AF_INET, iface_or_ip, &dummy4) == 1) {
34 strncpy(out_ip, iface_or_ip, out_len - 1);
35 out_ip[out_len - 1] = '\0';
36 return true;
37 }
38  
39 /* 2. Direct IPv6 literal validation (handles "[::1]" or "::1") */
40 const char* ip_ptr = iface_or_ip;
41 char unbracketed[128];
42 if (iface_or_ip[0] == '[') {
43 const char* end = strchr(iface_or_ip, ']');
44 if (end) {
45 size_t len = (size_t)(end - (iface_or_ip + 1));
46 if (len >= sizeof(unbracketed)) len = sizeof(unbracketed) - 1;
47 strncpy(unbracketed, iface_or_ip + 1, len);
48 unbracketed[len] = '\0';
49 ip_ptr = unbracketed;
50 }
51 }
52  
53 struct in6_addr dummy6;
54 if (inet_pton(AF_INET6, ip_ptr, &dummy6) == 1) {
55 strncpy(out_ip, ip_ptr, out_len - 1);
56 out_ip[out_len - 1] = '\0';
57 return true;
58 }
59  
60 /* 3. Match by interface name (e.g., "eth0", "lo", "enp47s0", "wlp46s0") */
61 #if defined(AVX_OS_WINDOWS) || defined(_WIN32)
62 if (strcmp(iface_or_ip, "lo") == 0 || strcasecmp(iface_or_ip, "loopback") == 0 || strcasecmp(iface_or_ip, "localhost") == 0) {
63 strncpy(out_ip, "127.0.0.1", out_len - 1);
64 out_ip[out_len - 1] = '\0';
65 return true;
66 }
67 #endif
68 #if defined(AVX_OS_POSIX)
69 struct ifaddrs *ifaddr = NULL, *ifa = NULL;
70 if (getifaddrs(&ifaddr) == -1) {
71 return false;
72 }
73  
74 bool found = false;
75 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
76 if (!ifa->ifa_addr || (ifa->ifa_addr->sa_family != AF_INET && ifa->ifa_addr->sa_family != AF_INET6)) {
77 continue;
78 }
79 bool match = (strcmp(ifa->ifa_name, iface_or_ip) == 0);
80 #if defined(AVX_OS_MACOS) || defined(AVX_OS_BSD)
81 if (!match && strcmp(iface_or_ip, "lo") == 0 && strcmp(ifa->ifa_name, "lo0") == 0) {
82 match = true;
83 }
84 #endif
85 if (match) {
86 if (ifa->ifa_addr->sa_family == AF_INET) {
87 struct sockaddr_in *s4 = (struct sockaddr_in*)ifa->ifa_addr;
88 if (inet_ntop(AF_INET, &s4->sin_addr, out_ip, (socklen_t)out_len) != NULL) {
89 found = true;
90 break;
91 }
92 } else if (ifa->ifa_addr->sa_family == AF_INET6) {
93 struct sockaddr_in6 *s6 = (struct sockaddr_in6*)ifa->ifa_addr;
94 if (!IN6_IS_ADDR_LINKLOCAL(&s6->sin6_addr)) {
95 if (inet_ntop(AF_INET6, &s6->sin6_addr, out_ip, (socklen_t)out_len) != NULL) {
96 found = true;
97 break;
98 }
99 }
100 }
101 }
102 }
103 freeifaddrs(ifaddr);
104 return found;
105 #else
106 return false;
107 #endif
108 }
109  
110 /* Discovers local default outbound IP by querying kernel routing table via unconnected UDP probe. */
111 bool avx_net_get_default_ip(char* out_ip, size_t out_len) {
112 if (!out_ip || out_len == 0) return false;
113 avx_platform_sockets_init();
114  
115 /* 1. Query OS routing table using dummy UDP socket connect to 8.8.8.8 */
116 avx_socket_t sock = socket(AF_INET, SOCK_DGRAM, 0);
117 if (sock != AVX_INVALID_SOCKET) {
118 struct sockaddr_in dest;
119 memset(&dest, 0, sizeof(dest));
120 dest.sin_family = AF_INET;
121 dest.sin_port = htons(53);
122 if (inet_pton(AF_INET, "8.8.8.8", &dest.sin_addr) > 0) {
123 if (connect(sock, (struct sockaddr*)&dest, sizeof(dest)) == 0) {
124 struct sockaddr_in local;
125 avx_socklen_t len = sizeof(local);
126 if (getsockname(sock, (struct sockaddr*)&local, &len) == 0) {
127 if (local.sin_addr.s_addr != 0 && local.sin_addr.s_addr != htonl(INADDR_LOOPBACK)) {
128 if (inet_ntop(AF_INET, &local.sin_addr, out_ip, (socklen_t)out_len) != NULL) {
129 avx_socket_close(sock);
130 return true;
131 }
132 }
133 }
134 }
135 }
136 avx_socket_close(sock);
137 }
138  
139 /* 2. Fallback: Scan active interfaces via getifaddrs() */
140 #if defined(AVX_OS_POSIX)
141 struct ifaddrs *ifaddr = NULL, *ifa = NULL;
142 if (getifaddrs(&ifaddr) == 0) {
143 char candidate[64] = {0};
144 bool candidate_is_virtual = true;
145  
146 for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
147 if (!ifa->ifa_addr || ifa->ifa_addr->sa_family != AF_INET) continue;
148 if (!(ifa->ifa_flags & IFF_UP) || (ifa->ifa_flags & IFF_LOOPBACK)) continue;
149  
150 struct sockaddr_in *s4 = (struct sockaddr_in*)ifa->ifa_addr;
151 char cur_ip[64];
152 if (inet_ntop(AF_INET, &s4->sin_addr, cur_ip, sizeof(cur_ip)) != NULL) {
153 bool is_virtual = (strncmp(ifa->ifa_name, "docker", 6) == 0 ||
154 strncmp(ifa->ifa_name, "br-", 3) == 0 ||
155 strncmp(ifa->ifa_name, "veth", 4) == 0);
156 if (candidate[0] == '\0' || (candidate_is_virtual && !is_virtual)) {
157 snprintf(candidate, sizeof(candidate), "%s", cur_ip);
158 candidate_is_virtual = is_virtual;
159 if (!is_virtual) break;
160 }
161 }
162 }
163 freeifaddrs(ifaddr);
164  
165 if (candidate[0] != '\0') {
166 snprintf(out_ip, out_len, "%s", candidate);
167 return true;
168 }
169 }
170 #endif
171  
172 /* 3. Fallback to loopback if completely offline / isolated */
173 snprintf(out_ip, out_len, "127.0.0.1");
174 return true;
175 }
176  
177 /*
178 * On POSIX, SO_REUSEADDR allows re-binding over TIME_WAIT without hijacking
179 * active listeners (which would require SO_REUSEPORT). On Windows Winsock2,
180 * SO_REUSEADDR allows multiple active listeners on the same IP:port, breaking
181 * dynamic port fallback across co-located transmitters; SO_EXCLUSIVEADDRUSE
182 * enforces exclusive port ownership per active listener.
183 */
184 static void avx_socket_set_server_bind_opts(avx_socket_t fd) {
185 int opt = 1;
186 #if defined(AVX_OS_WINDOWS)
187 setsockopt(fd, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (const char*)&opt, sizeof(opt));
188 #else
189 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
190 #endif
191 }
192  
193 /* Binds non-blocking TCP server socket with exclusive/reuse bind opts and tuned buffers. */
194 avx_socket_t avx_socket_create_tcp_server_bind(const char* bind_ip, uint16_t port) {
195 avx_platform_sockets_init();
196 int buf_size = 16 * 1024 * 1024; /* 16 MB buffer for video streaming */
197  
198 /* Case A: Explicit IPv6 literal (e.g. "::1" or "2001:...") */
199 struct in6_addr in6;
200 if (bind_ip && bind_ip[0] != '\0' && inet_pton(AF_INET6, bind_ip, &in6) == 1) {
201 avx_socket_t fd = socket(AF_INET6, SOCK_STREAM, 0);
202 if (fd == AVX_INVALID_SOCKET) return AVX_INVALID_SOCKET;
203  
204 avx_socket_set_server_bind_opts(fd);
205 avx_socket_set_nosigpipe(fd);
206 setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char*)&buf_size, sizeof(buf_size));
207 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char*)&buf_size, sizeof(buf_size));
208  
209 struct sockaddr_in6 addr6;
210 memset(&addr6, 0, sizeof(addr6));
211 addr6.sin6_family = AF_INET6;
212 addr6.sin6_port = htons(port);
213 addr6.sin6_addr = in6;
214  
215 if (bind(fd, (struct sockaddr*)&addr6, sizeof(addr6)) < 0 || listen(fd, 8) < 0) {
216 avx_socket_close(fd);
217 return AVX_INVALID_SOCKET;
218 }
219 return fd;
220 }
221  
222 /* Case B: Explicit IPv4 literal (e.g. "192.168.1.100" or "127.0.0.1") */
223 struct in_addr in4;
224 if (bind_ip && bind_ip[0] != '\0' && strcmp(bind_ip, "0.0.0.0") != 0 && strcmp(bind_ip, "::") != 0) {
225 if (inet_pton(AF_INET, bind_ip, &in4) == 1) {
226 avx_socket_t fd = socket(AF_INET, SOCK_STREAM, 0);
227 if (fd == AVX_INVALID_SOCKET) return AVX_INVALID_SOCKET;
228  
229 avx_socket_set_server_bind_opts(fd);
230 avx_socket_set_nosigpipe(fd);
231 setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char*)&buf_size, sizeof(buf_size));
232 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char*)&buf_size, sizeof(buf_size));
233  
234 struct sockaddr_in addr4;
235 memset(&addr4, 0, sizeof(addr4));
236 addr4.sin_family = AF_INET;
237 addr4.sin_port = htons(port);
238 addr4.sin_addr = in4;
239  
240 if (bind(fd, (struct sockaddr*)&addr4, sizeof(addr4)) < 0 || listen(fd, 8) < 0) {
241 avx_socket_close(fd);
242 return AVX_INVALID_SOCKET;
243 }
244 return fd;
245 }
246 }
247  
248 /* Case C: Wildcard Dual-Stack Binding (bind_ip is NULL, "", "0.0.0.0", or "::") */
249 /* Attempt AF_INET6 socket with IPV6_V6ONLY = 0 (dual-stack: accepts both IPv4 and IPv6) */
250 avx_socket_t fd = socket(AF_INET6, SOCK_STREAM, 0);
251 if (fd != AVX_INVALID_SOCKET) {
252 int no = 0;
253 setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&no, sizeof(no));
254 avx_socket_set_server_bind_opts(fd);
255 avx_socket_set_nosigpipe(fd);
256 setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char*)&buf_size, sizeof(buf_size));
257 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char*)&buf_size, sizeof(buf_size));
258  
259 struct sockaddr_in6 addr6;
260 memset(&addr6, 0, sizeof(addr6));
261 addr6.sin6_family = AF_INET6;
262 addr6.sin6_port = htons(port);
263 addr6.sin6_addr = in6addr_any;
264  
265 if (bind(fd, (struct sockaddr*)&addr6, sizeof(addr6)) == 0 && listen(fd, 8) == 0) {
266 return fd;
267 }
268 avx_socket_close(fd);
269 }
270  
271 /* Fallback to AF_INET if dual-stack is unsupported by OS */
272 fd = socket(AF_INET, SOCK_STREAM, 0);
273 if (fd == AVX_INVALID_SOCKET) return AVX_INVALID_SOCKET;
274  
275 avx_socket_set_server_bind_opts(fd);
276 avx_socket_set_nosigpipe(fd);
277 setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char*)&buf_size, sizeof(buf_size));
278 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char*)&buf_size, sizeof(buf_size));
279  
280 struct sockaddr_in addr4;
281 memset(&addr4, 0, sizeof(addr4));
282 addr4.sin_family = AF_INET;
283 addr4.sin_port = htons(port);
284 addr4.sin_addr.s_addr = INADDR_ANY;
285  
286 if (bind(fd, (struct sockaddr*)&addr4, sizeof(addr4)) < 0 || listen(fd, 8) < 0) {
287 avx_socket_close(fd);
288 return AVX_INVALID_SOCKET;
289 }
290 return fd;
291 }
292  
293 avx_socket_t avx_socket_create_tcp_server(uint16_t port) {
294 return avx_socket_create_tcp_server_bind(NULL, port);
295 }
296  
297 static struct addrinfo* avx_socket_resolve_tcp(const char* host, uint16_t port) {
298 if (!host || host[0] == '\0') return NULL;
299  
300 /* Strip brackets if host is formatted as "[::1]" -> "::1" */
301 char clean_host[128];
302 const char* h = host;
303 if (h[0] == '[') {
304 h++;
305 size_t len = strlen(h);
306 if (len > 0 && h[len - 1] == ']') {
307 len--;
308 }
309 if (len >= sizeof(clean_host)) len = sizeof(clean_host) - 1;
310 strncpy(clean_host, h, len);
311 clean_host[len] = '\0';
312 h = clean_host;
313 }
314  
315 char port_str[16];
316 snprintf(port_str, sizeof(port_str), "%u", port);
317  
318 struct addrinfo hints;
319 memset(&hints, 0, sizeof(hints));
320 hints.ai_family = AF_UNSPEC; /* IPv4 or IPv6 dual-stack */
321 hints.ai_socktype = SOCK_STREAM;
322 hints.ai_flags = AI_NUMERICSERV;
323  
324 struct addrinfo *res = NULL;
325 if (getaddrinfo(h, port_str, &hints, &res) != 0 || !res) {
326 return NULL;
327 }
328 return res;
329 }
330  
331 static avx_socket_t avx_socket_open_tuned_tcp(const struct addrinfo *rp, bool nonblocking) {
332 avx_platform_sockets_init();
333 avx_socket_t fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
334 if (fd == AVX_INVALID_SOCKET) return AVX_INVALID_SOCKET;
335  
336 avx_socket_set_nosigpipe(fd);
337  
338 int buf_size = 16 * 1024 * 1024;
339 setsockopt(fd, SOL_SOCKET, SO_SNDBUF, (const char*)&buf_size, sizeof(buf_size));
340 setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char*)&buf_size, sizeof(buf_size));
341 if (nonblocking) {
342 avx_socket_set_nonblocking(fd, true);
343 }
344 return fd;
345 }
346  
347 avx_socket_t avx_socket_start_nonblocking_connect(const char* host, uint16_t port, bool* connected_now) {
348 if (connected_now) *connected_now = false;
349 struct addrinfo *res = avx_socket_resolve_tcp(host, port);
350 if (!res) return AVX_INVALID_SOCKET;
351  
352 avx_socket_t fd = AVX_INVALID_SOCKET;
353 for (struct addrinfo *rp = res; rp != NULL; rp = rp->ai_next) {
354 fd = avx_socket_open_tuned_tcp(rp, true);
355 if (fd == AVX_INVALID_SOCKET) continue;
356  
357 int ret = connect(fd, rp->ai_addr, (socklen_t)rp->ai_addrlen);
358 if (ret == 0) {
359 avx_socket_set_nonblocking(fd, false);
360 avx_socket_set_keepalive(fd, 2, 1, 3);
361 avx_socket_set_tcp_nodelay(fd, true);
362 if (connected_now) *connected_now = true;
363 break;
364 }
365 #if defined(AVX_OS_WINDOWS)
366 int err = WSAGetLastError();
367 bool in_progress = (err == WSAEWOULDBLOCK || err == WSAEINPROGRESS);
368 #else
369 bool in_progress = (errno == EINPROGRESS);
370 #endif
371 if (in_progress) {
372 break;
373 }
374  
375 avx_socket_close(fd);
376 fd = AVX_INVALID_SOCKET;
377 }
378  
379 freeaddrinfo(res);
380 return fd;
381 }
382  
383 /* Initiates non-blocking TCP connection with polling deadline to prevent thread hangs. */
384 avx_socket_t avx_socket_connect_tcp_timeout(const char* host, uint16_t port, uint32_t timeout_ms) {
385 struct addrinfo *res = avx_socket_resolve_tcp(host, port);
386 if (!res) return AVX_INVALID_SOCKET;
387 struct addrinfo *rp = NULL;
388  
389 avx_socket_t fd = AVX_INVALID_SOCKET;
390 for (rp = res; rp != NULL; rp = rp->ai_next) {
391 fd = avx_socket_open_tuned_tcp(rp, timeout_ms > 0);
392 if (fd == AVX_INVALID_SOCKET) continue;
393  
394 if (timeout_ms > 0) {
395 int ret = connect(fd, rp->ai_addr, (socklen_t)rp->ai_addrlen);
396 if (ret == 0) {
397 avx_socket_set_nonblocking(fd, false);
398 avx_socket_set_keepalive(fd, 2, 1, 3);
399 avx_socket_set_tcp_nodelay(fd, true);
400 break; /* Successfully connected! */
401 }
402  
403 #if defined(AVX_OS_WINDOWS)
404 int err = WSAGetLastError();
405 bool in_progress = (err == WSAEWOULDBLOCK || err == WSAEINPROGRESS);
406 if (in_progress) {
407 fd_set wset, eset;
408 FD_ZERO(&wset);
409 FD_ZERO(&eset);
410 FD_SET(fd, &wset);
411 FD_SET(fd, &eset);
412 struct timeval tv;
413 tv.tv_sec = (long)(timeout_ms / 1000);
414 tv.tv_usec = (long)((timeout_ms % 1000) * 1000);
415 int sret = select((int)fd + 1, NULL, &wset, &eset, &tv);
416 if (sret > 0 && FD_ISSET(fd, &wset) && !FD_ISSET(fd, &eset)) {
417 int sock_err = 0;
418 socklen_t elen = sizeof(sock_err);
419 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (char*)&sock_err, &elen) == 0 && sock_err == 0) {
420 avx_socket_set_nonblocking(fd, false);
421 avx_socket_set_keepalive(fd, 2, 1, 3);
422 avx_socket_set_tcp_nodelay(fd, true);
423 break;
424 }
425 }
426 }
427 #else
428 int err = errno;
429 bool in_progress = (err == EINPROGRESS);
430 if (in_progress) {
431 struct pollfd pfd;
432 pfd.fd = fd;
433 pfd.events = POLLOUT;
434 pfd.revents = 0;
435 int pret = poll(&pfd, 1, (int)timeout_ms);
436 if (pret > 0 && (pfd.revents & POLLOUT) && !(pfd.revents & (POLLERR | POLLHUP | POLLNVAL))) {
437 int sock_err = 0;
438 socklen_t elen = sizeof(sock_err);
439 if (getsockopt(fd, SOL_SOCKET, SO_ERROR, &sock_err, &elen) == 0 && sock_err == 0) {
440 avx_socket_set_nonblocking(fd, false);
441 avx_socket_set_keepalive(fd, 2, 1, 3);
442 avx_socket_set_tcp_nodelay(fd, true);
443 break;
444 }
445 }
446 }
447 #endif
448 } else {
449 if (connect(fd, rp->ai_addr, (socklen_t)rp->ai_addrlen) == 0) {
450 avx_socket_set_keepalive(fd, 2, 1, 3);
451 avx_socket_set_tcp_nodelay(fd, true);
452 break; /* Successfully connected! */
453 }
454 }
455  
456 avx_socket_close(fd);
457 fd = AVX_INVALID_SOCKET;
458 }
459  
460 freeaddrinfo(res);
461 return fd;
462 }
463  
464 avx_socket_t avx_socket_connect_tcp(const char* host, uint16_t port) {
465 return avx_socket_connect_tcp_timeout(host, port, 3000);
466 }
467  
468 avx_socket_t avx_socket_create_mdns_multicast(void) {
469 avx_platform_sockets_init();
470 avx_socket_t fd = socket(AF_INET, SOCK_DGRAM, 0);
471 if (fd == AVX_INVALID_SOCKET) return AVX_INVALID_SOCKET;
472  
473 int opt = 1;
474 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char*)&opt, sizeof(opt));
475 avx_socket_set_nosigpipe(fd);
476  
477 struct sockaddr_in addr;
478 memset(&addr, 0, sizeof(addr));
479 addr.sin_family = AF_INET;
480 addr.sin_port = htons(AVX_MDNS_PORT);
481 addr.sin_addr.s_addr = INADDR_ANY;
482  
483 if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
484 avx_socket_close(fd);
485 return AVX_INVALID_SOCKET;
486 }
487  
488 /* Join multicast group 224.0.0.251 */
489 struct ip_mreq mreq;
490 memset(&mreq, 0, sizeof(mreq));
491 inet_pton(AF_INET, AVX_MDNS_MCAST_ADDR, &mreq.imr_multiaddr.s_addr);
492 mreq.imr_interface.s_addr = htonl(INADDR_ANY);
493 setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, (const char*)&mreq, sizeof(mreq));
494  
495 return fd;
496 }
497  
498 /* Zero-Sudo PCAP File Generation (Standard Ethernet DLT_EN10MB = 1) */
499 static FILE* g_pcap_file = NULL;
500 static avx_mutex_t g_pcap_lock = AVX_MUTEX_INITIALIZER;
501 static uint16_t g_pcap_ip_id = 1;
502  
503 AVX_PACKED_START
504 struct AVX_PACKED pcap_hdr_s {
505 uint32_t magic_number; /* 0xa1b2c3d4 */
506 uint16_t version_major; /* 2 */
507 uint16_t version_minor; /* 4 */
508 int32_t thiszone; /* 0 */
509 uint32_t sigfigs; /* 0 */
510 uint32_t snaplen; /* 65535 */
511 uint32_t network; /* 1 = DLT_EN10MB (Standard Ethernet) */
512 };
513  
514 struct AVX_PACKED pcaprec_hdr_s {
515 uint32_t ts_sec;
516 uint32_t ts_usec;
517 uint32_t incl_len;
518 uint32_t orig_len;
519 };
520 AVX_PACKED_END
521  
522 static uint16_t avx_pcap_ip_checksum(const void* buf, size_t len) {
523 const uint16_t* p = (const uint16_t*)buf;
524 uint32_t sum = 0;
525 while (len > 1) {
526 sum += *p++;
527 len -= 2;
528 }
529 if (len == 1) {
530 sum += *(const uint8_t*)p;
531 }
532 while (sum >> 16) {
533 sum = (sum & 0xffff) + (sum >> 16);
534 }
535 return (uint16_t)(~sum);
536 }
537  
538 void avx_pcap_init(const char* filepath) {
539 avx_mutex_lock(&g_pcap_lock);
540 if (!g_pcap_file && filepath) {
541 FILE *check = fopen(filepath, "rb");
542 bool has_header = false;
543 if (check) {
544 uint32_t magic = 0;
545 if (fread(&magic, sizeof(magic), 1, check) == 1 && magic == 0xa1b2c3d4) {
546 has_header = true;
547 }
548 fclose(check);
549 }
550  
551 if (has_header) {
552 g_pcap_file = fopen(filepath, "ab");
553 } else {
554 g_pcap_file = fopen(filepath, "wb");
555 if (g_pcap_file) {
556 struct pcap_hdr_s hdr = {
557 .magic_number = 0xa1b2c3d4,
558 .version_major = 2,
559 .version_minor = 4,
560 .thiszone = 0,
561 .sigfigs = 0,
562 .snaplen = 65535,
563 .network = 1 /* DLT_EN10MB */
564 };
565 fwrite(&hdr, sizeof(hdr), 1, g_pcap_file);
566 fflush(g_pcap_file);
567 }
568 }
569 }
570 avx_mutex_unlock(&g_pcap_lock);
571 }
572  
573 /* Synthesizes raw Ethernet/IPv4/UDP packets for Wireshark PCAP capture of live stream traffic. */
574 void avx_pcap_write_udp(uint32_t src_ip_net, uint16_t src_port_host, uint32_t dst_ip_net, uint16_t dst_port_host, const void* payload, size_t len) {
575 avx_mutex_lock(&g_pcap_lock);
576 if (!g_pcap_file) {
577 const char *pcap_env = getenv("OPENAVX_DUMP_PCAP");
578 if (pcap_env && pcap_env[0] != '\0') {
579 avx_mutex_unlock(&g_pcap_lock);
580 avx_pcap_init(pcap_env);
581 avx_mutex_lock(&g_pcap_lock);
582 }
583 if (!g_pcap_file) {
584 avx_mutex_unlock(&g_pcap_lock);
585 return;
586 }
587 }
588  
589 size_t clamped_len = len > 65000 ? 65000 : len;
590 size_t total_frame_len = 14 + 20 + 8 + clamped_len;
591 uint8_t *frame = (uint8_t*)malloc(total_frame_len);
592 if (!frame) {
593 avx_mutex_unlock(&g_pcap_lock);
594 return;
595 }
596  
597 /* 1. Ethernet Header (14 bytes) */
598 if (dst_ip_net == htonl(0xE00000FB)) {
599 uint8_t mcast_mac[6] = {0x01, 0x00, 0x5e, 0x00, 0x00, 0xfb};
600 memcpy(frame, mcast_mac, 6);
601 } else {
602 uint8_t dst_mac[6] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x02};
603 memcpy(frame, dst_mac, 6);
604 }
605 uint8_t src_mac[6] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x01};
606 memcpy(frame + 6, src_mac, 6);
607 uint16_t ethertype = htons(0x0800);
608 memcpy(frame + 12, &ethertype, 2);
609  
610 /* 2. IPv4 Header (20 bytes) */
611 uint8_t *ip = frame + 14;
612 ip[0] = 0x45;
613 ip[1] = 0x00;
614 uint16_t ip_len = htons((uint16_t)(20 + 8 + clamped_len));
615 memcpy(ip + 2, &ip_len, 2);
616 uint16_t ip_id = htons(g_pcap_ip_id++);
617 memcpy(ip + 4, &ip_id, 2);
618 uint16_t flags_frag = htons(0x4000);
619 memcpy(ip + 6, &flags_frag, 2);
620 ip[8] = 64;
621 ip[9] = 17; /* UDP */
622 uint16_t zero_csum = 0;
623 memcpy(ip + 10, &zero_csum, 2);
624 memcpy(ip + 12, &src_ip_net, 4);
625 memcpy(ip + 16, &dst_ip_net, 4);
626 uint16_t csum = avx_pcap_ip_checksum(ip, 20);
627 memcpy(ip + 10, &csum, 2);
628  
629 /* 3. UDP Header (8 bytes) */
630 uint8_t *udp = frame + 14 + 20;
631 uint16_t sp = htons(src_port_host);
632 uint16_t dp = htons(dst_port_host);
633 uint16_t ulen = htons((uint16_t)(8 + clamped_len));
634 memcpy(udp, &sp, 2);
635 memcpy(udp + 2, &dp, 2);
636 memcpy(udp + 4, &ulen, 2);
637 memcpy(udp + 6, &zero_csum, 2);
638  
639 /* 4. Payload */
640 if (payload && clamped_len > 0) {
641 memcpy(frame + 14 + 20 + 8, payload, clamped_len);
642 }
643  
644 struct timeval tv;
645 avx_gettimeofday(&tv, NULL);
646 struct pcaprec_hdr_s rec = {
647 .ts_sec = (uint32_t)tv.tv_sec,
648 .ts_usec = (uint32_t)tv.tv_usec,
649 .incl_len = (uint32_t)total_frame_len,
650 .orig_len = (uint32_t)(14 + 20 + 8 + len)
651 };
652 fwrite(&rec, sizeof(rec), 1, g_pcap_file);
653 fwrite(frame, total_frame_len, 1, g_pcap_file);
654 fflush(g_pcap_file);
655 free(frame);
656 avx_mutex_unlock(&g_pcap_lock);
657 }
658  
659 void avx_pcap_write_tcp(uint32_t src_ip_net, uint16_t src_port_host, uint32_t dst_ip_net, uint16_t dst_port_host, uint32_t seq, uint32_t ack, uint8_t flags, const void* payload, size_t len) {
660 avx_mutex_lock(&g_pcap_lock);
661 if (!g_pcap_file) {
662 const char *pcap_env = getenv("OPENAVX_DUMP_PCAP");
663 if (pcap_env && pcap_env[0] != '\0') {
664 avx_mutex_unlock(&g_pcap_lock);
665 avx_pcap_init(pcap_env);
666 avx_mutex_lock(&g_pcap_lock);
667 }
668 if (!g_pcap_file) {
669 avx_mutex_unlock(&g_pcap_lock);
670 return;
671 }
672 }
673  
674 size_t clamped_len = len > 65000 ? 65000 : len;
675 size_t total_frame_len = 14 + 20 + 20 + clamped_len;
676 uint8_t *frame = (uint8_t*)malloc(total_frame_len);
677 if (!frame) {
678 avx_mutex_unlock(&g_pcap_lock);
679 return;
680 }
681  
682 /* 1. Ethernet Header (14 bytes) */
683 uint8_t dst_mac[6] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x02};
684 uint8_t src_mac[6] = {0x02, 0x00, 0x00, 0x00, 0x00, 0x01};
685 memcpy(frame, dst_mac, 6);
686 memcpy(frame + 6, src_mac, 6);
687 uint16_t ethertype = htons(0x0800);
688 memcpy(frame + 12, &ethertype, 2);
689  
690 /* 2. IPv4 Header (20 bytes) */
691 uint8_t *ip = frame + 14;
692 ip[0] = 0x45;
693 ip[1] = 0x00;
694 uint16_t ip_len = htons((uint16_t)(20 + 20 + clamped_len));
695 memcpy(ip + 2, &ip_len, 2);
696 uint16_t ip_id = htons(g_pcap_ip_id++);
697 memcpy(ip + 4, &ip_id, 2);
698 uint16_t flags_frag = htons(0x4000);
699 memcpy(ip + 6, &flags_frag, 2);
700 ip[8] = 64;
701 ip[9] = 6; /* TCP */
702 uint16_t zero_csum = 0;
703 memcpy(ip + 10, &zero_csum, 2);
704 memcpy(ip + 12, &src_ip_net, 4);
705 memcpy(ip + 16, &dst_ip_net, 4);
706 uint16_t csum = avx_pcap_ip_checksum(ip, 20);
707 memcpy(ip + 10, &csum, 2);
708  
709 /* 3. TCP Header (20 bytes) */
710 uint8_t *tcp = frame + 14 + 20;
711 uint16_t sp = htons(src_port_host);
712 uint16_t dp = htons(dst_port_host);
713 uint32_t s = htonl(seq);
714 uint32_t a = htonl(ack);
715 uint16_t win = htons(65535);
716 memcpy(tcp, &sp, 2);
717 memcpy(tcp + 2, &dp, 2);
718 memcpy(tcp + 4, &s, 4);
719 memcpy(tcp + 8, &a, 4);
720 tcp[12] = 0x50; /* Data offset 20 bytes */
721 tcp[13] = flags;
722 memcpy(tcp + 14, &win, 2);
723 memcpy(tcp + 16, &zero_csum, 2);
724 memcpy(tcp + 18, &zero_csum, 2);
725  
726 /* 4. Payload */
727 if (payload && clamped_len > 0) {
728 memcpy(frame + 14 + 20 + 20, payload, clamped_len);
729 }
730  
731 struct timeval tv;
732 avx_gettimeofday(&tv, NULL);
733 struct pcaprec_hdr_s rec = {
734 .ts_sec = (uint32_t)tv.tv_sec,
735 .ts_usec = (uint32_t)tv.tv_usec,
736 .incl_len = (uint32_t)total_frame_len,
737 .orig_len = (uint32_t)(14 + 20 + 20 + len)
738 };
739 fwrite(&rec, sizeof(rec), 1, g_pcap_file);
740 fwrite(frame, total_frame_len, 1, g_pcap_file);
741 fflush(g_pcap_file);
742 free(frame);
743 avx_mutex_unlock(&g_pcap_lock);
744 }
745  
746 void avx_pcap_write_packet(const void* data, size_t len) {
747 avx_pcap_write_udp(htonl(0x7F000001), AVX_DEFAULT_PORT, htonl(0x7F000001), AVX_DEFAULT_PORT, data, len);
748 }
749  
750 void avx_pcap_close(void) {
751 avx_mutex_lock(&g_pcap_lock);
752 if (g_pcap_file) {
753 fclose(g_pcap_file);
754 g_pcap_file = NULL;
755 }
756 avx_mutex_unlock(&g_pcap_lock);
757 }
758  
759 /* Live Terminal Packet Tracer */
760 void avx_trace_packet(const char* direction, const char* tag, const void* data, size_t len) {
761 const char* trace_env = getenv("OPENAVX_PACKET_TRACE");
762 if (!trace_env || strcmp(trace_env, "0") == 0) return;
763  
764 bool use_color = false;
765 #if defined(AVX_OS_POSIX)
766 use_color = (isatty(fileno(stderr)) != 0);
767 #endif
768  
769 if (use_color) {
770 fprintf(stderr, "\033[1;36m[openavx:wire] [debug]\033[0m %s %s (%zu bytes)\n", direction, tag, len);
771 } else {
772 fprintf(stderr, "[openavx:wire] [debug] %s %s (%zu bytes)\n", direction, tag, len);
773 }
774  
775 const uint8_t* p = (const uint8_t*)data;
776 size_t preview_len = len > 64 ? 64 : len;
777  
778 fprintf(stderr, " hex : ");
779 for (size_t i = 0; i < preview_len; ++i) {
780 fprintf(stderr, "%02X ", p[i]);
781 if ((i + 1) % 16 == 0 && (i + 1) < preview_len) fprintf(stderr, "\n ");
782 }
783 if (len > 64) fprintf(stderr, "... (+%zu bytes)", len - 64);
784 fputc('\n', stderr);
785  
786 /* Print ASCII if printable characters detected */
787 bool has_ascii = false;
788 for (size_t i = 0; i < preview_len; ++i) {
789 if (p[i] >= 32 && p[i] <= 126) { has_ascii = true; break; }
790 }
791 if (has_ascii) {
792 fprintf(stderr, " asc : \"");
793 for (size_t i = 0; i < preview_len; ++i) {
794 fputc((p[i] >= 32 && p[i] <= 126) ? p[i] : '.', stderr);
795 }
796 fprintf(stderr, "\"\n");
797 }
798 fflush(stderr);
799 }
800  
801 /* Reads kernel socket diagnostics (TCP_INFO / queue ioctls) for RTT, retransmissions, and buffer backlog. */
802 void avx_socket_get_diagnostics(avx_socket_t sock, float *out_rtt_ms, uint32_t *out_retrans, uint32_t *out_send_q, uint32_t *out_recv_q) {
803 if (out_rtt_ms) *out_rtt_ms = 0.0f;
804 if (out_retrans) *out_retrans = 0;
805 if (out_send_q) *out_send_q = 0;
806 if (out_recv_q) *out_recv_q = 0;
807  
808 if (!avx_socket_is_valid(sock)) return;
809  
810 #if defined(AVX_OS_LINUX)
811 struct tcp_info info;
812 socklen_t len = sizeof(info);
813 if (getsockopt(sock, IPPROTO_TCP, TCP_INFO, &info, &len) == 0) {
814 if (out_rtt_ms) *out_rtt_ms = (float)info.tcpi_rtt / 1000.0f;
815 if (out_retrans) *out_retrans = info.tcpi_total_retrans;
816 }
817 int send_q = 0;
818 if (ioctl(sock, SIOCOUTQ, &send_q) == 0 && send_q > 0) {
819 if (out_send_q) *out_send_q = (uint32_t)send_q;
820 }
821 int recv_q = 0;
822 if (ioctl(sock, FIONREAD, &recv_q) == 0 && recv_q > 0) {
823 if (out_recv_q) *out_recv_q = (uint32_t)recv_q;
824 }
825 #elif defined(AVX_OS_MACOS)
826 #if defined(TCP_CONNECTION_INFO)
827 struct tcp_connection_info info;
828 socklen_t len = sizeof(info);
829 if (getsockopt(sock, IPPROTO_TCP, TCP_CONNECTION_INFO, &info, &len) == 0) {
830 if (out_rtt_ms) *out_rtt_ms = (float)info.tcpi_srtt;
831 if (out_retrans) *out_retrans = (uint32_t)info.tcpi_txretransmitpackets;
832 }
833 #endif
834 int recv_q = 0;
835 if (ioctl(sock, FIONREAD, &recv_q) == 0 && recv_q > 0) {
836 if (out_recv_q) *out_recv_q = (uint32_t)recv_q;
837 }
838 #elif defined(AVX_OS_WINDOWS)
839 u_long recv_q = 0;
840 if (ioctlsocket(sock, FIONREAD, &recv_q) == 0) {
841 if (out_recv_q) *out_recv_q = (uint32_t)recv_q;
842 }
843 #endif
844 }