Nilorea Library
C utilities for networking, threading, graphics
Loading...
Searching...
No Matches
n_network.c
Go to the documentation of this file.
1/*
2 * Nilorea Library
3 * Copyright (C) 2005-2026 Castagnier Mickael
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
14 * implied. See the License for the specific language governing
15 * permissions and limitations under the License.
16 *
17 * SPDX-License-Identifier: Apache-2.0
18 */
19
27
28#include <errno.h>
29#include <limits.h>
30#include <stdarg.h>
31#include <pthread.h>
32#include <unistd.h>
33#include <string.h>
34#include <ctype.h>
35#include <sys/types.h>
36
37#include "nilorea/n_network.h"
39#include "nilorea/n_reactor.h"
40#include "nilorea/n_log.h"
41#include "nilorea/n_hash.h"
42#include "nilorea/n_base64.h"
43#include "nilorea/n_zlib.h"
44#include "nilorea/n_lz4.h"
45#include "nilorea/n_time.h"
46
47/* Opportunistic payload compression. Threshold and ratio knobs live
48 * in nilorea/n_network.h so the reactor send path shares them. */
49
50/* MinGW does not provide strndup */
51#ifdef __windows__
52static char* _n_strndup(const char* s, size_t n) {
53 size_t len = strlen(s);
54 if (n < len) len = n;
55 char* p = (char*)malloc(len + 1);
56 if (p) {
57 memcpy(p, s, len);
58 p[len] = '\0';
59 }
60 return p;
61}
62#define strndup _n_strndup
63#endif
64
65#ifdef HAVE_OPENSSL
66#include <openssl/sha.h>
67#include <openssl/rand.h>
68#include <openssl/x509v3.h>
69#endif
70
71/* error capture infrastructure */
72
74#ifndef _Thread_local
75#define _Thread_local __thread
76#endif
77static _Thread_local char s_connect_errors[8][512];
80
82static void _netw_capture_error(NETWORK* netw, const char* fmt, ...) N_PRINTF_FORMAT(2, 3);
83static void _netw_capture_error(NETWORK* netw, const char* fmt, ...) {
84 if (!netw) return;
85 va_list ap;
86 va_start(ap, fmt);
87 vsnprintf(netw->netw_errors[netw->netw_err_next], 512, fmt, ap);
88 va_end(ap);
89 netw->netw_err_next = (netw->netw_err_next + 1) % 8;
90 if (netw->netw_err_count < 8) netw->netw_err_count++;
91}
92
94static void _netw_capture_connect_error(const char* fmt, ...) N_PRINTF_FORMAT(1, 2);
95static void _netw_capture_connect_error(const char* fmt, ...) {
96 va_list ap;
97 va_start(ap, fmt);
98 vsnprintf(s_connect_errors[s_connect_err_next], 512, fmt, ap);
99 va_end(ap);
102}
103
104/* public error accessors */
105
107 return netw ? netw->netw_err_count : 0;
108}
109
110const char* n_netw_get_error(const NETWORK* netw, int index) {
111 if (!netw || index < 0 || index >= netw->netw_err_count) return NULL;
112 int oldest = (netw->netw_err_next - netw->netw_err_count + 8) % 8;
113 return netw->netw_errors[(oldest + index) % 8];
114}
115
117 if (!netw) return;
118 netw->netw_err_count = 0;
119 netw->netw_err_next = 0;
120}
121
125
126const char* n_netw_get_connect_error(int index) {
127 if (index < 0 || index >= s_connect_err_count) return NULL;
128 int oldest = (s_connect_err_next - s_connect_err_count + 8) % 8;
129 return s_connect_errors[(oldest + index) % 8];
130}
131
136
139
140
145size_t htonst(size_t value) {
146#if __BYTE_ORDER == __LITTLE_ENDIAN
147 if (sizeof(size_t) == 4) {
148 return (size_t)htonl((uint32_t)value);
149 } else if (sizeof(size_t) == 8) {
150 return ((size_t)htonl((uint32_t)(value >> 32)) |
151 ((size_t)htonl((uint32_t)value) << 32));
152 }
153#endif
154 return value; // No conversion needed for big-endian
155}
156
162size_t ntohst(size_t value) {
163#if __BYTE_ORDER == __LITTLE_ENDIAN
164 if (sizeof(size_t) == 4) {
165 return (size_t)ntohl((uint32_t)value);
166 } else if (sizeof(size_t) == 8) {
167 return ((size_t)ntohl((uint32_t)(value >> 32)) |
168 ((size_t)ntohl((uint32_t)value) << 32));
169 }
170#endif
171 return value; // No conversion needed for big-endian
172}
173
174#ifdef __windows__
175
181char* wchar_to_char(const wchar_t* pwchar) {
182 __n_assert(pwchar, return NULL);
183
184 // get the number of characters in the string.
185 int currentCharIndex = 0;
186 char currentChar = (char)pwchar[currentCharIndex];
187 char* filePathC = NULL;
188
189 while (currentChar != '\0') {
190 currentCharIndex++;
191 currentChar = (char)pwchar[currentCharIndex];
192 }
193
194 const int charCount = currentCharIndex + 1;
195
196 // allocate a new block of memory size char (1 byte) instead of wide char (2 bytes)
197 Malloc(filePathC, char, (size_t)charCount);
198 __n_assert(filePathC, return NULL);
199
200 for (int i = 0; i < charCount; i++) {
201 // convert to char (1 byte)
202 char character = (char)pwchar[i];
203
204 *filePathC = character;
205
206 filePathC += sizeof(char);
207 }
208 filePathC += '\0';
209
210 filePathC -= (sizeof(char) * (size_t)charCount);
211
212 return filePathC;
213}
214
216#define NETW_CALL_RETRY(__retvar, __expression, __max_tries) \
217 do { \
218 int __nb_retries = 0; \
219 do { \
220 __retvar = (__expression); \
221 __nb_retries++; \
222 } while (__retvar == -1 && (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEWOULDBLOCK) && __nb_retries < (__max_tries)); \
223 if (__retvar == -1 && __nb_retries >= (__max_tries)) __retvar = -2; \
224 } while (0)
225
227#define neterrno WSAGetLastError()
228
232static char* netstrerror(int code) {
233 wchar_t* ws = NULL;
234 FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
235 NULL, (DWORD)code,
236 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
237 (LPWSTR)&ws, 0, NULL);
238 char* netstr = wchar_to_char(ws);
239 LocalFree(ws);
240 return netstr;
241}
242
243#if __GNUC__ <= 6 && __GNUC_MINOR__ <= 3
244
245/*--------------------------------------------------------------------------------------
246 By Marco Ladino - mladinox.. jan/2016
247 MinGW 3.45 thru 4.5 versions, don't have the socket functions:
248 --> inet_ntop(..)
249 --> inet_pton(..)
250 But with this adapted code using the original functions from FreeBSD,
251 one can to use it in the C/C++ Applications, without problem..!
252 This implementation, include tests for IPV4 and IPV6 addresses,
253 and is full C/C++ compatible..
254 --------------------------------------------------------------------------------------*/
255/* OpenBSD: strlcpy.c,v 1.11 2006/05/05 15:27:38 millert Exp */
256/*-
257 * Copyright (c) 1998 Todd C. Miller <Todd.Miller at courtesan.com>
258 *
259 * Permission to use, copy, modify, and distribute this software for any
260 * purpose with or without fee is hereby granted, provided that the above
261 * copyright notice and this permission notice appear in all copies.
262 *
263 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
264 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
265 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
266 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
267 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
268 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
269 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
270 */
271
279size_t strlcpy(char* dst, const char* src, size_t siz) {
280 char* d = dst;
281 const char* s = src;
282 size_t n = siz;
283
284 /* Copy as many bytes as will fit */
285 if (n != 0) {
286 while (--n != 0) {
287 if ((*d++ = *s++) == '\0')
288 break;
289 }
290 }
291
292 /* Not enough room in dst, add NUL and traverse rest of src */
293 if (n == 0) {
294 if (siz != 0)
295 *d = '\0'; /* NUL-terminate dst */
296 while (*s++);
297 }
298
299 return (s - src - 1); /* count does not include NUL */
300}
301
302/*
303 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
304 * Copyright (c) 1996-1999 by Internet Software Consortium.
305 *
306 * Permission to use, copy, modify, and distribute this software for any
307 * purpose with or without fee is hereby granted, provided that the above
308 * copyright notice and this permission notice appear in all copies.
309 *
310 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
311 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
312 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
313 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
314 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
315 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
316 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
317 */
318
319/*
320 * WARNING: Don't even consider trying to compile this on a system where
321 * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX.
322 */
323
324static char* inet_ntop4(const unsigned char* src, char* dst, socklen_t size);
325static char* inet_ntop6(const unsigned char* src, char* dst, socklen_t size);
326
335char* inet_ntop(int af, const void* src, char* dst, socklen_t size) {
336 switch (af) {
337 case AF_INET:
338 return (inet_ntop4((const unsigned char*)src, dst, size));
339 case AF_INET6:
340 return (inet_ntop6((const unsigned char*)src, dst, size));
341 default:
342 return (NULL);
343 }
344 /* NOTREACHED */
345}
346
347/* const char *
348 * inet_ntop4(src, dst, size)
349 * format an IPv4 address
350 * return:
351 * `dst' (as a const)
352 * notes:
353 * (1) uses no statics
354 * (2) takes a u_char* not an in_addr as input
355 * author:
356 * Paul Vixie, 1996.
357 */
358static char* inet_ntop4(const unsigned char* src, char* dst, socklen_t size) {
359 static const char fmt[] = "%u.%u.%u.%u";
360 char tmp[sizeof "255.255.255.255"];
361 int l;
362
363 l = snprintf(tmp, sizeof(tmp), fmt, src[0], src[1], src[2], src[3]);
364 if (l <= 0 || (socklen_t)l >= size) {
365 return (NULL);
366 }
367 strlcpy(dst, tmp, size);
368 return (dst);
369}
370
371/* const char *
372 * inet_ntop6(src, dst, size)
373 * convert IPv6 binary address into presentation (printable) format
374 * author:
375 * Paul Vixie, 1996.
376 */
377static char* inet_ntop6(const unsigned char* src, char* dst, socklen_t size) {
378 /*
379 * Note that int32_t and int16_t need only be "at least" large enough
380 * to contain a value of the specified size. On some systems, like
381 * Crays, there is no such thing as an integer variable with 16 bits.
382 * Keep this in mind if you think this function should have been coded
383 * to use pointer overlays. All the world's not a VAX.
384 */
385 char tmp[sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp;
386 struct
387 {
388 int base, len;
389 } best, cur;
390#define NS_IN6ADDRSZ 16
391#define NS_INT16SZ 2
392 u_int words[NS_IN6ADDRSZ / NS_INT16SZ];
393 int i;
394
395 /*
396 * Preprocess:
397 * Copy the input (bytewise) array into a wordwise array.
398 * Find the longest run of 0x00's in src[] for :: shorthanding.
399 */
400 memset(words, '\0', sizeof words);
401 for (i = 0; i < NS_IN6ADDRSZ; i++)
402 words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
403 best.base = -1;
404 best.len = 0;
405 cur.base = -1;
406 cur.len = 0;
407 for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
408 if (words[i] == 0) {
409 if (cur.base == -1)
410 cur.base = i, cur.len = 1;
411 else
412 cur.len++;
413 } else {
414 if (cur.base != -1) {
415 if (best.base == -1 || cur.len > best.len)
416 best = cur;
417 cur.base = -1;
418 }
419 }
420 }
421 if (cur.base != -1) {
422 if (best.base == -1 || cur.len > best.len)
423 best = cur;
424 }
425 if (best.base != -1 && best.len < 2)
426 best.base = -1;
427
428 /*
429 * Format the result.
430 */
431 tp = tmp;
432 for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
433 /* Are we inside the best run of 0x00's? */
434 if (best.base != -1 && i >= best.base &&
435 i < (best.base + best.len)) {
436 if (i == best.base)
437 *tp++ = ':';
438 continue;
439 }
440 /* Are we following an initial run of 0x00s or any real hex? */
441 if (i != 0)
442 *tp++ = ':';
443 /* Is this address an encapsulated IPv4? */
444 if (i == 6 && best.base == 0 && (best.len == 6 || (best.len == 7 && words[7] != 0x0001) || (best.len == 5 && words[5] == 0xffff))) {
445 if (!inet_ntop4(src + 12, tp, sizeof tmp - (tp - tmp)))
446 return (NULL);
447 tp += strlen(tp);
448 break;
449 }
450 tp += sprintf(tp, "%x", words[i]);
451 }
452 /* Was it a trailing run of 0x00's? */
453 if (best.base != -1 && (best.base + best.len) ==
454 (NS_IN6ADDRSZ / NS_INT16SZ))
455 *tp++ = ':';
456 *tp++ = '\0';
457
458 /*
459 * Check for overflow, copy, and we're done.
460 */
461 if ((socklen_t)(tp - tmp) > size) {
462 return (NULL);
463 }
464 strcpy(dst, tmp);
465 return (dst);
466}
467
468/*
469 * Copyright (c) 2004 by Internet Systems Consortium, Inc. ("ISC")
470 * Copyright (c) 1996,1999 by Internet Software Consortium.
471 *
472 * Permission to use, copy, modify, and distribute this software for any
473 * purpose with or without fee is hereby granted, provided that the above
474 * copyright notice and this permission notice appear in all copies.
475 *
476 * THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES
477 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
478 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR
479 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
480 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
481 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
482 * OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
483 */
484
485/*
486 * WARNING: Don't even consider trying to compile this on a system where
487 * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX.
488 */
489
490static int inet_pton4(const char* src, u_char* dst);
491static int inet_pton6(const char* src, u_char* dst);
492
500int inet_pton(int af, const char* src, void* dst) {
501 switch (af) {
502 case AF_INET:
503 return (inet_pton4(src, (unsigned char*)dst));
504 case AF_INET6:
505 return (inet_pton6(src, (unsigned char*)dst));
506 default:
507 return (-1);
508 }
509 /* NOTREACHED */
510}
511
512/* int
513 * inet_pton4(src, dst)
514 * like inet_aton() but without all the hexadecimal and shorthand.
515 * return:
516 * 1 if `src' is a valid dotted quad, else 0.
517 * notice:
518 * does not touch `dst' unless it's returning 1.
519 * author:
520 * Paul Vixie, 1996.
521 */
522static int inet_pton4(const char* src, u_char* dst) {
523 static const char digits[] = "0123456789";
524 int saw_digit, octets, ch;
525#define NS_INADDRSZ 4
526 /* Zero-initialise: the octets are filled through the `tp` alias
527 * below, which cppcheck's data flow can't follow, so it cannot
528 * prove tmp is fully written before the trailing memcpy. The
529 * init is harmless and removes the false uninitvar diagnostic. */
530 u_char tmp[NS_INADDRSZ] = {0}, *tp;
531
532 saw_digit = 0;
533 octets = 0;
534 tp = tmp;
535 while ((ch = *src++) != '\0') {
536 const char* pch;
537
538 if ((pch = strchr(digits, ch)) != NULL) {
539 u_int uiNew = *tp * 10 + (pch - digits);
540
541 if (saw_digit && *tp == 0)
542 return (0);
543 if (uiNew > 255)
544 return (0);
545 *tp = uiNew;
546 if (!saw_digit) {
547 if (++octets > 4)
548 return (0);
549 saw_digit = 1;
550 }
551 } else if (ch == '.' && saw_digit) {
552 if (octets == 4)
553 return (0);
554 *++tp = 0;
555 saw_digit = 0;
556 } else
557 return (0);
558 }
559 if (octets < 4)
560 return (0);
561 memcpy(dst, tmp, NS_INADDRSZ);
562 return (1);
563}
564
565/* int
566 * inet_pton6(src, dst)
567 * convert presentation level address to network order binary form.
568 * return:
569 * 1 if `src' is a valid [RFC1884 2.2] address, else 0.
570 * notice:
571 * (1) does not touch `dst' unless it's returning 1.
572 * (2) :: in a full address is silently ignored.
573 * credit:
574 * inspired by Mark Andrews.
575 * author:
576 * Paul Vixie, 1996.
577 */
578static int inet_pton6(const char* src, u_char* dst) {
579 static const char xdigits_l[] = "0123456789abcdef",
580 xdigits_u[] = "0123456789ABCDEF";
581#define NS_IN6ADDRSZ 16
582#define NS_INT16SZ 2
583 u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp;
584 const char* curtok;
585 int ch, seen_xdigits;
586 u_int val;
587
588 memset((tp = tmp), '\0', NS_IN6ADDRSZ);
589 endp = tp + NS_IN6ADDRSZ;
590 colonp = NULL;
591 /* Leading :: requires some special handling. */
592 if (*src == ':')
593 if (*++src != ':')
594 return (0);
595 curtok = src;
596 seen_xdigits = 0;
597 val = 0;
598 while ((ch = *src++) != '\0') {
599 const char* xdigits : const char* pch;
600
601 if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL)
602 pch = strchr((xdigits = xdigits_u), ch);
603 if (pch != NULL) {
604 val <<= 4;
605 val |= (pch - xdigits);
606 if (++seen_xdigits > 4)
607 return (0);
608 continue;
609 }
610 if (ch == ':') {
611 curtok = src;
612 if (!seen_xdigits) {
613 if (colonp)
614 return (0);
615 colonp = tp;
616 continue;
617 } else if (*src == '\0') {
618 return (0);
619 }
620 if (tp + NS_INT16SZ > endp)
621 return (0);
622 *tp++ = (u_char)(val >> 8) & 0xff;
623 *tp++ = (u_char)val & 0xff;
624 seen_xdigits = 0;
625 val = 0;
626 continue;
627 }
628 if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) &&
629 inet_pton4(curtok, tp) > 0) {
630 tp += NS_INADDRSZ;
631 seen_xdigits = 0;
632 break; /* '\\0' was seen by inet_pton4(). */
633 }
634 return (0);
635 }
636 if (seen_xdigits) {
637 if (tp + NS_INT16SZ > endp)
638 return (0);
639 *tp++ = (u_char)(val >> 8) & 0xff;
640 *tp++ = (u_char)val & 0xff;
641 }
642 if (colonp != NULL) {
643 /*
644 * Since some memmove()'s erroneously fail to handle
645 * overlapping regions, we'll do the shift by hand.
646 */
647 const int n = tp - colonp;
648 int i;
649
650 if (tp == endp)
651 return (0);
652 for (i = 1; i <= n; i++) {
653 endp[-i] = colonp[n - i];
654 colonp[n - i] = 0;
655 }
656 tp = endp;
657 }
658 if (tp != endp)
659 return (0);
660 memcpy(dst, tmp, NS_IN6ADDRSZ);
661 return (1);
662}
663
664#endif /* if GCC_VERSION <= 4.5 */
665
666#else /* not __windows__ */
667
668#include <sys/types.h>
669#include <sys/wait.h>
670
672#define NETW_CALL_RETRY(__retvar, __expression, __max_tries) \
673 do { \
674 int __nb_retries = 0; \
675 do { \
676 __retvar = (__expression); \
677 __nb_retries++; \
678 } while (__retvar == -1 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) && __nb_retries < (__max_tries)); \
679 if (__retvar == -1 && __nb_retries >= (__max_tries)) __retvar = -2; \
680 } while (0)
681
683#define neterrno errno
684
686/* #define netstrerror( code )({ \
687 size_t errmsglen = 512 ; // strerrorlen_s( code ) + 1 ; \
688 char *errmsg = NULL ; \
689 Malloc( errmsg , char , errmsglen ); \
690 if( errmsg ) \
691 { \
692 strerror_s( errmsg , errmsglen , code ); \
693 } \
694 errmsg ; \
695 }) */
696
700static char* netstrerror(int code) {
701 /* strdup returns NULL and sets errno=ENOMEM on allocation failure;
702 * propagate that NULL to the caller, who treats it as "no message". */
703 return strdup(strerror(code));
704}
705
706#endif /* if not def windows */
707
714NETWORK* netw_new(size_t send_list_limit, size_t recv_list_limit) {
715 NETWORK* netw = NULL;
716
717 Malloc(netw, NETWORK, 1);
718 __n_assert(netw, return NULL);
719
720 /* netw itself */
721 netw->nb_pending = -1;
722 netw->mode = -1;
723 netw->user_id = -1;
724 netw->nb_running_threads = 0;
726 netw->threaded_engine_status = NETW_THR_ENGINE_STOPPED;
727 /* Default to zlib for back-compat with the first compression
728 * pass that shipped before LZ4 support landed. Callers can
729 * switch to NONE or LZ4 via netw_set_compression_mode(). */
730 netw->compress_mode = NETW_COMPRESS_ZLIB;
731
732 /* netw -> link */
733 netw->link.sock = INVALID_SOCKET;
734 netw->link.port =
735 netw->link.ip = NULL;
736 memset(&netw->link.hints, 0, sizeof(struct addrinfo));
737 memset(&netw->link.raddr, 0, sizeof(struct sockaddr_storage));
738
739 /*initiliaze mutexs*/
740 if (pthread_mutex_init(&netw->sendbolt, NULL) != 0) {
741 n_log(LOG_ERR, "Error initializing netw -> sendbolt");
742 Free(netw);
743 return NULL;
744 }
745 /*initiliaze mutexs*/
746 if (pthread_mutex_init(&netw->recvbolt, NULL) != 0) {
747 n_log(LOG_ERR, "Error initializing netw -> recvbolt");
748 pthread_mutex_destroy(&netw->sendbolt);
749 Free(netw);
750 return NULL;
751 }
752 /*initiliaze mutexs*/
753 if (pthread_mutex_init(&netw->eventbolt, NULL) != 0) {
754 n_log(LOG_ERR, "Error initializing netw -> eventbolt");
755 pthread_mutex_destroy(&netw->sendbolt);
756 pthread_mutex_destroy(&netw->recvbolt);
757 Free(netw);
758 return NULL;
759 }
760 /* initialize send sem bolt */
761 if (sem_init(&netw->send_blocker, 0, 0) != 0) {
762 n_log(LOG_ERR, "Error initializing netw -> eventbolt");
763 pthread_mutex_destroy(&netw->eventbolt);
764 pthread_mutex_destroy(&netw->sendbolt);
765 pthread_mutex_destroy(&netw->recvbolt);
766 Free(netw);
767 return NULL;
768 }
769 /*initialize queues */
770 netw->recv_buf = new_generic_list(recv_list_limit);
771 if (!netw->recv_buf) {
772 n_log(LOG_ERR, "Error when creating receive list with %zu item limit", recv_list_limit);
774 return NULL;
775 }
776 netw->send_buf = new_generic_list(send_list_limit);
777 if (!netw->send_buf) {
778 n_log(LOG_ERR, "Error when creating send list with %zu item limit", send_list_limit);
780 return NULL;
781 }
783 if (!netw->pools) {
784 n_log(LOG_ERR, "Error when creating pools list");
786 return NULL;
787 }
788 netw->addr_infos_loaded = 0;
789 netw->send_queue_consecutive_wait = 0;
790 netw->so_reuseaddr = -1;
791 // netw -> so_reuseport = -1 ;
792 netw->so_keepalive = -1;
793 netw->tcpnodelay = -1;
794 netw->so_sndbuf = -1;
795 netw->so_rcvbuf = -1;
796 netw->so_rcvtimeo = -1;
797 netw->so_sndtimeo = -1;
798 netw->so_linger = -1;
799 netw->deplete_socket_timeout = -1;
800 netw->deplete_queues_timeout = -1;
801 netw->wait_close_timeout = -1;
802 netw->transport_type = NETWORK_TCP;
803 netw->crypto_algo = NETW_ENCRYPT_NONE;
804
805 netw->send_data = &send_data;
806 netw->recv_data = &recv_data;
807 netw->send_data_once = &send_data_once;
808 netw->recv_data_once = &recv_data_once;
809
810#ifdef HAVE_OPENSSL
811 netw->method = NULL;
812 netw->ctx = NULL;
813 netw->ssl = NULL;
814 netw->key = NULL;
815 netw->certificate = NULL;
816#endif
817
818 netw->link.is_blocking = 1;
819 return netw;
820
821} /* netw_new() */
822
828char* get_in_addr(struct sockaddr* sa) {
829 return sa->sa_family == AF_INET
830 ? (char*)&(((struct sockaddr_in*)sa)->sin_addr)
831 : (char*)&(((struct sockaddr_in6*)sa)->sin6_addr);
832}
833
841int netw_init_wsa(int mode, int v1, int v2) {
842 int compiler_warning_suppressor = 0;
843#if !defined(__linux__) && !defined(__sun) && !defined(_AIX)
844 static WSADATA WSAdata; /*WSA world*/
845 static int WSA_IS_INITIALIZED = 0; /*status checking*/
846
847 switch (mode) {
848 default:
849 /*returning WSA status*/
850 case 2:
851 return WSA_IS_INITIALIZED;
852 break;
853 /*loading WSA dll*/
854 case 1:
855 if (WSA_IS_INITIALIZED == 1)
856 return TRUE; /*already loaded*/
857 if ((WSAStartup(MAKEWORD(v1, v2), &WSAdata)) != 0) {
858 WSA_IS_INITIALIZED = 0;
859 return FALSE;
860 } else {
861 WSA_IS_INITIALIZED = 1;
862 return TRUE;
863 }
864 break;
865 /*unloading (closing) WSA */
866 case 0:
867 if (WSA_IS_INITIALIZED == 0)
868 return TRUE; /*already CLEANED or not loaded */
869 if (WSACleanup() == 0) {
870 WSA_IS_INITIALIZED = 0;
871 return TRUE;
872 }
873 break;
874 } /*switch(...)*/
875#endif /* ifndef __linux__ __sun _AIX */
876 compiler_warning_suppressor = mode + v1 + v2;
877 (void)compiler_warning_suppressor;
878 compiler_warning_suppressor = TRUE;
879 return compiler_warning_suppressor;
880} /*netw_init_wsa(...)*/
881
894 __n_assert(netw, return FALSE);
895 if (mode != NETW_COMPRESS_NONE &&
898 n_log(LOG_ERR, "netw_set_compression_mode: unknown mode %d", mode);
899 return FALSE;
900 }
901 netw->compress_mode = mode;
902 return TRUE;
903} /* netw_set_compression_mode */
904
911int netw_set_blocking(NETWORK* netw, unsigned long int is_blocking) {
912 __n_assert(netw, return FALSE);
913
914 int error = 0;
915 (void)error;
916 char* errmsg = NULL;
917
918#if defined(__linux__) || defined(__sun)
919 int flags = 0;
920 flags = fcntl(netw->link.sock, F_GETFL, 0);
921 if (netw->link.is_blocking != 0 && !is_blocking) {
922 if (flags & O_NONBLOCK) {
923 n_log(LOG_DEBUG, "socket %d was already in non-blocking mode", netw->link.sock);
924 /* in case we missed it, let's update the link mode */
925 netw->link.is_blocking = 0;
926 return TRUE;
927 }
928 } else if (netw->link.is_blocking != 1 && is_blocking) {
929 if (!(flags & O_NONBLOCK)) {
930 n_log(LOG_DEBUG, "socket %d was already in blocking mode", netw->link.sock);
931 /* in case we missed it, let's update the link mode */
932 netw->link.is_blocking = 1;
933 return TRUE;
934 }
935 }
936 if (fcntl(netw->link.sock, F_SETFL, is_blocking ? flags & ~O_NONBLOCK : flags | O_NONBLOCK) == -1) {
937 error = neterrno;
938 errmsg = netstrerror(error);
939 _netw_capture_error(netw, "couldn't set blocking mode %lu on %d: %s", is_blocking, netw->link.sock, _str(errmsg));
940 n_log(LOG_ERR, "couldn't set blocking mode %lu on %d: %s", is_blocking, netw->link.sock, _str(errmsg));
941 FreeNoLog(errmsg);
942 return FALSE;
943 }
944#else
945 unsigned long int blocking = 1 - is_blocking;
946 int res = ioctlsocket(netw->link.sock, (long)FIONBIO, &blocking);
947 error = neterrno;
948 if (res != NO_ERROR) {
949 errmsg = netstrerror(error);
950 _netw_capture_error(netw, "ioctlsocket failed with error: %d , neterrno: %s", res, _str(errmsg));
951 n_log(LOG_ERR, "ioctlsocket failed with error: %d , neterrno: %s", res, _str(errmsg));
952 FreeNoLog(errmsg);
954 return FALSE;
955 }
956#endif
957 netw->link.is_blocking = is_blocking;
958 return TRUE;
959} /* netw_set_blocking */
960
969int netw_setsockopt(NETWORK* netw, int optname, int value) {
970 __n_assert(netw, return FALSE);
971
972 int error = 0;
973 char* errmsg = NULL;
974
975 switch (optname) {
976 case TCP_NODELAY:
977 if (value >= 0) {
978 /* disable naggle algorithm */
979 if (setsockopt(netw->link.sock, IPPROTO_TCP, TCP_NODELAY, (const char*)&value, sizeof(value)) == -1) {
980 error = neterrno;
981 errmsg = netstrerror(error);
982 _netw_capture_error(netw, "Error from setsockopt(TCP_NODELAY) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
983 n_log(LOG_ERR, "Error from setsockopt(TCP_NODELAY) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
984 FreeNoLog(errmsg);
985 return FALSE;
986 }
987 }
988 netw->tcpnodelay = value;
989 break;
990 case SO_SNDBUF:
991 /* socket sending buffer size */
992 if (value >= 0) {
993 if (setsockopt(netw->link.sock, SOL_SOCKET, SO_SNDBUF, (const char*)&value, sizeof(value)) == -1) {
994 error = neterrno;
995 errmsg = netstrerror(error);
996 _netw_capture_error(netw, "Error from setsockopt(SO_SNDBUF) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
997 n_log(LOG_ERR, "Error from setsockopt(SO_SNDBUF) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
998 FreeNoLog(errmsg);
999 return FALSE;
1000 }
1001 }
1002 netw->so_sndbuf = value;
1003 break;
1004 case SO_RCVBUF:
1005 /* socket receiving buffer */
1006 if (value >= 0) {
1007 if (setsockopt(netw->link.sock, SOL_SOCKET, SO_RCVBUF, (const char*)&value, sizeof(value)) == -1) {
1008 error = neterrno;
1009 errmsg = netstrerror(error);
1010 _netw_capture_error(netw, "Error from setsockopt(SO_RCVBUF) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
1011 n_log(LOG_ERR, "Error from setsockopt(SO_RCVBUF) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
1012 FreeNoLog(errmsg);
1013 return FALSE;
1014 }
1015 }
1016 netw->so_rcvbuf = value;
1017 break;
1018 case SO_REUSEADDR:
1019 /* lose the pesky "Address already in use" error message*/
1020 if (setsockopt(netw->link.sock, SOL_SOCKET, SO_REUSEADDR, (char*)&value, sizeof(value)) == -1) {
1021 error = neterrno;
1022 errmsg = netstrerror(error);
1023 _netw_capture_error(netw, "Error from setsockopt(SO_REUSEADDR) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
1024 n_log(LOG_ERR, "Error from setsockopt(SO_REUSEADDR) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
1025 FreeNoLog(errmsg);
1026 return FALSE;
1027 }
1028 netw->so_reuseaddr = value;
1029 break;
1030 /*case SO_REUSEPORT :
1031 // lose the pesky "port already in use" error message
1032 if ( setsockopt( netw -> link . sock, SOL_SOCKET, SO_REUSEPORT, (char *)&value, sizeof( value ) ) == -1 )
1033 {
1034 error=neterrno ;
1035 errmsg = netstrerror( error );
1036 n_log( LOG_ERR, "Error from setsockopt(SO_REUSEPORT) on socket %d. neterrno: %s", netw -> link . sock, _str( errmsg ) );
1037 FreeNoLog( errmsg );
1038 return FALSE ;
1039 }
1040 netw -> so_reuseport = value ;
1041 break ;*/
1042 case SO_LINGER: {
1043 struct linger ling;
1044 if (value < 0) {
1045 ling.l_onoff = 0;
1046 ling.l_linger = 0;
1047 } else if (value == 0) {
1048 ling.l_onoff = 1;
1049 ling.l_linger = 0;
1050 } else {
1051 ling.l_onoff = 1;
1052#ifdef __windows__
1053 ling.l_linger = (u_short)value;
1054#else
1055 ling.l_linger = value;
1056#endif
1057 }
1058#ifndef __windows__
1059 if (setsockopt(netw->link.sock, SOL_SOCKET, SO_LINGER, &ling, sizeof(ling)) == -1) {
1060 error = neterrno;
1061 errmsg = netstrerror(error);
1062 _netw_capture_error(netw, "Error from setsockopt(SO_LINGER) on socket %d. neterrno: %s", netw->link.sock, _str(errmsg));
1063 n_log(LOG_ERR, "Error from setsockopt(SO_LINGER) on socket %d. neterrno: %s", netw->link.sock, _str(errmsg));
1064 FreeNoLog(errmsg);
1065 return FALSE;
1066 }
1067#else
1068 if (setsockopt(netw->link.sock, SOL_SOCKET, SO_LINGER, (const char*)&ling, sizeof(ling)) == -1) {
1069 error = neterrno;
1070 errmsg = netstrerror(error);
1071 _netw_capture_error(netw, "Error from setsockopt(SO_LINGER) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
1072 n_log(LOG_ERR, "Error from setsockopt(SO_LINGER) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
1073 FreeNoLog(errmsg);
1074 return FALSE;
1075 }
1076#endif // __windows__
1077 netw->so_linger = value;
1078 } break;
1079 case SO_RCVTIMEO:
1080 if (value >= 0) {
1081#ifndef __windows__
1082 {
1083 struct timeval tv;
1084 tv.tv_sec = value;
1085 tv.tv_usec = 0;
1086 if (setsockopt(netw->link.sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv) == -1) {
1087 error = neterrno;
1088 errmsg = netstrerror(error);
1089 _netw_capture_error(netw, "Error from setsockopt(SO_RCVTIMEO) on socket %d. neterrno: %s", netw->link.sock, _str(errmsg));
1090 n_log(LOG_ERR, "Error from setsockopt(SO_RCVTIMEO) on socket %d. neterrno: %s", netw->link.sock, _str(errmsg));
1091 FreeNoLog(errmsg);
1092 return FALSE;
1093 }
1094 }
1095#else
1096 if (setsockopt(netw->link.sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&value, sizeof value) == -1) {
1097 error = neterrno;
1098 errmsg = netstrerror(error);
1099 _netw_capture_error(netw, "Error from setsockopt(SO_RCVTIMEO) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
1100 n_log(LOG_ERR, "Error from setsockopt(SO_RCVTIMEO) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
1101 FreeNoLog(errmsg);
1102 return FALSE;
1103 }
1104#endif
1105 }
1106 netw->so_rcvtimeo = value;
1107 break;
1108 case SO_SNDTIMEO:
1109 if (value >= 0) {
1110#ifndef __windows__
1111 {
1112 struct timeval tv;
1113 tv.tv_sec = value;
1114 tv.tv_usec = 0;
1115
1116 if (setsockopt(netw->link.sock, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tv, sizeof tv) == -1) {
1117 error = neterrno;
1118 errmsg = netstrerror(error);
1119 _netw_capture_error(netw, "Error from setsockopt(SO_SNDTIMEO) on socket %d. neterrno: %s", netw->link.sock, _str(errmsg));
1120 n_log(LOG_ERR, "Error from setsockopt(SO_SNDTIMEO) on socket %d. neterrno: %s", netw->link.sock, _str(errmsg));
1121 FreeNoLog(errmsg);
1122 return FALSE;
1123 }
1124 }
1125#else
1126 if (setsockopt(netw->link.sock, SOL_SOCKET, SO_SNDTIMEO, (const char*)&value, sizeof value) == -1) {
1127 error = neterrno;
1128 errmsg = netstrerror(error);
1129 _netw_capture_error(netw, "Error from setsockopt(SO_SNDTIMEO) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
1130 n_log(LOG_ERR, "Error from setsockopt(SO_SNDTIMEO) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
1131 FreeNoLog(errmsg);
1132 return FALSE;
1133 }
1134#endif
1135 }
1136 netw->so_sndtimeo = value;
1137 break;
1139 netw->deplete_socket_timeout = value;
1140 break;
1142 netw->deplete_queues_timeout = value;
1143 break;
1145 netw->wait_close_timeout = value;
1146 break;
1148 netw->send_queue_consecutive_wait = value;
1149 break;
1150#ifdef __linux__
1151 case TCP_USER_TIMEOUT:
1152 if (value >= 0) {
1153 if (setsockopt(netw->link.sock, IPPROTO_TCP, TCP_USER_TIMEOUT, (const char*)&value, sizeof value) == -1) {
1154 error = neterrno;
1155 errmsg = netstrerror(error);
1156 _netw_capture_error(netw, "Error from setsockopt(TCP_USER_TIMEOUT) on socket %d. neterrno: %s", netw->link.sock, _str(errmsg));
1157 n_log(LOG_ERR, "Error from setsockopt(TCP_USER_TIMEOUT) on socket %d. neterrno: %s", netw->link.sock, _str(errmsg));
1158 FreeNoLog(errmsg);
1159 return FALSE;
1160 }
1161 }
1162 break;
1163 case TCP_QUICKACK:
1164 if (setsockopt(netw->link.sock, IPPROTO_TCP, TCP_QUICKACK, &value, sizeof(value)) < 0) {
1165 error = neterrno;
1166 errmsg = netstrerror(error);
1167 _netw_capture_error(netw, "Error setting setsockopt(TCP_QUICKACK) to %d on sock %d. neterrno: %s", value, netw->link.sock, _str(errmsg));
1168 n_log(LOG_ERR, "Error setting setsockopt(TCP_QUICKACK) to %d on sock %d. neterrno: %s", value, netw->link.sock, _str(errmsg));
1169 FreeNoLog(errmsg);
1170 return FALSE;
1171 }
1172 break;
1173#endif
1174 case SO_KEEPALIVE:
1175 if (setsockopt(netw->link.sock, SOL_SOCKET, SO_KEEPALIVE, (const char*)&value, sizeof value) == -1) {
1176 error = neterrno;
1177 errmsg = netstrerror(error);
1178 _netw_capture_error(netw, "Error from setsockopt(SO_KEEPALIVE) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
1179 n_log(LOG_ERR, "Error from setsockopt(SO_KEEPALIVE) on socket " SOCKET_SIZE_FORMAT ". neterrno: %s", netw->link.sock, _str(errmsg));
1180 FreeNoLog(errmsg);
1181 return FALSE;
1182 }
1183 netw->so_keepalive = value;
1184 break;
1185
1186 default:
1187 _netw_capture_error(netw, "%d is not a supported setsockopt", optname);
1188 n_log(LOG_ERR, "%d is not a supported setsockopt", optname);
1189 return FALSE;
1190 }
1191 return TRUE;
1192} /* netw_set_sock_opt */
1193
1194#ifdef HAVE_OPENSSL
1195
1201 BIO* bio = BIO_new(BIO_s_mem());
1202 if (!bio) {
1203 return NULL;
1204 }
1205
1206 ERR_print_errors(bio); // Write errors to the BIO
1207
1208 char* buf;
1209 size_t len = (size_t)BIO_get_mem_data(bio, &buf); // Get data from the BIO. Can return 0 if empty of failled
1210
1211 // Allocate memory for the error string and copy it
1212 char* error_str = malloc(len + 1);
1213 if (error_str) {
1214 memcpy(error_str, buf, len);
1215 error_str[len] = '\0'; // Null-terminate the string
1216 }
1217
1218 BIO_free(bio); // Free the BIO
1219
1220 return error_str;
1221}
1222
1232 unsigned long error = 0;
1233 while ((error = ERR_get_error())) {
1234 int level = LOG_ERR;
1235#ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING
1236 /* A peer that closes the TCP connection without a TLS close_notify makes
1237 OpenSSL 3.x queue "unexpected eof while reading". Clients (web browsers
1238 especially, on speculative/preconnect sockets) do this routinely, so it
1239 is expected disconnect noise rather than an error: log it at DEBUG so it
1240 does not drown a real TLS failure, which keeps its own reason code and
1241 LOG_ERR level. */
1242 if (ERR_GET_REASON(error) == SSL_R_UNEXPECTED_EOF_WHILE_READING)
1243 level = LOG_DEBUG;
1244#endif
1245 n_log(level, "socket " SOCKET_SIZE_FORMAT ": %s", socket, ERR_reason_error_string(error));
1246 }
1247}
1248
1249/***************************************************************************
1250 * _ _ ____ _
1251 * Project ___| | | | _ \| |
1252 * / __| | | | |_) | |
1253 * | (__| |_| | _ <| |___
1254 * \___|\___/|_| \_\_____|
1255 *
1256 * Copyright (C) 1998 - 2019, Daniel Stenberg, <daniel at haxx.se>, et al.
1257 *
1258 * This software is licensed as described in the file COPYING, which
1259 * you should have received as part of this distribution. The terms
1260 * are also available at https://curl.haxx.se/docs/copyright.html.
1261 *
1262 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
1263 * copies of the Software, and permit persons to whom the Software is
1264 * furnished to do so, under the terms of the COPYING file.
1265 *
1266 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
1267 * KIND, either express or implied.
1268 *
1269 ***************************************************************************/
1270/* <DESC>
1271 * Show the required mutex callback setups for GnuTLS and OpenSSL when using
1272 * libcurl multi-threaded.
1273 * </DESC>
1274 */
1275/* A multi-threaded example that uses pthreads and fetches 4 remote files at
1276 * once over HTTPS. The lock callbacks and stuff assume OpenSSL <1.1 or GnuTLS
1277 * (libgcrypt) so far.
1278 *
1279 * OpenSSL docs for this:
1280 * https://www.openssl.org/docs/man1.0.2/man3/CRYPTO_num_locks.html
1281 * gcrypt docs for this:
1282 * https://gnupg.org/documentation/manuals/gcrypt/Multi_002dThreading.html
1283 */
1284
1285/* we have this global to let the callback get easy access to it */
1286static pthread_mutex_t* netw_ssl_lockarray;
1287
1288__attribute__((unused)) static void netw_ssl_lock_callback(int mode, int type, char* file, int line) {
1289 (void)file;
1290 (void)line;
1291 if (mode & CRYPTO_LOCK) {
1292 pthread_mutex_lock(&(netw_ssl_lockarray[type]));
1293 } else {
1294 pthread_mutex_unlock(&(netw_ssl_lockarray[type]));
1295 }
1296}
1297
1298__attribute__((unused)) static unsigned long thread_id(void) {
1299 unsigned long ret;
1300
1301 ret = (unsigned long)pthread_self();
1302 return ret;
1303}
1304
1305static void netw_init_locks(void) {
1306 int i;
1307
1308 size_t lock_count = (size_t)CRYPTO_num_locks();
1309 netw_ssl_lockarray = (pthread_mutex_t*)OPENSSL_malloc((size_t)(lock_count * sizeof(pthread_mutex_t)));
1310
1311 for (i = 0; i < CRYPTO_num_locks(); i++) {
1312 pthread_mutex_init(&(netw_ssl_lockarray[i]), NULL);
1313 }
1314
1315 CRYPTO_set_id_callback((unsigned long (*)())thread_id);
1316 CRYPTO_set_locking_callback((void (*)())netw_ssl_lock_callback);
1317}
1318
1319static void netw_kill_locks(void) {
1320 int i;
1321
1322 CRYPTO_set_locking_callback(NULL);
1323 for (i = 0; i < CRYPTO_num_locks(); i++)
1324 pthread_mutex_destroy(&(netw_ssl_lockarray[i]));
1325
1326 OPENSSL_free(netw_ssl_lockarray);
1327}
1328
1330
1336 if (OPENSSL_IS_INITIALIZED == 1)
1337 return TRUE; /*already loaded*/
1338
1339 SSL_library_init();
1340 SSL_load_error_strings();
1341 // Before OpenSSL 1.1.0 (< 0x10100000L): ERR_load_BIO_strings(); was required to load error messages for BIO functions
1342#if OPENSSL_VERSION_NUMBER < 0x10100000L
1343 ERR_load_BIO_strings();
1344#endif
1345 OpenSSL_add_all_algorithms();
1347
1348#ifndef __windows__
1349 /* The raw send paths pass MSG_NOSIGNAL (NETFLAGS),
1350 * but OpenSSL's internal write(2) does not: a TLS peer that
1351 * disconnects mid-SSL_write delivers SIGPIPE and kills the whole
1352 * process (server, client, or test alike). Ignoring it here turns
1353 * that into the EPIPE errno the SSL error paths already handle.
1354 * Standard practice for OpenSSL applications; scoped to TLS users
1355 * since this only runs from netw_init_openssl. */
1356 signal(SIGPIPE, SIG_IGN);
1357#endif
1358
1360
1361 return TRUE;
1362} /*netw_init_openssl(...)*/
1363
1369 if (OPENSSL_IS_INITIALIZED == 0)
1370 return TRUE; /*already unloaded*/
1371
1373 EVP_cleanup();
1374
1376
1377 return TRUE;
1378} /*netw_unload_openssl(...)*/
1379
1380/* Release the half-built SSL context left by a failed netw_set_crypto() or
1381 * netw_set_crypto_pem(). Those functions only set crypto_algo once the whole
1382 * setup succeeded, so netw_close() would not recognise the ctx as owned and it
1383 * would leak. Call this on every failure path taken after SSL_CTX_new(). */
1385 __n_assert(netw, return);
1386 if (netw->ctx) {
1387 SSL_CTX_free(netw->ctx);
1388 netw->ctx = NULL;
1389 }
1390}
1391
1392/* Secure defaults for every server context this module creates (from a key
1393 * file, from PEM strings, or per connection on the SNI path): TLS 1.2 at
1394 * least, forward-secret AEAD ciphers only for TLS 1.2 (TLS 1.3 suites are all
1395 * AEAD already), X25519 / P-256 / P-384 key exchange, the server's cipher
1396 * order, and no compression (CRIME), renegotiation or session tickets (a
1397 * ticket key that is never rotated undoes forward secrecy; nothing here uses
1398 * resumption). A caller can still loosen or tighten a file/PEM context
1399 * afterwards with netw_ssl_set_versions() / netw_ssl_set_ciphers(). Returns
1400 * TRUE, or FALSE when OpenSSL refused a setting (the context is unusable). */
1401static int _netw_ssl_server_defaults(SSL_CTX* ctx) {
1402 __n_assert(ctx, return FALSE);
1403 /* one call per flag: the option type is long, unsigned long or uint64_t
1404 * depending on the OpenSSL release, and the macros carry the right one */
1405 SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION);
1406 SSL_CTX_set_options(ctx, SSL_OP_NO_TICKET);
1407 SSL_CTX_set_options(ctx, SSL_OP_CIPHER_SERVER_PREFERENCE);
1408#ifdef SSL_OP_NO_SSLv2
1409 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2);
1410#endif
1411#ifdef SSL_OP_NO_SSLv3
1412 SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv3);
1413#endif
1414#ifdef SSL_OP_NO_RENEGOTIATION
1415 SSL_CTX_set_options(ctx, SSL_OP_NO_RENEGOTIATION);
1416#endif
1417#if N_OSSL_HAVE_PROTO_VERSION_SETTERS
1418 if (SSL_CTX_set_min_proto_version(ctx, TLS1_2_VERSION) != 1) {
1419 n_log(LOG_ERR, "SSL_CTX_set_min_proto_version(TLS 1.2) failed");
1420 return FALSE;
1421 }
1422#endif
1423 if (SSL_CTX_set_cipher_list(ctx, "ECDHE+AESGCM:ECDHE+CHACHA20:!aNULL") != 1) {
1424 n_log(LOG_ERR, "SSL_CTX_set_cipher_list(secure defaults) failed");
1425 return FALSE;
1426 }
1427#if N_OSSL_OPENSSL_ATLEAST(0x10101000L) || N_OSSL_LIBRESSL_ATLEAST(0x2070000fL)
1428 if (SSL_CTX_set1_groups_list(ctx, "X25519:P-256:P-384") != 1) {
1429 n_log(LOG_ERR, "SSL_CTX_set1_groups_list(secure defaults) failed");
1430 return FALSE;
1431 }
1432#elif defined(SSL_CTX_set_ecdh_auto)
1433 SSL_CTX_set_ecdh_auto(ctx, 1);
1434#endif
1435 return TRUE;
1436}
1437
1449SSL_CTX* netw_ssl_server_ctx_new(const char* key_file, const char* cert_chain_file) {
1450 SSL_CTX* ctx = NULL;
1451 __n_assert(key_file, return NULL);
1452 __n_assert(cert_chain_file, return NULL);
1454#if OPENSSL_VERSION_NUMBER >= 0x10100000L
1455 ctx = SSL_CTX_new(TLS_server_method());
1456#else
1457 ctx = SSL_CTX_new(TLSv1_2_server_method());
1458#endif
1459 if (!ctx) {
1461 return NULL;
1462 }
1463 SSL_CTX_set_mode(ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1464 if (_netw_ssl_server_defaults(ctx) != TRUE) {
1466 SSL_CTX_free(ctx);
1467 return NULL;
1468 }
1469#if OPENSSL_VERSION_NUMBER >= 0x10101000L
1470 SSL_CTX_set_num_tickets(ctx, 0);
1471#endif
1472 if (SSL_CTX_use_certificate_chain_file(ctx, cert_chain_file) != 1 ||
1473 SSL_CTX_use_PrivateKey_file(ctx, key_file, SSL_FILETYPE_PEM) != 1 || SSL_CTX_check_private_key(ctx) != 1) {
1474 n_log(LOG_ERR, "netw_ssl_server_ctx_new: cannot load %s / %s, or they do not match", cert_chain_file, key_file);
1476 SSL_CTX_free(ctx);
1477 return NULL;
1478 }
1479 return ctx;
1480}
1481
1489int netw_set_crypto(NETWORK* netw, char* key, char* certificate) {
1490 __n_assert(netw, return FALSE);
1491
1492 char* tmp_key = NULL;
1493 char* tmp_cert = NULL;
1494 if (key && strlen(key) > 0) {
1495 tmp_key = strdup(key);
1496 if (!tmp_key) {
1497 n_log(LOG_ERR, "strdup failed for key in netw_set_crypto");
1498 return FALSE;
1499 }
1500 }
1501 if (certificate && strlen(certificate) > 0) {
1502 tmp_cert = strdup(certificate);
1503 if (!tmp_cert) {
1504 n_log(LOG_ERR, "strdup failed for certificate in netw_set_crypto");
1505 FreeNoLog(tmp_key);
1506 return FALSE;
1507 }
1508 }
1509 if (tmp_key) {
1510 FreeNoLog(netw->key);
1511 netw->key = tmp_key;
1512 }
1513 if (tmp_cert) {
1514 FreeNoLog(netw->certificate);
1515 netw->certificate = tmp_cert;
1516 }
1517 if (key && certificate) {
1519#if OPENSSL_VERSION_NUMBER >= 0x10100000L // OpenSSL 1.1.0 or later
1520 netw->method = TLS_method(); // create new server-method instance
1521#else
1522 netw->method = TLSv1_2_method(); // create new server-method instance
1523#endif
1524 netw->ctx = SSL_CTX_new(netw->method); // create new context from method
1525 // SSL_CTX_set_verify(netw -> ctx, SSL_VERIFY_PEER, NULL); // Enable certificate verification
1526
1527 if (netw->ctx == NULL) {
1528 netw_ssl_print_errors(netw->link.sock);
1529 return FALSE;
1530 }
1531 /* PARTIAL_WRITE: a short SSL_write can be resumed from the
1532 * caller's buffer+offset (required by the reactor's
1533 * single-attempt send path); MOVING_WRITE_BUFFER: tolerate the
1534 * resume pointer not being the original one. No-op for the
1535 * blocking thread engine. */
1536 SSL_CTX_set_mode(netw->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1537 if (_netw_ssl_server_defaults(netw->ctx) != TRUE) {
1538 netw_ssl_print_errors(netw->link.sock);
1540 return FALSE;
1541 }
1542
1543#if OPENSSL_VERSION_NUMBER >= 0x10101000L
1544 /* 2026-07-18: send ZERO TLS 1.3 session tickets. The threaded
1545 * client engine runs SSL_read (recv thread) and SSL_write (send
1546 * thread) on the same SSL*; OpenSSL does not support concurrent
1547 * use, and the one window where the read path MUTATES shared
1548 * session state is post-handshake NewSessionTicket processing,
1549 * which lands at the exact moment the client fires its first
1550 * application write (HELLO). On low-RTT links (loopback / LAN)
1551 * the overlap corrupts the client's outbound record stream and
1552 * the server dies with "decryption failed or bad record mac" on
1553 * its FIRST read (torn records can also sit unreadable for
1554 * seconds until more bytes complete them). Nothing here uses TLS
1555 * session resumption, so tickets are pure race surface, drop
1556 * them at the source. Higher-RTT links (the 8 ms VPS) rarely hit
1557 * the window, which is why this only surfaced on local servers. */
1558 SSL_CTX_set_num_tickets(netw->ctx, 0);
1559#endif
1560
1561 // Load default system certs
1562 if (SSL_CTX_load_verify_locations(netw->ctx, NULL, "/etc/ssl/certs/") != 1) {
1563 netw_ssl_print_errors(netw->link.sock);
1565 return FALSE;
1566 }
1567
1568 if (SSL_CTX_use_certificate_file(netw->ctx, certificate, SSL_FILETYPE_PEM) <= 0) {
1569 netw_ssl_print_errors(netw->link.sock);
1571 return FALSE;
1572 }
1573 if (SSL_CTX_use_PrivateKey_file(netw->ctx, key, SSL_FILETYPE_PEM) <= 0) {
1574 netw_ssl_print_errors(netw->link.sock);
1576 return FALSE;
1577 }
1578
1579 netw->send_data = &send_ssl_data;
1580 netw->recv_data = &recv_ssl_data;
1581 netw->send_data_once = &send_ssl_data_once;
1582 netw->recv_data_once = &recv_ssl_data_once;
1583
1584 netw->crypto_algo = NETW_ENCRYPT_OPENSSL;
1585 }
1586
1587 return TRUE;
1588} /* netw_set_crypto */
1589
1597int netw_set_crypto_pem(NETWORK* netw, const char* key_pem, const char* cert_pem) {
1598 __n_assert(netw, return FALSE);
1599 __n_assert(key_pem, return FALSE);
1600 __n_assert(cert_pem, return FALSE);
1601
1603#if OPENSSL_VERSION_NUMBER >= 0x10100000L
1604 netw->method = TLS_method();
1605#else
1606 netw->method = TLSv1_2_method();
1607#endif
1608 netw->ctx = SSL_CTX_new(netw->method);
1609 if (netw->ctx == NULL) {
1610 netw_ssl_print_errors(netw->link.sock);
1611 return FALSE;
1612 }
1613 /* PARTIAL_WRITE: a short SSL_write can be resumed from the
1614 * caller's buffer+offset (required by the reactor's
1615 * single-attempt send path); MOVING_WRITE_BUFFER: tolerate the
1616 * resume pointer not being the original one. No-op for the
1617 * blocking thread engine. */
1618 SSL_CTX_set_mode(netw->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1619 if (_netw_ssl_server_defaults(netw->ctx) != TRUE) {
1620 netw_ssl_print_errors(netw->link.sock);
1622 return FALSE;
1623 }
1624
1625#if OPENSSL_VERSION_NUMBER >= 0x10101000L
1626 /* 2026-07-18: zero TLS 1.3 session tickets; see the twin comment in
1627 * netw_set_crypto: post-handshake NewSessionTicket processing in the
1628 * client's recv thread races the send thread's first SSL_write on the
1629 * shared SSL* ("bad record mac" at connect on low-RTT links). No
1630 * consumer uses session resumption. */
1631 SSL_CTX_set_num_tickets(netw->ctx, 0);
1632#endif
1633
1634 /* Load certificate from PEM string */
1635 BIO* cert_bio = BIO_new_mem_buf(cert_pem, -1);
1636 if (!cert_bio) {
1637 n_log(LOG_ERR, "Failed to create BIO for certificate PEM");
1639 return FALSE;
1640 }
1641 X509* cert = PEM_read_bio_X509(cert_bio, NULL, NULL, NULL);
1642 BIO_free(cert_bio);
1643 if (!cert) {
1644 n_log(LOG_ERR, "Failed to parse certificate PEM");
1645 netw_ssl_print_errors(netw->link.sock);
1647 return FALSE;
1648 }
1649 if (SSL_CTX_use_certificate(netw->ctx, cert) <= 0) {
1650 X509_free(cert);
1651 netw_ssl_print_errors(netw->link.sock);
1653 return FALSE;
1654 }
1655 X509_free(cert);
1656
1657 /* Load private key from PEM string */
1658 BIO* key_bio = BIO_new_mem_buf(key_pem, -1);
1659 if (!key_bio) {
1660 n_log(LOG_ERR, "Failed to create BIO for key PEM");
1662 return FALSE;
1663 }
1664 EVP_PKEY* pkey = PEM_read_bio_PrivateKey(key_bio, NULL, NULL, NULL);
1665 BIO_free(key_bio);
1666 if (!pkey) {
1667 n_log(LOG_ERR, "Failed to parse private key PEM");
1668 netw_ssl_print_errors(netw->link.sock);
1670 return FALSE;
1671 }
1672 if (SSL_CTX_use_PrivateKey(netw->ctx, pkey) <= 0) {
1673 EVP_PKEY_free(pkey);
1674 netw_ssl_print_errors(netw->link.sock);
1676 return FALSE;
1677 }
1678 EVP_PKEY_free(pkey);
1679
1680 /* Verify that key matches certificate */
1681 if (!SSL_CTX_check_private_key(netw->ctx)) {
1682 n_log(LOG_ERR, "Private key does not match the certificate");
1684 return FALSE;
1685 }
1686
1687 netw->send_data = &send_ssl_data;
1688 netw->recv_data = &recv_ssl_data;
1689 netw->send_data_once = &send_ssl_data_once;
1690 netw->recv_data_once = &recv_ssl_data_once;
1691 netw->crypto_algo = NETW_ENCRYPT_OPENSSL;
1692
1693 return TRUE;
1694} /* netw_set_crypto_pem */
1695
1704int netw_set_crypto_chain(NETWORK* netw, char* key, char* certificate, char* ca_file) {
1705 __n_assert(netw, return FALSE);
1706 __n_assert(key, return FALSE);
1707 __n_assert(certificate, return FALSE);
1708 __n_assert(ca_file, return FALSE);
1709
1710 if (netw_set_crypto(netw, key, certificate) == FALSE) {
1711 return FALSE;
1712 }
1713
1714 /* Load the full certificate chain */
1715 if (SSL_CTX_use_certificate_chain_file(netw->ctx, certificate) <= 0) {
1716 n_log(LOG_ERR, "Failed to load certificate chain from %s", certificate);
1717 netw_ssl_print_errors(netw->link.sock);
1718 return FALSE;
1719 }
1720
1721 /* Load CA file for verification */
1722 if (SSL_CTX_load_verify_locations(netw->ctx, ca_file, NULL) != 1) {
1723 n_log(LOG_ERR, "Failed to load CA file %s", ca_file);
1724 netw_ssl_print_errors(netw->link.sock);
1725 return FALSE;
1726 }
1727
1728 return TRUE;
1729} /* netw_set_crypto_chain */
1730
1739int netw_set_crypto_chain_pem(NETWORK* netw, const char* key_pem, const char* cert_pem, const char* ca_pem) {
1740 __n_assert(netw, return FALSE);
1741 __n_assert(key_pem, return FALSE);
1742 __n_assert(cert_pem, return FALSE);
1743 __n_assert(ca_pem, return FALSE);
1744
1745 if (netw_set_crypto_pem(netw, key_pem, cert_pem) == FALSE) {
1746 return FALSE;
1747 }
1748
1749 /* Load CA certificate from PEM string into the trust store */
1750 BIO* ca_bio = BIO_new_mem_buf(ca_pem, -1);
1751 if (!ca_bio) {
1752 n_log(LOG_ERR, "Failed to create BIO for CA PEM");
1753 return FALSE;
1754 }
1755
1756 X509_STORE* store = SSL_CTX_get_cert_store(netw->ctx);
1757 if (!store) {
1758 BIO_free(ca_bio);
1759 n_log(LOG_ERR, "Failed to get certificate store from SSL context");
1760 return FALSE;
1761 }
1762
1763 X509* ca_cert = NULL;
1764 int ca_loaded = 0;
1765 while ((ca_cert = PEM_read_bio_X509(ca_bio, NULL, NULL, NULL)) != NULL) {
1766 if (X509_STORE_add_cert(store, ca_cert) != 1) {
1767 n_log(LOG_ERR, "Failed to add CA certificate to store");
1768 X509_free(ca_cert);
1769 BIO_free(ca_bio);
1770 return FALSE;
1771 }
1772 X509_free(ca_cert);
1773 ca_loaded++;
1774 }
1775 BIO_free(ca_bio);
1776
1777 if (ca_loaded == 0) {
1778 n_log(LOG_ERR, "No CA certificates were loaded from PEM string");
1779 return FALSE;
1780 }
1781
1782 /* Also load any extra chain certificates from the cert PEM */
1783 BIO* chain_bio = BIO_new_mem_buf(cert_pem, -1);
1784 if (chain_bio) {
1785 /* Skip the first certificate (already loaded as the leaf) */
1786 X509* skip_cert = PEM_read_bio_X509(chain_bio, NULL, NULL, NULL);
1787 if (skip_cert) {
1788 X509_free(skip_cert);
1789 }
1790 /* Load remaining certificates as chain intermediates */
1791 X509* chain_cert = NULL;
1792 while ((chain_cert = PEM_read_bio_X509(chain_bio, NULL, NULL, NULL)) != NULL) {
1793 if (SSL_CTX_add_extra_chain_cert(netw->ctx, chain_cert) != 1) {
1794 n_log(LOG_ERR, "Failed to add chain certificate");
1795 X509_free(chain_cert);
1796 }
1797 /* Note: SSL_CTX_add_extra_chain_cert takes ownership, so no X509_free on success */
1798 }
1799 BIO_free(chain_bio);
1800 }
1801
1802 return TRUE;
1803} /* netw_set_crypto_chain_pem */
1804
1805/* Install an in-memory certificate and key on a single SSL connection. Shared
1806 * by netw_set_crypto_pem_ctx and the SNI accept callback. Returns 0 on success,
1807 * -1 on error. */
1808static int _ssl_use_pem(SSL* ssl, const char* key_pem, const char* cert_pem) {
1809 BIO* cbio = BIO_new_mem_buf(cert_pem, -1);
1810 X509* cert = NULL;
1811 int rc = -1;
1812 if (!cbio)
1813 return -1;
1814 cert = PEM_read_bio_X509(cbio, NULL, NULL, NULL);
1815 BIO_free(cbio);
1816 if (!cert)
1817 return -1;
1818 if (SSL_use_certificate(ssl, cert) == 1) {
1819 BIO* kbio = BIO_new_mem_buf(key_pem, -1);
1820 if (kbio) {
1821 EVP_PKEY* pkey = PEM_read_bio_PrivateKey(kbio, NULL, NULL, NULL);
1822 BIO_free(kbio);
1823 if (pkey) {
1824 if (SSL_use_PrivateKey(ssl, pkey) == 1 && SSL_check_private_key(ssl) == 1)
1825 rc = 0;
1826 EVP_PKEY_free(pkey);
1827 }
1828 }
1829 }
1830 X509_free(cert);
1831 return rc;
1832}
1833
1840 __n_assert(netw, return NULL);
1841 if (!netw->ssl)
1842 return NULL;
1843 return SSL_get_servername(netw->ssl, TLSEXT_NAMETYPE_host_name);
1844}
1845
1853int netw_set_crypto_pem_ctx(NETWORK* netw, const N_STR* key_pem, const N_STR* cert_pem) {
1854 __n_assert(netw, return FALSE);
1855 __n_assert(netw->ssl, return FALSE);
1856 __n_assert(key_pem && key_pem->data, return FALSE);
1857 __n_assert(cert_pem && cert_pem->data, return FALSE);
1858 if (_ssl_use_pem(netw->ssl, key_pem->data, cert_pem->data) != 0) {
1859 netw_ssl_print_errors(netw->link.sock);
1860 return FALSE;
1861 }
1862 return TRUE;
1863}
1864
1865/* Arg handed (by stack pointer) to the servername and ALPN callbacks for the
1866 * duration of a single netw_accept_ssl_with_sni_cb call. */
1867typedef struct NETW_SNI_ARG {
1870 const char* const* alpn; /* protocols we accept, in server preference order */
1871 size_t alpn_count; /* how many, 0 when ALPN is not offered */
1872} NETW_SNI_ARG;
1873
1874/* OpenSSL ALPN select callback: fires during SSL_accept with the client's
1875 * protocol list (a series of length-prefixed names). Picks the first protocol
1876 * the server prefers that the client also offered. With no overlap it declines
1877 * (NOACK) rather than failing the handshake, so a client offering only protocols
1878 * we do not speak still connects and falls back to HTTP/1.1. */
1879static int _netw_alpn_select_cb(SSL* ssl, const unsigned char** out, unsigned char* outlen, const unsigned char* in, unsigned int inlen, void* arg) {
1880 NETW_SNI_ARG* a = (NETW_SNI_ARG*)arg;
1881 size_t i;
1882 (void)ssl;
1883 if (!a || !a->alpn || a->alpn_count == 0)
1884 return SSL_TLSEXT_ERR_NOACK;
1885 for (i = 0; i < a->alpn_count; i++) {
1886 size_t want = a->alpn[i] ? strlen(a->alpn[i]) : 0;
1887 unsigned int off = 0;
1888 if (want == 0 || want > 255)
1889 continue;
1890 while (off < inlen) {
1891 unsigned int l = in[off];
1892 if (l == 0 || off + 1 + l > inlen)
1893 break; /* malformed list: stop rather than read past it */
1894 if (l == want && memcmp(in + off + 1, a->alpn[i], want) == 0) {
1895 *out = in + off + 1;
1896 *outlen = (unsigned char)l;
1897 return SSL_TLSEXT_ERR_OK;
1898 }
1899 off += 1 + l;
1900 }
1901 }
1902 return SSL_TLSEXT_ERR_NOACK;
1903}
1904
1905/* Serialize a protocol list into the length-prefixed wire form ALPN uses.
1906 * Returns the bytes written, or 0 on a bad argument or an overflow. */
1907static size_t _netw_alpn_encode(const char* const* protos, size_t count, unsigned char* out, size_t out_cap) {
1908 size_t i, off = 0;
1909 if (!protos || count == 0 || !out)
1910 return 0;
1911 for (i = 0; i < count; i++) {
1912 size_t l = protos[i] ? strlen(protos[i]) : 0;
1913 if (l == 0 || l > 255 || off + 1 + l > out_cap)
1914 return 0;
1915 out[off++] = (unsigned char)l;
1916 memcpy(out + off, protos[i], l);
1917 off += l;
1918 }
1919 return off;
1920}
1921
1934int netw_ssl_set_alpn(NETWORK* netw, const char* const* protos, size_t count) {
1935 unsigned char wire[512];
1936 size_t len;
1937 __n_assert(netw, return FALSE);
1938 __n_assert(protos, return FALSE);
1939 __n_assert(netw->ctx, n_log(LOG_ERR, "SSL context not initialized, call netw_ssl_start_client first"); return FALSE);
1940 len = _netw_alpn_encode(protos, count, wire, sizeof(wire));
1941 if (len == 0) {
1942 n_log(LOG_ERR, "invalid ALPN protocol list");
1943 return FALSE;
1944 }
1945 if (SSL_CTX_set_alpn_protos(netw->ctx, wire, (unsigned int)len) != 0) {
1946 n_log(LOG_ERR, "OpenSSL refused the ALPN protocol list");
1947 return FALSE;
1948 }
1949 return TRUE;
1950}
1951
1964int netw_ssl_get_alpn(NETWORK* netw, char* out, size_t out_len) {
1965 const unsigned char* proto = NULL;
1966 unsigned int plen = 0;
1967 if (out && out_len > 0)
1968 out[0] = '\0';
1969 __n_assert(netw, return FALSE);
1970 __n_assert(out, return FALSE);
1971 if (!netw->ssl || out_len < 2)
1972 return FALSE;
1973 SSL_get0_alpn_selected(netw->ssl, &proto, &plen);
1974 if (!proto || plen == 0 || plen >= out_len)
1975 return FALSE;
1976 memcpy(out, proto, plen);
1977 out[plen] = '\0';
1978 return TRUE;
1979}
1980
1981/* OpenSSL servername callback: fires during SSL_accept once the ClientHello is
1982 * parsed. Picks a per-host certificate via the caller's pick() and installs it
1983 * on the current SSL so the handshake completes with a host-matching leaf. */
1984static int _netw_sni_servername_cb(SSL* ssl, int* al, void* arg) {
1985 NETW_SNI_ARG* a = (NETW_SNI_ARG*)arg;
1986 const char* sni;
1987 N_STR* cert_pem = NULL;
1988 N_STR* key_pem = NULL;
1989 int ok;
1990 (void)al;
1991 if (!a || !a->pick)
1992 return SSL_TLSEXT_ERR_OK;
1993 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1994 if (a->pick(sni, &cert_pem, &key_pem, a->user_data) != 0 || !cert_pem || !key_pem) {
1995 if (cert_pem)
1996 free_nstr(&cert_pem);
1997 if (key_pem)
1998 free_nstr(&key_pem);
1999 return SSL_TLSEXT_ERR_ALERT_FATAL;
2000 }
2001 ok = (_ssl_use_pem(ssl, key_pem->data, cert_pem->data) == 0);
2002 free_nstr(&cert_pem);
2003 free_nstr(&key_pem);
2004 return ok ? SSL_TLSEXT_ERR_OK : SSL_TLSEXT_ERR_ALERT_FATAL;
2005}
2006
2024 return netw_ssl_server_handshake_ex(netw, pick, user_data, NULL, 0);
2025}
2026
2047int netw_ssl_server_handshake_ex(NETWORK* netw, netw_sni_pick_cb pick, void* user_data, const char* const* alpn, size_t alpn_count) {
2048 NETW_SNI_ARG arg;
2049 __n_assert(netw, return FALSE);
2050 __n_assert(pick, return FALSE);
2051
2053#if OPENSSL_VERSION_NUMBER >= 0x10100000L
2054 netw->method = TLS_method();
2055#else
2056 netw->method = TLSv1_2_method();
2057#endif
2058 netw->ctx = SSL_CTX_new(netw->method);
2059 if (!netw->ctx) {
2060 netw_ssl_print_errors(netw->link.sock);
2061 return FALSE;
2062 }
2063 SSL_CTX_set_mode(netw->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
2064 /* this context is built here, per connection, so the caller never gets a
2065 * chance to harden it: it starts from the same secure defaults */
2066 if (_netw_ssl_server_defaults(netw->ctx) != TRUE) {
2067 netw_ssl_print_errors(netw->link.sock);
2068 return FALSE;
2069 }
2070#if OPENSSL_VERSION_NUMBER >= 0x10101000L
2071 SSL_CTX_set_num_tickets(netw->ctx, 0);
2072#endif
2073 SSL_CTX_set_tlsext_servername_callback(netw->ctx, _netw_sni_servername_cb);
2074
2075 /* The callback runs synchronously inside the blocking SSL_accept below, so a
2076 * stack-scoped arg is valid for its whole lifetime and needs no heap/free. */
2077 arg.pick = pick;
2078 arg.user_data = user_data;
2079 arg.alpn = alpn;
2080 arg.alpn_count = alpn ? alpn_count : 0;
2081 SSL_CTX_set_tlsext_servername_arg(netw->ctx, &arg);
2082 if (arg.alpn_count > 0)
2083 SSL_CTX_set_alpn_select_cb(netw->ctx, _netw_alpn_select_cb, &arg);
2084
2085 netw->ssl = SSL_new(netw->ctx);
2086 if (!netw->ssl) {
2087 netw_ssl_print_errors(netw->link.sock);
2088 return FALSE;
2089 }
2090 SSL_set_fd(netw->ssl, (int)netw->link.sock);
2091 netw->send_data = &send_ssl_data;
2092 netw->recv_data = &recv_ssl_data;
2093 netw->send_data_once = &send_ssl_data_once;
2094 netw->recv_data_once = &recv_ssl_data_once;
2095 netw->crypto_algo = NETW_ENCRYPT_OPENSSL;
2096
2097 if (SSL_accept(netw->ssl) <= 0) {
2098 netw_ssl_print_errors(netw->link.sock);
2099 return FALSE;
2100 }
2101 return TRUE;
2102}
2103
2117 NETWORK* client;
2118 __n_assert(listen, return NULL);
2119 __n_assert(pick, return NULL);
2120 client = netw_accept_from(listen);
2121 if (!client)
2122 return NULL;
2123 if (netw_ssl_server_handshake(client, pick, user_data) != TRUE) {
2125 return NULL;
2126 }
2127 return client;
2128}
2129
2137int netw_ssl_set_ca(NETWORK* netw, const char* ca_file, const char* ca_path) {
2138 __n_assert(netw, return FALSE);
2139 __n_assert(netw->ctx, n_log(LOG_ERR, "SSL context not initialized, call netw_set_crypto first"); return FALSE);
2140
2141 if (!ca_file && !ca_path) {
2142 n_log(LOG_ERR, "At least one of ca_file or ca_path must be specified");
2143 return FALSE;
2144 }
2145
2146 if (SSL_CTX_load_verify_locations(netw->ctx, ca_file, ca_path) != 1) {
2147 n_log(LOG_ERR, "Failed to load CA from file=%s path=%s", _str(ca_file), _str(ca_path));
2148 _netw_capture_error(netw, "Failed to load CA from file=%s path=%s", _str(ca_file), _str(ca_path));
2149 netw_ssl_print_errors(netw->link.sock);
2150 return FALSE;
2151 }
2152
2153 return TRUE;
2154} /* netw_ssl_set_ca */
2155
2163 __n_assert(netw, return FALSE);
2164 __n_assert(netw->ctx, n_log(LOG_ERR, "SSL context not initialized, call netw_set_crypto first"); return FALSE);
2165
2166 if (enable) {
2167 SSL_CTX_set_verify(netw->ctx, SSL_VERIFY_PEER, NULL);
2168 } else {
2169 SSL_CTX_set_verify(netw->ctx, SSL_VERIFY_NONE, NULL);
2170 }
2171
2172 return TRUE;
2173} /* netw_ssl_set_verify */
2174
2193// cppcheck-suppress constParameterPointer ; cppcheck does not parse the system OpenSSL headers, so OPENSSL_VERSION_NUMBER reads as 0 and only the 1.0.2 branch below is analysed, where netw is read-only. The >= 1.1.0 branch hands netw->ctx to SSL_CTX_set_min_proto_version(), which mutates it.
2194int netw_ssl_set_versions(NETWORK* netw, int min_version, int max_version) {
2195 __n_assert(netw, return FALSE);
2196 __n_assert(netw->ctx, n_log(LOG_ERR, "SSL context not initialized, call netw_set_crypto first"); return FALSE);
2197
2198#if N_OSSL_HAVE_PROTO_VERSION_SETTERS
2199 if (min_version != 0 && SSL_CTX_set_min_proto_version(netw->ctx, min_version) != 1) {
2200 n_log(LOG_ERR, "SSL_CTX_set_min_proto_version(%d) failed", min_version);
2201 return FALSE;
2202 }
2203 if (max_version != 0 && SSL_CTX_set_max_proto_version(netw->ctx, max_version) != 1) {
2204 n_log(LOG_ERR, "SSL_CTX_set_max_proto_version(%d) failed", max_version);
2205 return FALSE;
2206 }
2207#else
2208 /* SSL_CTX_set_min/max_proto_version() arrived in OpenSSL 1.1.0 (LibreSSL
2209 2.6). Without them the contexts this library builds come from
2210 TLSv1_2_method(), which is not version-flexible: TLS 1.2 is the only
2211 version they can ever speak.
2212 The only range that can be honoured is therefore one containing TLS 1.2.
2213 Refuse anything else rather than return TRUE and negotiate a version the
2214 caller did not ask for, which is the exact failure this call exists to
2215 prevent. */
2216 if (min_version != 0 && min_version > TLS1_2_VERSION) {
2217 n_log(LOG_ERR, "netw_ssl_set_versions: minimum %d is above TLS 1.2, the highest this OpenSSL supports", min_version);
2218 return FALSE;
2219 }
2220 if (max_version != 0 && max_version < TLS1_2_VERSION) {
2221 n_log(LOG_ERR, "netw_ssl_set_versions: maximum %d is below TLS 1.2, the only version this OpenSSL context speaks", max_version);
2222 return FALSE;
2223 }
2224#endif
2225 return TRUE;
2226} /* netw_ssl_set_versions */
2227
2244int netw_ssl_set_ciphers(NETWORK* netw, const char* cipher_list, const char* ciphersuites) {
2245 __n_assert(netw, return FALSE);
2246 __n_assert(netw->ctx, n_log(LOG_ERR, "SSL context not initialized, call netw_set_crypto first"); return FALSE);
2247
2248 if (cipher_list && cipher_list[0] && SSL_CTX_set_cipher_list(netw->ctx, cipher_list) != 1) {
2249 n_log(LOG_ERR, "SSL_CTX_set_cipher_list(%s) failed: no cipher matched", cipher_list);
2250 return FALSE;
2251 }
2252#if NETW_HAVE_TLS13
2253 if (ciphersuites && ciphersuites[0] && SSL_CTX_set_ciphersuites(netw->ctx, ciphersuites) != 1) {
2254 n_log(LOG_ERR, "SSL_CTX_set_ciphersuites(%s) failed", ciphersuites);
2255 return FALSE;
2256 }
2257#else
2258 /* SSL_CTX_set_ciphersuites() arrived with TLS 1.3 in OpenSSL 1.1.1 and only
2259 ever names TLS 1.3 suites. An OpenSSL that does not have the call cannot
2260 negotiate TLS 1.3 either, so there is no handshake for the string to
2261 restrict and nothing is silently left at a default: cipher_list above
2262 still governs every version this build can speak. Say so once and carry
2263 on, so a portable caller does not have to guard the argument. Callers
2264 that must know can test NETW_HAVE_TLS13. */
2265 if (ciphersuites && ciphersuites[0]) {
2266 n_log(LOG_DEBUG, "netw_ssl_set_ciphers: ignoring the TLS 1.3 ciphersuites '%s', this OpenSSL cannot negotiate TLS 1.3", ciphersuites);
2267 }
2268#endif
2269 return TRUE;
2270} /* netw_ssl_set_ciphers */
2271
2288int netw_ssl_get_verify_result(NETWORK* netw, const char* expected_host, char* errbuf, size_t errsz) {
2289 X509* cert = NULL;
2290 STACK_OF(X509)* chain = NULL;
2291 X509_STORE* store = NULL;
2292 X509_STORE_CTX* store_ctx = NULL;
2293 int chain_ok = 0;
2294 int host_ok = 1;
2295 int result = FALSE;
2296
2297 if (errbuf && errsz > 0)
2298 errbuf[0] = '\0';
2299 __n_assert(netw, return FALSE);
2300 __n_assert(netw->ssl, return FALSE);
2301
2303 if (!cert) {
2304 if (errbuf && errsz > 0)
2305 snprintf(errbuf, errsz, "no peer certificate");
2306 return FALSE;
2307 }
2308 chain = SSL_get_peer_cert_chain(netw->ssl);
2309
2310 store = X509_STORE_new();
2311 store_ctx = X509_STORE_CTX_new();
2312 if (!store || !store_ctx) {
2313 if (errbuf && errsz > 0)
2314 snprintf(errbuf, errsz, "out of memory");
2315 goto cleanup;
2316 }
2317 X509_STORE_set_default_paths(store);
2318 if (X509_STORE_CTX_init(store_ctx, store, cert, chain) != 1) {
2319 if (errbuf && errsz > 0)
2320 snprintf(errbuf, errsz, "verify init failed");
2321 goto cleanup;
2322 }
2323 if (X509_verify_cert(store_ctx) == 1) {
2324 chain_ok = 1;
2325 } else {
2326 int verr = X509_STORE_CTX_get_error(store_ctx);
2327 if (errbuf && errsz > 0)
2328 snprintf(errbuf, errsz, "%s", X509_verify_cert_error_string(verr));
2329 }
2330 if (expected_host && expected_host[0]) {
2331 if (X509_check_host(cert, expected_host, 0, 0, NULL) != 1) {
2332 host_ok = 0;
2333 if (errbuf && errsz > 0 && chain_ok)
2334 snprintf(errbuf, errsz, "hostname mismatch for %s", expected_host);
2335 }
2336 }
2337 result = (chain_ok && host_ok) ? TRUE : FALSE;
2338
2339cleanup:
2340 if (store_ctx)
2341 X509_STORE_CTX_free(store_ctx);
2342 if (store)
2343 X509_STORE_free(store);
2344 X509_free(cert);
2345 return result;
2346} /* netw_ssl_get_verify_result */
2347
2355int netw_ssl_set_client_cert(NETWORK* netw, const char* cert_file, const char* key_file) {
2356 __n_assert(netw, return FALSE);
2357 __n_assert(netw->ctx, n_log(LOG_ERR, "SSL context not initialized"); return FALSE);
2358 __n_assert(cert_file, return FALSE);
2359
2360 if (SSL_CTX_use_certificate_file(netw->ctx, cert_file, SSL_FILETYPE_PEM) != 1) {
2361 n_log(LOG_ERR, "Failed to load client certificate from %s", cert_file);
2362 _netw_capture_error(netw, "Failed to load client certificate from %s", cert_file);
2363 netw_ssl_print_errors(netw->link.sock);
2364 return FALSE;
2365 }
2366
2367 const char* kf = key_file ? key_file : cert_file;
2368 if (SSL_CTX_use_PrivateKey_file(netw->ctx, kf, SSL_FILETYPE_PEM) != 1) {
2369 n_log(LOG_ERR, "Failed to load client private key from %s", kf);
2370 _netw_capture_error(netw, "Failed to load client private key from %s", kf);
2371 netw_ssl_print_errors(netw->link.sock);
2372 return FALSE;
2373 }
2374
2375 if (SSL_CTX_check_private_key(netw->ctx) != 1) {
2376 n_log(LOG_ERR, "Client certificate and private key do not match");
2377 _netw_capture_error(netw, "Client certificate and private key do not match");
2378 netw_ssl_print_errors(netw->link.sock);
2379 return FALSE;
2380 }
2381
2382 return TRUE;
2383} /* netw_ssl_set_client_cert */
2384
2385#endif /* HAVE_OPENSSL */
2386
2389#define NETW_CONNECT_ABORT_POLL_MS 100
2390
2392static int (*_netw_connect_abort_cb)(void*) = NULL;
2394static void* _netw_connect_abort_ctx = NULL;
2395
2411static int _netw_timed_connect(NETWORK* netw, SOCKET sock, struct addrinfo* rp, int connect_timeout_ms) {
2412 if (connect_timeout_ms <= 0) {
2413 return connect(sock, rp->ai_addr, (socklen_t)rp->ai_addrlen);
2414 }
2415
2416 if (netw_set_blocking(netw, 0) == FALSE) {
2417 /* could not switch modes: fall back to a blocking connect */
2418 return connect(sock, rp->ai_addr, (socklen_t)rp->ai_addrlen);
2419 }
2420
2421 int rc = connect(sock, rp->ai_addr, (socklen_t)rp->ai_addrlen);
2422 if (rc == 0) {
2424 return 0;
2425 }
2426
2427 int in_progress = 0;
2428#ifdef __windows__
2429 if (neterrno == WSAEWOULDBLOCK || neterrno == WSAEINPROGRESS) in_progress = 1;
2430#else
2431 if (neterrno == EINPROGRESS) in_progress = 1;
2432#endif
2433 if (!in_progress) {
2435 return -1;
2436 }
2437
2438 /* select() blocks the thread in the kernel (no busy-wait). If a signal
2439 interrupts it (EINTR) we retry with the remaining time so the total
2440 wait still honours connect_timeout_ms. select() only rewrites the
2441 timeval argument on Linux, so the remaining time is tracked
2442 explicitly with N_TIME for portability (Windows/MinGW included).
2443 When a connect-abort callback is registered the per-select wait is
2444 capped to NETW_CONNECT_ABORT_POLL_MS so the loop wakes periodically to
2445 poll it, letting a caller interrupt a connect to an unresponsive host
2446 without waiting out the whole connect timeout. */
2447 N_TIME timer;
2448 start_HiTimer(&timer);
2449 time_t remaining_us = (time_t)connect_timeout_ms * 1000;
2450 time_t poll_us = _netw_connect_abort_cb ? (time_t)NETW_CONNECT_ABORT_POLL_MS * 1000 : 0;
2451 int connected = 0;
2452 int aborted = 0;
2453 for (;;) {
2455 aborted = 1;
2456 break;
2457 }
2458 /* Watch both the write set and the exception set: a completed
2459 connect signals writefds, but on Winsock a *failed* connect
2460 signals exceptfds (not writefds). Watching only writefds there
2461 would miss the failure and wait out the whole timeout. The
2462 SO_ERROR check after the loop is the final arbiter on both. */
2463 fd_set wset, eset;
2464 FD_ZERO(&wset);
2465 FD_SET(sock, &wset);
2466 FD_ZERO(&eset);
2467 FD_SET(sock, &eset);
2468 time_t wait_us = remaining_us;
2469 if (poll_us > 0 && wait_us > poll_us)
2470 wait_us = poll_us;
2471 struct timeval tv;
2472 tv.tv_sec = (long)(wait_us / 1000000);
2473 tv.tv_usec = (long)(wait_us % 1000000);
2474
2475 int sel = select((int)sock + 1, NULL, &wset, &eset, &tv);
2476 if (sel > 0) {
2477 connected = 1; /* socket signalled; SO_ERROR check decides below */
2478 break;
2479 }
2480 if (sel == 0) {
2481 /* the select() wait expired: subtract it from the remaining budget.
2482 If this was only a poll slice (an abort callback is registered) and
2483 time is left, loop to re-check the callback; otherwise the connect
2484 timeout has been reached. */
2485 remaining_us -= get_usec(&timer);
2486 if (remaining_us <= 0)
2487 break; /* connect timed out */
2488 continue;
2489 }
2490 /* sel < 0 */
2491#ifdef __windows__
2492 int interrupted = (neterrno == WSAEINTR);
2493#else
2494 int interrupted = (neterrno == EINTR);
2495#endif
2496 if (!interrupted) {
2497 break; /* genuine select() error */
2498 }
2499 /* interrupted by a signal: subtract the time already spent and
2500 retry only if some of the budget is left. */
2501 remaining_us -= get_usec(&timer);
2502 if (remaining_us <= 0) {
2503 break; /* budget exhausted while interrupted */
2504 }
2505 }
2506
2507 if (aborted || !connected) {
2509 return -1;
2510 }
2511
2512 int so_error = 0;
2513 socklen_t slen = sizeof(so_error);
2514 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (char*)&so_error, &slen) == -1 || so_error != 0) {
2516 return -1;
2517 }
2518
2520 return 0;
2521} /* _netw_timed_connect */
2522
2539void netw_set_connect_abort_cb(int (*cb)(void* ctx), void* ctx) {
2542} /* netw_set_connect_abort_cb(...) */
2543
2557int netw_connect_ex_to(NETWORK** netw, char* host, char* port, size_t send_list_limit, size_t recv_list_limit, int ip_version, char* ssl_key_file, char* ssl_cert_file, int connect_timeout_ms) {
2558 // kill compilation warning when there is no openssl
2559 (void)ssl_key_file;
2560 (void)ssl_cert_file;
2561 int error = 0, net_status = 0;
2562 char* errmsg = NULL;
2563
2564 /*do not work over an already used netw*/
2565 if ((*netw)) {
2566 n_log(LOG_ERR, "Unable to allocate (*netw), already existing. You must use empty NETWORK *structs.");
2567 return FALSE;
2568 }
2569
2570 /*creating array*/
2571 (*netw) = netw_new(send_list_limit, recv_list_limit);
2572 __n_assert(netw && (*netw), return FALSE);
2573
2574 /*checking WSA when under windows*/
2575 if (netw_init_wsa(1, 2, 2) == FALSE) {
2576 n_log(LOG_ERR, "Unable to load WSA dll's");
2578 return FALSE;
2579 }
2580
2581 /* choose ip version */
2582 if (ip_version == NETWORK_IPV4) {
2583 (*netw)->link.hints.ai_family = AF_INET; /* Allow IPv4 */
2584 } else if (ip_version == NETWORK_IPV6) {
2585 (*netw)->link.hints.ai_family = AF_INET6; /* Allow IPv6 */
2586 } else {
2587 /* NETWORK_ALL or unknown value */
2588 (*netw)->link.hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
2589 }
2590
2591 (*netw)->link.hints.ai_socktype = SOCK_STREAM;
2592 (*netw)->link.hints.ai_protocol = IPPROTO_TCP;
2593 (*netw)->link.hints.ai_flags = AI_PASSIVE;
2594 (*netw)->link.hints.ai_canonname = NULL;
2595 (*netw)->link.hints.ai_next = NULL;
2596
2597 /* Time the resolve and connect phases so callers can present a
2598 connect-timing breakdown. get_usec returns the delta since the
2599 previous call, so the first reads the DNS phase and the second
2600 reads the TCP-connect phase. */
2601 N_TIME connect_timer;
2602 start_HiTimer(&connect_timer);
2603
2604 /* Note: on some system, i.e Solaris, it WILL show leak in getaddrinfo.
2605 * Testing it inside a 1,100 loop showed not effect on the amount of leaked
2606 * memory */
2607 error = getaddrinfo(host, port, &(*netw)->link.hints, &(*netw)->link.rhost);
2608 if (error != 0) {
2609 _netw_capture_error(*netw, "Error when resolving %s:%s getaddrinfo: %s", host, port, gai_strerror(error));
2610 n_log(LOG_ERR, "Error when resolving %s:%s getaddrinfo: %s", host, port, gai_strerror(error));
2611 _netw_capture_connect_error("DNS resolution failed for %s:%s: %s", host, port, gai_strerror(error));
2613 return FALSE;
2614 }
2615 (*netw)->addr_infos_loaded = 1;
2616 (*netw)->connect_dns_usec = (long long)get_usec(&connect_timer);
2617 Malloc((*netw)->link.ip, char, 64);
2618 __n_assert((*netw)->link.ip, netw_close(netw); return FALSE);
2619
2620 /* getaddrinfo() returns a list of address structures. Try each address until we successfully connect. If socket or connect fails, we close the socket and try the next address. */
2621 struct addrinfo* rp = NULL;
2622 for (rp = (*netw)->link.rhost; rp != NULL; rp = rp->ai_next) {
2623 SOCKET sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
2624 if (sock == INVALID_SOCKET) {
2625 error = neterrno;
2626 errmsg = netstrerror(error);
2627 n_log(LOG_ERR, "Error while trying to make a socket: %s", _str(errmsg));
2628 FreeNoLog(errmsg);
2629 continue;
2630 }
2631
2632 (*netw)->link.sock = sock;
2633
2634 net_status = _netw_timed_connect(*netw, sock, rp, connect_timeout_ms);
2635 if (net_status == -1) {
2636 error = neterrno;
2637 errmsg = netstrerror(error);
2638 n_log(LOG_INFO, "connecting to %s:%s : %s", host, port, _str(errmsg));
2639 FreeNoLog(errmsg);
2640 closesocket(sock);
2641 (*netw)->link.sock = INVALID_SOCKET;
2642 continue;
2643 } else {
2644 /*storing connected port and ip address*/
2645 if (!inet_ntop(rp->ai_family, get_in_addr(rp->ai_addr), (*netw)->link.ip, 64)) {
2646 error = neterrno;
2647 errmsg = netstrerror(error);
2648 n_log(LOG_ERR, "inet_ntop: %p , %s", rp, _str(errmsg));
2649 FreeNoLog(errmsg);
2650 }
2651 break; /* Success */
2652 }
2653 }
2654 if (rp == NULL) {
2655 /* No address succeeded */
2656 _netw_capture_error(*netw, "Couldn't connect to %s:%s : no address succeeded", host, port);
2657 n_log(LOG_ERR, "Couldn't connect to %s:%s : no address succeeded", host, port);
2658 _netw_capture_connect_error("TCP connect failed for %s:%s: no address succeeded", host, port);
2660 return FALSE;
2661 }
2662 (*netw)->connect_tcp_usec = (long long)get_usec(&connect_timer);
2663
2664 (*netw)->link.port = strdup(port);
2665 __n_assert((*netw)->link.port, netw_close(netw); return FALSE);
2666
2667 if (ssl_key_file && ssl_cert_file) {
2668#ifdef HAVE_OPENSSL
2669 if (netw_set_crypto((*netw), ssl_key_file, ssl_cert_file) == FALSE) {
2670 /* could not initialize SSL */
2671 n_log(LOG_ERR, "couldn't initialize SSL !");
2672 _netw_capture_error(*netw, "SSL initialization failed");
2674 return FALSE;
2675 }
2676
2677 (*netw)->ssl = SSL_new((*netw)->ctx);
2678 SSL_set_fd((*netw)->ssl, (int)(*netw)->link.sock);
2679
2680 // Perform SSL Handshake
2681 if (SSL_connect((*netw)->ssl) <= 0) {
2682 /* could not connect with SSL */
2683 n_log(LOG_ERR, "SSL Handshake error !");
2684 _netw_capture_error(*netw, "SSL handshake failed for %s:%s", (*netw)->link.ip, (*netw)->link.port);
2686 return FALSE;
2687 }
2688 n_log(LOG_DEBUG, "SSL-Connected to %s:%s", (*netw)->link.ip, (*netw)->link.port);
2689#else
2690 _netw_capture_error(*netw, "%s:%s trying to configure SSL but application was compiled without SSL support !", (*netw)->link.ip, (*netw)->link.port);
2691 n_log(LOG_ERR, "%s:%s trying to configure SSL but application was compiled without SSL support !", (*netw)->link.ip, (*netw)->link.port);
2692#endif
2693 } else {
2694 n_log(LOG_DEBUG, "Connected to %s:%s", (*netw)->link.ip, (*netw)->link.port);
2695 }
2696
2698
2699 return TRUE;
2700} /* netw_connect_ex_to(...)*/
2701
2713 while (netw->link.connect_rp) {
2714 struct addrinfo* rp = netw->link.connect_rp;
2715 SOCKET sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
2716 if (sock == INVALID_SOCKET) {
2717 netw->link.connect_rp = rp->ai_next;
2718 continue;
2719 }
2720 netw->link.sock = sock;
2721 if (netw_set_blocking(netw, 0) == FALSE) {
2722 closesocket(sock);
2723 netw->link.sock = INVALID_SOCKET;
2724 netw->link.connect_rp = rp->ai_next;
2725 continue;
2726 }
2727 if (connect(sock, rp->ai_addr, (socklen_t)rp->ai_addrlen) == 0)
2728 return TRUE; /* connected immediately (common on loopback) */
2729#ifdef __windows__
2730 if (neterrno == WSAEWOULDBLOCK || neterrno == WSAEINPROGRESS)
2731#else
2732 if (neterrno == EINPROGRESS)
2733#endif
2734 return TRUE; /* connect in flight: poll the socket for writability */
2735 /* hard failure on this address: close and try the next one */
2736 closesocket(sock);
2737 netw->link.sock = INVALID_SOCKET;
2738 netw->link.connect_rp = rp->ai_next;
2739 }
2740 return FALSE;
2741} /* _netw_start_nonblock_connect */
2742
2760int netw_connect_nonblock(NETWORK** netw, char* host, char* port, int ip_version) {
2761 int error = 0;
2762 __n_assert(netw, return FALSE);
2763 if (*netw) {
2764 n_log(LOG_ERR, "netw_connect_nonblock: pass an empty NETWORK* (got a non-NULL one)");
2765 return FALSE;
2766 }
2768 __n_assert(*netw, return FALSE);
2769 if (netw_init_wsa(1, 2, 2) == FALSE) {
2770 n_log(LOG_ERR, "netw_connect_nonblock: unable to load WSA");
2772 return FALSE;
2773 }
2774 if (ip_version == NETWORK_IPV4)
2775 (*netw)->link.hints.ai_family = AF_INET;
2776 else if (ip_version == NETWORK_IPV6)
2777 (*netw)->link.hints.ai_family = AF_INET6;
2778 else
2779 (*netw)->link.hints.ai_family = AF_UNSPEC;
2780 (*netw)->link.hints.ai_socktype = SOCK_STREAM;
2781 (*netw)->link.hints.ai_protocol = IPPROTO_TCP;
2782
2783 /* netw_new leaves link.ip NULL; netw_connect_check writes the peer address
2784 * into it via inet_ntop, so allocate the 64-byte buffer up front (mirrors
2785 * netw_connect_ex_to). */
2786 Malloc((*netw)->link.ip, char, 64);
2787 __n_assert((*netw)->link.ip, netw_close(netw); return FALSE);
2788
2789 error = getaddrinfo(host, port, &(*netw)->link.hints, &(*netw)->link.rhost);
2790 if (error != 0) {
2791 _netw_capture_error(*netw, "netw_connect_nonblock resolve %s:%s: %s", host, port, gai_strerror(error));
2792 n_log(LOG_ERR, "netw_connect_nonblock resolve %s:%s: %s", host, port, gai_strerror(error));
2794 return FALSE;
2795 }
2796 (*netw)->addr_infos_loaded = 1;
2797 (*netw)->link.connect_rp = (*netw)->link.rhost;
2798 (*netw)->link.port = strdup(port);
2799 __n_assert((*netw)->link.port, netw_close(netw); return FALSE);
2800
2801 if (_netw_start_nonblock_connect(*netw) == FALSE) {
2802 _netw_capture_error(*netw, "netw_connect_nonblock: could not initiate connect to %s:%s", host, port);
2803 n_log(LOG_ERR, "netw_connect_nonblock: could not initiate connect to %s:%s", host, port);
2805 return FALSE;
2806 }
2807 return TRUE;
2808} /* netw_connect_nonblock */
2809
2823 __n_assert(netw, return FALSE);
2824 if (netw->link.sock == INVALID_SOCKET)
2825 return FALSE;
2826
2827 fd_set wset, eset;
2828 FD_ZERO(&wset);
2829 FD_SET(netw->link.sock, &wset);
2830 FD_ZERO(&eset);
2831 FD_SET(netw->link.sock, &eset);
2832 struct timeval tv;
2833 tv.tv_sec = 0;
2834 tv.tv_usec = 0;
2835 int sel = select((int)netw->link.sock + 1, NULL, &wset, &eset, &tv);
2836 if (sel == 0)
2837 return NETW_IO_WANT_WRITE; /* not writable yet: still connecting */
2838 if (sel < 0) {
2839 if (neterrno == EINTR)
2840 return NETW_IO_WANT_WRITE;
2841 return FALSE;
2842 }
2843
2844 /* The socket signalled: SO_ERROR is the arbiter of success/failure. */
2845 int so_err = 0;
2846 socklen_t slen = sizeof(so_err);
2847 if (getsockopt(netw->link.sock, SOL_SOCKET, SO_ERROR, (char*)&so_err, &slen) != 0)
2848 so_err = neterrno;
2849
2850 if (so_err == 0) {
2851 /* Connected: record the peer address, mirror netw_connect_ex_to. */
2852 if (netw->link.connect_rp &&
2853 !inet_ntop(netw->link.connect_rp->ai_family, get_in_addr(netw->link.connect_rp->ai_addr), netw->link.ip, 64)) {
2854 n_log(LOG_ERR, "netw_connect_check: inet_ntop failed on socket " SOCKET_SIZE_FORMAT "", netw->link.sock);
2855 }
2857 return TRUE;
2858 }
2859
2860 /* This address failed: close it and try the next resolved address. */
2861 {
2862 char* errmsg = netstrerror(so_err);
2863 n_log(LOG_INFO, "netw_connect_check: connect failed on an address: %s", _str(errmsg));
2864 FreeNoLog(errmsg);
2865 }
2866 closesocket(netw->link.sock);
2867 netw->link.sock = INVALID_SOCKET;
2868 netw->link.connect_rp = netw->link.connect_rp ? netw->link.connect_rp->ai_next : NULL;
2870 return NETW_IO_WANT_WRITE; /* now trying the next address */
2871 return FALSE; /* every address failed */
2872} /* netw_connect_check */
2873
2886int netw_connect_ex(NETWORK** netw, char* host, char* port, size_t send_list_limit, size_t recv_list_limit, int ip_version, char* ssl_key_file, char* ssl_cert_file) {
2887 return netw_connect_ex_to(netw, host, port, send_list_limit, recv_list_limit, ip_version, ssl_key_file, ssl_cert_file, 0);
2888} /* netw_connect_ex(...)*/
2889
2898int netw_connect(NETWORK** netw, char* host, char* port, int ip_version) {
2899 n_log(LOG_INFO, "Trying to connect to %s : %s", _str(host), _str(port));
2900 return netw_connect_ex(netw, host, port, MAX_LIST_ITEMS, MAX_LIST_ITEMS, ip_version, NULL, NULL);
2901} /* netw_connect() */
2902
2912int netw_connect_to(NETWORK** netw, char* host, char* port, int ip_version, int connect_timeout_ms) {
2913 n_log(LOG_INFO, "Trying to connect to %s : %s (connect timeout %d ms)", _str(host), _str(port), connect_timeout_ms);
2914 return netw_connect_ex_to(netw, host, port, MAX_LIST_ITEMS, MAX_LIST_ITEMS, ip_version, NULL, NULL, connect_timeout_ms);
2915} /* netw_connect_to() */
2916
2917#ifdef HAVE_OPENSSL
2928int netw_ssl_connect(NETWORK** netw, char* host, char* port, int ip_version, char* ssl_key_file, char* ssl_cert_file) {
2929 n_log(LOG_INFO, "Trying to connect to %s : %s", _str(host), _str(port));
2930 return netw_connect_ex(netw, host, port, MAX_LIST_ITEMS, MAX_LIST_ITEMS, ip_version, ssl_key_file, ssl_cert_file);
2931} /* netw_connect() */
2932
2948int netw_ssl_connect_client_to(NETWORK** netw, char* host, char* port, int ip_version, int connect_timeout_ms) {
2949 __n_assert(netw, return FALSE);
2950 /* TCP connect first (no SSL params) */
2951 if (netw_connect_ex_to(netw, host, port, MAX_LIST_ITEMS, MAX_LIST_ITEMS, ip_version, NULL, NULL, connect_timeout_ms) == FALSE) {
2952 return FALSE;
2953 }
2954 if (netw_ssl_start_client(*netw) == FALSE) {
2956 return FALSE;
2957 }
2958 return TRUE;
2959} /* netw_ssl_connect_client_to */
2960
2978 __n_assert(netw, return FALSE);
2979 /* Create SSL context for client */
2981#if OPENSSL_VERSION_NUMBER >= 0x10100000L
2982 netw->method = TLS_client_method();
2983#else
2984 netw->method = TLSv1_2_client_method();
2985#endif
2986 netw->ctx = SSL_CTX_new(netw->method);
2987 if (!netw->ctx) {
2988 netw_ssl_print_errors(netw->link.sock);
2989 return FALSE;
2990 }
2991 /* PARTIAL_WRITE: a short SSL_write can be resumed from the
2992 * caller's buffer+offset (required by the reactor's
2993 * single-attempt send path); MOVING_WRITE_BUFFER: tolerate the
2994 * resume pointer not being the original one. No-op for the
2995 * blocking thread engine. */
2996 SSL_CTX_set_mode(netw->ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
2997 /* Load default system CA paths */
2998 SSL_CTX_set_default_verify_paths(netw->ctx);
2999 /* Set send/recv to SSL variants */
3000 netw->send_data = &send_ssl_data;
3001 netw->recv_data = &recv_ssl_data;
3002 netw->send_data_once = &send_ssl_data_once;
3003 netw->recv_data_once = &recv_ssl_data_once;
3004 netw->crypto_algo = NETW_ENCRYPT_OPENSSL;
3005 return TRUE;
3006} /* netw_ssl_start_client */
3007
3020int netw_ssl_connect_client(NETWORK** netw, char* host, char* port, int ip_version) {
3022} /* netw_ssl_connect_client */
3023
3034static int netw_is_ip_literal(const char* host) {
3035 struct in_addr v4;
3036 struct in6_addr v6;
3037 if (!host || !host[0])
3038 return 0;
3039 if (inet_pton(AF_INET, host, &v4) == 1)
3040 return 1;
3041 if (inet_pton(AF_INET6, host, &v6) == 1)
3042 return 1;
3043 return 0;
3044}
3045
3057int netw_ssl_do_handshake(NETWORK* netw, const char* sni_hostname) {
3058 __n_assert(netw, return FALSE);
3059 __n_assert(netw->ctx, n_log(LOG_ERR, "netw_ssl_do_handshake: no SSL context"); return FALSE);
3060
3061 netw->ssl = SSL_new(netw->ctx);
3062 if (!netw->ssl) {
3063 _netw_capture_error(netw, "SSL_new failed");
3064 netw_ssl_print_errors(netw->link.sock);
3065 return FALSE;
3066 }
3067 SSL_set_fd(netw->ssl, (int)netw->link.sock);
3068 if (sni_hostname) {
3069 SSL_set_tlsext_host_name(netw->ssl, sni_hostname);
3070 /* SNI says which certificate to SEND; it does not say which names are
3071 acceptable ON it. Without the identity below, SSL_VERIFY_PEER validates the
3072 chain and nothing else, so any certificate that chains to a trusted root is
3073 accepted for any host: exactly the interception a TLS client exists to
3074 detect. An IP literal is matched against the certificate's IP entries, a
3075 name against its subjectAltName / CN. Partial wildcards (w*.example.com)
3076 are refused; a full one (*.example.com) still matches.
3077 With SSL_VERIFY_PEER set this makes the handshake fail on a mismatch; with
3078 verification off the handshake still completes and the mismatch is reported
3079 by netw_ssl_get_verify_result(), so a caller that deliberately does not
3080 verify is unaffected. */
3081 if (netw_is_ip_literal(sni_hostname)) {
3082 /* there is no SSL_set1_ip_asc; the IP form goes through the verify param */
3083 X509_VERIFY_PARAM* vp = SSL_get0_param(netw->ssl);
3084 if (!vp || X509_VERIFY_PARAM_set1_ip_asc(vp, sni_hostname) != 1)
3085 n_log(LOG_ERR, "netw_ssl_do_handshake: could not set the expected peer IP %s", sni_hostname);
3086 } else {
3087 SSL_set_hostflags(netw->ssl, X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
3088 if (SSL_set1_host(netw->ssl, sni_hostname) != 1)
3089 n_log(LOG_ERR, "netw_ssl_do_handshake: could not set the expected peer name %s", sni_hostname);
3090 }
3091 }
3092 if (SSL_connect(netw->ssl) <= 0) {
3093 n_log(LOG_ERR, "SSL handshake failed");
3094 unsigned long err = ERR_peek_error();
3095 _netw_capture_error(netw, "SSL handshake failed for %s:%s: %s",
3096 _str(netw->link.ip), _str(netw->link.port),
3097 err ? ERR_reason_error_string(err) : "unknown error");
3098 netw_ssl_print_errors(netw->link.sock);
3099 return FALSE;
3100 }
3101 n_log(LOG_DEBUG, "SSL handshake completed with %s:%s", _str(netw->link.ip), _str(netw->link.port));
3102 return TRUE;
3103} /* netw_ssl_do_handshake */
3104
3113 ERR_clear_error();
3114 errno = 0;
3115 int r = SSL_do_handshake(netw->ssl);
3116 int sys_errno = errno; /* before anything else can overwrite it */
3117 if (r == 1)
3118 return TRUE;
3119 int e = SSL_get_error(netw->ssl, r);
3120 if (e == SSL_ERROR_WANT_READ)
3121 return NETW_IO_WANT_READ;
3122 if (e == SSL_ERROR_WANT_WRITE)
3123 return NETW_IO_WANT_WRITE;
3124 {
3125 unsigned long err = ERR_peek_error();
3126 const char* why = err ? ERR_reason_error_string(err) : NULL;
3127 _netw_capture_error(netw, "TLS handshake failed for %s:%s: %s",
3128 _str(netw->link.ip), _str(netw->link.port),
3129 why ? why : "unknown error");
3130 /* Say WHY: "failed" alone left a burst of 1,375 failures in a server
3131 * log with nothing to tell a peer closing mid-handshake (SSL_ERROR_
3132 * SYSCALL / ZERO_RETURN, errno 0 or ECONNRESET) from a protocol or
3133 * certificate alert (SSL_ERROR_SSL and its reason string). */
3134 n_log(LOG_ERR, "socket " SOCKET_SIZE_FORMAT ": non-blocking TLS handshake failed (SSL_get_error %d, %s, errno %d)",
3135 netw->link.sock, e, why ? why : (e == SSL_ERROR_ZERO_RETURN ? "peer closed" : (e == SSL_ERROR_SYSCALL ? "syscall/EOF" : "no reason")), sys_errno);
3136 }
3137 /* A handshake mismatch/error queues entries; drain them so a stale reason
3138 * cannot mislead a later, unrelated OpenSSL call on this thread. */
3139 ERR_clear_error();
3140 return FALSE;
3141} /* _netw_ssl_handshake_step */
3142
3159int netw_ssl_handshake_once(NETWORK* netw, const char* sni_hostname) {
3160 __n_assert(netw, return FALSE);
3161 __n_assert(netw->ctx, n_log(LOG_ERR, "netw_ssl_handshake_once: no SSL context"); return FALSE);
3162 if (!netw->ssl) {
3163 netw->ssl = SSL_new(netw->ctx);
3164 if (!netw->ssl) {
3165 _netw_capture_error(netw, "SSL_new failed");
3166 netw_ssl_print_errors(netw->link.sock);
3167 return FALSE;
3168 }
3169 SSL_set_fd(netw->ssl, (int)netw->link.sock);
3170 SSL_set_connect_state(netw->ssl);
3171 if (sni_hostname)
3172 SSL_set_tlsext_host_name(netw->ssl, sni_hostname);
3173 if (netw_set_blocking(netw, 0) == FALSE)
3174 return FALSE;
3175 }
3177} /* netw_ssl_handshake_once */
3178
3203 __n_assert(netw, return FALSE);
3204 __n_assert(ctx, n_log(LOG_ERR, "netw_ssl_server_handshake_once: no SSL context"); return FALSE);
3205 if (!netw->ssl) {
3206 netw->ssl = SSL_new(ctx);
3207 if (!netw->ssl) {
3208 _netw_capture_error(netw, "SSL_new failed");
3209 netw_ssl_print_errors(netw->link.sock);
3210 return FALSE;
3211 }
3212 SSL_set_fd(netw->ssl, (int)netw->link.sock);
3213 SSL_set_accept_state(netw->ssl);
3214 netw->send_data = &send_ssl_data;
3215 netw->recv_data = &recv_ssl_data;
3216 netw->send_data_once = &send_ssl_data_once;
3217 netw->recv_data_once = &recv_ssl_data_once;
3218 netw->crypto_algo = NETW_ENCRYPT_OPENSSL;
3219 /* netw->ctx stays NULL: this connection borrows the caller's shared
3220 * ctx, so netw_close() frees the SSL but not the context (accepted
3221 * connections borrow ctx from the owner). */
3222 if (netw_set_blocking(netw, 0) == FALSE)
3223 return FALSE;
3224 }
3226} /* netw_ssl_server_handshake_once */
3227
3228#endif
3229
3237int netw_get_state(NETWORK* netw, uint32_t* state, int* thr_engine_status) {
3238 if (netw) {
3239 /* use eventbolt: netw_set() writes state/threaded_engine_status under eventbolt */
3240 pthread_mutex_lock(&netw->eventbolt);
3241 if (state)
3242 (*state) = netw_atomic_read_state(netw);
3243 if (thr_engine_status)
3244 (*thr_engine_status) = netw->threaded_engine_status;
3245 pthread_mutex_unlock(&netw->eventbolt);
3246 return TRUE;
3247 } else {
3248 n_log(LOG_ERR, "Can't get status of a NULL network");
3249 }
3250 return FALSE;
3251} /*netw_get_state() */
3252
3259int netw_set(NETWORK* netw, int flag) {
3260 __n_assert(netw, return FALSE);
3261 if (flag & NETW_EMPTY_SENDBUF) {
3262 pthread_mutex_lock(&netw->sendbolt);
3263 if (netw->send_buf)
3264 list_empty(netw->send_buf);
3265 pthread_mutex_unlock(&netw->sendbolt);
3266 };
3267 if (flag & NETW_EMPTY_RECVBUF) {
3268 pthread_mutex_lock(&netw->recvbolt);
3269 if (netw->recv_buf)
3270 list_empty(netw->recv_buf);
3271 pthread_mutex_unlock(&netw->recvbolt);
3272 }
3273 if (flag & NETW_DESTROY_SENDBUF) {
3274 pthread_mutex_lock(&netw->sendbolt);
3275 if (netw->send_buf)
3276 list_destroy(&netw->send_buf);
3277 pthread_mutex_unlock(&netw->sendbolt);
3278 };
3279 if (flag & NETW_DESTROY_RECVBUF) {
3280 pthread_mutex_lock(&netw->recvbolt);
3281 if (netw->recv_buf)
3282 list_destroy(&netw->recv_buf);
3283 pthread_mutex_unlock(&netw->recvbolt);
3284 }
3285 pthread_mutex_lock(&netw->eventbolt);
3286 if (flag & NETW_CLIENT) {
3287 netw->mode = NETW_CLIENT;
3288 }
3289 if (flag & NETW_SERVER) {
3290 netw->mode = NETW_SERVER;
3291 }
3292 if (flag & NETW_RUN) {
3294 }
3295 if (flag & NETW_EXITED) {
3297 }
3298 if (flag & NETW_ERROR) {
3300 }
3301 if (flag & NETW_EXIT_ASKED) {
3303 }
3304 if (flag & NETW_THR_ENGINE_STARTED) {
3305 netw->threaded_engine_status = NETW_THR_ENGINE_STARTED;
3306 }
3307 if (flag & NETW_THR_ENGINE_STOPPED) {
3308 netw->threaded_engine_status = NETW_THR_ENGINE_STOPPED;
3309 }
3310 pthread_mutex_unlock(&netw->eventbolt);
3311
3312 /* Only wake the send thread for state changes it actually cares
3313 * about. The inner loop in netw_send_func branches on NETW_ERROR,
3314 * NETW_EXITED, and NETW_EXIT_ASKED; every other flag (mode /
3315 * thread-engine-status / buffer maintenance) is invisible to it,
3316 * and posting unconditionally creates a spurious wakeup that,
3317 * paired with an empty send_buf, produces the classic
3318 * "offset-by-one semaphore" bug where every subsequent real
3319 * list_push leaves one extra post in the semaphore for the next
3320 * sem_wait to consume on a drained list. Avoiding the spurious
3321 * post here is the root cause fix and removes the need for a
3322 * defensive branch in the common path. */
3323 if (flag & (NETW_ERROR | NETW_EXITED | NETW_EXIT_ASKED)) {
3324 sem_post(&netw->send_blocker);
3325 }
3326
3327 return TRUE;
3328} /* netw_set(...) */
3329
3336int deplete_send_buffer(int fd, int timeout) {
3337#if defined(__linux__)
3338 int outstanding = 0;
3339 if (timeout <= 0) {
3340 return 0;
3341 }
3342 for (int it = 0; it < timeout; it += 100) {
3343 outstanding = 0;
3344 if (ioctl(fd, SIOCOUTQ, &outstanding) == -1) {
3345 int error = errno;
3346 n_log(LOG_ERR, "ioctl SIOCOUTQ returned -1: %s for socket %d", strerror(error), fd);
3347 return -1;
3348 }
3349 if (!outstanding) {
3350 break;
3351 }
3352 usleep(100000);
3353 }
3354 return outstanding;
3355#else
3356 (void)fd;
3357 (void)timeout;
3358 return 0;
3359#endif
3360}
3361
3368 __n_assert(netw && (*netw), return FALSE);
3369 uint32_t state = 0;
3370 int thr_engine_status = 0;
3371 int nb_running = 0;
3372
3373 /* Reactor close handshake. Synchronously wait for the reactor to
3374 * finish with this connection (drains pending sends best-effort,
3375 * shutdown(SHUT_WR) so the peer sees EOF, removes the fd from the
3376 * epoll set, publishes the close ack) before any of the existing
3377 * close logic runs. After this returns the reactor will never touch
3378 * the NETWORK again, so the rest of netw_close (and the final Free)
3379 * proceeds exactly like the thread-mode path.
3380 *
3381 * Keyed on reactor_registered, NOT the live reactor_mode: the reactor
3382 * clears reactor_mode partway through unregister (peer EOF / hard
3383 * error) and keeps touching the NETWORK for a few more lines before
3384 * acking. Gating on reactor_mode would let a clear that lands just
3385 * before this read send us straight to Free() while the reactor is
3386 * still mid-unregister (use-after-free). reactor_registered is set
3387 * once at register time and never cleared, so this is race-free.
3388 *
3389 * Compile-time gated on N_REACTOR_AVAILABLE so non-Linux/Android
3390 * builds (Windows MinGW, Solaris) don't pull in n_reactor.o just
3391 * to satisfy this symbol, the reactor is unavailable there anyway
3392 * and reactor_registered can never be set. */
3393#if N_REACTOR_AVAILABLE
3394 if (__atomic_load_n(&(*netw)->reactor_registered, __ATOMIC_ACQUIRE)) {
3396 }
3397#endif
3398
3399 if ((*netw)->deplete_queues_timeout > 0) {
3400 /* use iteration count to avoid integer overflow with large timeouts */
3401 int max_iterations = (*netw)->deplete_queues_timeout * 10; /* each iteration ~100ms */
3402 netw_get_state((*netw), &state, &thr_engine_status);
3403 if (thr_engine_status == NETW_THR_ENGINE_STARTED) {
3404 int it = 0;
3405 do {
3406 pthread_mutex_lock(&(*netw)->eventbolt);
3407 nb_running = (*netw)->nb_running_threads;
3408 pthread_mutex_unlock(&(*netw)->eventbolt);
3409 usleep(100000);
3410 it++;
3411 } while (nb_running > 0 && it < max_iterations);
3412 netw_get_state((*netw), &state, &thr_engine_status);
3413 if (it >= max_iterations && nb_running > 0) {
3414 n_log(LOG_ERR, "netw " SOCKET_SIZE_FORMAT ": %d threads are still running after %d seconds, netw is in state %s (%" PRIu32 ")", (*netw)->link.sock, nb_running, (*netw)->deplete_queues_timeout, N_ENUM_ENTRY(__netw_code_type, toString)(state), state);
3415 }
3416 }
3417 }
3418
3419 if ((*netw)->link.sock != INVALID_SOCKET) {
3420 int remaining = deplete_send_buffer((int)(*netw)->link.sock, (*netw)->deplete_socket_timeout);
3421 // cppcheck-suppress knownConditionTrueFalse ; remaining can be > 0 on Linux (SIOCOUTQ)
3422 if (remaining > 0) {
3423 n_log(LOG_ERR, "socket " SOCKET_SIZE_FORMAT " (%s:%s) %d octets still in send buffer before closing after a wait of %d msecs", (*netw)->link.sock, (*netw)->link.ip, (*netw)->link.port, remaining, (*netw)->deplete_socket_timeout);
3424 }
3425 }
3426
3427 list_foreach(node, (*netw)->pools) {
3428 NETWORK_POOL* pool = (NETWORK_POOL*)node->ptr;
3430 }
3431 list_destroy(&(*netw)->pools);
3432
3433 netw_get_state((*netw), &state, &thr_engine_status);
3434 if (thr_engine_status == NETW_THR_ENGINE_STARTED) {
3436 }
3437
3438 /* recompute nb_running after joining threads so the SSL_shutdown
3439 * decision reflects the actual post-join state */
3440 pthread_mutex_lock(&(*netw)->eventbolt);
3441 nb_running = (*netw)->nb_running_threads;
3442 pthread_mutex_unlock(&(*netw)->eventbolt);
3443
3444 if ((*netw)->link.sock != INVALID_SOCKET) {
3445#ifdef HAVE_OPENSSL
3446 if ((*netw)->crypto_algo == NETW_ENCRYPT_OPENSSL) {
3447 if ((*netw)->ssl) {
3448 /* only attempt SSL_shutdown if threads have fully stopped,
3449 * otherwise SSL operations may race with send/recv threads */
3450 if (nb_running == 0) {
3451 int shutdown_res = SSL_shutdown((*netw)->ssl);
3452 if (shutdown_res == 0) {
3453 /* try again to complete bidirectional shutdown;
3454 * peer may have already closed (common for HTTP),
3455 * so SYSCALL/SSL errors are non-fatal here */
3456 shutdown_res = SSL_shutdown((*netw)->ssl);
3457 }
3458 if (shutdown_res < 0) {
3459 int err = SSL_get_error((*netw)->ssl, shutdown_res);
3460 if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
3461 /* Non-blocking socket: the close_notify handshake
3462 * cannot complete synchronously. We tear the socket
3463 * down immediately afterwards anyway, so this is a
3464 * normal teardown, not an error. Drain the queue so
3465 * it cannot mislead a later OpenSSL call. */
3466 n_log(LOG_DEBUG, "SSL_shutdown() would block on non-blocking socket " SOCKET_SIZE_FORMAT ": %d", (*netw)->link.sock, err);
3467 ERR_clear_error();
3468 } else if (err != SSL_ERROR_SYSCALL && err != SSL_ERROR_SSL) {
3469 n_log(LOG_ERR, "SSL_shutdown() failed: %d", err);
3470 } else {
3471 n_log(LOG_DEBUG, "SSL_shutdown() peer already closed: %d", err);
3472 }
3473 }
3474 } else {
3475 n_log(LOG_WARNING, "netw " SOCKET_SIZE_FORMAT ": forcing bidirectional SSL_shutdown with %d threads still running", (*netw)->link.sock, nb_running);
3476 int shutdown_res = SSL_shutdown((*netw)->ssl);
3477 if (shutdown_res == 0) {
3478 /* send close_notify and wait for peer's close_notify */
3479 shutdown_res = SSL_shutdown((*netw)->ssl);
3480 }
3481 if (shutdown_res < 0) {
3482 int err = SSL_get_error((*netw)->ssl, shutdown_res);
3483 n_log(LOG_ERR, "netw " SOCKET_SIZE_FORMAT ": SSL_shutdown() failed with %d threads still running: %d", (*netw)->link.sock, nb_running, err);
3484 }
3485 }
3486 /* a shutdown that failed (mid-handshake, peer gone) leaves
3487 * entries on THIS thread's queue; on a single-threaded
3488 * server they would surface as the next connection's error */
3489 ERR_clear_error();
3490 SSL_free((*netw)->ssl);
3491 } else {
3492 if ((*netw)->mode != NETW_SERVER) {
3493 n_log(LOG_ERR, "SSL handle of socket " SOCKET_SIZE_FORMAT " was already NULL", (*netw)->link.sock);
3494 } else {
3495 n_log(LOG_DEBUG, "listening socket " SOCKET_SIZE_FORMAT " has no SSL handle (expected)", (*netw)->link.sock);
3496 }
3497 }
3498 }
3499#endif
3500
3501 /* inform peer that we have finished */
3502 shutdown((*netw)->link.sock, SHUT_WR);
3503
3504 if ((*netw)->wait_close_timeout > 0) {
3505 /* wait for fin ack using select() to avoid busy-waiting.
3506 * Use iteration count to avoid integer overflow. */
3507 char buffer[4096] = "";
3508 int max_iters = (*netw)->wait_close_timeout * 10; /* each iteration ~100ms */
3509 for (int it = 0; it < max_iters; it++) {
3510 fd_set rfds;
3511 struct timeval tv;
3512 FD_ZERO(&rfds);
3513#pragma GCC diagnostic push
3514#pragma GCC diagnostic ignored "-Wsign-conversion"
3515 FD_SET((*netw)->link.sock, &rfds);
3516#pragma GCC diagnostic pop
3517 tv.tv_sec = 0;
3518 tv.tv_usec = 100000; /* 100ms */
3519 int sel = select((int)(*netw)->link.sock + 1, &rfds, NULL, NULL, &tv);
3520 if (sel > 0) {
3521 ssize_t res = recv((*netw)->link.sock, buffer, 4096, NETFLAGS);
3522 if (!res)
3523 break;
3524 if (res < 0) {
3525 int error = neterrno;
3526 if (error != ENOTCONN && error != EINTR && error != ECONNRESET
3527#ifdef __windows__
3528 && error != WSAENOTCONN && error != WSAECONNRESET && error != WSAESHUTDOWN && error != WSAEWOULDBLOCK && error != WSAEINTR
3529#endif
3530 ) {
3531 char* errmsg = netstrerror(error);
3532 n_log(LOG_ERR, "read returned error %d when closing socket " SOCKET_SIZE_FORMAT " (%s:%s): %s", error, (*netw)->link.sock, _str((*netw)->link.ip), (*netw)->link.port, _str(errmsg));
3533 FreeNoLog(errmsg);
3534 } else {
3535 n_log(LOG_DEBUG, "wait close: connection gracefully closed on socket " SOCKET_SIZE_FORMAT " (%s:%s)", (*netw)->link.sock, _str((*netw)->link.ip), (*netw)->link.port);
3536 }
3537 break;
3538 }
3539 } else if (sel < 0) {
3540 /* select error, bail out */
3541 int error = neterrno;
3542 if (error != EINTR
3543#ifdef __windows__
3544 && error != WSAEINTR
3545#endif
3546 ) {
3547 char* errmsg = netstrerror(error);
3548 n_log(LOG_ERR, "select() error on socket " SOCKET_SIZE_FORMAT " during close: %s", (*netw)->link.sock, _str(errmsg));
3549 FreeNoLog(errmsg);
3550 break;
3551 }
3552 }
3553 /* sel == 0: timeout, continue waiting */
3554 }
3555 }
3556
3557 /* effectively close socket */
3558 closesocket((*netw)->link.sock);
3559
3560#ifdef HAVE_OPENSSL
3561 /* clean openssl state. Accepted server-side SSL connections borrow
3562 * ctx from the listener (their ctx is NULL by design), so a NULL
3563 * ctx here is not an error, only the owner frees it. */
3564 if ((*netw)->crypto_algo == NETW_ENCRYPT_OPENSSL && (*netw)->ctx) {
3565 SSL_CTX_free((*netw)->ctx);
3566 }
3567 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " closed", (*netw)->link.sock);
3568 FreeNoLog((*netw)->key);
3569 FreeNoLog((*netw)->certificate);
3570#endif
3571 }
3572
3573 FreeNoLog((*netw)->link.ip);
3574 FreeNoLog((*netw)->link.port);
3575
3576 if ((*netw)->link.rhost) {
3577 freeaddrinfo((*netw)->link.rhost);
3578 }
3579
3580 /*list freeing*/
3582
3583 pthread_mutex_destroy(&(*netw)->recvbolt);
3584 pthread_mutex_destroy(&(*netw)->sendbolt);
3585 pthread_mutex_destroy(&(*netw)->eventbolt);
3586 sem_destroy(&(*netw)->send_blocker);
3587
3588 Free((*netw));
3589
3590 return TRUE;
3591} /* netw_close(...)*/
3592
3602int netw_make_listening(NETWORK** netw, char* addr, char* port, int nbpending, int ip_version) {
3603 __n_assert(port, return FALSE);
3604
3605 int error = 0;
3606 char* errmsg = NULL;
3607
3608 if (*netw) {
3609 n_log(LOG_ERR, "Cannot use an allocated network. Please pass a NULL network to modify");
3610 return FALSE;
3611 }
3612
3613 /*checking WSA when under windows*/
3614 if (netw_init_wsa(1, 2, 2) == FALSE) {
3615 n_log(LOG_ERR, "Unable to load WSA dll's");
3616 return FALSE;
3617 }
3618
3620 __n_assert((*netw), return FALSE);
3621 (*netw)->link.port = strdup(port);
3622 /*creating array*/
3623 if (ip_version == NETWORK_IPV4) {
3624 (*netw)->link.hints.ai_family = AF_INET; /* Allow IPv4 */
3625 } else if (ip_version == NETWORK_IPV6) {
3626 (*netw)->link.hints.ai_family = AF_INET6; /* Allow IPv6 */
3627 } else {
3628 /* NETWORK_ALL or unknown value */
3629 (*netw)->link.hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
3630 }
3631 if (!addr) {
3632 (*netw)->link.hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */
3633 }
3634 (*netw)->link.hints.ai_socktype = SOCK_STREAM;
3635 (*netw)->link.hints.ai_protocol = IPPROTO_TCP;
3636 (*netw)->link.hints.ai_canonname = NULL;
3637 (*netw)->link.hints.ai_next = NULL;
3638
3639 error = getaddrinfo(addr, port, &(*netw)->link.hints, &(*netw)->link.rhost);
3640 if (error != 0) {
3641 _netw_capture_error(*netw, "Error when resolving %s:%s getaddrinfo: %s", _str(addr), port, gai_strerror(error));
3642 n_log(LOG_ERR, "Error when resolving %s:%s getaddrinfo: %s", _str(addr), port, gai_strerror(error));
3644 return FALSE;
3645 }
3646 (*netw)->addr_infos_loaded = 1;
3647
3648 /* getaddrinfo() returns a list of address structures.
3649 Try each address until we successfully connect(2).
3650 If socket(2) (or connect(2)) fails, we (close the socket
3651 and) try the next address. */
3652 struct addrinfo* rp = NULL;
3653 for (rp = (*netw)->link.rhost; rp != NULL; rp = rp->ai_next) {
3654 (*netw)->link.sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
3655 if ((*netw)->link.sock == INVALID_SOCKET) {
3656 error = neterrno;
3657 errmsg = netstrerror(error);
3658 n_log(LOG_ERR, "Error while trying to make a socket: %s", _str(errmsg));
3659 FreeNoLog(errmsg);
3660 continue;
3661 }
3662 /* SO_REUSEADDR means opposite things on the two platforms, so it is POSIX-only.
3663 * On POSIX it lets a restarted listener re-take the port it just released, which is
3664 * what it is here for. On Windows it lets an UNRELATED process bind over a socket
3665 * that is already holding the port: the second bind succeeds, and which socket gets
3666 * a given connection is not defined. A program that reports "listening" while
3667 * another process owns the port is worse than one that fails to start, and for a
3668 * security tool it is worse again, because the traffic it was asked to intercept can
3669 * go somewhere else entirely. Windows already refuses the second bind by default,
3670 * which is the behaviour wanted, so the option is simply not set there.
3671 * (SO_EXCLUSIVEADDRUSE would additionally stop others binding over US, and is worth
3672 * considering if port hijacking by a process that starts LATER ever matters here.) */
3673#ifndef __windows__
3674 netw_setsockopt((*netw), SO_REUSEADDR, 1);
3675#endif
3676 // netw_setsockopt( (*netw), SO_REUSEPORT, 1 );
3677 if (bind((*netw)->link.sock, rp->ai_addr, (socklen_t)rp->ai_addrlen) == 0) {
3678 char* ip = NULL;
3679 Malloc(ip, char, 64);
3680 if (!ip) {
3681 n_log(LOG_ERR, "Error allocating 64 bytes for ip");
3683 return FALSE;
3684 }
3685 if (!inet_ntop(rp->ai_family, get_in_addr(rp->ai_addr), ip, 64)) {
3686 error = neterrno;
3687 errmsg = netstrerror(error);
3688 n_log(LOG_ERR, "inet_ntop: %p , %s", (void*)&(*netw)->link.raddr, _str(errmsg));
3689 FreeNoLog(errmsg);
3690 }
3691 /*n_log( LOG_DEBUG, "Socket %d successfully binded to %s %s", (*netw) -> link . sock, _str( ip ) , _str( port ) );*/
3692 (*netw)->link.ip = ip;
3693 break; /* Success */
3694 }
3695 error = neterrno;
3696 errmsg = netstrerror(error);
3697 _netw_capture_error(*netw, "Error from bind() on port %s neterrno: %s", port, errmsg);
3698 n_log(LOG_ERR, "Error from bind() on port %s neterrno: %s", port, errmsg);
3699 FreeNoLog(errmsg);
3700 closesocket((*netw)->link.sock);
3701 }
3702 if (rp == NULL) {
3703 /* No address succeeded */
3704 _netw_capture_error(*netw, "Couldn't get a socket for listening on port %s", port);
3705 n_log(LOG_ERR, "Couldn't get a socket for listening on port %s", port);
3707 return FALSE;
3708 }
3709
3710 /* nb_pending connections*/
3711 (*netw)->nb_pending = nbpending;
3712 if (listen((*netw)->link.sock, (*netw)->nb_pending) != 0) {
3713 error = neterrno;
3714 errmsg = netstrerror(error);
3715 _netw_capture_error(*netw, "listen() failed on port %s: %s", port, _str(errmsg));
3716 n_log(LOG_ERR, "listen() failed on port %s: %s", port, _str(errmsg));
3717 FreeNoLog(errmsg);
3719 return FALSE;
3720 }
3721
3723
3724 return TRUE;
3725} /* netw_make_listening(...)*/
3726
3735int netw_bind_udp(NETWORK** netw, char* addr, char* port, int ip_version) {
3736 __n_assert(port, return FALSE);
3737
3738 int error = 0;
3739 char* errmsg = NULL;
3740
3741 if (*netw) {
3742 n_log(LOG_ERR, "Cannot use an allocated network. Please pass a NULL network to modify");
3743 return FALSE;
3744 }
3745
3746 /*checking WSA when under windows*/
3747 if (netw_init_wsa(1, 2, 2) == FALSE) {
3748 n_log(LOG_ERR, "Unable to load WSA dll's");
3749 return FALSE;
3750 }
3751
3753 __n_assert((*netw), return FALSE);
3754 (*netw)->link.port = strdup(port);
3755 (*netw)->transport_type = NETWORK_UDP;
3756
3757 /* choose ip version */
3758 if (ip_version == NETWORK_IPV4) {
3759 (*netw)->link.hints.ai_family = AF_INET;
3760 } else if (ip_version == NETWORK_IPV6) {
3761 (*netw)->link.hints.ai_family = AF_INET6;
3762 } else {
3763 (*netw)->link.hints.ai_family = AF_UNSPEC;
3764 }
3765 if (!addr) {
3766 (*netw)->link.hints.ai_flags = AI_PASSIVE;
3767 }
3768 (*netw)->link.hints.ai_socktype = SOCK_DGRAM;
3769 (*netw)->link.hints.ai_protocol = IPPROTO_UDP;
3770 (*netw)->link.hints.ai_canonname = NULL;
3771 (*netw)->link.hints.ai_next = NULL;
3772
3773 error = getaddrinfo(addr, port, &(*netw)->link.hints, &(*netw)->link.rhost);
3774 if (error != 0) {
3775 _netw_capture_error(*netw, "Error when resolving %s:%s getaddrinfo: %s", _str(addr), port, gai_strerror(error));
3776 n_log(LOG_ERR, "Error when resolving %s:%s getaddrinfo: %s", _str(addr), port, gai_strerror(error));
3778 return FALSE;
3779 }
3780 (*netw)->addr_infos_loaded = 1;
3781
3782 struct addrinfo* rp = NULL;
3783 for (rp = (*netw)->link.rhost; rp != NULL; rp = rp->ai_next) {
3784 (*netw)->link.sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
3785 if ((*netw)->link.sock == INVALID_SOCKET) {
3786 error = neterrno;
3787 errmsg = netstrerror(error);
3788 n_log(LOG_ERR, "Error while trying to make a UDP socket: %s", _str(errmsg));
3789 FreeNoLog(errmsg);
3790 continue;
3791 }
3792 /* SO_REUSEADDR means opposite things on the two platforms, so it is POSIX-only.
3793 * On POSIX it lets a restarted listener re-take the port it just released, which is
3794 * what it is here for. On Windows it lets an UNRELATED process bind over a socket
3795 * that is already holding the port: the second bind succeeds, and which socket gets
3796 * a given connection is not defined. A program that reports "listening" while
3797 * another process owns the port is worse than one that fails to start, and for a
3798 * security tool it is worse again, because the traffic it was asked to intercept can
3799 * go somewhere else entirely. Windows already refuses the second bind by default,
3800 * which is the behaviour wanted, so the option is simply not set there.
3801 * (SO_EXCLUSIVEADDRUSE would additionally stop others binding over US, and is worth
3802 * considering if port hijacking by a process that starts LATER ever matters here.) */
3803#ifndef __windows__
3804 netw_setsockopt((*netw), SO_REUSEADDR, 1);
3805#endif
3806 if (bind((*netw)->link.sock, rp->ai_addr, (socklen_t)rp->ai_addrlen) == 0) {
3807 char* ip = NULL;
3808 Malloc(ip, char, 64);
3809 if (!ip) {
3810 n_log(LOG_ERR, "Error allocating 64 bytes for ip");
3812 return FALSE;
3813 }
3814 if (!inet_ntop(rp->ai_family, get_in_addr(rp->ai_addr), ip, 64)) {
3815 error = neterrno;
3816 errmsg = netstrerror(error);
3817 n_log(LOG_ERR, "inet_ntop: %p , %s", (void*)&(*netw)->link.raddr, _str(errmsg));
3818 FreeNoLog(errmsg);
3819 }
3820 (*netw)->link.ip = ip;
3821 break; /* Success */
3822 }
3823 error = neterrno;
3824 errmsg = netstrerror(error);
3825 _netw_capture_error(*netw, "Error from bind() on UDP port %s neterrno: %s", port, errmsg);
3826 n_log(LOG_ERR, "Error from bind() on UDP port %s neterrno: %s", port, errmsg);
3827 FreeNoLog(errmsg);
3828 closesocket((*netw)->link.sock);
3829 }
3830 if (rp == NULL) {
3831 _netw_capture_error(*netw, "Couldn't get a socket for UDP binding on port %s", port);
3832 n_log(LOG_ERR, "Couldn't get a socket for UDP binding on port %s", port);
3834 return FALSE;
3835 }
3836
3837 /* set send/recv to UDP functions */
3838 (*netw)->send_data = &send_udp_data;
3839 (*netw)->recv_data = &recv_udp_data;
3840
3842
3843 n_log(LOG_DEBUG, "UDP socket bound to %s:%s", _str((*netw)->link.ip), port);
3844
3845 return TRUE;
3846} /* netw_bind_udp(...)*/
3847
3856int netw_connect_udp(NETWORK** netw, char* host, char* port, int ip_version) {
3857 int error = 0;
3858 char* errmsg = NULL;
3859
3860 if ((*netw)) {
3861 n_log(LOG_ERR, "Unable to allocate (*netw), already existing. You must use empty NETWORK *structs.");
3862 return FALSE;
3863 }
3864
3866 __n_assert(netw && (*netw), return FALSE);
3867 (*netw)->transport_type = NETWORK_UDP;
3868
3869 if (netw_init_wsa(1, 2, 2) == FALSE) {
3870 n_log(LOG_ERR, "Unable to load WSA dll's");
3872 return FALSE;
3873 }
3874
3875 /* choose ip version */
3876 if (ip_version == NETWORK_IPV4) {
3877 (*netw)->link.hints.ai_family = AF_INET;
3878 } else if (ip_version == NETWORK_IPV6) {
3879 (*netw)->link.hints.ai_family = AF_INET6;
3880 } else {
3881 (*netw)->link.hints.ai_family = AF_UNSPEC;
3882 }
3883
3884 (*netw)->link.hints.ai_socktype = SOCK_DGRAM;
3885 (*netw)->link.hints.ai_protocol = IPPROTO_UDP;
3886 (*netw)->link.hints.ai_flags = AI_PASSIVE;
3887 (*netw)->link.hints.ai_canonname = NULL;
3888 (*netw)->link.hints.ai_next = NULL;
3889
3890 error = getaddrinfo(host, port, &(*netw)->link.hints, &(*netw)->link.rhost);
3891 if (error != 0) {
3892 _netw_capture_error(*netw, "Error when resolving %s:%s getaddrinfo: %s", host, port, gai_strerror(error));
3893 n_log(LOG_ERR, "Error when resolving %s:%s getaddrinfo: %s", host, port, gai_strerror(error));
3895 return FALSE;
3896 }
3897 (*netw)->addr_infos_loaded = 1;
3898 Malloc((*netw)->link.ip, char, 64);
3899 __n_assert((*netw)->link.ip, netw_close(netw); return FALSE);
3900
3901 struct addrinfo* rp = NULL;
3902 for (rp = (*netw)->link.rhost; rp != NULL; rp = rp->ai_next) {
3903 SOCKET sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
3904 if (sock == INVALID_SOCKET) {
3905 error = neterrno;
3906 errmsg = netstrerror(error);
3907 n_log(LOG_ERR, "Error while trying to make a UDP socket: %s", _str(errmsg));
3908 FreeNoLog(errmsg);
3909 continue;
3910 }
3911
3912 (*netw)->link.sock = sock;
3913
3914 /* connect() on UDP sets the default destination for send/recv */
3915 if (connect(sock, rp->ai_addr, (socklen_t)rp->ai_addrlen) == -1) {
3916 error = neterrno;
3917 errmsg = netstrerror(error);
3918 n_log(LOG_INFO, "UDP connecting to %s:%s : %s", host, port, _str(errmsg));
3919 FreeNoLog(errmsg);
3920 closesocket(sock);
3921 (*netw)->link.sock = INVALID_SOCKET;
3922 continue;
3923 } else {
3924 if (!inet_ntop(rp->ai_family, get_in_addr(rp->ai_addr), (*netw)->link.ip, 64)) {
3925 error = neterrno;
3926 errmsg = netstrerror(error);
3927 n_log(LOG_ERR, "inet_ntop: %p , %s", rp, _str(errmsg));
3928 FreeNoLog(errmsg);
3929 }
3930 break; /* Success */
3931 }
3932 }
3933 if (rp == NULL) {
3934 _netw_capture_error(*netw, "Couldn't connect UDP to %s:%s : no address succeeded", host, port);
3935 n_log(LOG_ERR, "Couldn't connect UDP to %s:%s : no address succeeded", host, port);
3937 return FALSE;
3938 }
3939
3940 (*netw)->link.port = strdup(port);
3941 __n_assert((*netw)->link.port, netw_close(netw); return FALSE);
3942
3943 /* set send/recv to UDP functions */
3944 (*netw)->send_data = &send_udp_data;
3945 (*netw)->recv_data = &recv_udp_data;
3946
3948
3949 n_log(LOG_DEBUG, "UDP-Connected to %s:%s", (*netw)->link.ip, (*netw)->link.port);
3950
3951 return TRUE;
3952} /* netw_connect_udp(...)*/
3953
3961ssize_t send_udp_data(void* netw, char* buf, uint32_t n) {
3963 __n_assert(buf, return NETW_SOCKET_ERROR);
3964
3965 SOCKET s = ((NETWORK*)netw)->link.sock;
3966 int error = 0;
3967 char* errmsg = NULL;
3968
3969 if (n == 0) {
3970 _netw_capture_error((NETWORK*)netw, "Send of 0 is unsupported.");
3971 n_log(LOG_ERR, "Send of 0 is unsupported.");
3972 return NETW_SOCKET_ERROR;
3973 }
3974
3975 ssize_t bs = send(s, buf, NETW_BUFLEN_CAST(n), NETFLAGS);
3976 error = neterrno;
3977 if (bs < 0) {
3978 if (error == ECONNRESET || error == ENOTCONN
3979#ifdef __windows__
3980 || error == WSAECONNRESET || error == WSAENOTCONN
3981#endif
3982 ) {
3983 n_log(LOG_DEBUG, "UDP socket " SOCKET_SIZE_FORMAT " disconnected !", s);
3985 }
3986 errmsg = netstrerror(error);
3987 _netw_capture_error((NETWORK*)netw, "UDP Socket " SOCKET_SIZE_FORMAT " send Error: %zd , %s", s, bs, _str(errmsg));
3988 n_log(LOG_ERR, "UDP Socket " SOCKET_SIZE_FORMAT " send Error: %zd , %s", s, bs, _str(errmsg));
3989 FreeNoLog(errmsg);
3990 return NETW_SOCKET_ERROR;
3991 }
3992 return bs;
3993} /*send_udp_data(...)*/
3994
4002ssize_t recv_udp_data(void* netw, char* buf, uint32_t n) {
4004 __n_assert(buf, return NETW_SOCKET_ERROR);
4005
4006 SOCKET s = ((NETWORK*)netw)->link.sock;
4007
4008 if (n == 0) {
4009 _netw_capture_error((NETWORK*)netw, "Recv of 0 is unsupported.");
4010 n_log(LOG_ERR, "Recv of 0 is unsupported.");
4011 return NETW_SOCKET_ERROR;
4012 }
4013
4014 ssize_t br = recv(s, buf, NETW_BUFLEN_CAST(n), NETFLAGS);
4015 int error = neterrno;
4016 if (br < 0) {
4017 char* errmsg = netstrerror(error);
4018 _netw_capture_error((NETWORK*)netw, "UDP socket " SOCKET_SIZE_FORMAT " recv returned %zd, error: %s", s, br, _str(errmsg));
4019 n_log(LOG_ERR, "UDP socket " SOCKET_SIZE_FORMAT " recv returned %zd, error: %s", s, br, _str(errmsg));
4020 FreeNoLog(errmsg);
4021 return NETW_SOCKET_ERROR;
4022 }
4023 if (br == 0) {
4024 n_log(LOG_DEBUG, "UDP socket " SOCKET_SIZE_FORMAT ": zero-length recv", s);
4025 }
4026 return br;
4027} /*recv_udp_data(...)*/
4028
4038ssize_t netw_udp_sendto(NETWORK* netw, char* buf, uint32_t n, struct sockaddr* dest_addr, socklen_t dest_len) {
4040 __n_assert(buf, return NETW_SOCKET_ERROR);
4041 __n_assert(dest_addr, return NETW_SOCKET_ERROR);
4042
4043 if (n == 0) {
4044 _netw_capture_error(netw, "Sendto of 0 is unsupported.");
4045 n_log(LOG_ERR, "Sendto of 0 is unsupported.");
4046 return NETW_SOCKET_ERROR;
4047 }
4048
4049 ssize_t bs = sendto(netw->link.sock, buf, NETW_BUFLEN_CAST(n), NETFLAGS, dest_addr, dest_len);
4050 if (bs < 0) {
4051 int error = neterrno;
4052 char* errmsg = netstrerror(error);
4053 _netw_capture_error(netw, "UDP socket " SOCKET_SIZE_FORMAT " sendto Error: %zd , %s", netw->link.sock, bs, _str(errmsg));
4054 n_log(LOG_ERR, "UDP socket " SOCKET_SIZE_FORMAT " sendto Error: %zd , %s", netw->link.sock, bs, _str(errmsg));
4055 FreeNoLog(errmsg);
4056 return NETW_SOCKET_ERROR;
4057 }
4058 return bs;
4059} /*netw_udp_sendto(...)*/
4060
4070ssize_t netw_udp_recvfrom(NETWORK* netw, char* buf, uint32_t n, struct sockaddr* src_addr, socklen_t* src_len) {
4072 __n_assert(buf, return NETW_SOCKET_ERROR);
4073
4074 if (n == 0) {
4075 _netw_capture_error(netw, "Recvfrom of 0 is unsupported.");
4076 n_log(LOG_ERR, "Recvfrom of 0 is unsupported.");
4077 return NETW_SOCKET_ERROR;
4078 }
4079
4080 ssize_t br = recvfrom(netw->link.sock, buf, NETW_BUFLEN_CAST(n), NETFLAGS, src_addr, src_len);
4081 if (br < 0) {
4082 int error = neterrno;
4083 char* errmsg = netstrerror(error);
4084 _netw_capture_error(netw, "UDP socket " SOCKET_SIZE_FORMAT " recvfrom returned %zd, error: %s", netw->link.sock, br, _str(errmsg));
4085 n_log(LOG_ERR, "UDP socket " SOCKET_SIZE_FORMAT " recvfrom returned %zd, error: %s", netw->link.sock, br, _str(errmsg));
4086 FreeNoLog(errmsg);
4087 return NETW_SOCKET_ERROR;
4088 }
4089 return br;
4090} /*netw_udp_recvfrom(...)*/
4091
4101NETWORK* netw_accept_from_ex(NETWORK* from, size_t send_list_limit, size_t recv_list_limit, int blocking, int* retval) {
4102 SOCKET tmp = INVALID_SOCKET;
4103 int error;
4104 char* errmsg = NULL;
4105
4106#if defined(__linux__) || defined(__sun) || defined(_AIX)
4107 socklen_t sin_size = 0;
4108#else
4109 int sin_size = 0;
4110#endif
4111
4112 NETWORK* netw = NULL;
4113
4114 /*checking WSA when under windows*/
4115 if (netw_init_wsa(1, 2, 2) == FALSE) {
4116 n_log(LOG_ERR, "Unable to load WSA dll's");
4117 return NULL;
4118 }
4119
4120 __n_assert(from, return NULL);
4121
4122 netw = netw_new(send_list_limit, recv_list_limit);
4123
4124 sin_size = sizeof(netw->link.raddr);
4125
4126 if (blocking > 0) {
4127 int secs = blocking / 1000;
4128 int usecs = (blocking % 1000) * 1000;
4129 struct timeval select_timeout = {secs, usecs};
4130
4131 fd_set accept_set;
4132 FD_ZERO(&accept_set);
4133#pragma GCC diagnostic push
4134#pragma GCC diagnostic ignored "-Wsign-conversion"
4135 FD_SET(from->link.sock, &accept_set);
4136#pragma GCC diagnostic pop
4137
4138 int ret = select((int)(from->link.sock + 1), &accept_set, NULL, NULL, &select_timeout);
4139 if (ret == -1) {
4140 error = neterrno;
4141 errmsg = netstrerror(error);
4142 if (retval != NULL)
4143 (*retval) = error;
4144 n_log(LOG_DEBUG, "error on select with timeout %ds (%d.%ds), neterrno: %s", blocking, secs, usecs, _str(errmsg));
4145 FreeNoLog(errmsg);
4146 netw_close(&netw);
4147 return NULL;
4148 } else if (ret == 0) {
4149 /* that one produce waaaay too much logs under a lot of cases */
4150 n_log(LOG_DEBUG, "No connection waiting on " SOCKET_SIZE_FORMAT "", from->link.sock);
4151 netw_close(&netw);
4152 return NULL;
4153 }
4154#pragma GCC diagnostic push
4155#pragma GCC diagnostic ignored "-Wsign-conversion"
4156 if (FD_ISSET(from->link.sock, &accept_set)) {
4157#pragma GCC diagnostic pop
4158 // n_log( LOG_DEBUG, "select accept call on %d", from -> link . sock );
4159 tmp = accept(from->link.sock, (struct sockaddr*)&netw->link.raddr, &sin_size);
4160 if (tmp == INVALID_SOCKET) {
4161 error = neterrno;
4162 errmsg = netstrerror(error);
4163 if (retval != NULL)
4164 (*retval) = error;
4165 n_log(LOG_DEBUG, "error accepting on " SOCKET_SIZE_FORMAT ", %s", netw->link.sock, _str(errmsg));
4166 FreeNoLog(errmsg);
4167 netw_close(&netw);
4168 return NULL;
4169 }
4170 } else {
4171 _netw_capture_error(from, "FD_ISSET returned false on " SOCKET_SIZE_FORMAT "", from->link.sock);
4172 n_log(LOG_ERR, "FD_ISSET returned false on " SOCKET_SIZE_FORMAT "", from->link.sock);
4173 netw_close(&netw);
4174 return NULL;
4175 }
4176 netw->link.is_blocking = 0;
4177 } else if (blocking == -1) {
4178 if (from->link.is_blocking != 0) {
4179 netw_set_blocking(from, 0);
4180 }
4181 tmp = accept(from->link.sock, (struct sockaddr*)&netw->link.raddr, &sin_size);
4182 error = neterrno;
4183 if (retval != NULL)
4184 (*retval) = error;
4185 if (tmp == INVALID_SOCKET) {
4186 if (error != EINTR && error != EAGAIN
4187#ifdef __windows__
4188 && error != WSAEWOULDBLOCK
4189#endif
4190 ) {
4191 char* errmsg_nb = netstrerror(error);
4192 // cppcheck-suppress unknownMacro ; SOCKET_SIZE_FORMAT is a platform-specific printf format macro
4193 n_log(LOG_ERR, "accept returned an invalid socket (" SOCKET_SIZE_FORMAT "), neterrno: %s", tmp, _str(errmsg_nb));
4194 FreeNoLog(errmsg_nb);
4195 }
4196 netw_close(&netw);
4197 return NULL;
4198 }
4199 netw->link.is_blocking = 0;
4200 } else {
4201 if (from->link.is_blocking == 0) {
4202 netw_set_blocking(from, 1);
4203 n_log(LOG_DEBUG, "(default) blocking accept call on socket " SOCKET_SIZE_FORMAT "", from->link.sock);
4204 }
4205 tmp = accept(from->link.sock, (struct sockaddr*)&netw->link.raddr, &sin_size);
4206 if (tmp == INVALID_SOCKET) {
4207 error = neterrno;
4208 errmsg = netstrerror(error);
4209 if (retval != NULL)
4210 (*retval) = error;
4211 n_log(LOG_DEBUG, "error accepting on socket " SOCKET_SIZE_FORMAT ", %s", netw->link.sock, _str(errmsg));
4212 FreeNoLog(errmsg);
4213 netw_close(&netw);
4214 return NULL;
4215 }
4216 netw->link.is_blocking = 1;
4217 }
4218 netw->link.sock = tmp;
4219
4220 /* On Windows and Solaris, the accepted socket inherits the non-blocking
4221 * mode from the listening socket. The send/recv engine expects a
4222 * blocking socket, so force it to blocking here. On Linux this is a
4223 * harmless no-op since accept() always returns a blocking socket. */
4225 netw->link.is_blocking = 1;
4226
4227 netw->link.port = strdup(from->link.port);
4228 Malloc(netw->link.ip, char, 64);
4229 if (!netw->link.ip) {
4230 n_log(LOG_ERR, "Error allocating 64 bytes for ip");
4231 netw_close(&netw);
4232 return NULL;
4233 }
4234 if (!inet_ntop(netw->link.raddr.ss_family, get_in_addr(((struct sockaddr*)&netw->link.raddr)), netw->link.ip, 64)) {
4235 error = neterrno;
4236 errmsg = netstrerror(error);
4237 n_log(LOG_ERR, "inet_ntop: %p , %s", (void*)&netw->link.raddr, _str(errmsg));
4238 FreeNoLog(errmsg);
4239 netw_close(&netw);
4240 return NULL;
4241 }
4242
4243 netw_setsockopt(netw, SO_REUSEADDR, 1);
4244 // netw_setsockopt( netw, SO_REUSEPORT, 1 );
4245 netw_setsockopt(netw, SO_KEEPALIVE, 1);
4247 // netw_set_blocking(netw, 1);
4248
4249 n_log(LOG_DEBUG, "Connection accepted from %s:%s socket " SOCKET_SIZE_FORMAT "", netw->link.ip, netw->link.port, netw->link.sock);
4250
4251#ifdef HAVE_OPENSSL
4252 if (from->crypto_algo == NETW_ENCRYPT_OPENSSL) {
4253 netw->ssl = SSL_new(from->ctx);
4254 SSL_set_fd(netw->ssl, (int)netw->link.sock);
4255
4256 netw->send_data = &send_ssl_data;
4257 netw->recv_data = &recv_ssl_data;
4258 netw->send_data_once = &send_ssl_data_once;
4259 netw->recv_data_once = &recv_ssl_data_once;
4260 /* mark accepted netw as SSL so netw_close() runs SSL_free on its ssl;
4261 * ctx stays NULL, it is borrowed from the listener and freed there */
4262 netw->crypto_algo = NETW_ENCRYPT_OPENSSL;
4263
4264 if (SSL_accept(netw->ssl) <= 0) {
4265 error = errno;
4266 _netw_capture_error(netw, "SSL error on " SOCKET_SIZE_FORMAT "", netw->link.sock);
4267 n_log(LOG_ERR, "SSL error on " SOCKET_SIZE_FORMAT "", netw->link.sock);
4268 if (retval != NULL)
4269 (*retval) = error;
4270 netw_ssl_print_errors(netw->link.sock);
4271 netw_close(&netw);
4272 return NULL;
4273 } else {
4274 n_log(LOG_DEBUG, " socket " SOCKET_SIZE_FORMAT ": SSL connection established", netw->link.sock);
4275 }
4276 }
4277#endif
4278
4279 return netw;
4280} /* netw_accept_from_ex(...) */
4281
4288 return netw_accept_from_ex(from, MAX_LIST_ITEMS, MAX_LIST_ITEMS, 0, NULL);
4289} /* network_accept_from( ... ) */
4290
4298 return netw_accept_from_ex(from, MAX_LIST_ITEMS, MAX_LIST_ITEMS, blocking, NULL);
4299} /* network_accept_from( ... ) */
4300
4307/* Process-wide byte counters. See netw_bytes_stats_get in
4308 * n_network_msg.c. Every connection thread updates them, so they are only
4309 * touched with relaxed atomic operations: telemetry, no ordering implied. */
4310long long g_netw_bytes_sent = 0;
4311long long g_netw_bytes_recv = 0;
4312
4314 __n_assert(netw, return FALSE);
4315 __n_assert(msg, return FALSE);
4316 __n_assert(msg->data, return FALSE);
4317
4318 if (msg->length == 0) {
4319 _netw_capture_error(netw, "Empty messages are not supported. msg(%p)->length=%zu", msg, msg->length);
4320 n_log(LOG_ERR, "Empty messages are not supported. msg(%p)->length=%zu", msg, msg->length);
4321 return FALSE;
4322 }
4323
4324 /* Capture msg->written for the byte counter before the push:
4325 * list_push transfers ownership to send_buf with free_nstr_ptr
4326 * as the destructor, so once we release sendbolt the consumer
4327 * (send thread or reactor) can shift, send, and free `msg`,
4328 * making any post-unlock `msg->written` read a use-after-free.
4329 * The race is mostly latent in thread mode (send thread blocks
4330 * on the syscall before freeing) but the reactor consumes within
4331 * microseconds and TSan flags it consistently. */
4332 long long bytes_for_counter = (long long)msg->written;
4333
4334 pthread_mutex_lock(&netw->sendbolt);
4335
4336 if (list_push(netw->send_buf, msg, free_nstr_ptr) == FALSE) {
4337 pthread_mutex_unlock(&netw->sendbolt);
4338 return FALSE;
4339 }
4340
4341 pthread_mutex_unlock(&netw->sendbolt);
4342
4343 /* Reactor mode: wake the reactor's epoll_wait via its
4344 * wake-eventfd so it picks up the new send_buf entry. The
4345 * thread engine's sem_post path stays as the default; the wake
4346 * call is a single non-blocking eventfd write when reactor_mode
4347 * is set. Forward declared in n_reactor.h to avoid a circular
4348 * include with this header, the function pointer dispatch
4349 * happens through netw->reactor_handle.
4350 *
4351 * Compile-time gated on N_REACTOR_AVAILABLE: on Windows / Solaris
4352 * the reactor is unavailable, reactor_mode is always 0, and we
4353 * never want this TU to reference n_reactor_notify_send (which
4354 * would force linking n_reactor.o for a code path that can never
4355 * fire). The unconditional sem_post fallback matches the
4356 * non-reactor branch of the gated form. */
4357#if N_REACTOR_AVAILABLE
4359 extern void n_reactor_notify_send(NETWORK*);
4361 } else {
4362 sem_post(&netw->send_blocker);
4363 }
4364#else
4365 sem_post(&netw->send_blocker);
4366#endif
4367
4368 __atomic_fetch_add(&g_netw_bytes_sent, bytes_for_counter, __ATOMIC_RELAXED);
4369 return TRUE;
4370} /* netw_add_msg(...) */
4371
4379int netw_add_msg_ex(NETWORK* netw, char* str, unsigned int length) {
4380 __n_assert(netw, return FALSE);
4381 __n_assert(str, return FALSE);
4382 if (length == 0) {
4383 return FALSE;
4384 }
4385
4386 N_STR* nstr = NULL;
4387 Malloc(nstr, N_STR, 1);
4388 __n_assert(nstr, return FALSE);
4389
4390 nstr->data = str;
4391 nstr->written = nstr->length = length;
4392
4393 pthread_mutex_lock(&netw->sendbolt);
4394 if (list_push(netw->send_buf, nstr, free_nstr_ptr) == FALSE) {
4395 pthread_mutex_unlock(&netw->sendbolt);
4396 return FALSE;
4397 }
4398 pthread_mutex_unlock(&netw->sendbolt);
4399
4400 sem_post(&netw->send_blocker);
4401
4402 return TRUE;
4403} /* netw_add_msg_ex(...) */
4404
4411 N_STR* ptr = NULL;
4412
4413 __n_assert(netw, return NULL);
4414
4415 pthread_mutex_lock(&netw->recvbolt);
4416
4417 ptr = list_shift(netw->recv_buf, N_STR);
4418
4419 pthread_mutex_unlock(&netw->recvbolt);
4420
4421 if (ptr) __atomic_fetch_add(&g_netw_bytes_recv, (long long)ptr->written, __ATOMIC_RELAXED);
4422 return ptr;
4423} /* netw_get_msg(...)*/
4424
4432N_STR* netw_wait_msg(NETWORK* netw, unsigned int refresh, size_t timeout) {
4433 size_t timed = 0;
4434 unsigned int secs = 0;
4435 unsigned int usecs = 0;
4436
4437 __n_assert(netw, return NULL);
4438
4439 usecs = refresh;
4440 if (refresh > 999999) {
4441 secs = refresh / 1000000;
4442 usecs = refresh % 1000000;
4443 }
4444
4445 if (timeout > 0)
4446 timed = timeout;
4447
4448 n_log(LOG_DEBUG, "wait from socket " SOCKET_SIZE_FORMAT ", refresh: %u usec (%u secs, %u usecs), timeout %zu usec", netw->link.sock, refresh, secs, usecs, timeout);
4449 uint32_t state = NETW_RUN;
4450 int thr_state = 0;
4451 do {
4452 N_STR* nstrptr = netw_get_msg(netw);
4453 if (nstrptr)
4454 return nstrptr;
4455
4456 if (timeout > 0) {
4457 if (timed >= refresh)
4458 timed -= refresh;
4459 if (timed == 0 || timed < refresh) {
4460 _netw_capture_error(netw, "netw " SOCKET_SIZE_FORMAT ", status: %s (%" PRIu32 "), timeouted after waiting %zu msecs", netw->link.sock, N_ENUM_ENTRY(__netw_code_type, toString)(state), state, timeout);
4461 n_log(LOG_ERR, "netw " SOCKET_SIZE_FORMAT ", status: %s (%" PRIu32 "), timeouted after waiting %zu msecs", netw->link.sock, N_ENUM_ENTRY(__netw_code_type, toString)(state), state, timeout);
4462 return NULL;
4463 }
4464 }
4465 if (secs > 0)
4466 sleep(secs);
4467 if (usecs > 0)
4468 u_sleep(usecs);
4469
4470 netw_get_state(netw, &state, &thr_state);
4471 } while (state != NETW_EXITED && state != NETW_ERROR);
4472
4473 _netw_capture_error(netw, "got no answer and netw " SOCKET_SIZE_FORMAT " is no more running, state: %s (%" PRIu32 ")", netw->link.sock, N_ENUM_ENTRY(__netw_code_type, toString)(state), state);
4474 n_log(LOG_ERR, "got no answer and netw " SOCKET_SIZE_FORMAT " is no more running, state: %s (%" PRIu32 ")", netw->link.sock, N_ENUM_ENTRY(__netw_code_type, toString)(state), state);
4475
4476 return NULL;
4477} /* netw_wait_msg(...) */
4478
4485 __n_assert(netw, return FALSE);
4486
4487 pthread_mutex_lock(&netw->eventbolt);
4488 if (netw->threaded_engine_status == NETW_THR_ENGINE_STARTED) {
4489 _netw_capture_error(netw, "THR Engine already started for network %p (%s)", netw, _str(netw->link.ip));
4490 n_log(LOG_ERR, "THR Engine already started for network %p (%s)", netw, _str(netw->link.ip));
4491 pthread_mutex_unlock(&netw->eventbolt);
4492 return FALSE;
4493 }
4494
4495 if (pthread_create(&netw->recv_thr, NULL, netw_recv_func, (void*)netw) != 0) {
4496 _netw_capture_error(netw, "Unable to create recv_thread for network %p (%s)", netw, _str(netw->link.ip));
4497 n_log(LOG_ERR, "Unable to create recv_thread for network %p (%s)", netw, _str(netw->link.ip));
4498 pthread_mutex_unlock(&netw->eventbolt);
4499 return FALSE;
4500 }
4501 netw->nb_running_threads++;
4502 if (pthread_create(&netw->send_thr, NULL, netw_send_func, (void*)netw) != 0) {
4503 _netw_capture_error(netw, "Unable to create send_thread for network %p (%s)", netw, _str(netw->link.ip));
4504 n_log(LOG_ERR, "Unable to create send_thread for network %p (%s)", netw, _str(netw->link.ip));
4505 /* Android's Bionic libc has no pthread_cancel. Stop the just-started
4506 * recv thread the portable way netw_stop_thr_engine already uses: it
4507 * polls NETW_EXIT_ASKED and returns. Elsewhere pthread_cancel is the
4508 * forceful backup for a recv blocked with no read timeout. */
4509#if defined(__ANDROID__)
4511#else
4512 pthread_cancel(netw->recv_thr);
4513#endif
4514 pthread_join(netw->recv_thr, NULL);
4515 netw->nb_running_threads--;
4516 pthread_mutex_unlock(&netw->eventbolt);
4517 return FALSE;
4518 }
4519 netw->nb_running_threads++;
4520
4521 netw->threaded_engine_status = NETW_THR_ENGINE_STARTED;
4522
4523 pthread_mutex_unlock(&netw->eventbolt);
4524
4525 return TRUE;
4526} /* netw_create_recv_thread(....) */
4527
4533void* netw_send_func(void* NET) {
4534 int DONE = 0;
4535
4536 ssize_t net_status = 0;
4537
4538 uint32_t state;
4539 uint32_t nboctet;
4540
4541 char nboct[5] = "";
4542
4543 N_STR* ptr = NULL;
4544
4545 NETWORK* netw = (NETWORK*)NET;
4546 __n_assert(netw, return NULL);
4547
4548 do {
4549 /* do not consume cpu for nothing, reduce delay */
4550 sem_wait(&netw->send_blocker);
4551 int message_sent = 0;
4552 while (message_sent == 0 && !DONE) {
4554 if (state & NETW_ERROR) {
4556 } else if (state & NETW_EXITED) {
4558 } else if (state & NETW_EXIT_ASKED) {
4560 /* sending state */
4561 nboctet = htonl(NETW_EXIT_ASKED);
4562 memcpy(nboct, &nboctet, sizeof(uint32_t));
4563 n_log(LOG_DEBUG, "" SOCKET_SIZE_FORMAT " Sending Quit !", netw->link.sock);
4564 net_status = netw->send_data(netw, nboct, sizeof(int32_t));
4565 /* Peer disconnect during QUIT send is the expected
4566 * end of the handshake; only a real socket error
4567 * deserves the DONE=4 error path. */
4568 if (net_status < 0 && net_status != NETW_SOCKET_DISCONNECTED)
4569 DONE = 4;
4570 n_log(LOG_DEBUG, "" SOCKET_SIZE_FORMAT " Quit sent!", netw->link.sock);
4571 } else {
4572 pthread_mutex_lock(&netw->sendbolt);
4573 ptr = list_shift(netw->send_buf, N_STR);
4574 pthread_mutex_unlock(&netw->sendbolt);
4575 if (ptr && ptr->length > 0 && ptr->data) {
4576 /* Headroom for the 8-byte state+length header so
4577 * frame_len below cannot overflow the uint32 the
4578 * send_data API takes. */
4579 if (ptr->written <= UINT_MAX - 2 * sizeof(uint32_t)) {
4580 n_log(LOG_DEBUG, "Sending ptr size %zu written %zu...", ptr->length, ptr->written);
4581
4582 /* Opportunistic compression. Gated on threshold
4583 * + ratio so small packets and incompressible
4584 * binary snapshots don't pay the codec cost.
4585 * Algorithm picked per-connection via
4586 * netw_set_compression_mode(); NONE skips the
4587 * entire attempt. */
4588 uint32_t pkt_state = state;
4589 if (netw->compress_mode != NETW_COMPRESS_NONE &&
4591 N_STR* zipped = NULL;
4592 uint32_t flag_bit = 0;
4593 if (netw->compress_mode == NETW_COMPRESS_LZ4) {
4594 zipped = zip4_nstr(ptr);
4595 flag_bit = NETW_COMPRESSED_LZ4;
4596 } else {
4597 zipped = zip_nstr(ptr);
4598 flag_bit = NETW_COMPRESSED_ZLIB;
4599 }
4600 if (zipped && zipped->written > 0 &&
4601 zipped->written * 100u <=
4602 ptr->written * (100u - NETW_COMPRESS_MIN_RATIO)) {
4603 /* Good enough shrink, swap. */
4604 free_nstr(&ptr);
4605 ptr = zipped;
4606 pkt_state |= flag_bit;
4607 } else if (zipped) {
4608 free_nstr(&zipped);
4609 }
4610 }
4611
4612 /* Single-write framing. The frame
4613 * used to go out as three separate send_data
4614 * calls (4B state, 4B length, payload): three
4615 * syscalls, and three TLS records on crypto
4616 * sockets, per message, with the two 4-byte
4617 * writes interacting badly with Nagle +
4618 * delayed-ACK on small-message streams (game
4619 * inputs, snapshots). Build the contiguous
4620 * frame and hand the kernel one write.
4621 * Peer disconnect (NETW_SOCKET_DISCONNECTED)
4622 * during the send is a normal end-of-life: the
4623 * connection is over, nothing to log. Only a
4624 * real socket error trips the DONE=1 error
4625 * path so the tail logger emits LOG_ERR. */
4626 size_t frame_len = 2 * sizeof(uint32_t) + ptr->written;
4627 char* frame = NULL;
4628 Malloc(frame, char, frame_len);
4629 if (frame) {
4630 nboctet = htonl(pkt_state);
4631 memcpy(frame, &nboctet, sizeof(uint32_t));
4632 nboctet = htonl((uint32_t)ptr->written);
4633 memcpy(frame + sizeof(uint32_t), &nboctet, sizeof(uint32_t));
4634 memcpy(frame + 2 * sizeof(uint32_t), ptr->data, ptr->written);
4635 net_status = netw->send_data(netw, frame, (uint32_t)frame_len);
4636 if (net_status < 0)
4637 DONE = (net_status == NETW_SOCKET_DISCONNECTED) ? NETW_THR_EXIT_OK : 1;
4638 Free(frame);
4639 } else {
4640 /* OOM building the frame: drop the message
4641 * (stream alignment is preserved, nothing
4642 * was written) and keep the connection up,
4643 * mirroring the oversize-discard branch. */
4644 _netw_capture_error(netw, "could not allocate %zu byte send frame, packet dropped", frame_len);
4645 n_log(LOG_ERR, "could not allocate %zu byte send frame, packet dropped", frame_len);
4646 }
4647 if (netw->send_queue_consecutive_wait >= 0) {
4648 u_sleep((unsigned int)netw->send_queue_consecutive_wait);
4649 }
4650 message_sent = 1;
4651 free_nstr(&ptr);
4652 } else {
4653 _netw_capture_error(netw, "discarded packet of size %zu which is greater than %" PRIu32, ptr->written, UINT_MAX);
4654 n_log(LOG_ERR, "discarded packet of size %zu which is greater than %" PRIu32, ptr->written, UINT_MAX);
4655 message_sent = 1;
4656 free_nstr(&ptr);
4657 }
4658 } else {
4659 /* Empty send_buf or malformed head entry: the
4660 * producer-consumer contract means sem_post was
4661 * called without a usable list_push, or a state
4662 * transition posted without a real message. Break
4663 * out of the inner loop and block on sem_wait
4664 * rather than spinning, spinning grabs sendbolt
4665 * at MHz rates and creates main-thread contention
4666 * in netw_add_msg. */
4667 if (ptr) free_nstr(&ptr);
4668 message_sent = 1;
4669 }
4670 }
4671 }
4672 } while (!DONE);
4673
4674 if (DONE == 1) {
4675 _netw_capture_error(netw, "Error when sending state %" PRIu32 " on socket " SOCKET_SIZE_FORMAT " (%s), network: %s", netw_atomic_read_state(netw), netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4676 n_log(LOG_ERR, "Error when sending state %" PRIu32 " on socket " SOCKET_SIZE_FORMAT " (%s), network: %s", netw_atomic_read_state(netw), netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4677 } else if (DONE == 2) {
4678 _netw_capture_error(netw, "Error when sending number of octet to socket " SOCKET_SIZE_FORMAT " (%s), network: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4679 n_log(LOG_ERR, "Error when sending number of octet to socket " SOCKET_SIZE_FORMAT " (%s), network: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4680 } else if (DONE == 3)
4681 n_log(LOG_DEBUG, "Error when sending data on socket " SOCKET_SIZE_FORMAT " (%s), network: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4682 else if (DONE == 4) {
4683 _netw_capture_error(netw, "Error when sending state QUIT on socket " SOCKET_SIZE_FORMAT " (%s), network: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4684 n_log(LOG_ERR, "Error when sending state QUIT on socket " SOCKET_SIZE_FORMAT " (%s), network: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4685 } else if (DONE == 5) {
4686 _netw_capture_error(netw, "Error when sending state QUIT number of octet (0) on socket " SOCKET_SIZE_FORMAT " (%s), network: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4687 n_log(LOG_ERR, "Error when sending state QUIT number of octet (0) on socket " SOCKET_SIZE_FORMAT " (%s), network: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4688 }
4689
4690 if (DONE == NETW_THR_EXIT_OK) {
4691 n_log(LOG_DEBUG, "Socket " SOCKET_SIZE_FORMAT ": Sending thread exiting correctly", netw->link.sock);
4693 } else {
4694 _netw_capture_error(netw, "Socket " SOCKET_SIZE_FORMAT " (%s): Sending thread exiting with error %d !", netw->link.sock, _str(netw->link.ip), DONE);
4695 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " (%s): Sending thread exiting with error %d !", netw->link.sock, _str(netw->link.ip), DONE);
4697 }
4698
4699 pthread_mutex_lock(&netw->eventbolt);
4700 netw->nb_running_threads--;
4701 pthread_mutex_unlock(&netw->eventbolt);
4702
4703 pthread_exit(0);
4704
4705 /* suppress compiler warning */
4706#if !defined(__linux__)
4707 return NULL;
4708#endif
4709} /* netw_send_func(...) */
4710
4716void* netw_recv_func(void* NET) {
4717 int DONE = 0;
4718 ssize_t net_status = 0;
4719
4720 uint32_t nboctet;
4721 uint32_t tmpstate;
4722 uint32_t state;
4723
4724 char nboct[5] = "";
4725
4726 N_STR* recvdmsg = NULL;
4727
4728 NETWORK* netw = (NETWORK*)NET;
4729
4730 __n_assert(netw, return NULL);
4731
4732 do {
4734 if (state & NETW_EXIT_ASKED || state & NETW_EXITED) {
4736 }
4737 if (state & NETW_ERROR) {
4739 }
4740 if (!DONE) {
4741 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " : waiting to receive status", netw->link.sock);
4742 /* receiving state */
4743 net_status = netw->recv_data(netw, nboct, sizeof(uint32_t));
4744 if (net_status < 0) {
4745 /* Peer disconnect (NETW_SOCKET_DISCONNECTED) is the
4746 * normal end of a connection, no log noise, exit
4747 * via the clean NETW_THR_EXIT_OK path so the
4748 * application observes NETW_EXIT_ASKED, not
4749 * NETW_ERROR. Only NETW_SOCKET_ERROR routes through
4750 * the DONE=N error tail logger. */
4751 DONE = (net_status == NETW_SOCKET_DISCONNECTED) ? NETW_THR_EXIT_OK : 1;
4752 } else {
4753 memcpy(&nboctet, nboct, sizeof(uint32_t));
4754 tmpstate = ntohl(nboctet);
4755 nboctet = tmpstate;
4756 /* Freeze the per-packet state word before the next
4757 * recv_data call reuses tmpstate for the payload
4758 * length, the NETW_COMPRESSED_* flag check below
4759 * reads pkt_state, not tmpstate. */
4760 uint32_t pkt_state = tmpstate;
4761 if (tmpstate == NETW_EXIT_ASKED) {
4762 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " : receiving order to QUIT !", netw->link.sock);
4764 } else {
4765 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " : waiting to receive next message nboctets", netw->link.sock);
4766 /* receiving nboctet */
4767 net_status = netw->recv_data(netw, nboct, sizeof(uint32_t));
4768 if (net_status < 0) {
4769 DONE = (net_status == NETW_SOCKET_DISCONNECTED) ? NETW_THR_EXIT_OK : 2;
4770 } else {
4771 memcpy(&nboctet, nboct, sizeof(uint32_t));
4772 tmpstate = ntohl(nboctet);
4773 nboctet = tmpstate;
4774
4775 Malloc(recvdmsg, N_STR, 1);
4776 if (!recvdmsg) {
4777 DONE = 3;
4778 } else if (nboctet > NETW_MSG_MAX_FRAME_SIZE) {
4779 /* Hostile / corrupt length prefix. Reject before
4780 * allocating the payload: an unbounded value is a
4781 * memory-DoS, and 0xFFFFFFFF would wrap the
4782 * `nboctet + 1` below to 0, yielding a zero-byte
4783 * buffer that the payload recv then overflows. */
4784 free_nstr(&recvdmsg);
4785 DONE = 8;
4786 } else {
4787 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " : %" PRIu32 " octets to receive...", netw->link.sock, nboctet);
4788 Malloc(recvdmsg->data, char, nboctet + 1);
4789 if (!recvdmsg->data) {
4790 free_nstr(&recvdmsg);
4791 DONE = 4;
4792 } else {
4793 recvdmsg->length = nboctet + 1;
4794 recvdmsg->written = nboctet;
4795
4796 /* receiving the data itself */
4797 net_status = netw->recv_data(netw, recvdmsg->data, nboctet);
4798 if (net_status < 0) {
4799 free_nstr(&recvdmsg);
4800 DONE = (net_status == NETW_SOCKET_DISCONNECTED) ? NETW_THR_EXIT_OK : 5;
4801 } else {
4802 /* Inverse of the compression step on
4803 * the send side. Each NETW_COMPRESSED_*
4804 * bit identifies the codec the sender
4805 * chose; we decode regardless of our
4806 * own compress_mode so two peers
4807 * running different algorithms still
4808 * interop. */
4809 int want_zlib = (pkt_state & NETW_COMPRESSED_ZLIB) != 0;
4810 int want_lz4 = (pkt_state & NETW_COMPRESSED_LZ4) != 0;
4811 if (want_zlib || want_lz4) {
4812 recvdmsg->data[nboctet] = '\0';
4813 N_STR* plain = want_lz4
4814 ? unzip4_nstr(recvdmsg)
4815 : unzip_nstr(recvdmsg);
4816 if (plain) {
4817 free_nstr(&recvdmsg);
4818 recvdmsg = plain;
4819 } else {
4820 n_log(LOG_ERR,
4821 "socket " SOCKET_SIZE_FORMAT " : failed to decompress payload (%" PRIu32 " bytes, codec=%s); dropping",
4822 netw->link.sock, nboctet,
4823 want_lz4 ? "lz4" : "zlib");
4824 free_nstr(&recvdmsg);
4825 DONE = 7;
4826 }
4827 }
4828 if (!DONE) {
4829 pthread_mutex_lock(&netw->recvbolt);
4830 if (list_push(netw->recv_buf, recvdmsg, free_nstr_ptr) == FALSE)
4831 DONE = 6;
4832 pthread_mutex_unlock(&netw->recvbolt);
4833 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " : %" PRIu32 " octets received !", netw->link.sock, nboctet);
4834 }
4835 } /* recv data */
4836 } /* recv data allocation */
4837 } /* recv struct allocation */
4838 } /* recv nb octet*/
4839 } /* exit asked */
4840 } /* recv state */
4841 } /* if( !done) */
4842 } while (!DONE);
4843
4844 if (DONE == 1) {
4845 _netw_capture_error(netw, "Error when receiving state from socket " SOCKET_SIZE_FORMAT " (%s), net_status: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4846 n_log(LOG_ERR, "Error when receiving state from socket " SOCKET_SIZE_FORMAT " (%s), net_status: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4847 } else if (DONE == 2) {
4848 _netw_capture_error(netw, "Error when receiving nboctet from socket " SOCKET_SIZE_FORMAT " (%s), net_status: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4849 n_log(LOG_ERR, "Error when receiving nboctet from socket " SOCKET_SIZE_FORMAT " (%s), net_status: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4850 } else if (DONE == 3) {
4851 _netw_capture_error(netw, "Error when receiving data from socket " SOCKET_SIZE_FORMAT " (%s), net_status: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4852 n_log(LOG_ERR, "Error when receiving data from socket " SOCKET_SIZE_FORMAT " (%s), net_status: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4853 } else if (DONE == 4) {
4854 _netw_capture_error(netw, "Error allocating received message struct from socket " SOCKET_SIZE_FORMAT " (%s), net_status: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4855 n_log(LOG_ERR, "Error allocating received message struct from socket " SOCKET_SIZE_FORMAT " (%s), net_status: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4856 } else if (DONE == 5) {
4857 _netw_capture_error(netw, "Error allocating received messages data array from socket " SOCKET_SIZE_FORMAT " (%s), net_status: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4858 n_log(LOG_ERR, "Error allocating received messages data array from socket " SOCKET_SIZE_FORMAT " (%s), net_status: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4859 } else if (DONE == 6) {
4860 _netw_capture_error(netw, "Error adding receved message from socket " SOCKET_SIZE_FORMAT " (%s), net_status: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4861 n_log(LOG_ERR, "Error adding receved message from socket " SOCKET_SIZE_FORMAT " (%s), net_status: %s", netw->link.sock, _str(netw->link.ip), (net_status == NETW_SOCKET_DISCONNECTED) ? "disconnected" : "socket error");
4862 } else if (DONE == 8) {
4863 _netw_capture_error(netw, "Rejected oversized frame from socket " SOCKET_SIZE_FORMAT " (%s): length exceeds NETW_MSG_MAX_FRAME_SIZE (%lu bytes)", netw->link.sock, _str(netw->link.ip), (unsigned long)NETW_MSG_MAX_FRAME_SIZE);
4864 n_log(LOG_ERR, "Rejected oversized frame from socket " SOCKET_SIZE_FORMAT " (%s): length exceeds NETW_MSG_MAX_FRAME_SIZE (%lu bytes)", netw->link.sock, _str(netw->link.ip), (unsigned long)NETW_MSG_MAX_FRAME_SIZE);
4865 }
4866
4867 if (DONE == NETW_THR_EXIT_OK) {
4868 n_log(LOG_DEBUG, "Socket " SOCKET_SIZE_FORMAT " (%s): Receive thread exiting correctly", netw->link.sock, _str(netw->link.ip));
4870 } else {
4871 _netw_capture_error(netw, "Socket " SOCKET_SIZE_FORMAT " (%s): Receive thread exiting with code %d !", netw->link.sock, _str(netw->link.ip), DONE);
4872 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " (%s): Receive thread exiting with code %d !", netw->link.sock, _str(netw->link.ip), DONE);
4874 }
4875
4876 pthread_mutex_lock(&netw->eventbolt);
4877 netw->nb_running_threads--;
4878 pthread_mutex_unlock(&netw->eventbolt);
4879
4880 pthread_exit(0);
4881
4882 /* suppress compiler warning */
4883#if !defined(__linux__)
4884 return NULL;
4885#endif
4886} /* netw_recv_func(...) */
4887
4894 __n_assert(netw, return FALSE);
4895 uint32_t state = 0;
4896 int thr_engine_status = 0;
4897
4898 n_log(LOG_DEBUG, "Network " SOCKET_SIZE_FORMAT " stop threads event", netw->link.sock);
4899
4900 netw_get_state(netw, &state, &thr_engine_status);
4901
4902 if (thr_engine_status != NETW_THR_ENGINE_STARTED) {
4903 _netw_capture_error(netw, "Thread engine status already stopped for network %p", netw);
4904 n_log(LOG_ERR, "Thread engine status already stopped for network %p", netw);
4905 return FALSE;
4906 }
4907
4909
4910 n_log(LOG_DEBUG, "Network " SOCKET_SIZE_FORMAT " waits for send threads to stop", netw->link.sock);
4911 for (int it = 0; it < 10; it++) {
4912 sem_post(&netw->send_blocker);
4913 usleep(1000);
4914 }
4915 pthread_join(netw->send_thr, NULL);
4916 n_log(LOG_DEBUG, "Network " SOCKET_SIZE_FORMAT " waits for recv threads to stop", netw->link.sock);
4917 pthread_join(netw->recv_thr, NULL);
4918
4920
4921 n_log(LOG_DEBUG, "Network " SOCKET_SIZE_FORMAT " threads Stopped !", netw->link.sock);
4922
4923 return TRUE;
4924} /* Stop_Network( ... ) */
4925
4933ssize_t send_data(void* netw, char* buf, uint32_t n) {
4935 __n_assert(buf, return NETW_SOCKET_ERROR);
4936
4937 SOCKET s = ((NETWORK*)netw)->link.sock;
4938 ssize_t bcount = 0; /* counts bytes sent */
4939 int error;
4940 char* errmsg = NULL;
4941
4942 if (n == 0) {
4943 _netw_capture_error((NETWORK*)netw, "Send of 0 is unsupported.");
4944 n_log(LOG_ERR, "Send of 0 is unsupported.");
4945 return NETW_SOCKET_ERROR;
4946 }
4947
4948 char* tmp_buf = buf;
4949 while (bcount < n) /* loop until all sent */
4950 {
4951 ssize_t bs = 0; /* bytes sent this pass */
4952
4953 NETW_CALL_RETRY(bs, send(s, tmp_buf, NETW_BUFLEN_CAST(n - bcount), NETFLAGS), NETW_MAX_RETRIES);
4954 error = neterrno;
4955
4956 if (bs > 0) {
4957 bcount += bs; /* increment byte counter */
4958 tmp_buf += bs; /* move buffer ptr for next send */
4959 } else if (error == ECONNRESET || error == ENOTCONN || error == EPIPE
4960#ifdef __windows__
4961 || error == WSAECONNRESET || error == WSAENOTCONN || error == WSAESHUTDOWN
4962#endif
4963 ) {
4964 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " disconnected !", s);
4966 } else if (bs == -1) {
4967 /* real network error */
4968 errmsg = netstrerror(error);
4969 _netw_capture_error((NETWORK*)netw, "Socket " SOCKET_SIZE_FORMAT " send error: %zd, %s", s, bs, _str(errmsg));
4970 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " send error: %zd, %s", s, bs, _str(errmsg));
4971 FreeNoLog(errmsg);
4972 return NETW_SOCKET_ERROR;
4973 } else if (bs == -2) {
4974 /* EINTR/WOULDBLOCK retries exhausted */
4975 _netw_capture_error((NETWORK*)netw, "Socket " SOCKET_SIZE_FORMAT " : retry storm on send (%d retries)", s, NETW_MAX_RETRIES);
4976 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " : retry storm on send (%d retries)", s, NETW_MAX_RETRIES);
4977 return NETW_SOCKET_ERROR;
4978 } else if (bs == 0) {
4979 /* should never happen on send() */
4980 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " : send returned 0", s);
4982 }
4983 }
4984 return bcount;
4985} /*send_data(...)*/
4986
4994ssize_t recv_data(void* netw, char* buf, uint32_t n) {
4996 __n_assert(buf, return NETW_SOCKET_ERROR);
4997
4998 SOCKET s = ((NETWORK*)netw)->link.sock;
4999 ssize_t bcount = 0; /* counts bytes read */
5000 int error;
5001 char* errmsg = NULL;
5002
5003#if defined(NETWORK_DISABLE_ZERO_LENGTH_RECV) && (NETWORK_DISABLE_ZERO_LENGTH_RECV == TRUE)
5004 if (n == 0) {
5005 _netw_capture_error((NETWORK*)netw, "Recv of 0 is unsupported.");
5006 n_log(LOG_ERR, "Recv of 0 is unsupported.");
5007 return NETW_SOCKET_ERROR;
5008 }
5009#endif
5010
5011 char* tmp_buf = buf;
5012 while (bcount < n) /* loop until all received */
5013 {
5014 ssize_t br = 0; /* bytes received this pass */
5015
5016 NETW_CALL_RETRY(br, recv(s, tmp_buf, NETW_BUFLEN_CAST(n - bcount), NETFLAGS), NETW_MAX_RETRIES);
5017 error = neterrno;
5018
5019 if (br > 0) {
5020 bcount += br; /* increment byte counter */
5021 tmp_buf += br; /* move buffer ptr for next recv */
5022 } else if (br == 0) {
5023 /* clean shutdown from peer */
5024 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " : peer closed connection", s);
5026 } else if (error == ECONNRESET || error == ENOTCONN
5027#ifdef __windows__
5028 || error == WSAECONNRESET || error == WSAENOTCONN || error == WSAESHUTDOWN
5029#endif
5030 ) {
5031 /* connection reset or not connected */
5032 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " disconnected !", s);
5034 } else if (br == -1) {
5035 /* real network error */
5036 errmsg = netstrerror(error);
5037 _netw_capture_error((NETWORK*)netw, "Socket " SOCKET_SIZE_FORMAT " recv error: %zd, %s", s, br, _str(errmsg));
5038 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " recv error: %zd, %s", s, br, _str(errmsg));
5039 FreeNoLog(errmsg);
5040 return NETW_SOCKET_ERROR;
5041 } else if (br == -2) {
5042 /* EINTR/WOULDBLOCK retries exhausted */
5043 _netw_capture_error((NETWORK*)netw, "Socket " SOCKET_SIZE_FORMAT " : retry storm on recv (%d retries)", s, NETW_MAX_RETRIES);
5044 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " : retry storm on recv (%d retries)", s, NETW_MAX_RETRIES);
5045 return NETW_SOCKET_ERROR;
5046 }
5047 }
5048 return bcount;
5049} /*recv_data(...)*/
5050
5061ssize_t send_data_once(void* netw, char* buf, uint32_t n) {
5063 __n_assert(buf, return NETW_SOCKET_ERROR);
5064
5065 SOCKET s = ((NETWORK*)netw)->link.sock;
5066 if (n == 0) {
5067 _netw_capture_error((NETWORK*)netw, "Send of 0 is unsupported.");
5068 n_log(LOG_ERR, "Send of 0 is unsupported.");
5069 return NETW_SOCKET_ERROR;
5070 }
5071 for (;;) {
5072 ssize_t bs = send(s, buf, NETW_BUFLEN_CAST(n), NETFLAGS);
5073 int error = neterrno;
5074 if (bs > 0) return bs;
5075 if (bs == 0) {
5076 /* should never happen on send() */
5077 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " : send returned 0", s);
5079 }
5080 if (error == EINTR
5081#ifdef __windows__
5082 || error == WSAEINTR
5083#endif
5084 )
5085 continue;
5086 if (error == EAGAIN || error == EWOULDBLOCK
5087#ifdef __windows__
5088 || error == WSAEWOULDBLOCK
5089#endif
5090 )
5091 return NETW_IO_WANT_WRITE;
5092 if (error == ECONNRESET || error == ENOTCONN || error == EPIPE
5093#ifdef __windows__
5094 || error == WSAECONNRESET || error == WSAENOTCONN || error == WSAESHUTDOWN
5095#endif
5096 ) {
5097 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " disconnected !", s);
5099 }
5100 char* errmsg = netstrerror(error);
5101 _netw_capture_error((NETWORK*)netw, "Socket " SOCKET_SIZE_FORMAT " send_once error: %s", s, _str(errmsg));
5102 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " send_once error: %s", s, _str(errmsg));
5103 FreeNoLog(errmsg);
5104 return NETW_SOCKET_ERROR;
5105 }
5106} /*send_data_once(...)*/
5107
5117ssize_t recv_data_once(void* netw, char* buf, uint32_t n) {
5119 __n_assert(buf, return NETW_SOCKET_ERROR);
5120
5121 SOCKET s = ((NETWORK*)netw)->link.sock;
5122 if (n == 0) {
5123 _netw_capture_error((NETWORK*)netw, "Recv of 0 is unsupported.");
5124 n_log(LOG_ERR, "Recv of 0 is unsupported.");
5125 return NETW_SOCKET_ERROR;
5126 }
5127 for (;;) {
5128 ssize_t br = recv(s, buf, NETW_BUFLEN_CAST(n), NETFLAGS);
5129 int error = neterrno;
5130 if (br > 0) return br;
5131 if (br == 0) {
5132 /* orderly shutdown by peer */
5133 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " disconnected !", s);
5135 }
5136 if (error == EINTR
5137#ifdef __windows__
5138 || error == WSAEINTR
5139#endif
5140 )
5141 continue;
5142 if (error == EAGAIN || error == EWOULDBLOCK
5143#ifdef __windows__
5144 || error == WSAEWOULDBLOCK
5145#endif
5146 )
5147 return NETW_IO_WANT_READ;
5148 if (error == ECONNRESET || error == ENOTCONN
5149#ifdef __windows__
5150 || error == WSAECONNRESET || error == WSAENOTCONN
5151#endif
5152 ) {
5153 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " disconnected !", s);
5155 }
5156 char* errmsg = netstrerror(error);
5157 _netw_capture_error((NETWORK*)netw, "Socket " SOCKET_SIZE_FORMAT " recv_once error: %s", s, _str(errmsg));
5158 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " recv_once error: %s", s, _str(errmsg));
5159 FreeNoLog(errmsg);
5160 return NETW_SOCKET_ERROR;
5161 }
5162} /*recv_data_once(...)*/
5163
5164#ifdef HAVE_OPENSSL
5172ssize_t send_ssl_data(void* netw, char* buf, uint32_t n) {
5173 __n_assert(netw, return -1);
5174 __n_assert(buf, return -1);
5175
5176 SSL* ssl = ((NETWORK*)netw)->ssl;
5177 __n_assert(ssl, return -1);
5178
5179 SOCKET s = ((NETWORK*)netw)->link.sock;
5180
5181 ssize_t bcount = 0; // counts bytes sent
5182 int error;
5183 char* errmsg = NULL;
5184
5185 if (n == 0) {
5186 _netw_capture_error((NETWORK*)netw, "Send of 0 is unsupported.");
5187 n_log(LOG_ERR, "Send of 0 is unsupported.");
5188 return -1;
5189 }
5190
5191 while (bcount < n) // loop until full buffer
5192 {
5193 size_t bs = 0; // bytes sent this pass
5194 /* the thread's error queue must be empty before the call, or
5195 * SSL_get_error() reports another connection's stale error */
5196 ERR_clear_error();
5197#if OPENSSL_VERSION_NUMBER < 0x1010107fL
5198 int status = SSL_write(ssl, buf, (int)(n - bcount)); // OpenSSL < 1.1.1
5199 bs = (status > 0) ? (size_t)status : 0;
5200#else
5201 int status = SSL_write_ex(ssl, buf, (size_t)(n - bcount), &bs); // OpenSSL >= 1.1.1
5202#endif
5203 error = neterrno;
5204 if (status > 0) {
5205 bcount += (ssize_t)bs; // increment byte counter
5206 buf += bs; // move buffer ptr for next read
5207 } else {
5208 int ssl_error = SSL_get_error(ssl, status);
5209 if (ssl_error == SSL_ERROR_WANT_READ || ssl_error == SSL_ERROR_WANT_WRITE) {
5210 /* Rare on the blocking sockets the thread engine uses
5211 * (renegotiation / partial record). usleep(0) was a
5212 * pure busy-yield, burn a bounded 1 ms instead so a
5213 * stuck WANT state can't peg a core. */
5214 u_sleep(1000);
5215 continue;
5216 }
5217 /* Peer-closed connection is a normal end-of-life, not a
5218 * protocol error. SSL_ERROR_ZERO_RETURN is a clean TLS
5219 * close_notify; SSL_ERROR_SYSCALL with errno EPIPE /
5220 * ECONNRESET / ENOTCONN (or errno 0, OpenSSL's "unexpected
5221 * EOF" signal) means the socket went away under us. Mirror
5222 * the plaintext send_data() path: log at DEBUG and return
5223 * NETW_SOCKET_DISCONNECTED so the send thread's QUIT / normal
5224 * branches treat it as a graceful exit instead of an error.
5225 * Without this, a TLS client quitting after the server has
5226 * already dropped the link logs three spurious LOG_ERR lines
5227 * (SSL_write syscall error / state QUIT / thread exit err 4). */
5228 if (ssl_error == SSL_ERROR_ZERO_RETURN ||
5229 (ssl_error == SSL_ERROR_SYSCALL &&
5230 (error == 0 || error == EPIPE || error == ECONNRESET || error == ENOTCONN
5231#ifdef __windows__
5232 || error == WSAECONNRESET || error == WSAENOTCONN || error == WSAESHUTDOWN
5233#endif
5234 ))) {
5235 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " disconnected during SSL_write !", s);
5237 }
5238 errmsg = netstrerror(error);
5239 switch (ssl_error) {
5240 case SSL_ERROR_SYSCALL:
5241 // Real, unexpected syscall failure (errno set to something other than a peer close)
5242 _netw_capture_error((NETWORK*)netw, "socket " SOCKET_SIZE_FORMAT " SSL_write syscall error: %s", s, _str(errmsg));
5243 n_log(LOG_ERR, "socket " SOCKET_SIZE_FORMAT " SSL_write syscall error: %s", s, _str(errmsg));
5244 break;
5245 case SSL_ERROR_SSL:
5246 // Handle SSL protocol failure
5247 _netw_capture_error((NETWORK*)netw, "socket " SOCKET_SIZE_FORMAT " SSL_write returned %zu, error: %s", s, bs, ERR_reason_error_string(ERR_get_error()));
5248 n_log(LOG_ERR, "socket " SOCKET_SIZE_FORMAT " SSL_write returned %zu, error: %s", s, bs, ERR_reason_error_string(ERR_get_error()));
5249 break;
5250 default:
5251 // Other errors
5252 _netw_capture_error((NETWORK*)netw, "socket " SOCKET_SIZE_FORMAT " SSL_write returned %zu, errno: %s", s, bs, _str(errmsg));
5253 n_log(LOG_ERR, "socket " SOCKET_SIZE_FORMAT " SSL_write returned %zu, errno: %s", s, bs, _str(errmsg));
5254 break;
5255 }
5256 FreeNoLog(errmsg);
5257 return NETW_SOCKET_ERROR;
5258 }
5259 }
5260 return bcount;
5261} /*send_ssl_data(...)*/
5262
5270ssize_t recv_ssl_data(void* netw, char* buf, uint32_t n) {
5271 __n_assert(netw, return -1);
5272 __n_assert(buf, return -1);
5273
5274 SSL* ssl = ((NETWORK*)netw)->ssl;
5275 __n_assert(ssl, return -1);
5276
5277 SOCKET s = ((NETWORK*)netw)->link.sock;
5278 ssize_t bcount = 0; // counts bytes read
5279 int error;
5280 char* errmsg = NULL;
5281
5282 if (n == 0) {
5283 _netw_capture_error((NETWORK*)netw, "Recv of 0 is unsupported.");
5284 n_log(LOG_ERR, "Recv of 0 is unsupported.");
5285 return -1;
5286 }
5287
5288 while (bcount < n) {
5289 size_t br = 0; // bytes read this pass
5290 // loop until full buffer
5291 ERR_clear_error(); /* see send_ssl_data: a stale entry misreports */
5292#if OPENSSL_VERSION_NUMBER < 0x10101000L
5293 int status = SSL_read(ssl, buf, (int)(n - bcount)); // OpenSSL < 1.1.1
5294 br = (status > 0) ? (size_t)status : 0;
5295#else
5296 int status = SSL_read_ex(ssl, buf, (size_t)(n - bcount), &br); // OpenSSL >= 1.1.1
5297#endif
5298 error = neterrno;
5299 if (status > 0) {
5300 bcount += (ssize_t)br; // increment byte counter
5301 buf += br; // move buffer ptr for next read
5302 } else {
5303 int ssl_error = SSL_get_error(ssl, status);
5304 if (ssl_error == SSL_ERROR_WANT_READ || ssl_error == SSL_ERROR_WANT_WRITE) {
5305 /* Same bounded back-off as send_ssl_data, usleep(0)
5306 * was a busy-yield that could peg a core on a stuck
5307 * WANT state. */
5308 u_sleep(1000);
5309 continue;
5310 }
5311 /* Connection teardown is the normal end of a session, not an
5312 * error. Mirror the plaintext recv_data() and the
5313 * non-blocking recv_ssl_data_once() paths: return
5314 * NETW_SOCKET_DISCONNECTED so netw_recv_func() exits via the
5315 * clean NETW_THR_EXIT_OK path with no LOG_ERR noise -- and so
5316 * the recv thread does not flip the NETWORK into NETW_ERROR,
5317 * which is what was tripping the send thread into the
5318 * "exiting with error 666" (NETW_THR_EXIT_ERROR) tail on a
5319 * normal client exit. */
5320 if (ssl_error == SSL_ERROR_ZERO_RETURN) {
5321 /* peer sent a clean close_notify */
5322 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " : TLS session closed by peer (close_notify)", s);
5324 }
5325 if (ssl_error == SSL_ERROR_SYSCALL && (error == 0 || error == ECONNRESET || error == ENOTCONN
5326#ifdef __windows__
5327 || error == WSAECONNRESET || error == WSAENOTCONN || error == WSAESHUTDOWN
5328#endif
5329 )) {
5330 /* peer vanished without close_notify (TCP FIN/RST) */
5331 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " : peer closed connection (TLS, no close_notify)", s);
5333 }
5334 /* Pop the queued reason exactly ONCE and reuse it below;
5335 * calling ERR_get_error() twice (capture + log) cleared the
5336 * queue between calls, so the second read always printed
5337 * "(null)" instead of the real reason. */
5338 unsigned long ssl_reason = ERR_get_error();
5339 ERR_clear_error(); /* the rest would fail the next connection */
5340#ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING
5341 if (ssl_error == SSL_ERROR_SSL && ERR_GET_REASON(ssl_reason) == SSL_R_UNEXPECTED_EOF_WHILE_READING) {
5342 /* OpenSSL >= 3.0 reports an unclean TCP close as an
5343 * SSL_ERROR_SSL/UNEXPECTED_EOF rather than the
5344 * SSL_ERROR_SYSCALL/errno-0 of 1.1.1; still a disconnect. */
5345 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " : peer closed connection (TLS unexpected EOF)", s);
5347 }
5348#endif
5349 errmsg = netstrerror(error);
5350 switch (ssl_error) {
5351 case SSL_ERROR_SYSCALL:
5352 // Genuine syscall-level failure (not a peer close)
5353 _netw_capture_error((NETWORK*)netw, "socket " SOCKET_SIZE_FORMAT " SSL_read syscall error: %s", s, _str(errmsg));
5354 n_log(LOG_ERR, "socket " SOCKET_SIZE_FORMAT " SSL_read syscall error: %s", s, _str(errmsg));
5355 break;
5356 case SSL_ERROR_SSL:
5357 // Genuine TLS protocol failure
5358 _netw_capture_error((NETWORK*)netw, "socket " SOCKET_SIZE_FORMAT " SSL_read protocol error: %s", s, _str((char*)ERR_reason_error_string(ssl_reason)));
5359 n_log(LOG_ERR, "socket " SOCKET_SIZE_FORMAT " SSL_read protocol error: %s", s, _str((char*)ERR_reason_error_string(ssl_reason)));
5360 break;
5361 default:
5362 // Other errors
5363 _netw_capture_error((NETWORK*)netw, "socket " SOCKET_SIZE_FORMAT " SSL_read returned %zu, errno: %s", s, br, _str(errmsg));
5364 n_log(LOG_ERR, "socket " SOCKET_SIZE_FORMAT " SSL_read returned %zu, errno: %s", s, br, _str(errmsg));
5365 break;
5366 }
5367 FreeNoLog(errmsg);
5368 return NETW_SOCKET_ERROR;
5369 }
5370 }
5371 return bcount;
5372} /*recv_ssl_data(...)*/
5373
5388ssize_t send_ssl_data_once(void* netw, char* buf, uint32_t n) {
5390 __n_assert(buf, return NETW_SOCKET_ERROR);
5391
5392 SSL* ssl = ((NETWORK*)netw)->ssl;
5393 __n_assert(ssl, return NETW_SOCKET_ERROR);
5394 SOCKET s = ((NETWORK*)netw)->link.sock;
5395
5396 if (n == 0) {
5397 _netw_capture_error((NETWORK*)netw, "Send of 0 is unsupported.");
5398 n_log(LOG_ERR, "Send of 0 is unsupported.");
5399 return NETW_SOCKET_ERROR;
5400 }
5401
5402 size_t bs = 0;
5403 /* OpenSSL requires an EMPTY error queue before SSL_write/SSL_read:
5404 * SSL_get_error() returns SSL_ERROR_SSL whenever the queue holds
5405 * anything, so a stale entry left by ANOTHER connection (a shutdown
5406 * mid-handshake, say) turns this one's ordinary WANT_WRITE into a
5407 * fatal error, and a single-threaded server closes an innocent
5408 * connection with the other one's reason. Measured in DarkChan
5409 * (2026-10-08): a client's first frames were lost that way. */
5410 ERR_clear_error();
5411#if OPENSSL_VERSION_NUMBER < 0x1010107fL
5412 int status = SSL_write(ssl, buf, (int)n);
5413 bs = (status > 0) ? (size_t)status : 0;
5414#else
5415 int status = SSL_write_ex(ssl, buf, (size_t)n, &bs);
5416#endif
5417 int error = neterrno;
5418 if (status > 0) return (ssize_t)bs;
5419
5420 int ssl_error = SSL_get_error(ssl, status);
5421 switch (ssl_error) {
5422 case SSL_ERROR_WANT_READ:
5423 return NETW_IO_WANT_READ;
5424 case SSL_ERROR_WANT_WRITE:
5425 return NETW_IO_WANT_WRITE;
5426 case SSL_ERROR_ZERO_RETURN:
5427 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " TLS session closed by peer", s);
5429 case SSL_ERROR_SYSCALL:
5430 if (error == 0 || error == ECONNRESET || error == EPIPE || error == ENOTCONN
5431#ifdef __windows__
5432 || error == WSAECONNRESET || error == WSAENOTCONN
5433#endif
5434 ) {
5435 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " SSL_write syscall: connection closed by peer", s);
5437 }
5438 if (error == EINTR || error == EAGAIN || error == EWOULDBLOCK
5439#ifdef __windows__
5440 || error == WSAEINTR || error == WSAEWOULDBLOCK
5441#endif
5442 )
5443 return NETW_IO_WANT_WRITE;
5444 {
5445 char* errmsg = netstrerror(error);
5446 _netw_capture_error((NETWORK*)netw, "socket " SOCKET_SIZE_FORMAT " SSL_write_once syscall error: %s", s, _str(errmsg));
5447 n_log(LOG_ERR, "socket " SOCKET_SIZE_FORMAT " SSL_write_once syscall error: %s", s, _str(errmsg));
5448 FreeNoLog(errmsg);
5449 }
5450 return NETW_SOCKET_ERROR;
5451 default: {
5452 /* pop the reason ONCE (two ERR_get_error() calls logged the
5453 * second entry, or "(null)"), then drop the rest so it cannot
5454 * fail the next connection's I/O */
5455 unsigned long ssl_reason = ERR_get_error();
5456 ERR_clear_error();
5457 _netw_capture_error((NETWORK*)netw, "socket " SOCKET_SIZE_FORMAT " SSL_write_once error: %s", s, _str((char*)ERR_reason_error_string(ssl_reason)));
5458 n_log(LOG_ERR, "socket " SOCKET_SIZE_FORMAT " SSL_write_once error: %s", s, _str((char*)ERR_reason_error_string(ssl_reason)));
5459 return NETW_SOCKET_ERROR;
5460 }
5461 }
5462} /*send_ssl_data_once(...)*/
5463
5476ssize_t recv_ssl_data_once(void* netw, char* buf, uint32_t n) {
5478 __n_assert(buf, return NETW_SOCKET_ERROR);
5479
5480 SSL* ssl = ((NETWORK*)netw)->ssl;
5481 __n_assert(ssl, return NETW_SOCKET_ERROR);
5482 SOCKET s = ((NETWORK*)netw)->link.sock;
5483
5484 if (n == 0) {
5485 _netw_capture_error((NETWORK*)netw, "Recv of 0 is unsupported.");
5486 n_log(LOG_ERR, "Recv of 0 is unsupported.");
5487 return NETW_SOCKET_ERROR;
5488 }
5489
5490 size_t br = 0;
5491 ERR_clear_error(); /* empty before the call: see send_ssl_data_once */
5492#if OPENSSL_VERSION_NUMBER < 0x10101000L
5493 int status = SSL_read(ssl, buf, (int)n);
5494 br = (status > 0) ? (size_t)status : 0;
5495#else
5496 int status = SSL_read_ex(ssl, buf, (size_t)n, &br);
5497#endif
5498 int error = neterrno;
5499 if (status > 0) return (ssize_t)br;
5500
5501 int ssl_error = SSL_get_error(ssl, status);
5502 switch (ssl_error) {
5503 case SSL_ERROR_WANT_READ:
5504 return NETW_IO_WANT_READ;
5505 case SSL_ERROR_WANT_WRITE:
5506 return NETW_IO_WANT_WRITE;
5507 case SSL_ERROR_ZERO_RETURN:
5508 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " TLS session closed by peer", s);
5510 case SSL_ERROR_SYSCALL:
5511 if (error == 0 || error == ECONNRESET || error == ENOTCONN
5512#ifdef __windows__
5513 || error == WSAECONNRESET || error == WSAENOTCONN
5514#endif
5515 ) {
5516 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " SSL_read syscall: connection closed by peer", s);
5518 }
5519 if (error == EINTR || error == EAGAIN || error == EWOULDBLOCK
5520#ifdef __windows__
5521 || error == WSAEINTR || error == WSAEWOULDBLOCK
5522#endif
5523 )
5524 return NETW_IO_WANT_READ;
5525 {
5526 char* errmsg = netstrerror(error);
5527 _netw_capture_error((NETWORK*)netw, "socket " SOCKET_SIZE_FORMAT " SSL_read_once syscall error: %s", s, _str(errmsg));
5528 n_log(LOG_ERR, "socket " SOCKET_SIZE_FORMAT " SSL_read_once syscall error: %s", s, _str(errmsg));
5529 FreeNoLog(errmsg);
5530 }
5531 return NETW_SOCKET_ERROR;
5532 default: {
5533 /* Pop the reason once (a second ERR_get_error() would clear
5534 * the queue and print "(null)"). OpenSSL >= 3.0 reports an
5535 * unclean TCP close here as SSL_ERROR_SSL/UNEXPECTED_EOF --
5536 * a disconnect, not a protocol error. */
5537 unsigned long ssl_reason = ERR_get_error();
5538 ERR_clear_error(); /* the rest would fail the next connection */
5539#ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING
5540 if (ssl_error == SSL_ERROR_SSL && ERR_GET_REASON(ssl_reason) == SSL_R_UNEXPECTED_EOF_WHILE_READING) {
5541 n_log(LOG_DEBUG, "socket " SOCKET_SIZE_FORMAT " : peer closed connection (TLS unexpected EOF)", s);
5543 }
5544#endif
5545 _netw_capture_error((NETWORK*)netw, "socket " SOCKET_SIZE_FORMAT " SSL_read_once error: %s", s, _str((char*)ERR_reason_error_string(ssl_reason)));
5546 n_log(LOG_ERR, "socket " SOCKET_SIZE_FORMAT " SSL_read_once error: %s", s, _str((char*)ERR_reason_error_string(ssl_reason)));
5547 return NETW_SOCKET_ERROR;
5548 }
5549 }
5550} /*recv_ssl_data_once(...)*/
5551#endif
5552
5561ssize_t send_php(SOCKET s, int _code, char* buf, int n) {
5562 ssize_t bcount = 0; /* counts bytes read */
5563 ssize_t bs; /* bytes read this pass */
5564
5565 int error;
5566 char* errmsg = NULL;
5567
5568 char* ptr = NULL; /* temp char ptr ;-) */
5569 char head[HEAD_SIZE + 1] = "";
5570 char code[HEAD_CODE + 1] = "";
5571
5572 // Format and assign to head
5573 snprintf(head, HEAD_SIZE + 1, "%0*d", HEAD_SIZE, n);
5574 // Format and assign to code
5575 snprintf(code, HEAD_CODE + 1, "%0*d", HEAD_CODE, _code);
5576
5577 /* sending head */
5578 bcount = 0;
5579 ptr = head;
5580 while (bcount < HEAD_SIZE) /* loop until full buffer */
5581 {
5582 bs = send(s, ptr, NETW_BUFLEN_CAST(HEAD_SIZE - bcount), NETFLAGS);
5583 error = neterrno;
5584 if (bs > 0) {
5585 bcount += bs; /* increment byte counter */
5586 ptr += bs; /* move buffer ptr for next read */
5587 } else {
5588 /* signal an error to the caller */
5589 errmsg = netstrerror(error);
5590 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " sending Error %zd when sending head size, neterrno: %s", s, bs, _str(errmsg));
5591 FreeNoLog(errmsg);
5592 return -1;
5593 }
5594 }
5595
5596 /* sending code */
5597 bcount = 0;
5598 ptr = code;
5599 while (bcount < HEAD_CODE) /* loop until full buffer */
5600 {
5601 bs = send(s, ptr, NETW_BUFLEN_CAST(HEAD_CODE - bcount), NETFLAGS);
5602 error = neterrno;
5603 if (bs > 0) {
5604 bcount += bs; /* increment byte counter */
5605 ptr += bs; /* move buffer ptr for next read */
5606 } else {
5607 errmsg = netstrerror(error);
5608 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " sending Error %zd when sending head code, neterrno: %s", s, bs, _str(errmsg));
5609 FreeNoLog(errmsg);
5610 return -1;
5611 }
5612 }
5613
5614 /* sending buf */
5615 bcount = 0;
5616 while (bcount < n) /* loop until full buffer */
5617 {
5618 bs = send(s, buf, NETW_BUFLEN_CAST(n - bcount), NETFLAGS);
5619 error = neterrno;
5620 if (bs > 0) {
5621 bcount += bs; /* increment byte counter */
5622 buf += bs; /* move buffer ptr for next read */
5623 } else {
5624 /* signal an error to the caller */
5625 errmsg = netstrerror(error);
5626 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " sending Error %zd when sending message of size %d, neterrno: %s", s, bs, n, _str(errmsg));
5627 FreeNoLog(errmsg);
5628 return -1;
5629 }
5630 }
5631
5632 return bcount;
5633
5634} /*send_php(...)*/
5635
5643ssize_t recv_php(SOCKET s, int* _code, char** buf) {
5644 ssize_t bcount = 0; /* counts bytes read */
5645 ssize_t br; /* bytes read this pass */
5646 long int tmpnb = 0, size = 0; /* size of message to receive */
5647 char* ptr = NULL;
5648
5649 int error;
5650 char* errmsg = NULL;
5651
5652 char head[HEAD_SIZE + 1] = "";
5653 char code[HEAD_CODE + 1] = "";
5654
5655 /* Receiving total message size */
5656 bcount = 0;
5657 ptr = head;
5658 while (bcount < HEAD_SIZE) {
5659 /* loop until full buffer */
5660 br = recv(s, ptr, NETW_BUFLEN_CAST(HEAD_SIZE - bcount), NETFLAGS);
5661 error = neterrno;
5662 if (br > 0) {
5663 bcount += br; /* increment byte counter */
5664 ptr += br; /* move buffer ptr for next read */
5665 } else {
5666 /* signal an error to the caller */
5667 errmsg = netstrerror(error);
5668 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " receive %zd Error %s", s, br, _str(errmsg));
5669 FreeNoLog(errmsg);
5670 return FALSE;
5671 }
5672 }
5673
5674 tmpnb = strtol(head, NULL, 10);
5675 if (tmpnb == LONG_MIN || tmpnb == LONG_MAX) {
5676 n_log(LOG_ERR, "Size received ( %ld ) can not be determined on socket " SOCKET_SIZE_FORMAT "", tmpnb, s);
5677 return FALSE;
5678 }
5679
5680 size = tmpnb;
5681
5682 /* receiving request code */
5683 bcount = 0;
5684 ptr = code;
5685 while (bcount < HEAD_CODE) {
5686 /* loop until full buffer */
5687 br = recv(s, ptr, NETW_BUFLEN_CAST(HEAD_CODE - bcount), NETFLAGS);
5688 error = neterrno;
5689 if (br > 0) {
5690 bcount += br; /* increment byte counter */
5691 ptr += br; /* move buffer ptr for next read */
5692 } else {
5693 /* signal an error to the caller */
5694 errmsg = netstrerror(error);
5695 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " receive %zd Error , neterrno: %s", s, br, _str(errmsg));
5696 FreeNoLog(errmsg);
5697 return FALSE;
5698 }
5699 }
5700
5701 tmpnb = strtol(code, NULL, 10);
5702 if (tmpnb <= INT_MIN || tmpnb >= INT_MAX) {
5703 n_log(LOG_ERR, "Code received ( %ld ) too big or too little to be valid code on socket " SOCKET_SIZE_FORMAT "", tmpnb, s);
5704 return FALSE;
5705 }
5706
5707 (*_code) = (int)tmpnb;
5708
5709 /* receving message */
5710 if ((*buf)) {
5711 // cppcheck-suppress identicalInnerCondition ; Free() macro rechecks pointer internally
5712 Free((*buf));
5713 }
5714 Malloc((*buf), char, (size_t)(size + 1));
5715 if (!(*buf)) {
5716 n_log(LOG_ERR, "Could not allocate PHP receive buf");
5717 return FALSE;
5718 }
5719
5720 bcount = 0;
5721 ptr = (*buf);
5722 while (bcount < size) {
5723 /* loop until full buffer */
5724 br = recv(s, ptr, NETW_BUFLEN_CAST(size - bcount), NETFLAGS);
5725 error = neterrno;
5726 if (br > 0) {
5727 bcount += br; /* increment byte counter */
5728 ptr += br; /* move buffer ptr for next read */
5729 } else {
5730 /* signal an error to the caller */
5731 errmsg = netstrerror(error);
5732 n_log(LOG_ERR, "Socket " SOCKET_SIZE_FORMAT " receive %zd Error neterrno: %s", s, br, _str(errmsg));
5733 FreeNoLog(errmsg);
5734 return FALSE;
5735 }
5736 }
5737 return size;
5738} /*recv_php(...)*/
5739
5748int netw_get_queue_status(NETWORK* netw, size_t* nb_to_send, size_t* nb_to_read) {
5749 __n_assert(netw, return FALSE);
5750
5751 pthread_mutex_lock(&netw->sendbolt);
5752 (*nb_to_send) = netw->send_buf->nb_items;
5753 pthread_mutex_unlock(&netw->sendbolt);
5754
5755 pthread_mutex_lock(&netw->recvbolt);
5756 (*nb_to_read) = netw->recv_buf->nb_items;
5757 pthread_mutex_unlock(&netw->recvbolt);
5758
5759 return TRUE;
5760} /* get queue states */
5761
5767NETWORK_POOL* netw_new_pool(size_t nb_min_element) {
5768 NETWORK_POOL* netw_pool = NULL;
5769
5770 Malloc(netw_pool, NETWORK_POOL, 1);
5771 __n_assert(netw_pool, return NULL);
5772
5773 netw_pool->pool = new_ht(nb_min_element);
5774 __n_assert(netw_pool->pool, Free(netw_pool); return NULL);
5775
5776 init_lock(netw_pool->rwlock);
5777
5778 return netw_pool;
5779} /* netw_new_pool() */
5780
5787 __n_assert(netw_pool && (*netw_pool), return FALSE);
5788
5789 write_lock((*netw_pool)->rwlock);
5790 if ((*netw_pool)->pool)
5791 destroy_ht(&(*netw_pool)->pool);
5792 unlock((*netw_pool)->rwlock);
5793
5794 rw_lock_destroy((*netw_pool)->rwlock);
5795
5796 Free((*netw_pool));
5797
5798 return TRUE;
5799} /* netw_destroy_pool() */
5800
5805void netw_pool_netw_close(void* netw_ptr) {
5806 NETWORK* netw = (NETWORK*)netw_ptr;
5807 __n_assert(netw, return);
5808 n_log(LOG_DEBUG, "Network pool %p: network id " SOCKET_SIZE_FORMAT " still active !!", netw, netw->link.sock);
5809 return;
5810} /* netw_pool_netw_close() */
5811
5819 __n_assert(netw_pool, return FALSE);
5820 __n_assert(netw, return FALSE);
5821
5822 n_log(LOG_DEBUG, "Trying to add %lld to %p", (unsigned long long)netw->link.sock, netw_pool->pool);
5823
5824 /* write lock the pool */
5825 write_lock(netw_pool->rwlock);
5826 /* test if not already added */
5827 N_STR* key = NULL;
5828 nstrprintf(key, "%lld", (unsigned long long)netw->link.sock);
5829 HASH_NODE* node = NULL;
5830 if (ht_get_ptr(netw_pool->pool, _nstr(key), (void*)&node) == TRUE) {
5831 _netw_capture_error(netw, "Network id " SOCKET_SIZE_FORMAT " already added !", netw->link.sock);
5832 n_log(LOG_ERR, "Network id " SOCKET_SIZE_FORMAT " already added !", netw->link.sock);
5833 free_nstr(&key);
5834 unlock(netw_pool->rwlock);
5835 return FALSE;
5836 }
5837 int retval;
5838 /* add it */
5839 if ((retval = ht_put_ptr(netw_pool->pool, _nstr(key), netw, &netw_pool_netw_close, NULL)) == TRUE) {
5840 if ((retval = list_push(netw->pools, netw_pool, NULL)) == TRUE) {
5841 n_log(LOG_DEBUG, "added netw " SOCKET_SIZE_FORMAT " to pool %p", netw->link.sock, netw_pool);
5842 } else {
5843 _netw_capture_error(netw, "could not add netw " SOCKET_SIZE_FORMAT " to pool %p", netw->link.sock, netw_pool);
5844 n_log(LOG_ERR, "could not add netw " SOCKET_SIZE_FORMAT " to pool %p", netw->link.sock, netw_pool);
5845 }
5846 } else {
5847 _netw_capture_error(netw, "could not add netw " SOCKET_SIZE_FORMAT " to pool %p", netw->link.sock, netw_pool);
5848 n_log(LOG_ERR, "could not add netw " SOCKET_SIZE_FORMAT " to pool %p", netw->link.sock, netw_pool);
5849 }
5850 free_nstr(&key);
5851
5852 /* unlock the pool */
5853 unlock(netw_pool->rwlock);
5854
5855 return retval;
5856} /* netw_pool_add() */
5857
5865 __n_assert(netw_pool, return FALSE);
5866 __n_assert(netw, return FALSE);
5867
5868 /* write lock the pool */
5869 write_lock(netw_pool->rwlock);
5870 /* test if present */
5871 N_STR* key = NULL;
5872 nstrprintf(key, "%lld", (unsigned long long int)netw->link.sock);
5873 if (ht_remove(netw_pool->pool, _nstr(key)) == TRUE) {
5874 LIST_NODE* node = list_search(netw->pools, netw_pool);
5875 if (node) {
5876 if (!remove_list_node(netw->pools, node, NETWORK_POOL)) {
5877 _netw_capture_error(netw, "Network id " SOCKET_SIZE_FORMAT " could not be removed !", netw->link.sock);
5878 n_log(LOG_ERR, "Network id " SOCKET_SIZE_FORMAT " could not be removed !", netw->link.sock);
5879 }
5880 }
5881 unlock(netw_pool->rwlock);
5882 n_log(LOG_DEBUG, "Network id " SOCKET_SIZE_FORMAT " removed !", netw->link.sock);
5883 free_nstr(&key);
5884 return TRUE;
5885 }
5886 free_nstr(&key);
5887 _netw_capture_error(netw, "Network id " SOCKET_SIZE_FORMAT " already removed !", netw->link.sock);
5888 n_log(LOG_ERR, "Network id " SOCKET_SIZE_FORMAT " already removed !", netw->link.sock);
5889 /* unlock the pool */
5890 unlock(netw_pool->rwlock);
5891 return FALSE;
5892} /* netw_pool_remove */
5893
5901int netw_pool_broadcast(NETWORK_POOL* netw_pool, const NETWORK* from, N_STR* net_msg) {
5902 __n_assert(netw_pool, return FALSE);
5903 __n_assert(net_msg, return FALSE);
5904
5905 /* write lock the pool */
5906 read_lock(netw_pool->rwlock);
5907 ht_foreach(node, netw_pool->pool) {
5908 NETWORK* netw = hash_val(node, NETWORK);
5909 if (from) {
5910 if (netw->link.sock != from->link.sock)
5911 netw_add_msg(netw, nstrdup(net_msg));
5912 } else {
5913 netw_add_msg(netw, nstrdup(net_msg));
5914 }
5915 }
5916 unlock(netw_pool->rwlock);
5917 return TRUE;
5918} /* netw_pool_broadcast */
5919
5926 __n_assert(netw_pool, return 0);
5927
5928 size_t nb = 0;
5929 read_lock(netw_pool->rwlock);
5930 nb = netw_pool->pool->nb_keys;
5931 unlock(netw_pool->rwlock);
5932
5933 return nb;
5934} /* netw_pool_nbclients() */
5935
5943 __n_assert(netw, return FALSE);
5944 netw->user_id = id;
5945 return TRUE;
5946} /* netw_set_user_id() */
5947
5957int netw_send_ping(NETWORK* netw, int type, int id_from, int id_to, int time) {
5958 N_STR* tmpstr = NULL;
5959 __n_assert(netw, return FALSE);
5960
5961 tmpstr = netmsg_make_ping(type, id_from, id_to, time);
5962 __n_assert(tmpstr, return FALSE);
5963
5964 return netw_add_msg(netw, tmpstr);
5965} /* netw_send_ping( ... ) */
5966
5976int netw_send_ident(NETWORK* netw, int type, int id, N_STR* name, N_STR* passwd) {
5977 N_STR* tmpstr = NULL;
5978
5979 __n_assert(netw, return FALSE);
5980
5981 tmpstr = netmsg_make_ident(type, id, name, passwd);
5982 __n_assert(tmpstr, return FALSE);
5983
5984 return netw_add_msg(netw, tmpstr);
5985} /* netw_send_ident( ... ) */
5986
6000int netw_send_position(NETWORK* netw, int id, double X, double Y, double vx, double vy, double acc_x, double acc_y, int time_stamp) {
6001 N_STR* tmpstr = NULL;
6002
6003 __n_assert(netw, return FALSE);
6004
6005 tmpstr = netmsg_make_position_msg(id, X, Y, vx, vy, acc_x, acc_y, time_stamp);
6006
6007 __n_assert(tmpstr, return FALSE);
6008
6009 return netw_add_msg(netw, tmpstr);
6010} /* netw_send_position( ... ) */
6011
6022int netw_send_string_to(NETWORK* netw, int id_to, N_STR* name, N_STR* chan, N_STR* txt, int color) {
6023 N_STR* tmpstr = NULL;
6024
6025 __n_assert(netw, return FALSE);
6026
6027 tmpstr = netmsg_make_string_msg(netw->user_id, id_to, name, chan, txt, color);
6028 __n_assert(tmpstr, return FALSE);
6029
6030 return netw_add_msg(netw, tmpstr);
6031} /* netw_send_string_to( ... ) */
6032
6042int netw_send_string_to_all(NETWORK* netw, N_STR* name, N_STR* chan, N_STR* txt, int color) {
6043 N_STR* tmpstr = NULL;
6044
6045 __n_assert(netw, return FALSE);
6046
6047 tmpstr = netmsg_make_string_msg(netw->user_id, -1, name, chan, txt, color);
6048 __n_assert(tmpstr, return FALSE);
6049
6050 return netw_add_msg(netw, tmpstr);
6051} /* netw_send_string_to_all( ... ) */
6052
6059 __n_assert(netw, return FALSE);
6060
6061 N_STR* tmpstr = NULL;
6062
6063 tmpstr = netmsg_make_quit_msg();
6064 __n_assert(tmpstr, return FALSE);
6065
6066 return netw_add_msg(netw, tmpstr);
6067} /* netw_send_quit( ... ) */
6068
6075size_t netw_calculate_urlencoded_size(const char* str, size_t len) {
6076 __n_assert(str, return 0);
6077
6078 size_t encoded_size = 0;
6079
6080 for (size_t i = 0; i < len; i++) {
6081 unsigned char c = (unsigned char)str[i];
6082 if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
6083 encoded_size += 1; // Safe character, no encoding needed
6084 } else {
6085 encoded_size += 3; // Unsafe character, will be encoded as %XX
6086 }
6087 }
6088
6089 return encoded_size;
6090}
6091
6098char* netw_urlencode(const char* str, size_t len) {
6099 __n_assert(str, return NULL);
6100
6101 static const char* hex = "0123456789ABCDEF";
6102 size_t encoded_size = netw_calculate_urlencoded_size(str, len);
6103 char* encoded = (char*)malloc(encoded_size + 1); // Allocate memory for the encoded string (+1 for the null terminator)
6104
6105 if (!encoded) {
6106 return NULL; // Return NULL if memory allocation fails
6107 }
6108
6109 char* pbuf = encoded;
6110
6111 for (size_t i = 0; i < len; i++) {
6112 unsigned char c = (unsigned char)str[i];
6113 if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
6114 *pbuf++ = (char)c; // Copy safe characters directly
6115 } else {
6116 *pbuf++ = '%'; // Encode unsafe characters as %XX
6117 *pbuf++ = hex[c >> 4];
6118 *pbuf++ = hex[c & 0xF];
6119 }
6120 }
6121
6122 *pbuf = '\0'; // Null-terminate the encoded string
6123 return encoded;
6124}
6125
6131char* netw_extract_http_request_type(const char* request) {
6132 __n_assert(request, return NULL);
6133 // Find the first space in the request string
6134 const char* space = strchr(request, ' ');
6135
6136 if (space == NULL) {
6137 // No space found, invalid request format
6138 return NULL;
6139 }
6140
6141 // Calculate the length of the request type
6142 size_t method_length = (size_t)(space - request);
6143
6144 // Allocate memory for the method string (+1 for the null terminator)
6145 char* method = (char*)malloc(method_length + 1);
6146
6147 if (method == NULL) {
6148 // Memory allocation failed
6149 return NULL;
6150 }
6151
6152 // Copy the request method to the allocated memory
6153 strncpy(method, request, method_length);
6154 method[method_length] = '\0'; // Null-terminate the string
6155
6156 return method;
6157}
6158
6165 NETWORK_HTTP_INFO info = {.content_length = 0, .body = NULL, .type = NULL, .content_type = {0}};
6166
6167 __n_assert(request, return info);
6168
6169 // Hold the request-type allocation in a local until just before return.
6170 // The clang static analyzer's unix.Malloc checker mis-tracks ownership
6171 // when a malloc'd pointer is parked in a returned-by-value struct member
6172 // early in the function; keeping it local until the final assignment
6173 // makes the escape via the returned struct unambiguous to the analyzer.
6174 char* request_type = netw_extract_http_request_type(request);
6175
6176 // Find Content-Type header (Optional)
6177 const char* content_type_header = strstr(request, "Content-Type:");
6178 if (content_type_header) {
6179 const char* start = content_type_header + strlen("Content-Type: ");
6180 const char* end = strstr(start, "\r\n");
6181 if (end) {
6182 size_t length = (size_t)(end - start);
6183 if (length > 255) length = 255;
6184 strncpy(info.content_type, start, length);
6185 info.content_type[length] = '\0';
6186 }
6187 } else {
6188 // If no Content-Type header found, set default
6189 strncpy(info.content_type, "text/plain", sizeof(info.content_type) - 1);
6190 }
6191
6192 // Find Content-Length header (Optional)
6193 const char* content_length_header = strstr(request, "Content-Length:");
6194 if (content_length_header) {
6195 const char* start = content_length_header + strlen("Content-Length: ");
6196 errno = 0;
6197 unsigned long tmp_cl = strtoul(start, NULL, 10); /* parse once */
6198 int error = errno;
6199 // Handle out-of-range error (e.g., set a safe default or return an error)
6200 // Only when ULONG_MAX is larger than SIZE_MAX, to prevent a constant false comparison warning
6201#if ULONG_MAX > SIZE_MAX
6202 if (error == ERANGE || tmp_cl > SIZE_MAX) {
6203#else
6204 if (error == ERANGE) {
6205#endif
6206 n_log(LOG_ERR, "could not get content_length for request %p, returned %s", request, strerror(error));
6207 info.content_length = SIZE_MAX; /* clamp to the maximum supported value */
6208 } else {
6209 info.content_length = (size_t)tmp_cl;
6210 }
6211 }
6212
6213 // Find the start of the body (after \r\n\r\n)
6214 const char* body_start = strstr(request, "\r\n\r\n");
6215 if (body_start) {
6216 body_start += 4; // Skip the \r\n\r\n
6217
6218 // If there is a Content-Length, and it's greater than 0, copy the body
6219 if (info.content_length > 0 && info.content_length < SIZE_MAX) {
6220 info.body = malloc(info.content_length + 1); // Allocate memory for body
6221 if (info.body) {
6222 strncpy(info.body, body_start, info.content_length);
6223 info.body[info.content_length] = '\0'; // Null-terminate the body
6224 }
6225 }
6226 }
6227
6228 info.type = request_type;
6229 return info;
6230}
6231
6238 FreeNoLog(http_request.body);
6239 FreeNoLog(http_request.type);
6240 return TRUE;
6241}
6242
6250int netw_get_url_from_http_request(const char* request, char* url, size_t size) {
6251 __n_assert(request && strlen(request) > 0, return FALSE);
6252 __n_assert(url && size > 1, return FALSE);
6253
6254 /* Default output */
6255 strncpy(url, "/", size - 1);
6256 url[size - 1] = '\0';
6257
6258 /* Example request line: "GET /path/to/resource HTTP/1.1" */
6259 const char* first_space = strchr(request, ' ');
6260 if (!first_space) {
6261 /* Malformed request, return default '/' */
6262 return FALSE;
6263 }
6264
6265 const char* second_space = strchr(first_space + 1, ' ');
6266 if (!second_space) {
6267 /* Malformed request, return default '/' */
6268 return FALSE;
6269 }
6270
6271 size_t len = (size_t)(second_space - first_space - 1);
6272 if (len >= size) {
6273 len = size - 1;
6274 }
6275
6276 strncpy(url, first_space + 1, len);
6277 url[len] = '\0'; /* Null-terminate the URL */
6278
6279 return TRUE;
6280}
6281
6287char* netw_urldecode(const char* str) {
6288 __n_assert(str, return NULL);
6289 char* decoded = malloc(strlen(str) + 1);
6290 __n_assert(decoded, return NULL);
6291
6292 char* p = decoded;
6293 while (*str) {
6294 if (*str == '%') {
6295 if (isxdigit((unsigned char)str[1]) && isxdigit((unsigned char)str[2])) {
6296 unsigned int value;
6297 if (sscanf(str + 1, "%2x", &value) >= 1) {
6298 *p++ = (char)value;
6299 str += 3;
6300 } else {
6301 n_log(LOG_ERR, "sscanf could not parse char *str (%p) for a %%2x", str);
6302 Free(decoded);
6303 return NULL;
6304 }
6305 } else {
6306 *p++ = *str++;
6307 }
6308 } else if (*str == '+') {
6309 *p++ = ' ';
6310 str++;
6311 } else {
6312 *p++ = *str++;
6313 }
6314 }
6315 *p = '\0';
6316 return decoded;
6317}
6318
6324HASH_TABLE* netw_parse_post_data(const char* post_data) {
6325 __n_assert(post_data, return NULL);
6326
6327 // Create a copy of the post_data string because strtok modifies the string
6328 char* data = strdup(post_data);
6329 __n_assert(data, return NULL);
6330
6331 char* pair = data;
6332
6333 HASH_TABLE* post_data_table = new_ht(32);
6334
6335 while (pair != NULL) {
6336 // Find the next key-value pair separated by '&'
6337 char* ampersand_pos = strchr(pair, '&');
6338
6339 // If found, replace it with '\0' to isolate the current pair
6340 if (ampersand_pos != NULL) {
6341 *ampersand_pos = '\0';
6342 }
6343
6344 // Now split each pair by '=' to get the key and value
6345 char* equal_pos = strchr(pair, '=');
6346 if (equal_pos != NULL) {
6347 *equal_pos = '\0'; // Terminate the key string
6348 const char* key = pair;
6349 const char* value = equal_pos + 1;
6350
6351 // Decode the value since POST data is URL-encoded
6352 char* decoded_value = netw_urldecode(value);
6353 ht_put_string(post_data_table, key, decoded_value);
6354 // printf("Key: %s, Value: %s\n", key, decoded_value);
6355 free(decoded_value);
6356 }
6357 // Move to the next key-value pair (if any)
6358 pair = (ampersand_pos != NULL) ? (ampersand_pos + 1) : NULL;
6359 }
6360 // Free the duplicated string
6361 free(data);
6362 return post_data_table;
6363}
6364
6370const char* netw_guess_http_content_type(const char* url) {
6371 __n_assert(url, return NULL);
6372
6373 // Create a copy of the URL to work on (to avoid modifying the original string)
6374 char url_copy[1024];
6375 strncpy(url_copy, url, sizeof(url_copy) - 1);
6376 url_copy[sizeof(url_copy) - 1] = '\0';
6377
6378 // Find if there is a '?' (indicating GET parameters) and terminate the string there
6379 char* query_start = strchr(url_copy, '?');
6380 if (query_start) {
6381 *query_start = '\0'; // Terminate the string before the query parameters
6382 }
6383
6384 // Find the last occurrence of a dot in the URL (file extension)
6385 const char* ext = strrchr(url_copy, '.');
6386
6387 // If no extension is found, return "unknown"
6388 if (!ext) {
6389 return "unknown";
6390 }
6391
6392 // Compare the extension to known content types
6393 if (strcmp(ext, ".html") == 0 || strcmp(ext, ".htm") == 0) {
6394 return "text/html";
6395 } else if (strcmp(ext, ".txt") == 0) {
6396 return "text/plain";
6397 } else if (strcmp(ext, ".jpg") == 0 || strcmp(ext, ".jpeg") == 0) {
6398 return "image/jpeg";
6399 } else if (strcmp(ext, ".png") == 0) {
6400 return "image/png";
6401 } else if (strcmp(ext, ".gif") == 0) {
6402 return "image/gif";
6403 } else if (strcmp(ext, ".css") == 0) {
6404 return "text/css";
6405 } else if (strcmp(ext, ".js") == 0) {
6406 return "application/javascript";
6407 } else if (strcmp(ext, ".json") == 0) {
6408 return "application/json";
6409 } else if (strcmp(ext, ".xml") == 0) {
6410 return "application/xml";
6411 } else if (strcmp(ext, ".pdf") == 0) {
6412 return "application/pdf";
6413 } else if (strcmp(ext, ".zip") == 0) {
6414 return "application/zip";
6415 } else if (strcmp(ext, ".mp4") == 0) {
6416 return "video/mp4";
6417 } else if (strcmp(ext, ".mp3") == 0) {
6418 return "audio/mpeg";
6419 } else if (strcmp(ext, ".wav") == 0) {
6420 return "audio/wav";
6421 } else if (strcmp(ext, ".ogg") == 0) {
6422 return "audio/ogg";
6423 }
6424
6425 // Return unknown for other types
6426 return "unknown";
6427}
6428
6434const char* netw_get_http_status_message(int status_code) {
6435 switch (status_code) {
6436 case 200:
6437 return "OK";
6438 case 204:
6439 return "No Content";
6440 case 304:
6441 return "Not Modified";
6442 case 404:
6443 return "Not Found";
6444 case 500:
6445 return "Internal Server Error";
6446 // Add more status codes as needed
6447 default:
6448 return "Unknown";
6449 }
6450}
6451
6452int n_http_status_class(int status_code) {
6453 if (status_code < 100 || status_code > 599)
6454 return 0;
6455 return status_code / 100;
6456}
6457
6459 return n_http_status_class(status_code) == 1;
6460}
6461
6462int n_http_status_is_success(int status_code) {
6463 return n_http_status_class(status_code) == 2;
6464}
6465
6466int n_http_status_is_redirect(int status_code) {
6467 return n_http_status_class(status_code) == 3;
6468}
6469
6470int n_http_status_is_client_error(int status_code) {
6471 return n_http_status_class(status_code) == 4;
6472}
6473
6474int n_http_status_is_server_error(int status_code) {
6475 return n_http_status_class(status_code) == 5;
6476}
6477
6478/* Inflate src/len with the given zlib window bits into a fresh N_STR.
6479 * window_bits: 15+16 for gzip framing, -15 for raw deflate, 15 for zlib-wrapped.
6480 * Returns 0 on success (*out set), -1 on error. */
6481static int n_http_inflate(const unsigned char* src, size_t len, int window_bits, N_STR** out) {
6482 z_stream strm;
6483 size_t alloc, total = 0;
6484 char* buf;
6485 int ret;
6486 *out = NULL;
6487 memset(&strm, 0, sizeof(strm));
6488 if (inflateInit2(&strm, window_bits) != Z_OK)
6489 return -1;
6490 alloc = len * 4;
6491 if (alloc < 4096)
6492 alloc = 4096;
6493 buf = malloc(alloc);
6494 if (!buf) {
6495 inflateEnd(&strm);
6496 return -1;
6497 }
6498 strm.next_in = (Bytef*)src;
6499 strm.avail_in = (uInt)len;
6500 do {
6501 if (total >= alloc - 1) {
6502 char* tmp;
6503 alloc *= 2;
6504 tmp = realloc(buf, alloc);
6505 if (!tmp) {
6506 free(buf);
6507 inflateEnd(&strm);
6508 return -1;
6509 }
6510 buf = tmp;
6511 }
6512 strm.next_out = (Bytef*)(buf + total);
6513 strm.avail_out = (uInt)(alloc - total - 1);
6514 ret = inflate(&strm, Z_NO_FLUSH);
6515 if (ret == Z_STREAM_ERROR || ret == Z_DATA_ERROR || ret == Z_MEM_ERROR || ret == Z_NEED_DICT) {
6516 free(buf);
6517 inflateEnd(&strm);
6518 return -1;
6519 }
6520 total = alloc - 1 - strm.avail_out;
6521 } while (ret != Z_STREAM_END);
6522 inflateEnd(&strm);
6523 buf[total] = '\0';
6524 {
6525 N_STR* r = NULL;
6526 char_to_nstr_ex(buf, (NSTRBYTE)total, &r);
6527 free(buf);
6528 if (!r)
6529 return -1;
6530 *out = r;
6531 }
6532 return 0;
6533}
6534
6535int n_http_decompress_body(const N_STR* body, const char* encoding, N_STR** out) {
6536 char enc[32];
6537 int is_gzip = 0, is_deflate = 0;
6538 if (!body || !out)
6539 return -1;
6540 *out = NULL;
6541
6542 enc[0] = '\0';
6543 if (encoding) {
6544 size_t i;
6545 for (i = 0; i < sizeof(enc) - 1 && encoding[i]; i++)
6546 enc[i] = (char)tolower((unsigned char)encoding[i]);
6547 enc[i] = '\0';
6548 }
6549 if (strstr(enc, "gzip"))
6550 is_gzip = 1;
6551 else if (strstr(enc, "deflate"))
6552 is_deflate = 1;
6553
6554 /* identity / unknown / empty body: pass a copy through unchanged */
6555 if ((!is_gzip && !is_deflate) || !body->data || body->written == 0) {
6556 N_STR* copy = nstrdup((N_STR*)body);
6557 if (!copy)
6558 return -1;
6559 *out = copy;
6560 return 0;
6561 }
6562
6563 if (is_gzip)
6564 return n_http_inflate((const unsigned char*)body->data, body->written, 15 + 16, out);
6565 /* "deflate" is sent both raw (-15) and zlib-wrapped (15); try raw, then wrapped */
6566 if (n_http_inflate((const unsigned char*)body->data, body->written, -15, out) == 0)
6567 return 0;
6568 return n_http_inflate((const unsigned char*)body->data, body->written, 15, out);
6569}
6570
6571/* Binary substring search: first offset of needle in hay, or -1. */
6572static long mp_find(const unsigned char* hay, size_t hlen, const char* needle, size_t nlen) {
6573 size_t i;
6574 if (nlen == 0 || nlen > hlen)
6575 return -1;
6576 for (i = 0; i + nlen <= hlen; i++) {
6577 if (hay[i] == (unsigned char)needle[0] && memcmp(hay + i, needle, nlen) == 0)
6578 return (long)i;
6579 }
6580 return -1;
6581}
6582
6583/* Duplicate len bytes of s into a fresh NUL-terminated C string. */
6584static char* mp_strndup(const char* s, size_t len) {
6585 char* r = NULL;
6586 Malloc(r, char, len + 1);
6587 if (!r)
6588 return NULL;
6589 if (len)
6590 memcpy(r, s, len);
6591 r[len] = '\0';
6592 return r;
6593}
6594
6595int n_http_multipart_boundary(const char* content_type, char* out, size_t outsz) {
6596 const char* p;
6597 size_t i;
6598 if (!content_type || !out || outsz == 0)
6599 return -1;
6600 /* case-insensitive search for "boundary=" */
6601 for (p = content_type; *p; p++) {
6602 if (strncasecmp(p, "boundary=", 9) == 0)
6603 break;
6604 }
6605 if (!*p)
6606 return -1;
6607 p += 9;
6608 i = 0;
6609 if (*p == '"') {
6610 p++;
6611 while (*p && *p != '"' && i + 1 < outsz)
6612 out[i++] = *p++;
6613 } else {
6614 while (*p && *p != ';' && *p != ' ' && *p != '\r' && *p != '\n' && i + 1 < outsz)
6615 out[i++] = *p++;
6616 }
6617 out[i] = '\0';
6618 return i > 0 ? 0 : -1;
6619}
6620
6621/* Free an N_HTTP_MULTIPART_PART stored in a LIST. */
6622static void mp_part_free(void* ptr) {
6624 if (!mp)
6625 return;
6626 FreeNoLog(mp->name);
6627 FreeNoLog(mp->filename);
6630 if (mp->body)
6631 free_nstr(&mp->body);
6632 Free(mp);
6633}
6634
6636 if (parts && *parts)
6637 list_destroy(parts);
6638}
6639
6640/* Within a header block, find the value of the named header (case-insensitive),
6641 * returning a pointer to the value start and its length (trailing CRLF trimmed). */
6642static const char* mp_header_value(const char* block, size_t blen, const char* name, size_t* vlen) {
6643 size_t nlen = strlen(name);
6644 size_t i = 0;
6645 *vlen = 0;
6646 while (i < blen) {
6647 size_t line_end = i;
6648 while (line_end < blen && block[line_end] != '\n')
6649 line_end++;
6650 /* line spans [i, line_end) (may include a trailing '\r') */
6651 if (line_end - i > nlen + 1 && strncasecmp(block + i, name, nlen) == 0 && block[i + nlen] == ':') {
6652 const char* v = block + i + nlen + 1;
6653 size_t vl = line_end - (i + nlen + 1);
6654 while (vl > 0 && (*v == ' ' || *v == '\t')) {
6655 v++;
6656 vl--;
6657 }
6658 while (vl > 0 && (v[vl - 1] == '\r' || v[vl - 1] == ' ' || v[vl - 1] == '\t'))
6659 vl--;
6660 *vlen = vl;
6661 return v;
6662 }
6663 i = line_end + 1;
6664 }
6665 return NULL;
6666}
6667
6668/* Extract a quoted (or token) parameter value from a Content-Disposition value,
6669 * e.g. param "name" from `form-data; name="x"; filename="y"`. */
6670static char* mp_disp_param(const char* disp, size_t dlen, const char* param) {
6671 char key[32];
6672 size_t klen, i;
6673 snprintf(key, sizeof(key), "%s=", param);
6674 klen = strlen(key);
6675 for (i = 0; i + klen <= dlen; i++) {
6676 if (strncasecmp(disp + i, key, klen) == 0) {
6677 const char* v = disp + i + klen;
6678 size_t avail = dlen - (i + klen);
6679 size_t j = 0;
6680 if (avail > 0 && *v == '"') {
6681 v++;
6682 avail--;
6683 while (j < avail && v[j] != '"')
6684 j++;
6685 } else {
6686 while (j < avail && v[j] != ';' && v[j] != ' ')
6687 j++;
6688 }
6689 return mp_strndup(v, j);
6690 }
6691 }
6692 return NULL;
6693}
6694
6695LIST* n_http_parse_multipart(const N_STR* body, const char* boundary) {
6696 char dash[256];
6697 char crlf_dash[260];
6698 const unsigned char* data;
6699 size_t len, dlen, cdlen, cursor;
6700 long first;
6701 LIST* parts;
6702
6703 if (!body || !body->data || !boundary || !boundary[0])
6704 return NULL;
6705 if (strlen(boundary) + 2 >= sizeof(dash))
6706 return NULL;
6707 snprintf(dash, sizeof(dash), "--%s", boundary);
6708 snprintf(crlf_dash, sizeof(crlf_dash), "\r\n--%s", boundary);
6709 dlen = strlen(dash);
6710 cdlen = strlen(crlf_dash);
6711
6712 parts = new_generic_list(0);
6713 if (!parts)
6714 return NULL;
6715
6716 data = (const unsigned char*)body->data;
6717 len = body->written;
6718 first = mp_find(data, len, dash, dlen);
6719 if (first < 0)
6720 return parts; /* no boundary present: empty result */
6721 cursor = (size_t)first + dlen;
6722
6723 for (;;) {
6724 long rel;
6725 size_t part_start, part_end;
6726 size_t hvl;
6728 /* closing delimiter "--boundary--" */
6729 if (cursor + 2 <= len && data[cursor] == '-' && data[cursor + 1] == '-')
6730 break;
6731 /* skip the CRLF that follows the delimiter */
6732 if (cursor + 2 <= len && data[cursor] == '\r' && data[cursor + 1] == '\n')
6733 cursor += 2;
6734 else if (cursor < len && data[cursor] == '\n')
6735 cursor += 1;
6736 part_start = cursor;
6737 rel = mp_find(data + part_start, len - part_start, crlf_dash, cdlen);
6738 if (rel < 0)
6739 break; /* malformed: no closing delimiter */
6740 part_end = part_start + (size_t)rel;
6741
6743 if (!mp)
6744 break;
6745 mp->name = NULL;
6746 mp->filename = NULL;
6747 mp->content_type = NULL;
6748 mp->body = NULL;
6749 /* split the part into its header block and body at the blank line */
6750 {
6751 long s = mp_find(data + part_start, part_end - part_start, "\r\n\r\n", 4);
6752 if (s >= 0) {
6753 size_t hlen = (size_t)s;
6754 size_t bbeg = part_start + (size_t)s + 4;
6755 const char* hblock = (const char*)(data + part_start);
6756 const char* hv = mp_header_value(hblock, hlen, "Content-Disposition", &hvl);
6757 if (hv) {
6758 mp->name = mp_disp_param(hv, hvl, "name");
6759 mp->filename = mp_disp_param(hv, hvl, "filename");
6760 }
6761 hv = mp_header_value(hblock, hlen, "Content-Type", &hvl);
6762 if (hv)
6763 mp->content_type = mp_strndup(hv, hvl);
6764 {
6765 size_t blen = part_end - bbeg;
6766 mp->body = new_nstr(blen + 1);
6767 if (mp->body) {
6768 if (blen)
6769 memcpy(mp->body->data, data + bbeg, blen);
6770 mp->body->data[blen] = '\0';
6771 mp->body->written = blen;
6772 }
6773 }
6774 }
6775 }
6776 if (!mp->name)
6777 mp->name = mp_strndup("", 0);
6778 if (!mp->filename)
6779 mp->filename = mp_strndup("", 0);
6780 if (!mp->content_type)
6781 mp->content_type = mp_strndup("", 0);
6782 if (!mp->body)
6783 mp->body = new_nstr(1);
6784 list_push(parts, mp, mp_part_free);
6785
6786 cursor = part_end + cdlen; /* skip "\r\n--boundary" to the next part/closing */
6787 }
6788 return parts;
6789}
6790
6791/* Append n bytes to buf at *pos (sizing pass when buf == NULL). */
6792static void mp_put(char* buf, size_t* pos, const void* src, size_t n) {
6793 if (buf && n)
6794 memcpy(buf + *pos, src, n);
6795 *pos += n;
6796}
6797
6798/* Append a NUL-terminated string (length via strlen). */
6799static void mp_puts(char* buf, size_t* pos, const char* s) {
6800 if (s)
6801 mp_put(buf, pos, s, strlen(s));
6802}
6803
6804/* Emit the full multipart body into buf (or size it when buf == NULL). */
6805static void mp_emit(char* buf, size_t* pos, LIST* parts, const char* dash) {
6806 list_foreach(node, parts) {
6807 const N_HTTP_MULTIPART_PART* mp = (const N_HTTP_MULTIPART_PART*)node->ptr;
6808 if (!mp)
6809 continue;
6810 mp_puts(buf, pos, dash);
6811 mp_puts(buf, pos, "\r\nContent-Disposition: form-data; name=\"");
6812 mp_puts(buf, pos, mp->name ? mp->name : "");
6813 mp_puts(buf, pos, "\"");
6814 if (mp->filename && mp->filename[0]) {
6815 mp_puts(buf, pos, "; filename=\"");
6816 mp_puts(buf, pos, mp->filename);
6817 mp_puts(buf, pos, "\"");
6818 }
6819 if (mp->disposition_extra && mp->disposition_extra[0])
6820 mp_puts(buf, pos, mp->disposition_extra); /* verbatim, separator included */
6821 mp_puts(buf, pos, "\r\n");
6822 if (mp->content_type && mp->content_type[0]) {
6823 mp_puts(buf, pos, "Content-Type: ");
6824 mp_puts(buf, pos, mp->content_type);
6825 mp_puts(buf, pos, "\r\n");
6826 }
6827 mp_puts(buf, pos, "\r\n");
6828 if (mp->body && mp->body->written)
6829 mp_put(buf, pos, mp->body->data, mp->body->written);
6830 mp_puts(buf, pos, "\r\n");
6831 }
6832 mp_puts(buf, pos, dash);
6833 mp_puts(buf, pos, "--\r\n");
6834}
6835
6836N_STR* n_http_build_multipart(LIST* parts, const char* boundary) {
6837 char dash[256];
6838 size_t total = 0;
6839 char* buf;
6840 N_STR* out = NULL;
6841 if (!parts || !boundary || !boundary[0])
6842 return NULL;
6843 if (strlen(boundary) + 2 >= sizeof(dash))
6844 return NULL;
6845 snprintf(dash, sizeof(dash), "--%s", boundary);
6846
6847 mp_emit(NULL, &total, parts, dash); /* sizing pass */
6848 Malloc(buf, char, total + 1);
6849 if (!buf)
6850 return NULL;
6851 total = 0;
6852 mp_emit(buf, &total, parts, dash); /* fill pass */
6853 buf[total] = '\0';
6854 char_to_nstr_ex(buf, (NSTRBYTE)total, &out);
6855 free(buf);
6856 return out;
6857}
6858
6865int netw_get_http_date(char* buffer, size_t buffer_size) {
6866 __n_assert(buffer, return FALSE);
6867 const time_t now = time(NULL);
6868 struct tm gmt;
6869#ifdef _WIN32
6870 if (gmtime_s(&gmt, &now) != 0) {
6871 n_log(LOG_ERR, "gmtime_s failed");
6872 return FALSE;
6873 }
6874#else
6875 if (!gmtime_r(&now, &gmt)) {
6876 n_log(LOG_ERR, "gmtime_r returned NULL");
6877 return FALSE;
6878 }
6879#endif
6880 if (strftime(buffer, buffer_size, "%a, %d %b %Y %H:%M:%S GMT", &gmt) == 0) {
6881 n_log(LOG_ERR, "strftime failed: buffer too small");
6882 return FALSE;
6883 }
6884 return TRUE;
6885}
6886
6897int netw_build_http_response(N_STR** http_response, int status_code, const char* server_name, const char* content_type, char* additional_headers, N_STR* body) {
6898 __n_assert(server_name, return FALSE);
6899 __n_assert(content_type, return FALSE);
6900 __n_assert(additional_headers, return FALSE);
6901
6902 const char* status_message = netw_get_http_status_message(status_code);
6903 const char* connection_type = "close";
6904
6905 // Buffer for the date header
6906 char date_buffer[128] = "";
6907 netw_get_http_date(date_buffer, sizeof(date_buffer));
6908
6909 if ((*http_response)) {
6910 (*http_response)->written = 0;
6911 }
6912
6913 if (!body || body->written == 0) {
6914 // Handle the case where there is no body
6915 nstrprintf((*http_response),
6916 "HTTP/1.1 %d %s\r\n"
6917 "Date: %s\r\n"
6918 "Server: %s\r\n"
6919 "Content-Length: 0\r\n"
6920 "%s"
6921 "Connection: %s\r\n\r\n",
6922 status_code, status_message, date_buffer, server_name, additional_headers, connection_type);
6923 n_log(LOG_DEBUG, "empty response");
6924 } else {
6925 // Build the response with body
6926 nstrprintf((*http_response),
6927 "HTTP/1.1 %d %s\r\n"
6928 "Date: %s\r\n"
6929 "Server: %s\r\n"
6930 "Content-Type: %s\r\n"
6931 "Content-Length: %zu\r\n"
6932 "%s"
6933 "Connection: %s\r\n\r\n",
6934 status_code, status_message, date_buffer, server_name, content_type, body->written, additional_headers, connection_type);
6935 nstrcat((*http_response), body);
6936 n_log(LOG_DEBUG, "body response");
6937 }
6938 return TRUE;
6939}
6940
6941#ifdef HAVE_OPENSSL
6942
6948static ssize_t _ws_write(N_WS_CONN* conn, const void* buf, size_t len) {
6949 __n_assert(conn, return -1);
6950 __n_assert(conn->netw, return -1);
6951 if (conn->netw->crypto_algo == NETW_ENCRYPT_OPENSSL && conn->netw->ssl) {
6952 int ret = SSL_write(conn->netw->ssl, buf, (int)len);
6953 return (ret > 0) ? (ssize_t)ret : -1;
6954 }
6955 ssize_t ret = send(conn->netw->link.sock, buf, NETW_BUFLEN_CAST(len), NETFLAGS);
6956 return ret;
6957}
6958
6964static ssize_t _ws_read(N_WS_CONN* conn, void* buf, size_t len) {
6965 __n_assert(conn, return -1);
6966 __n_assert(conn->netw, return -1);
6967 size_t total = 0;
6968 char* p = (char*)buf;
6969 while (total < len) {
6970 ssize_t ret = 0;
6971 if (conn->netw->crypto_algo == NETW_ENCRYPT_OPENSSL && conn->netw->ssl) {
6972 ret = SSL_read(conn->netw->ssl, p + total, (int)(len - total));
6973 } else {
6974 ret = recv(conn->netw->link.sock, p + total, NETW_BUFLEN_CAST(len - total), 0);
6975 }
6976 if (ret <= 0) {
6977 return -1;
6978 }
6979 total += (size_t)ret;
6980 }
6981 return (ssize_t)total;
6982}
6983
6995N_WS_CONN* n_ws_connect(const char* host, const char* port, const char* path, int use_ssl) {
6996 __n_assert(host, return NULL);
6997 __n_assert(port, return NULL);
6998 __n_assert(path, return NULL);
6999
7000 N_WS_CONN* conn = NULL;
7001 Malloc(conn, N_WS_CONN, 1);
7002 __n_assert(conn, return NULL);
7003
7004 conn->netw = NULL;
7005 conn->connected = 0;
7006 conn->host = strdup(host);
7007 conn->path = strdup(path);
7008 if (!conn->host || !conn->path) {
7009 n_log(LOG_ERR, "n_ws_connect: strdup failed");
7010 goto ws_connect_fail;
7011 }
7012
7013 /* establish TCP + optional SSL */
7014 if (use_ssl) {
7015 if (netw_ssl_connect_client(&conn->netw, (char*)host, (char*)port, NETWORK_IPALL) == FALSE) {
7016 n_log(LOG_ERR, "n_ws_connect: TCP+SSL context setup failed for %s:%s", host, port);
7017 goto ws_connect_fail;
7018 }
7019 if (netw_ssl_do_handshake(conn->netw, host) == FALSE) {
7020 _netw_capture_error(conn->netw, "n_ws_connect: SSL handshake failed for %s:%s", host, port);
7021 n_log(LOG_ERR, "n_ws_connect: SSL handshake failed for %s:%s", host, port);
7022 goto ws_connect_fail;
7023 }
7024 } else {
7025 if (netw_connect(&conn->netw, (char*)host, (char*)port, NETWORK_IPALL) == FALSE) {
7026 n_log(LOG_ERR, "n_ws_connect: TCP connect failed for %s:%s", host, port);
7027 goto ws_connect_fail;
7028 }
7029 }
7030
7031 /* generate Sec-WebSocket-Key: base64 of 16 random bytes */
7032 unsigned char rand_bytes[16];
7033 if (RAND_bytes(rand_bytes, 16) != 1) {
7034 _netw_capture_error(conn->netw, "n_ws_connect: RAND_bytes failed");
7035 n_log(LOG_ERR, "n_ws_connect: RAND_bytes failed");
7036 goto ws_connect_fail;
7037 }
7038
7039 N_STR* rand_nstr = new_nstr(16);
7040 __n_assert(rand_nstr, goto ws_connect_fail);
7041 memcpy(rand_nstr->data, rand_bytes, 16);
7042 rand_nstr->written = 16;
7043
7044 N_STR* ws_key_nstr = n_base64_encode(rand_nstr);
7045 free_nstr(&rand_nstr);
7046 __n_assert(ws_key_nstr, goto ws_connect_fail);
7047 /* strip any trailing whitespace from base64 output */
7048 while (ws_key_nstr->written > 0 &&
7049 (ws_key_nstr->data[ws_key_nstr->written - 1] == '\n' ||
7050 ws_key_nstr->data[ws_key_nstr->written - 1] == '\r' ||
7051 ws_key_nstr->data[ws_key_nstr->written - 1] == ' ')) {
7052 ws_key_nstr->data[--ws_key_nstr->written] = '\0';
7053 }
7054
7055 /* build HTTP upgrade request */
7056 char upgrade_req[2048];
7057 int req_len = snprintf(upgrade_req, sizeof(upgrade_req),
7058 "GET %s HTTP/1.1\r\n"
7059 "Host: %s\r\n"
7060 "Upgrade: websocket\r\n"
7061 "Connection: Upgrade\r\n"
7062 "Sec-WebSocket-Key: %s\r\n"
7063 "Sec-WebSocket-Version: 13\r\n"
7064 "\r\n",
7065 path, host, ws_key_nstr->data);
7066
7067 if (req_len < 0 || (size_t)req_len >= sizeof(upgrade_req)) {
7068 _netw_capture_error(conn->netw, "n_ws_connect: upgrade request too large");
7069 n_log(LOG_ERR, "n_ws_connect: upgrade request too large");
7070 free_nstr(&ws_key_nstr);
7071 goto ws_connect_fail;
7072 }
7073
7074 /* send upgrade request */
7075 if (_ws_write(conn, upgrade_req, (size_t)req_len) < 0) {
7076 _netw_capture_error(conn->netw, "n_ws_connect: failed to send upgrade request");
7077 n_log(LOG_ERR, "n_ws_connect: failed to send upgrade request");
7078 free_nstr(&ws_key_nstr);
7079 goto ws_connect_fail;
7080 }
7081
7082 /* read response (up to 4096 bytes, look for \r\n\r\n) */
7083 char resp_buf[4096];
7084 memset(resp_buf, 0, sizeof(resp_buf));
7085 size_t resp_len = 0;
7086 while (resp_len < sizeof(resp_buf) - 1) {
7087 ssize_t r = 0;
7088 if (conn->netw->crypto_algo == NETW_ENCRYPT_OPENSSL && conn->netw->ssl) {
7089 r = SSL_read(conn->netw->ssl, resp_buf + resp_len, 1);
7090 } else {
7091 r = recv(conn->netw->link.sock, resp_buf + resp_len, 1, 0);
7092 }
7093 if (r <= 0) {
7094 _netw_capture_error(conn->netw, "n_ws_connect: failed reading handshake response");
7095 n_log(LOG_ERR, "n_ws_connect: failed reading handshake response");
7096 free_nstr(&ws_key_nstr);
7097 goto ws_connect_fail;
7098 }
7099 resp_len += (size_t)r;
7100 if (resp_len >= 4 &&
7101 resp_buf[resp_len - 4] == '\r' && resp_buf[resp_len - 3] == '\n' &&
7102 resp_buf[resp_len - 2] == '\r' && resp_buf[resp_len - 1] == '\n') {
7103 break;
7104 }
7105 }
7106 resp_buf[resp_len] = '\0';
7107
7108 /* verify 101 Switching Protocols */
7109 if (strstr(resp_buf, "101") == NULL) {
7110 _netw_capture_error(conn->netw, "n_ws_connect: server did not return 101: %.128s", resp_buf);
7111 n_log(LOG_ERR, "n_ws_connect: server did not return 101: %.128s", resp_buf);
7112 free_nstr(&ws_key_nstr);
7113 goto ws_connect_fail;
7114 }
7115
7116 /* verify Sec-WebSocket-Accept */
7117 static const char ws_magic[] = "258EAFA5-E914-47DA-95CA-5AB5FE44F513";
7118 char concat_key[256];
7119 snprintf(concat_key, sizeof(concat_key), "%s%s", ws_key_nstr->data, ws_magic);
7120 n_log(LOG_DEBUG, "n_ws_connect: key sent: [%s] len:%zu", ws_key_nstr->data, ws_key_nstr->written);
7121 n_log(LOG_DEBUG, "n_ws_connect: concat_key: [%s]", concat_key);
7122 free_nstr(&ws_key_nstr);
7123
7124 unsigned char sha1_hash[SHA_DIGEST_LENGTH];
7125 SHA1((const unsigned char*)concat_key, strlen(concat_key), sha1_hash);
7126
7127 N_STR* sha1_nstr = new_nstr(SHA_DIGEST_LENGTH);
7128 __n_assert(sha1_nstr, goto ws_connect_fail);
7129 memcpy(sha1_nstr->data, sha1_hash, SHA_DIGEST_LENGTH);
7130 sha1_nstr->written = SHA_DIGEST_LENGTH;
7131
7132 N_STR* expected_accept = n_base64_encode(sha1_nstr);
7133 free_nstr(&sha1_nstr);
7134 __n_assert(expected_accept, goto ws_connect_fail);
7135 /* strip trailing whitespace from base64 output */
7136 while (expected_accept->written > 0 &&
7137 (expected_accept->data[expected_accept->written - 1] == '\n' ||
7138 expected_accept->data[expected_accept->written - 1] == '\r' ||
7139 expected_accept->data[expected_accept->written - 1] == ' ')) {
7140 expected_accept->data[--expected_accept->written] = '\0';
7141 }
7142
7143 /* find Sec-WebSocket-Accept in response (case-insensitive search) */
7144 const char* accept_hdr = NULL;
7145 char* search_pos = resp_buf;
7146 while (*search_pos) {
7147 if (strncasecmp(search_pos, "Sec-WebSocket-Accept:", 21) == 0) {
7148 accept_hdr = search_pos + 21;
7149 break;
7150 }
7151 search_pos++;
7152 }
7153 if (!accept_hdr) {
7154 _netw_capture_error(conn->netw, "n_ws_connect: no Sec-WebSocket-Accept header in response");
7155 n_log(LOG_ERR, "n_ws_connect: no Sec-WebSocket-Accept header in response");
7156 free_nstr(&expected_accept);
7157 goto ws_connect_fail;
7158 }
7159 /* skip whitespace */
7160 while (*accept_hdr == ' ') accept_hdr++;
7161 /* compare up to expected length; trim trailing \r\n from accept_hdr */
7162 char accept_val[128];
7163 {
7164 int ai = 0;
7165 while (ai < (int)sizeof(accept_val) - 1 && accept_hdr[ai] && accept_hdr[ai] != '\r' && accept_hdr[ai] != '\n') {
7166 accept_val[ai] = accept_hdr[ai];
7167 ai++;
7168 }
7169 accept_val[ai] = '\0';
7170 }
7171 if (strcmp(accept_val, expected_accept->data) != 0) {
7172 /* Many proxies (Fly.io, Cloudflare, etc.) re-key the handshake,
7173 * so the accept may not match. Log as debug, not error. */
7174 n_log(LOG_DEBUG, "n_ws_connect: Sec-WebSocket-Accept mismatch (proxy?): got [%s] expected [%s]",
7175 accept_val, expected_accept->data);
7176 }
7177 free_nstr(&expected_accept);
7178
7179 conn->connected = 1;
7180 n_log(LOG_INFO, "n_ws_connect: WebSocket handshake completed with %s:%s%s", host, port, path);
7181 return conn;
7182
7183ws_connect_fail:
7184 n_ws_conn_free(&conn);
7185 return NULL;
7186}
7187
7199int n_ws_send(N_WS_CONN* conn, const char* payload, size_t len, int opcode) {
7200 __n_assert(conn, return -1);
7201 __n_assert(conn->netw, return -1);
7202
7203 /* max frame overhead: 2 (header) + 8 (ext len) + 4 (mask) = 14 */
7204 size_t frame_max = 14 + len;
7205 unsigned char* frame = NULL;
7206 Malloc(frame, unsigned char, frame_max);
7207 __n_assert(frame, return -1);
7208
7209 size_t pos = 0;
7210
7211 /* byte 0: FIN + opcode */
7212 frame[pos++] = (unsigned char)(0x80 | (opcode & 0x0F));
7213
7214 /* byte 1+: mask bit set + payload length */
7215 if (len <= 125) {
7216 frame[pos++] = (unsigned char)(0x80 | len);
7217 } else if (len <= 65535) {
7218 frame[pos++] = (unsigned char)(0x80 | 126);
7219 frame[pos++] = (unsigned char)((len >> 8) & 0xFF);
7220 frame[pos++] = (unsigned char)(len & 0xFF);
7221 } else {
7222 frame[pos++] = (unsigned char)(0x80 | 127);
7223 for (int i = 7; i >= 0; i--) {
7224 frame[pos++] = (unsigned char)((len >> (8 * i)) & 0xFF);
7225 }
7226 }
7227
7228 /* masking key: 4 random bytes */
7229 unsigned char mask_key[4];
7230 if (RAND_bytes(mask_key, 4) != 1) {
7231 _netw_capture_error(conn->netw, "n_ws_send: RAND_bytes failed for mask key");
7232 n_log(LOG_ERR, "n_ws_send: RAND_bytes failed for mask key");
7233 FreeNoLog(frame);
7234 return -1;
7235 }
7236 memcpy(frame + pos, mask_key, 4);
7237 pos += 4;
7238
7239 /* masked payload */
7240 if (payload && len > 0) {
7241 for (size_t i = 0; i < len; i++) {
7242 frame[pos + i] = (unsigned char)((unsigned char)payload[i] ^ mask_key[i % 4]);
7243 }
7244 pos += len;
7245 }
7246
7247 ssize_t written = _ws_write(conn, frame, pos);
7248 FreeNoLog(frame);
7249 if (written < 0 || (size_t)written != pos) {
7250 _netw_capture_error(conn->netw, "n_ws_send: write failed (wrote %zd of %zu)", written, pos);
7251 n_log(LOG_ERR, "n_ws_send: write failed (wrote %zd of %zu)", written, pos);
7252 return -1;
7253 }
7254 return 0;
7255}
7256
7266int n_ws_recv(N_WS_CONN* conn, N_WS_MESSAGE* msg_out) {
7267 __n_assert(conn, return -1);
7268 __n_assert(conn->netw, return -1);
7269 __n_assert(msg_out, return -1);
7270
7271 memset(msg_out, 0, sizeof(*msg_out));
7272
7273 /* read 2-byte header */
7274 unsigned char hdr[2];
7275 if (_ws_read(conn, hdr, 2) < 0) {
7276 return -1;
7277 }
7278
7279 /* int fin = (hdr[0] >> 7) & 1; */
7280 int opcode = hdr[0] & 0x0F;
7281 int mask_bit = (hdr[1] >> 7) & 1;
7282 uint64_t payload_len = hdr[1] & 0x7F;
7283
7284 /* extended payload length */
7285 if (payload_len == 126) {
7286 unsigned char ext[2];
7287 if (_ws_read(conn, ext, 2) < 0) return -1;
7288 payload_len = ((uint64_t)ext[0] << 8) | (uint64_t)ext[1];
7289 } else if (payload_len == 127) {
7290 unsigned char ext[8];
7291 if (_ws_read(conn, ext, 8) < 0) return -1;
7292 payload_len = 0;
7293 for (int i = 0; i < 8; i++) {
7294 payload_len = (payload_len << 8) | (uint64_t)ext[i];
7295 }
7296 }
7297
7298 /* the length above comes straight off the wire: bound it BEFORE it is used to
7299 size an allocation. Without this a hostile peer declares a 64-bit length whose
7300 terminator arithmetic wraps to a tiny allocation and the payload read below then
7301 writes past it, or simply asks for an allocation large enough to exhaust memory */
7302 if (payload_len > (uint64_t)N_WS_MAX_PAYLOAD) {
7303 _netw_capture_error(conn->netw, "n_ws_recv: payload length %llu exceeds N_WS_MAX_PAYLOAD (%zu)", (unsigned long long)payload_len, (size_t)N_WS_MAX_PAYLOAD);
7304 n_log(LOG_ERR, "n_ws_recv: payload length %llu exceeds N_WS_MAX_PAYLOAD (%zu)", (unsigned long long)payload_len, (size_t)N_WS_MAX_PAYLOAD);
7305 return -1;
7306 }
7307
7308 /* read masking key if present */
7309 unsigned char mask_key[4] = {0};
7310 if (mask_bit) {
7311 if (_ws_read(conn, mask_key, 4) < 0) return -1;
7312 }
7313
7314 /* read payload */
7315 N_STR* payload = new_nstr((size_t)payload_len + 1);
7316 __n_assert(payload, return -1);
7317
7318 if (payload_len > 0) {
7319 if (_ws_read(conn, payload->data, (size_t)payload_len) < 0) {
7320 free_nstr(&payload);
7321 return -1;
7322 }
7323 /* unmask if needed */
7324 if (mask_bit) {
7325 for (uint64_t i = 0; i < payload_len; i++) {
7326 payload->data[i] = (char)((unsigned char)payload->data[i] ^ mask_key[i % 4]);
7327 }
7328 }
7329 }
7330 payload->written = (size_t)payload_len;
7331 payload->data[payload_len] = '\0';
7332
7333 msg_out->opcode = opcode;
7334 msg_out->payload = payload;
7335 msg_out->masked = mask_bit;
7336
7337 return 0;
7338}
7339
7349 __n_assert(conn, return);
7350
7351 if (conn->connected && conn->netw) {
7352 /* send close frame with empty payload */
7353 n_ws_send(conn, NULL, 0, N_WS_OP_CLOSE);
7354
7355 /* try to read close response with a short timeout */
7356 /* set non-blocking or just try one read */
7357 N_WS_MESSAGE msg;
7358 memset(&msg, 0, sizeof(msg));
7359 /* best effort: read one frame, ignore errors */
7360 if (n_ws_recv(conn, &msg) == 0) {
7361 free_nstr(&msg.payload);
7362 }
7363 conn->connected = 0;
7364 }
7365
7366 if (conn->netw) {
7367 netw_close(&conn->netw);
7368 }
7369}
7370
7379 __n_assert(conn, return);
7380 __n_assert(*conn, return);
7381
7382 N_WS_CONN* c = *conn;
7383
7384 if (c->connected) {
7385 n_ws_close(c);
7386 }
7387
7388 if (c->netw) {
7389 netw_close(&c->netw);
7390 }
7391
7392 FreeNoLog(c->host);
7393 FreeNoLog(c->path);
7394 FreeNoLog(c);
7395 *conn = NULL;
7396}
7397
7403 if (!event) return;
7404 if (event->event) free_nstr(&event->event);
7405 if (event->data) free_nstr(&event->data);
7406 if (event->id) free_nstr(&event->id);
7407 event->retry = 0;
7408}
7409
7415 __n_assert(conn, return);
7416 __atomic_store_n(&conn->stop_flag, 1, __ATOMIC_RELEASE);
7417}
7418
7424 __n_assert(conn, return);
7425 __n_assert(*conn, return);
7426
7427 N_SSE_CONN* c = *conn;
7428 if (c->netw) {
7429 netw_close(&c->netw);
7430 }
7431 FreeNoLog(c);
7432 *conn = NULL;
7433}
7434
7441static ssize_t _sse_read_byte(NETWORK* netw, char* ch, volatile int* stop_flag) {
7442 __n_assert(netw, return -1);
7443
7444 /* poll with 500ms timeout so we can check stop_flag periodically */
7445 for (;;) {
7446 if (stop_flag && __atomic_load_n(stop_flag, __ATOMIC_ACQUIRE)) {
7447 return -1;
7448 }
7449 struct timeval tv;
7450 tv.tv_sec = 0;
7451 tv.tv_usec = 500000; /* 500ms */
7452 fd_set fds;
7453 FD_ZERO(&fds);
7454 FD_SET(netw->link.sock, &fds);
7455
7456 /* For SSL: check if there's already buffered data */
7457 int ready = 0;
7458 if (netw->crypto_algo == NETW_ENCRYPT_OPENSSL && netw->ssl) {
7459 if (SSL_pending(netw->ssl) > 0) {
7460 ready = 1;
7461 }
7462 }
7463 if (!ready) {
7464 int sel = select((int)netw->link.sock + 1, &fds, NULL, NULL, &tv);
7465 if (sel < 0) return -1; /* error */
7466 if (sel == 0) continue; /* timeout, loop back to check stop_flag */
7467 }
7468
7469 ssize_t ret = 0;
7470 if (netw->crypto_algo == NETW_ENCRYPT_OPENSSL && netw->ssl) {
7471 ret = SSL_read(netw->ssl, ch, 1);
7472 } else {
7473 ret = recv(netw->link.sock, ch, 1, 0);
7474 }
7475 return (ret == 1) ? 1 : -1;
7476 }
7477}
7478
7484static ssize_t _sse_write(NETWORK* netw, const void* buf, size_t len) {
7485 __n_assert(netw, return -1);
7486 if (netw->crypto_algo == NETW_ENCRYPT_OPENSSL && netw->ssl) {
7487 int ret = SSL_write(netw->ssl, buf, (int)len);
7488 return (ret > 0) ? (ssize_t)ret : -1;
7489 }
7490 ssize_t ret = send(netw->link.sock, buf, NETW_BUFLEN_CAST(len), NETFLAGS);
7491 return ret;
7492}
7493
7508N_SSE_CONN* n_sse_connect(const char* host, const char* port, const char* path, int use_ssl, const char* user_agent, void (*on_event)(N_SSE_EVENT*, N_SSE_CONN*, void*), void* user_data) {
7509 __n_assert(host, return NULL);
7510 __n_assert(port, return NULL);
7511 __n_assert(path, return NULL);
7512 __n_assert(on_event, return NULL);
7513
7514 N_SSE_CONN* conn = NULL;
7515 Malloc(conn, N_SSE_CONN, 1);
7516 __n_assert(conn, return NULL);
7517
7518 conn->netw = NULL;
7519 conn->stop_flag = 0;
7520 conn->on_event = on_event;
7521 conn->user_data = user_data;
7522
7523 /* establish TCP + optional SSL */
7524 if (use_ssl) {
7525 if (netw_ssl_connect_client(&conn->netw, (char*)host, (char*)port, NETWORK_IPALL) == FALSE) {
7526 n_log(LOG_ERR, "n_sse_connect: TCP+SSL context setup failed for %s:%s", host, port);
7527 goto sse_connect_fail;
7528 }
7529 if (netw_ssl_do_handshake(conn->netw, host) == FALSE) {
7530 _netw_capture_error(conn->netw, "n_sse_connect: SSL handshake failed for %s:%s", host, port);
7531 n_log(LOG_ERR, "n_sse_connect: SSL handshake failed for %s:%s", host, port);
7532 goto sse_connect_fail;
7533 }
7534 } else {
7535 if (netw_connect(&conn->netw, (char*)host, (char*)port, NETWORK_IPALL) == FALSE) {
7536 n_log(LOG_ERR, "n_sse_connect: TCP connect failed for %s:%s", host, port);
7537 goto sse_connect_fail;
7538 }
7539 }
7540
7541 /* send HTTP GET with SSE headers */
7542 char request[4096];
7543 int req_len;
7544 if (user_agent && user_agent[0]) {
7545 req_len = snprintf(request, sizeof(request),
7546 "GET %s HTTP/1.1\r\n"
7547 "Host: %s\r\n"
7548 "Accept: text/event-stream\r\n"
7549 "Cache-Control: no-cache\r\n"
7550 "Connection: keep-alive\r\n"
7551 "User-Agent: %s\r\n"
7552 "\r\n",
7553 path, host, user_agent);
7554 } else {
7555 req_len = snprintf(request, sizeof(request),
7556 "GET %s HTTP/1.1\r\n"
7557 "Host: %s\r\n"
7558 "Accept: text/event-stream\r\n"
7559 "Cache-Control: no-cache\r\n"
7560 "Connection: keep-alive\r\n"
7561 "\r\n",
7562 path, host);
7563 }
7564
7565 if (req_len < 0 || (size_t)req_len >= sizeof(request)) {
7566 _netw_capture_error(conn->netw, "n_sse_connect: request too large");
7567 n_log(LOG_ERR, "n_sse_connect: request too large");
7568 goto sse_connect_fail;
7569 }
7570
7571 if (_sse_write(conn->netw, request, (size_t)req_len) < 0) {
7572 _netw_capture_error(conn->netw, "n_sse_connect: failed to send HTTP request");
7573 n_log(LOG_ERR, "n_sse_connect: failed to send HTTP request");
7574 goto sse_connect_fail;
7575 }
7576
7577 /* read HTTP response headers (byte by byte until \r\n\r\n) */
7578 char resp_buf[8192];
7579 size_t resp_len = 0;
7580 while (resp_len < sizeof(resp_buf) - 1) {
7581 char ch = 0;
7582 if (_sse_read_byte(conn->netw, &ch, NULL) < 0) {
7583 _netw_capture_error(conn->netw, "n_sse_connect: failed reading HTTP response");
7584 n_log(LOG_ERR, "n_sse_connect: failed reading HTTP response");
7585 goto sse_connect_fail;
7586 }
7587 resp_buf[resp_len++] = ch;
7588 if (resp_len >= 4 &&
7589 resp_buf[resp_len - 4] == '\r' && resp_buf[resp_len - 3] == '\n' &&
7590 resp_buf[resp_len - 2] == '\r' && resp_buf[resp_len - 1] == '\n') {
7591 break;
7592 }
7593 }
7594 resp_buf[resp_len] = '\0';
7595
7596 /* verify HTTP 200 status */
7597 if (strstr(resp_buf, "200") == NULL) {
7598 _netw_capture_error(conn->netw, "n_sse_connect: server did not return 200: %.128s", resp_buf);
7599 n_log(LOG_ERR, "n_sse_connect: server did not return 200: %.128s", resp_buf);
7600 goto sse_connect_fail;
7601 }
7602
7603 n_log(LOG_INFO, "n_sse_connect: SSE connected to %s:%s%s", host, port, path);
7604
7605 /* enter SSE read loop */
7606 {
7607 N_SSE_EVENT current;
7608 memset(&current, 0, sizeof(current));
7609
7610 /* line buffer for SSE parsing */
7611 char line[8192];
7612 size_t line_len = 0;
7613
7614 while (!__atomic_load_n(&conn->stop_flag, __ATOMIC_ACQUIRE)) {
7615 char ch = 0;
7616 if (_sse_read_byte(conn->netw, &ch, &conn->stop_flag) < 0) {
7617 n_log(LOG_DEBUG, "n_sse_connect: connection closed or read error");
7618 break;
7619 }
7620
7621 if (ch == '\n') {
7622 /* terminate line (strip trailing \r) */
7623 if (line_len > 0 && line[line_len - 1] == '\r') {
7624 line_len--;
7625 }
7626 line[line_len] = '\0';
7627
7628 if (line_len == 0) {
7629 /* empty line = dispatch event if we have data */
7630 if (current.data) {
7631 conn->on_event(&current, conn, conn->user_data);
7632 n_sse_event_clean(&current);
7633 memset(&current, 0, sizeof(current));
7634 }
7635 } else if (line[0] == ':') {
7636 /* comment line, ignore */
7637 n_log(LOG_DEBUG, "n_sse_connect: comment: %s", line + 1);
7638 } else {
7639 /* parse field:value */
7640 char* colon = strchr(line, ':');
7641 const char* field = line;
7642 const char* value = "";
7643 if (colon) {
7644 *colon = '\0';
7645 value = colon + 1;
7646 /* skip single leading space after colon */
7647 if (*value == ' ') value++;
7648 }
7649
7650 if (strcmp(field, "data") == 0) {
7651 if (current.data) {
7652 /* append newline + value to existing data */
7653 nstrprintf_cat(current.data, "\n%s", value);
7654 } else {
7655 current.data = char_to_nstr((char*)value);
7656 }
7657 } else if (strcmp(field, "event") == 0) {
7658 if (current.event) free_nstr(&current.event);
7659 current.event = char_to_nstr((char*)value);
7660 } else if (strcmp(field, "id") == 0) {
7661 if (current.id) free_nstr(&current.id);
7662 current.id = char_to_nstr((char*)value);
7663 } else if (strcmp(field, "retry") == 0) {
7664 current.retry = atoi(value);
7665 }
7666 }
7667
7668 line_len = 0;
7669 } else {
7670 if (line_len < sizeof(line) - 1) {
7671 line[line_len++] = ch;
7672 }
7673 }
7674 }
7675
7676 /* clean up any partial event */
7677 n_sse_event_clean(&current);
7678 }
7679
7680 return conn;
7681
7682sse_connect_fail:
7683 n_sse_conn_free(&conn);
7684 return NULL;
7685}
7686
7687#endif /* HAVE_OPENSSL */
7688
7691#define N_WS_FRAME_MAX_PAYLOAD (16U * 1024U * 1024U)
7692
7702int n_ws_frame_parse(const unsigned char* buf, size_t len, N_WS_FRAME* frame, size_t* consumed) {
7703 size_t hdr = 2;
7704 uint64_t plen;
7705 int len7;
7706 if (!buf || !frame || !consumed)
7707 return -1;
7708 if (len < 2)
7709 return 0;
7710 frame->fin = (buf[0] & 0x80) ? 1 : 0;
7711 frame->rsv = (buf[0] >> 4) & 0x07;
7712 frame->opcode = buf[0] & 0x0F;
7713 frame->masked = (buf[1] & 0x80) ? 1 : 0;
7714 len7 = buf[1] & 0x7F;
7715 if (len7 < 126) {
7716 plen = (uint64_t)len7;
7717 } else if (len7 == 126) {
7718 if (len < 4)
7719 return 0;
7720 plen = ((uint64_t)buf[2] << 8) | (uint64_t)buf[3];
7721 hdr = 4;
7722 } else {
7723 int i;
7724 if (len < 10)
7725 return 0;
7726 plen = 0;
7727 for (i = 0; i < 8; i++)
7728 plen = (plen << 8) | (uint64_t)buf[2 + i];
7729 hdr = 10;
7730 }
7731 if (plen > N_WS_FRAME_MAX_PAYLOAD)
7732 return -1;
7733 if (frame->masked) {
7734 if (len < hdr + 4)
7735 return 0;
7736 memcpy(frame->mask, buf + hdr, 4);
7737 hdr += 4;
7738 } else {
7739 memset(frame->mask, 0, 4);
7740 }
7741 if (len < hdr + plen)
7742 return 0;
7743 frame->payload_len = plen;
7744 frame->payload = buf + hdr;
7745 *consumed = hdr + (size_t)plen;
7746 return 1;
7747}
7748
7749void n_ws_unmask(unsigned char* dst, const unsigned char* src, size_t len, const unsigned char mask[4]) {
7750 size_t i;
7751 if (!dst || !src || !mask)
7752 return;
7753 for (i = 0; i < len; i++)
7754 dst[i] = (unsigned char)(src[i] ^ mask[i & 3]);
7755}
7756
7757size_t n_ws_frame_build(int fin, int opcode, int do_mask, const unsigned char* payload, size_t len, const unsigned char mask_key[4], unsigned char* out, size_t out_cap) {
7758 size_t pos = 0;
7759 unsigned char b1 = (unsigned char)(do_mask ? 0x80 : 0);
7760 if (!out || out_cap < 2)
7761 return 0;
7762 out[pos++] = (unsigned char)((fin ? 0x80 : 0) | (opcode & 0x0F));
7763 if (len <= 125) {
7764 out[pos++] = (unsigned char)(b1 | (unsigned char)len);
7765 } else if (len <= 65535) {
7766 if (out_cap < pos + 3)
7767 return 0;
7768 out[pos++] = (unsigned char)(b1 | 126);
7769 out[pos++] = (unsigned char)((len >> 8) & 0xFF);
7770 out[pos++] = (unsigned char)(len & 0xFF);
7771 } else {
7772 int i;
7773 if (out_cap < pos + 9)
7774 return 0;
7775 out[pos++] = (unsigned char)(b1 | 127);
7776 for (i = 7; i >= 0; i--)
7777 out[pos++] = (unsigned char)((len >> (8 * i)) & 0xFF);
7778 }
7779 if (do_mask) {
7780 if (!mask_key || out_cap < pos + 4)
7781 return 0;
7782 memcpy(out + pos, mask_key, 4);
7783 pos += 4;
7784 }
7785 if (out_cap < pos + len)
7786 return 0;
7787 if (do_mask && mask_key) {
7788 size_t i;
7789 for (i = 0; i < len; i++)
7790 out[pos + i] = (unsigned char)((payload ? payload[i] : 0) ^ mask_key[i & 3]);
7791 } else if (payload && len > 0) {
7792 memcpy(out + pos, payload, len);
7793 }
7794 pos += len;
7795 return pos;
7796}
7797
7803static void _n_mock_parse_request(const char* buf, N_HTTP_REQUEST* req) {
7804 if (!buf || !req) return;
7805
7806 /* parse request line: METHOD PATH?QUERY HTTP/1.x */
7807 const char* line_end = strstr(buf, "\r\n");
7808 if (!line_end) line_end = strchr(buf, '\n');
7809 if (!line_end) return;
7810
7811 size_t line_len = (size_t)(line_end - buf);
7812 char line[4096];
7813 if (line_len >= sizeof(line)) line_len = sizeof(line) - 1;
7814 memcpy(line, buf, line_len);
7815 line[line_len] = '\0';
7816
7817 /* method */
7818 char* sp1 = strchr(line, ' ');
7819 if (!sp1) return;
7820 size_t mlen = (size_t)(sp1 - line);
7821 if (mlen >= sizeof(req->method)) mlen = sizeof(req->method) - 1;
7822 memcpy(req->method, line, mlen);
7823 req->method[mlen] = '\0';
7824
7825 /* path and query */
7826 sp1++;
7827 char* sp2 = strchr(sp1, ' ');
7828 if (sp2) *sp2 = '\0';
7829 char* qmark = strchr(sp1, '?');
7830 if (qmark) {
7831 *qmark = '\0';
7832 strncpy(req->query, qmark + 1, sizeof(req->query) - 1);
7833 req->query[sizeof(req->query) - 1] = '\0';
7834 }
7835 strncpy(req->path, sp1, sizeof(req->path) - 1);
7836 req->path[sizeof(req->path) - 1] = '\0';
7837
7838 /* headers: skip past request line */
7839 const char* hdr_start = line_end;
7840 if (*hdr_start == '\r') hdr_start++;
7841 if (*hdr_start == '\n') hdr_start++;
7842
7843 req->headers = new_generic_list(0);
7844
7845 const char* body_start = NULL;
7846 while (hdr_start && *hdr_start) {
7847 const char* next = strstr(hdr_start, "\r\n");
7848 if (!next) next = strchr(hdr_start, '\n');
7849 if (!next) break;
7850
7851 size_t hlen = (size_t)(next - hdr_start);
7852 if (hlen == 0) {
7853 /* blank line = end of headers */
7854 body_start = next;
7855 if (*body_start == '\r') body_start++;
7856 if (*body_start == '\n') body_start++;
7857 break;
7858 }
7859
7860 char* header_line = strndup(hdr_start, hlen);
7861 if (header_line) {
7862 list_push(req->headers, header_line, free);
7863 }
7864
7865 hdr_start = next;
7866 if (*hdr_start == '\r') hdr_start++;
7867 if (*hdr_start == '\n') hdr_start++;
7868 }
7869
7870 /* body */
7871 if (body_start && *body_start) {
7872 req->body = char_to_nstr(body_start);
7873 }
7874}
7875
7881 if (!req) return;
7882 if (req->headers) list_destroy(&req->headers);
7883 if (req->body) free_nstr(&req->body);
7884}
7885
7894 void (*on_request)(N_HTTP_REQUEST*, N_HTTP_RESPONSE*, void*),
7895 void* user_data) {
7896 __n_assert(on_request, return NULL);
7897
7898 N_MOCK_SERVER* server = NULL;
7900 __n_assert(server, return NULL);
7901 memset(server, 0, sizeof(*server));
7902
7903 server->on_request = on_request;
7904 server->user_data = user_data;
7905 server->port = port;
7906 server->stop_flag = 0;
7907
7908 char port_str[16];
7909 snprintf(port_str, sizeof(port_str), "%d", port);
7910
7911 NETWORK* listener = NULL;
7912 if (netw_make_listening(&listener, NULL, port_str, 5, NETWORK_IPALL) != TRUE) {
7913 n_log(LOG_ERR, "n_mock_server_start: failed to listen on port %d", port);
7915 return NULL;
7916 }
7917 server->listener = listener;
7918
7919 n_log(LOG_INFO, "mock server listening on port %d", port);
7920 return server;
7921}
7922
7928 __n_assert(server, return);
7929 __n_assert(server->listener, return);
7930
7931 while (!__atomic_load_n(&server->stop_flag, __ATOMIC_ACQUIRE)) {
7932 /* Use select with timeout to avoid blocking forever */
7933 fd_set readfds;
7934 FD_ZERO(&readfds);
7935 FD_SET(server->listener->link.sock, &readfds);
7936 struct timeval tv;
7937 tv.tv_sec = 0;
7938 tv.tv_usec = 200000; /* 200ms */
7939 int sel = select((int)(server->listener->link.sock + 1), &readfds, NULL, NULL, &tv);
7940 if (sel <= 0) continue;
7941
7942 /* Accept connection using netw_accept_from_ex with 1000ms timeout */
7943 int ret = 0;
7944 NETWORK* client = netw_accept_from_ex(server->listener, 0, 0, 1000, &ret);
7945 if (!client) continue;
7946
7947 /* Read HTTP request */
7948 char buf[8192];
7949 ssize_t n = recv(client->link.sock, buf, sizeof(buf) - 1, 0);
7950 if (n <= 0) {
7952 continue;
7953 }
7954 buf[n] = '\0';
7955
7956 /* Parse request */
7957 N_HTTP_REQUEST req;
7958 memset(&req, 0, sizeof(req));
7959 _n_mock_parse_request(buf, &req);
7960
7961 /* Prepare default response */
7962 N_HTTP_RESPONSE resp;
7963 memset(&resp, 0, sizeof(resp));
7964 resp.status_code = 404;
7965 strncpy(resp.content_type, "text/plain", sizeof(resp.content_type) - 1);
7966
7967 /* Call handler */
7968 server->on_request(&req, &resp, server->user_data);
7969
7970 /* Build HTTP response */
7971 const char* status_msg = netw_get_http_status_message(resp.status_code);
7972 if (!status_msg) status_msg = "Unknown";
7973
7974 size_t body_len = 0;
7975 const char* body_data = "";
7976 if (resp.body && resp.body->data) {
7977 body_data = resp.body->data;
7978 body_len = resp.body->written;
7979 }
7980
7981 char header_buf[1024];
7982 int hlen = snprintf(header_buf, sizeof(header_buf),
7983 "HTTP/1.1 %d %s\r\n"
7984 "Content-Type: %s\r\n"
7985 "Content-Length: %zu\r\n"
7986 "Connection: close\r\n"
7987 "\r\n",
7988 resp.status_code, status_msg,
7989 resp.content_type,
7990 body_len);
7991
7992 if (hlen > 0) {
7993 send(client->link.sock, header_buf, NETW_BUFLEN_CAST(hlen), NETFLAGS);
7994 }
7995 if (body_len > 0) {
7996 send(client->link.sock, body_data, NETW_BUFLEN_CAST(body_len), NETFLAGS);
7997 }
7998
7999 /* Cleanup */
8000 if (resp.body) free_nstr(&resp.body);
8003 }
8004
8005 n_log(LOG_INFO, "mock server stopped");
8006}
8007
8013 __n_assert(server, return);
8014 __atomic_store_n(&server->stop_flag, 1, __ATOMIC_RELEASE);
8015}
8016
8022 __n_assert(server && *server, return);
8023 if ((*server)->listener) {
8024 netw_close(&(*server)->listener);
8025 }
8026 FreeNoLog(*server);
8027 *server = NULL;
8028}
8029
8030static void _n_parse_query_params(N_URL* u, const char* qs) {
8031 if (!u || !qs || !qs[0]) return;
8032 char* buf = strdup(qs);
8033 if (!buf) return;
8034 char* saveptr = NULL;
8035 /* NOT const: this walks the mutable copy in buf, and the loop writes a NUL into it
8036 to split key from value */
8037 // cppcheck-suppress constVariablePointer ; see above, strchr() on a const char* still yields a char* in C and the loop writes through it
8038 char* tok = strtok_r(buf, "&", &saveptr);
8039 while (tok && u->nb_params < N_URL_MAX_PARAMS) {
8040 char* eq = strchr(tok, '=');
8041 if (eq) {
8042 *eq = '\0';
8043 u->params[u->nb_params].key = strdup(tok);
8044 u->params[u->nb_params].value = strdup(eq + 1);
8045 } else {
8046 u->params[u->nb_params].key = strdup(tok);
8047 u->params[u->nb_params].value = strdup("");
8048 }
8049 u->nb_params++;
8050 tok = strtok_r(NULL, "&", &saveptr);
8051 }
8052 free(buf);
8053}
8054
8055N_URL* n_url_parse(const char* url) {
8056 if (!url) return NULL;
8057 N_URL* u = NULL;
8058 Malloc(u, N_URL, 1);
8059 if (!u) return NULL;
8060 memset(u, 0, sizeof(*u));
8061 const char* p = url;
8062 const char* scheme_end = strstr(p, "://");
8063 if (scheme_end) {
8064 u->scheme = strndup(p, (size_t)(scheme_end - p));
8065 p = scheme_end + 3;
8066 } else {
8067 u->scheme = strdup("http");
8068 }
8069 const char* host_end = p;
8070 while (*host_end && *host_end != '/' && *host_end != '?' && *host_end != ':') host_end++;
8071 u->host = strndup(p, (size_t)(host_end - p));
8072 p = host_end;
8073 if (*p == ':') {
8074 p++;
8075 u->port = atoi(p);
8076 while (*p && *p != '/' && *p != '?') p++;
8077 }
8078 if (*p == '/') {
8079 const char* pe = p;
8080 while (*pe && *pe != '?') pe++;
8081 u->path = strndup(p, (size_t)(pe - p));
8082 p = pe;
8083 } else {
8084 u->path = strdup("/");
8085 }
8086 if (*p == '?') {
8087 p++;
8088 u->query = strdup(p);
8090 }
8091 return u;
8092}
8093
8095 if (!u) return NULL;
8096 N_STR* result = new_nstr(512);
8097 if (!result) return NULL;
8098 nstrprintf(result, "%s://%s", u->scheme ? u->scheme : "http", u->host ? u->host : "localhost");
8099 if (u->port > 0) {
8100 int dp = (u->scheme && strcmp(u->scheme, "https") == 0) ? 443 : 80;
8101 if (u->port != dp) nstrprintf_cat(result, ":%d", u->port);
8102 }
8103 nstrprintf_cat(result, "%s", u->path ? u->path : "/");
8104 if (u->query && u->query[0]) nstrprintf_cat(result, "?%s", u->query);
8105 return result;
8106}
8107
8114static void _n_url_normalize_path(const char* path, char* out, size_t outsz) {
8115 const char* seg_starts[256];
8116 size_t seg_lens[256];
8117 int nb = 0;
8118 const char* p = (path && path[0]) ? path : "/";
8119 size_t pos = 0;
8120 int i;
8121 /* split on '/', applying the dot-segment rules */
8122 while (*p) {
8123 const char* slash;
8124 size_t slen;
8125 if (*p == '/') {
8126 p++;
8127 continue;
8128 }
8129 slash = strchr(p, '/');
8130 slen = slash ? (size_t)(slash - p) : strlen(p);
8131 if (slen == 1 && p[0] == '.') {
8132 /* skip "." */
8133 } else if (slen == 2 && p[0] == '.' && p[1] == '.') {
8134 if (nb > 0) nb--; /* pop one segment */
8135 } else if (nb < 256) {
8136 seg_starts[nb] = p;
8137 seg_lens[nb] = slen;
8138 nb++;
8139 }
8140 p += slen;
8141 }
8142 /* rebuild with a leading slash */
8143 if (outsz == 0) return;
8144 out[pos++] = '/';
8145 for (i = 0; i < nb && pos < outsz - 1; i++) {
8146 size_t k;
8147 if (i > 0 && pos < outsz - 1) out[pos++] = '/';
8148 for (k = 0; k < seg_lens[i] && pos < outsz - 1; k++)
8149 out[pos++] = seg_starts[i][k];
8150 }
8151 /* preserve a trailing slash from the original (it can be significant) */
8152 if (path && path[0] && path[strlen(path) - 1] == '/' && pos < outsz - 1 && (nb > 0))
8153 out[pos++] = '/';
8154 out[pos] = '\0';
8155}
8156
8167 N_STR* result = NULL;
8168 char scheme[16];
8169 char host[256];
8170 char path[2048];
8171 size_t i;
8172 if (!u) return NULL;
8173 snprintf(scheme, sizeof(scheme), "%s", u->scheme ? u->scheme : "http");
8174 snprintf(host, sizeof(host), "%s", u->host ? u->host : "");
8175 for (i = 0; scheme[i]; i++) scheme[i] = (char)tolower((unsigned char)scheme[i]);
8176 for (i = 0; host[i]; i++) host[i] = (char)tolower((unsigned char)host[i]);
8177 _n_url_normalize_path(u->path, path, sizeof(path));
8178 result = new_nstr(2560);
8179 if (!result) return NULL;
8180 nstrprintf(result, "%s://%s", scheme, host);
8181 if (u->port > 0) {
8182 int dp = (strcmp(scheme, "https") == 0) ? 443 : 80;
8183 if (u->port != dp) nstrprintf_cat(result, ":%d", u->port);
8184 }
8185 nstrprintf_cat(result, "%s", path);
8186 if (u->query && u->query[0]) nstrprintf_cat(result, "?%s", u->query);
8187 return result;
8188}
8189
8196 N_URL* u = n_url_parse(url);
8197 N_STR* out;
8198 if (!u) return NULL;
8199 out = n_url_canonicalize(u);
8200 n_url_free(&u);
8201 return out;
8202}
8203
8209static int _n_url_has_scheme(const char* s) {
8210 if (!s || !isalpha((unsigned char)s[0])) return 0;
8211 size_t i = 1;
8212 while (s[i] && (isalnum((unsigned char)s[i]) || s[i] == '+' || s[i] == '-' || s[i] == '.')) i++;
8213 return s[i] == ':';
8214}
8215
8233N_STR* n_url_resolve(const char* base, const char* ref) {
8234 if (!base) return NULL;
8235
8236 /* fragment-stripped working copy of the reference */
8237 char* refbuf = strdup(ref ? ref : "");
8238 if (!refbuf) return NULL;
8239 char* frag = strchr(refbuf, '#');
8240 if (frag) *frag = '\0';
8241
8242 /* absolute reference: it carries its own scheme, return it verbatim */
8243 if (_n_url_has_scheme(refbuf)) {
8244 N_STR* out = new_nstr(strlen(refbuf) + 1);
8245 if (out) nstrprintf(out, "%s", refbuf);
8246 free(refbuf);
8247 return out;
8248 }
8249
8250 N_URL* b = n_url_parse(base);
8251 if (!b) {
8252 free(refbuf);
8253 return NULL;
8254 }
8255
8256 /* split the reference into its path and query parts at the first '?' */
8257 char* refq = strchr(refbuf, '?');
8258 const char* ref_query = NULL;
8259 if (refq) {
8260 *refq = '\0';
8261 ref_query = refq + 1;
8262 }
8263
8264 /* base authority = host plus a non-elided port */
8265 char authority[300];
8266 if (b->port > 0)
8267 snprintf(authority, sizeof(authority), "%s:%d", b->host ? b->host : "", b->port);
8268 else
8269 snprintf(authority, sizeof(authority), "%s", b->host ? b->host : "");
8270
8271 char rawpath[4096];
8272 const char* t_scheme = b->scheme ? b->scheme : "http";
8273 const char* t_query = NULL;
8274
8275 if (refbuf[0] == '\0') {
8276 /* empty path: same resource; keep the base query unless one was given */
8277 snprintf(rawpath, sizeof(rawpath), "%s", b->path ? b->path : "/");
8278 t_query = refq ? ref_query : b->query;
8279 } else if (refbuf[0] == '/' && refbuf[1] == '/') {
8280 /* scheme-relative: base scheme, new authority + path from the reference */
8281 const char* a = refbuf + 2;
8282 const char* slash = strchr(a, '/');
8283 if (slash) {
8284 snprintf(authority, sizeof(authority), "%.*s", (int)(slash - a), a);
8285 snprintf(rawpath, sizeof(rawpath), "%s", slash);
8286 } else {
8287 snprintf(authority, sizeof(authority), "%s", a);
8288 snprintf(rawpath, sizeof(rawpath), "/");
8289 }
8290 t_query = ref_query;
8291 } else if (refbuf[0] == '/') {
8292 /* absolute-path reference */
8293 snprintf(rawpath, sizeof(rawpath), "%s", refbuf);
8294 t_query = ref_query;
8295 } else {
8296 /* relative-path reference: merge against the base path */
8297 const char* bp = (b->path && b->path[0]) ? b->path : "/";
8298 const char* lastslash = strrchr(bp, '/');
8299 size_t prefixlen = lastslash ? (size_t)(lastslash - bp) + 1 : 0;
8300 snprintf(rawpath, sizeof(rawpath), "%.*s%s", (int)prefixlen, bp, refbuf);
8301 t_query = ref_query;
8302 }
8303
8304 char normpath[4096];
8305 _n_url_normalize_path(rawpath, normpath, sizeof(normpath));
8306
8307 N_STR* out = new_nstr(strlen(authority) + sizeof(normpath) + 32);
8308 if (out) {
8309 nstrprintf(out, "%s://%s%s", t_scheme, authority, normpath);
8310 if (t_query && t_query[0]) nstrprintf_cat(out, "?%s", t_query);
8311 }
8312 n_url_free(&b);
8313 free(refbuf);
8314 return out;
8315}
8316
8317N_STR* n_url_encode(const char* str) {
8318 return n_str_url_encode(str);
8319}
8320
8321N_STR* n_url_decode(const char* str) {
8322 if (!str) return NULL;
8323 size_t len = strlen(str);
8324 N_STR* result = new_nstr(len + 1);
8325 if (!result) return NULL;
8326 for (size_t i = 0; i < len; i++) {
8327 if (str[i] == '%' && i + 2 < len && isxdigit((unsigned char)str[i + 1]) && isxdigit((unsigned char)str[i + 2])) {
8328 const char hex[3] = {str[i + 1], str[i + 2], '\0'};
8329 unsigned int val = 0;
8330 sscanf(hex, "%x", &val);
8331 nstrprintf_cat(result, "%c", (char)val);
8332 i += 2;
8333 } else if (str[i] == '+') {
8334 nstrprintf_cat(result, " ");
8335 } else {
8336 nstrprintf_cat(result, "%c", str[i]);
8337 }
8338 }
8339 return result;
8340}
8341
8343 if (!u || !*u) return;
8344 N_URL* p = *u;
8345 FreeNoLog(p->scheme);
8346 FreeNoLog(p->host);
8347 FreeNoLog(p->path);
8348 FreeNoLog(p->query);
8349 for (int i = 0; i < p->nb_params; i++) {
8350 FreeNoLog(p->params[i].key);
8351 FreeNoLog(p->params[i].value);
8352 }
8353 FreeNoLog(p);
8354 *u = NULL;
8355}
8356
8363static SOCKET _proxy_tcp_connect(const char* host, int port) {
8364 char port_str[16];
8365 snprintf(port_str, sizeof(port_str), "%d", port);
8366
8367 struct addrinfo hints;
8368 memset(&hints, 0, sizeof(hints));
8369 hints.ai_family = AF_UNSPEC;
8370 hints.ai_socktype = SOCK_STREAM;
8371
8372 struct addrinfo* res = NULL;
8373 int gai_rc = getaddrinfo(host, port_str, &hints, &res);
8374 if (gai_rc != 0 || !res) {
8375 n_log(LOG_ERR, "n_proxy: DNS lookup failed for %s:%d: %s",
8376 host, port, gai_strerror(gai_rc));
8377 return INVALID_SOCKET;
8378 }
8379
8380 SOCKET fd = INVALID_SOCKET;
8381 struct addrinfo* rp = NULL;
8382 for (rp = res; rp; rp = rp->ai_next) {
8383 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
8384 if (fd == INVALID_SOCKET) continue;
8385 if (connect(fd, rp->ai_addr, (socklen_t)rp->ai_addrlen) == 0) break;
8386 closesocket(fd);
8387 fd = INVALID_SOCKET;
8388 }
8389 freeaddrinfo(res);
8390
8391 if (fd == INVALID_SOCKET) {
8392 n_log(LOG_ERR, "n_proxy: TCP connect to %s:%d failed", host, port);
8393 }
8394 return fd;
8395}
8396
8398 if (!url) return NULL;
8399
8400 /* Expect scheme://... */
8401 const char* sep = strstr(url, "://");
8402 if (!sep) {
8403 n_log(LOG_ERR, "n_proxy_cfg_parse: no scheme in '%s'", url);
8404 return NULL;
8405 }
8406
8407 size_t scheme_len = (size_t)(sep - url);
8408 if (scheme_len == 0 || scheme_len > 16) return NULL;
8409
8410 char scheme[17];
8411 memcpy(scheme, url, scheme_len);
8412 scheme[scheme_len] = '\0';
8413
8414 /* Only http, https, and socks5 */
8415 if (strcmp(scheme, "http") != 0 && strcmp(scheme, "https") != 0 && strcmp(scheme, "socks5") != 0) {
8416 n_log(LOG_ERR, "n_proxy_cfg_parse: unsupported scheme '%s'", scheme);
8417 return NULL;
8418 }
8419
8420 const char* after = sep + 3; /* after :// */
8421 if (!*after) return NULL;
8422
8423 /* Check for user:pass@host:port */
8424 const char* at = strchr(after, '@');
8425 const char* host_start = NULL;
8426 char* username = NULL;
8427 char* password = NULL;
8428
8429 if (at) {
8430 /* Parse user:pass */
8431 const char* colon = strchr(after, ':');
8432 if (colon && colon < at) {
8433 username = strndup(after, (size_t)(colon - after));
8434 password = strndup(colon + 1, (size_t)(at - colon - 1));
8435 } else {
8436 username = strndup(after, (size_t)(at - after));
8437 }
8438 host_start = at + 1;
8439 } else {
8440 host_start = after;
8441 }
8442
8443 /* Parse host:port */
8444 /* Handle IPv6 [host]:port */
8445 char* hostname = NULL;
8446 int port = 0;
8447
8448 if (host_start[0] == '[') {
8449 const char* bracket = strchr(host_start, ']');
8450 if (!bracket) goto fail;
8451 hostname = strndup(host_start + 1, (size_t)(bracket - host_start - 1));
8452 if (bracket[1] == ':') {
8453 port = atoi(bracket + 2);
8454 }
8455 } else {
8456 const char* colon = strchr(host_start, ':');
8457 if (colon) {
8458 hostname = strndup(host_start, (size_t)(colon - host_start));
8459 port = atoi(colon + 1);
8460 } else {
8461 hostname = strdup(host_start);
8462 }
8463 }
8464
8465 if (!hostname || !hostname[0]) goto fail;
8466 if (port <= 0 || port > 65535) {
8467 /* Default ports */
8468 if (strcmp(scheme, "http") == 0 || strcmp(scheme, "https") == 0)
8469 port = 3128;
8470 else if (strcmp(scheme, "socks5") == 0)
8471 port = 1080;
8472 }
8473
8474 N_PROXY_CFG* cfg = NULL;
8475 Malloc(cfg, N_PROXY_CFG, 1);
8476 if (!cfg) goto fail;
8477 memset(cfg, 0, sizeof(*cfg));
8478 cfg->scheme = strdup(scheme);
8479 cfg->host = hostname;
8480 cfg->port = port;
8481 cfg->username = username;
8482 cfg->password = password;
8483 return cfg;
8484
8485fail:
8486 FreeNoLog(hostname);
8487 FreeNoLog(username);
8488 FreeNoLog(password);
8489 return NULL;
8490}
8491
8493 if (!cfg || !*cfg) return;
8494 N_PROXY_CFG* p = *cfg;
8495 FreeNoLog(p->scheme);
8496 FreeNoLog(p->host);
8497 FreeNoLog(p->username);
8498 FreeNoLog(p->password);
8499 FreeNoLog(p);
8500 *cfg = NULL;
8501}
8502
8504 const char* target_host,
8505 int target_port) {
8506 if (!proxy || !target_host) return -1;
8507
8508 SOCKET fd = _proxy_tcp_connect(proxy->host, proxy->port);
8509 if (fd == INVALID_SOCKET) return -1;
8510
8511 /* Build CONNECT request */
8512 char connect_req[2048];
8513 int len = 0;
8514
8515 len = snprintf(connect_req, sizeof(connect_req),
8516 "CONNECT %s:%d HTTP/1.1\r\n"
8517 "Host: %s:%d\r\n",
8518 target_host, target_port,
8519 target_host, target_port);
8520
8521 /* Proxy-Authorization if credentials present */
8522 if (proxy->username && proxy->username[0]) {
8523 char cred[512];
8524 snprintf(cred, sizeof(cred), "%s:%s",
8525 proxy->username, proxy->password ? proxy->password : "");
8526 N_STR* cred_nstr = char_to_nstr(cred);
8527 if (cred_nstr) {
8528 N_STR* b64 = n_base64_encode(cred_nstr);
8529 if (b64 && b64->data) {
8530 len += snprintf(connect_req + len,
8531 sizeof(connect_req) - (size_t)len,
8532 "Proxy-Authorization: Basic %s\r\n",
8533 b64->data);
8534 }
8535 if (b64) free_nstr(&b64);
8536 free_nstr(&cred_nstr);
8537 }
8538 }
8539
8540 len += snprintf(connect_req + len, sizeof(connect_req) - (size_t)len,
8541 "\r\n");
8542
8543 /* Send CONNECT */
8544 ssize_t sent = send(fd, connect_req, NETW_BUFLEN_CAST(len), 0);
8545 if (sent != (ssize_t)len) {
8546 n_log(LOG_ERR, "n_proxy_connect_tunnel: send CONNECT failed");
8547 closesocket(fd);
8548 return -1;
8549 }
8550
8551 /* Read response */
8552 char resp_buf[4096];
8553 ssize_t nr = recv(fd, resp_buf, NETW_BUFLEN_CAST(sizeof(resp_buf) - 1), 0);
8554 if (nr <= 0) {
8555 n_log(LOG_ERR, "n_proxy_connect_tunnel: no response from proxy");
8556 closesocket(fd);
8557 return -1;
8558 }
8559 resp_buf[nr] = '\0';
8560
8561 /* Check for "HTTP/1.x 200" */
8562 if (strstr(resp_buf, " 200 ") == NULL) {
8563 n_log(LOG_ERR, "n_proxy_connect_tunnel: proxy rejected CONNECT: %.*s",
8564 (int)(strchr(resp_buf, '\r') ? strchr(resp_buf, '\r') - resp_buf : nr),
8565 resp_buf);
8566 closesocket(fd);
8567 return -1;
8568 }
8569
8570 n_log(LOG_DEBUG, "n_proxy_connect_tunnel: tunnel established to %s:%d via %s:%d",
8571 target_host, target_port, proxy->host, proxy->port);
8572 return (int)fd;
8573}
8574
8575#ifdef HAVE_OPENSSL
8577 const char* target_host,
8578 int target_port) {
8579 if (!proxy || !target_host) return -1;
8580
8581 SOCKET fd = _proxy_tcp_connect(proxy->host, proxy->port);
8582 if (fd == INVALID_SOCKET) return -1;
8583
8584 /* TLS handshake to the proxy itself */
8586
8587#if OPENSSL_VERSION_NUMBER >= 0x10100000L
8588 const SSL_METHOD* method = TLS_client_method();
8589#else
8590 const SSL_METHOD* method = TLSv1_2_client_method();
8591#endif
8592 SSL_CTX* ctx = SSL_CTX_new(method);
8593 if (!ctx) {
8594 n_log(LOG_ERR, "n_proxy_connect_tunnel_ssl: SSL_CTX_new failed");
8595 closesocket(fd);
8596 return -1;
8597 }
8598 SSL_CTX_set_default_verify_paths(ctx);
8599
8600 SSL* ssl = SSL_new(ctx);
8601 if (!ssl) {
8602 n_log(LOG_ERR, "n_proxy_connect_tunnel_ssl: SSL_new failed");
8603 SSL_CTX_free(ctx);
8604 closesocket(fd);
8605 return -1;
8606 }
8607 SSL_set_fd(ssl, (int)fd);
8608 SSL_set_tlsext_host_name(ssl, proxy->host);
8609
8610 if (SSL_connect(ssl) <= 0) {
8611 n_log(LOG_ERR, "n_proxy_connect_tunnel_ssl: TLS handshake to proxy %s:%d failed",
8612 proxy->host, proxy->port);
8613 SSL_free(ssl);
8614 SSL_CTX_free(ctx);
8615 closesocket(fd);
8616 return -1;
8617 }
8618
8619 n_log(LOG_DEBUG, "n_proxy_connect_tunnel_ssl: TLS established to proxy %s:%d",
8620 proxy->host, proxy->port);
8621
8622 /* Build CONNECT request */
8623 char connect_req[2048];
8624 int len = 0;
8625
8626 len = snprintf(connect_req, sizeof(connect_req),
8627 "CONNECT %s:%d HTTP/1.1\r\n"
8628 "Host: %s:%d\r\n",
8629 target_host, target_port,
8630 target_host, target_port);
8631
8632 /* Proxy-Authorization if credentials present */
8633 if (proxy->username && proxy->username[0]) {
8634 char cred[512];
8635 snprintf(cred, sizeof(cred), "%s:%s",
8636 proxy->username, proxy->password ? proxy->password : "");
8637 N_STR* cred_nstr = char_to_nstr(cred);
8638 if (cred_nstr) {
8639 N_STR* b64 = n_base64_encode(cred_nstr);
8640 if (b64 && b64->data) {
8641 len += snprintf(connect_req + len,
8642 sizeof(connect_req) - (size_t)len,
8643 "Proxy-Authorization: Basic %s\r\n",
8644 b64->data);
8645 }
8646 if (b64) free_nstr(&b64);
8647 free_nstr(&cred_nstr);
8648 }
8649 }
8650
8651 len += snprintf(connect_req + len, sizeof(connect_req) - (size_t)len,
8652 "\r\n");
8653
8654 /* Send CONNECT over TLS */
8655 if (SSL_write(ssl, connect_req, len) != len) {
8656 n_log(LOG_ERR, "n_proxy_connect_tunnel_ssl: send CONNECT failed");
8657 SSL_free(ssl);
8658 SSL_CTX_free(ctx);
8659 closesocket(fd);
8660 return -1;
8661 }
8662
8663 /* Read response over TLS */
8664 char resp_buf[4096];
8665 int nr = SSL_read(ssl, resp_buf, (int)(sizeof(resp_buf) - 1));
8666 if (nr <= 0) {
8667 n_log(LOG_ERR, "n_proxy_connect_tunnel_ssl: no response from proxy");
8668 SSL_free(ssl);
8669 SSL_CTX_free(ctx);
8670 closesocket(fd);
8671 return -1;
8672 }
8673 resp_buf[nr] = '\0';
8674
8675 /* Check for "HTTP/1.x 200" */
8676 if (strstr(resp_buf, " 200 ") == NULL) {
8677 n_log(LOG_ERR, "n_proxy_connect_tunnel_ssl: proxy rejected CONNECT: %.*s",
8678 (int)(strchr(resp_buf, '\r') ? strchr(resp_buf, '\r') - resp_buf : nr),
8679 resp_buf);
8680 SSL_free(ssl);
8681 SSL_CTX_free(ctx);
8682 closesocket(fd);
8683 return -1;
8684 }
8685
8686 /* Tunnel established, tear down the proxy TLS session but keep the fd.
8687 * SSL_shutdown sends close_notify; the proxy knows the CONNECT handshake
8688 * is done and the raw tunnel begins. We call SSL_set_quiet_shutdown to
8689 * avoid waiting for the peer's close_notify (the proxy won't send one
8690 * mid-tunnel). */
8691 SSL_set_quiet_shutdown(ssl, 1);
8692 SSL_shutdown(ssl);
8693 SSL_free(ssl);
8694 SSL_CTX_free(ctx);
8695
8696 n_log(LOG_DEBUG, "n_proxy_connect_tunnel_ssl: tunnel established to %s:%d via https://%s:%d",
8697 target_host, target_port, proxy->host, proxy->port);
8698 return (int)fd;
8699}
8700#endif /* HAVE_OPENSSL */
8701
8703 const char* target_host,
8704 int target_port) {
8705 if (!proxy || !target_host) return -1;
8706
8707 SOCKET fd = _proxy_tcp_connect(proxy->host, proxy->port);
8708 if (fd == INVALID_SOCKET) return -1;
8709
8710 int use_auth = (proxy->username && proxy->username[0]) ? 1 : 0;
8711
8712 /* SOCKS5 greeting */
8713 char greeting[4];
8714 if (use_auth) {
8715 greeting[0] = 0x05; /* version */
8716 greeting[1] = 0x02; /* 2 methods */
8717 greeting[2] = 0x00; /* no auth */
8718 greeting[3] = 0x02; /* user/pass */
8719 if (send(fd, greeting, 4, 0) != 4) goto fail;
8720 } else {
8721 greeting[0] = 0x05;
8722 greeting[1] = 0x01;
8723 greeting[2] = 0x00;
8724 if (send(fd, greeting, 3, 0) != 3) goto fail;
8725 }
8726
8727 /* Read server method selection */
8728 char method_resp[2];
8729 if (recv(fd, method_resp, 2, 0) != 2) goto fail;
8730 if (method_resp[0] != 0x05) goto fail;
8731
8732 if (method_resp[1] == 0x02 && use_auth) {
8733 /* User/pass auth sub-negotiation (RFC 1929) */
8734 size_t ulen = strlen(proxy->username);
8735 size_t plen = proxy->password ? strlen(proxy->password) : 0;
8736 if (ulen > 255 || plen > 255) goto fail;
8737
8738 char auth_req[515]; /* 1+1+255+1+255 */
8739 size_t pos = 0;
8740 auth_req[pos++] = 0x01; /* version */
8741 auth_req[pos++] = (char)ulen;
8742 memcpy(auth_req + pos, proxy->username, ulen);
8743 pos += ulen;
8744 auth_req[pos++] = (char)plen;
8745 if (plen > 0) {
8746 memcpy(auth_req + pos, proxy->password, plen);
8747 pos += plen;
8748 }
8749 /* SOCKS5 username/password auth (RFC 1929) transmits the credentials
8750 * in cleartext by design; the protocol has no in-band encryption. A
8751 * caller needing confidentiality must tunnel this over an encrypted
8752 * link (e.g. an HTTPS CONNECT proxy). Not a fixable defect here. */
8753 if (send(fd, auth_req, NETW_BUFLEN_CAST(pos), 0) != (ssize_t)pos) goto fail;
8754
8755 char auth_resp[2];
8756 if (recv(fd, auth_resp, 2, 0) != 2) goto fail;
8757 if (auth_resp[1] != 0x00) {
8758 n_log(LOG_ERR, "n_proxy_connect_socks5: auth rejected");
8759 goto fail;
8760 }
8761 } else if (method_resp[1] != 0x00) {
8762 n_log(LOG_ERR, "n_proxy_connect_socks5: no acceptable method");
8763 goto fail;
8764 }
8765
8766 /* Send connect request (domain name addressing) */
8767 {
8768 size_t hlen = strlen(target_host);
8769 if (hlen > 255) goto fail;
8770
8771 char conn_req[263]; /* 4 + 1 + 255 + 2 */
8772 size_t pos = 0;
8773 conn_req[pos++] = 0x05; /* version */
8774 conn_req[pos++] = 0x01; /* connect */
8775 conn_req[pos++] = 0x00; /* reserved */
8776 conn_req[pos++] = 0x03; /* domain name */
8777 conn_req[pos++] = (char)hlen;
8778 memcpy(conn_req + pos, target_host, hlen);
8779 pos += hlen;
8780 conn_req[pos++] = (char)((target_port >> 8) & 0xFF);
8781 conn_req[pos++] = (char)(target_port & 0xFF);
8782
8783 if (send(fd, conn_req, NETW_BUFLEN_CAST(pos), 0) != (ssize_t)pos) goto fail;
8784 }
8785
8786 /* Read connect response */
8787 {
8788 char conn_resp[10];
8789 /* Minimum response: 4 bytes header + address (varies) */
8790 ssize_t nr = recv(fd, conn_resp, NETW_BUFLEN_CAST(sizeof(conn_resp)), 0);
8791 if (nr < 4) goto fail;
8792 if (conn_resp[0] != 0x05 || conn_resp[1] != 0x00) {
8793 n_log(LOG_ERR, "n_proxy_connect_socks5: connect failed, reply=%02x",
8794 conn_resp[1]);
8795 goto fail;
8796 }
8797
8798 /* If address type is domain (0x03), we may need to read more */
8799 if (conn_resp[3] == 0x03 && nr < 5) {
8800 /* Read remaining bytes */
8801 char extra[256];
8802 recv(fd, extra, NETW_BUFLEN_CAST(sizeof(extra)), 0);
8803 } else if (conn_resp[3] == 0x04 && nr < 10) {
8804 /* IPv6: 16 + 2 bytes remaining */
8805 char extra[18];
8806 size_t need = 22 - (size_t)nr; /* total IPv6 response = 4+16+2=22 */
8807 if (need <= sizeof(extra)) {
8808 recv(fd, extra, NETW_BUFLEN_CAST(need), 0);
8809 }
8810 }
8811 }
8812
8813 n_log(LOG_DEBUG, "n_proxy_connect_socks5: tunnel established to %s:%d via %s:%d",
8814 target_host, target_port, proxy->host, proxy->port);
8815 return (int)fd;
8816
8817fail:
8818 n_log(LOG_ERR, "n_proxy_connect_socks5: handshake failed");
8819 closesocket(fd);
8820 return -1;
8821}
8822
8840int netw_adopt_client_fd(NETWORK** netw, SOCKET fd, const char* host, const char* port) {
8841 __n_assert(netw, return FALSE);
8842 if ((*netw)) {
8843 n_log(LOG_ERR, "netw_adopt_client_fd: target NETWORK must be empty");
8844 return FALSE;
8845 }
8846 if (fd == INVALID_SOCKET) {
8847 n_log(LOG_ERR, "netw_adopt_client_fd: invalid socket");
8848 return FALSE;
8849 }
8850 if (netw_init_wsa(1, 2, 2) == FALSE) {
8851 n_log(LOG_ERR, "netw_adopt_client_fd: unable to load WSA dll's");
8852 return FALSE;
8853 }
8855 __n_assert(netw && (*netw), return FALSE);
8856
8857 (*netw)->link.sock = fd;
8858 (*netw)->link.ip = strdup(host ? host : "");
8859 if (!(*netw)->link.ip) {
8861 return FALSE;
8862 }
8863 (*netw)->link.port = strdup(port ? port : "");
8864 if (!(*netw)->link.port) {
8866 return FALSE;
8867 }
8868
8870 n_log(LOG_DEBUG, "netw_adopt_client_fd: adopted socket %d for %s:%s", (int)fd, (*netw)->link.ip, (*netw)->link.port);
8871 return TRUE;
8872} /* netw_adopt_client_fd */
int DONE
Definition ex_fluid.c:58
static int mode
static char * port_str
static NETWORK_POOL * pool
static void type(N_GUI_CTX *gui, const char *s)
Type a whole string into whatever has focus.
static int on_request(void *ud, N_H2_SERVER *srv, const N_H2_REQUEST *req)
static N_HTTP_SERVER * start(N_HTTP_SERVER_CONFIG *cfg, char *port, int base)
start a server on the first free port from base
a test client connection, plain or TLS
NETWORK * netw
Network for server mode, accepting incomming.
Definition ex_network.c:39
char * ca_file
NETWORK * server
int ip_version
char * addr
char * cert
char * port
static int eq(double a, double b)
Definition ex_wrap.c:93
void line(BITMAP *bmp, int x1, int y1, int x2, int y2, int color)
draw a line
volatile char key[227]
TRUE while the key is held.
#define init_lock(__rwlock_mutex)
Macro for initializing a rwlock.
Definition n_common.h:350
#define FreeNoLog(__ptr)
Free Handler without log.
Definition n_common.h:272
#define Malloc(__ptr, __struct, __size)
Malloc Handler to get errors and set to 0.
Definition n_common.h:204
#define __n_assert(__ptr, __ret)
macro to assert things
Definition n_common.h:279
#define _str(__PTR)
define true
Definition n_common.h:193
#define rw_lock_destroy(__rwlock_mutex)
Macro to destroy rwlock mutex.
Definition n_common.h:409
#define unlock(__rwlock_mutex)
Macro for releasing read/write lock a rwlock mutex.
Definition n_common.h:396
#define endif
close a ifwhatever block
Definition n_common.h:325
#define write_lock(__rwlock_mutex)
Macro for acquiring a write lock on a rwlock mutex.
Definition n_common.h:382
#define Free(__ptr)
Free Handler to get errors.
Definition n_common.h:263
#define read_lock(__rwlock_mutex)
Macro for acquiring a read lock on a rwlock mutex.
Definition n_common.h:368
#define _nstr(__PTR)
N_STR or "NULL" string for logging purposes.
Definition n_common.h:199
N_STR * n_base64_encode(N_STR *input)
encode a N_STR *string
Definition n_base64.c:270
#define N_ENUM_DEFINE(MACRO_DEFINITION, enum_name)
Macro to define an N_ENUM.
Definition n_enum.h:169
#define N_ENUM_ENTRY(class, method)
helper to build an N_ENUM
Definition n_enum.h:46
size_t nb_keys
total number of used keys in the table
Definition n_hash.h:142
int ht_get_ptr(HASH_TABLE *table, const char *key, void **val)
get pointer at 'key' from 'table'
Definition n_hash.c:2214
#define ht_foreach(__ITEM_, __HASH_)
ForEach macro helper (classic / old).
Definition n_hash.h:192
int destroy_ht(HASH_TABLE **table)
empty a table and destroy it
Definition n_hash.c:2348
int ht_remove(HASH_TABLE *table, const char *key)
remove and delete node at key in table
Definition n_hash.c:2306
HASH_TABLE * new_ht(size_t size)
Create a hash table with the given size.
Definition n_hash.c:2115
int ht_put_ptr(HASH_TABLE *table, const char *key, void *ptr, void(*destructor)(void *ptr), void *(*duplicator)(void *ptr))
put an arbitrary pointer value with given key in the targeted hash table
Definition n_hash.c:2268
int ht_put_string(HASH_TABLE *table, const char *key, char *string)
put a string value (copy/dup) with given key in the targeted hash table
Definition n_hash.c:2281
#define hash_val(node, type)
Cast a HASH_NODE element.
Definition n_hash.h:188
structure of a hash table node
Definition n_hash.h:112
structure of a hash table
Definition n_hash.h:138
#define list_shift(__LIST_, __TYPE_)
Shift macro helper for void pointer casting.
Definition n_list.h:96
int list_empty(LIST *list)
Empty a LIST list of pointers.
Definition n_list.c:501
LIST_NODE * list_search(LIST *list, const void *ptr)
search ptr in list
Definition n_list.c:469
int list_push(LIST *list, void *ptr, void(*destructor)(void *ptr))
Add a pointer to the end of the list.
Definition n_list.c:228
#define list_foreach(__ITEM_, __LIST_)
ForEach macro helper, safe for node removal during iteration.
Definition n_list.h:89
#define remove_list_node(__LIST_, __NODE_, __TYPE_)
Remove macro helper for void pointer casting.
Definition n_list.h:98
int list_destroy(LIST **list)
Empty and Free a list container.
Definition n_list.c:548
LIST * new_generic_list(size_t max_items)
Initialiaze a generic list container to max_items pointers.
Definition n_list.c:37
#define MAX_LIST_ITEMS
flag to pass to new_generic_list for the maximum possible number of item in a list
Definition n_list.h:75
Structure of a generic LIST container.
Definition n_list.h:59
Structure of a generic list node.
Definition n_list.h:44
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
Definition n_log.h:113
#define LOG_DEBUG
debug-level messages
Definition n_log.h:108
#define LOG_ERR
error conditions
Definition n_log.h:100
#define N_PRINTF_FORMAT(fmt, args)
declare a function printf-like; nothing on a compiler without attributes
Definition n_log.h:63
#define LOG_WARNING
warning conditions
Definition n_log.h:102
#define LOG_INFO
informational
Definition n_log.h:106
N_STR * zip4_nstr(N_STR *src)
Compress src with LZ4 block format.
Definition n_lz4.c:55
N_STR * unzip4_nstr(N_STR *src)
Decompress an N_STR produced by zip4_nstr.
Definition n_lz4.c:107
size_t written
number of meaningful bytes in data, excluding the null terminator; the size including the null termin...
Definition n_str.h:68
char * data
the string
Definition n_str.h:63
size_t length
total allocation (in bytes) of the data buffer, padding included
Definition n_str.h:65
void free_nstr_ptr(void *ptr)
Free a N_STR pointer structure.
Definition n_str.c:70
N_STR * n_str_url_encode(const char *src)
Percent-encode a C string per RFC 3986 (unreserved set kept as-is).
Definition n_str.c:1819
size_t NSTRBYTE
N_STR base unit.
Definition n_str.h:58
#define free_nstr(__ptr)
free a N_STR structure and set the pointer to NULL
Definition n_str.h:203
#define nstrcat(__nstr_dst, __nstr_src)
Macro to quickly concatenate two N_STR.
Definition n_str.h:125
N_STR * nstrdup(N_STR *str)
Duplicate a N_STR.
Definition n_str.c:723
#define nstrprintf_cat(__nstr_var, __format,...)
Macro to quickly allocate and sprintf and cat to a N_STR.
Definition n_str.h:121
N_STR * char_to_nstr(const char *src)
Convert a char into a N_STR, short version.
Definition n_str.c:262
N_STR * new_nstr(NSTRBYTE size)
create a new N_STR string
Definition n_str.c:209
#define nstrprintf(__nstr_var, __format,...)
Macro to quickly allocate and sprintf to N_STR.
Definition n_str.h:117
int char_to_nstr_ex(const char *from, NSTRBYTE nboct, N_STR **to)
Convert a char into a N_STR, extended version.
Definition n_str.c:239
A box including a string and his lenght.
Definition n_str.h:61
void u_sleep(unsigned int usec)
wrapper around usleep for API consistency
Definition n_time.c:55
int start_HiTimer(N_TIME *timer)
Initialize or restart from zero any N_TIME HiTimer.
Definition n_time.c:86
time_t get_usec(N_TIME *timer)
Poll any N_TIME HiTimer, returning usec, and moving currentTime to startTime.
Definition n_time.c:108
Timing Structure.
Definition n_time.h:49
N_STR * netmsg_make_position_msg(int id, double X, double Y, double vx, double vy, double acc_x, double acc_y, int time_stamp)
make a network NETMSG_POSITION message with given parameters
N_STR * netmsg_make_ident(int type, int id, N_STR *name, N_STR *passwd)
Add a formatted NETWMSG_IDENT message to the specified network.
N_STR * netmsg_make_quit_msg(void)
make a generic network NETMSG_QUIT message
N_STR * netmsg_make_ping(int type, int id_from, int id_to, int time)
Make a ping message to send to a network.
N_STR * netmsg_make_string_msg(int id_from, int id_to, N_STR *name, N_STR *chan, N_STR *txt, int color)
make a network NETMSG_STRING message with given parameters
volatile int stop_flag
atomic stop flag
Definition n_network.h:1139
char query[2048]
query string (or empty)
Definition n_network.h:1165
N_SOCKET link
networking socket
Definition n_network.h:454
size_t content_length
Store content length.
Definition n_network.h:639
char * type
Type of request.
Definition n_network.h:643
char * filename
Content-Disposition filename, or "".
Definition n_network.h:902
int port
port number (0 if not specified)
Definition n_network.h:1033
int masked
MASK bit (client-to-server frames are masked).
Definition n_network.h:1091
char * host
proxy hostname
Definition n_network.h:934
pthread_rwlock_t rwlock
thread safety
Definition n_network.h:630
NETWORK * netw
underlying network connection
Definition n_network.h:1138
char * host
hostname
Definition n_network.h:1032
char * path
path starting with "/", or "/" if empty
Definition n_network.h:1034
char * content_type
the part's Content-Type, or ""
Definition n_network.h:903
N_STR * body
response body
Definition n_network.h:1174
char * scheme
"http" or "https"
Definition n_network.h:1031
int opcode
opcode (N_WS_OP_*)
Definition n_network.h:1090
NETWORK * netw
underlying network connection
Definition n_network.h:1079
void(* on_event)(N_SSE_EVENT *event, struct N_SSE_CONN *conn, void *user_data)
callback
Definition n_network.h:1140
N_STR * body
the part's raw body bytes (binary-safe), or NULL
Definition n_network.h:904
int fin
FIN bit (1 = final fragment).
Definition n_network.h:1088
N_STR * event
event type (or NULL for default)
Definition n_network.h:1128
int connected
1 if handshake completed
Definition n_network.h:1080
N_STR * data
event data
Definition n_network.h:1129
N_STR * body
request body (or NULL)
Definition n_network.h:1167
char * key
parameter name
Definition n_network.h:1025
uint64_t payload_len
payload length in bytes
Definition n_network.h:1093
char * password
NULL if no auth.
Definition n_network.h:937
char * query
raw query string without leading '?
Definition n_network.h:1035
int port
proxy port
Definition n_network.h:935
N_URL_PARAM params[64]
parsed key=value pairs
Definition n_network.h:1036
char * body
Pointer to the body data.
Definition n_network.h:641
LIST * headers
list of char* "Name: Value" strings
Definition n_network.h:1166
char * value
parameter value
Definition n_network.h:1026
char * host
remote hostname
Definition n_network.h:1081
SOCKET sock
a normal socket
Definition n_network.h:356
char path[2048]
request path
Definition n_network.h:1164
char * scheme
"http", "https", or "socks5"
Definition n_network.h:933
char * port
port of socket
Definition n_network.h:354
int nb_params
number of parsed parameters
Definition n_network.h:1037
char * name
Content-Disposition form-field name, or "".
Definition n_network.h:901
SSL_CTX * ctx
SSL context holder.
Definition n_network.h:444
const unsigned char * payload
pointer into the input buffer (still masked)
Definition n_network.h:1094
int retry
retry interval in ms (0 if not set)
Definition n_network.h:1131
char content_type[256]
Store content type.
Definition n_network.h:637
N_STR * id
last event ID (or NULL)
Definition n_network.h:1130
char * path
resource path
Definition n_network.h:1082
int rsv
the three reserved bits, rsv1<<2 | rsv2<<1 | rsv3
Definition n_network.h:1089
N_STR * payload
message payload
Definition n_network.h:1073
char method[16]
HTTP method.
Definition n_network.h:1163
int opcode
frame opcode
Definition n_network.h:1072
unsigned char mask[4]
masking key when masked, else zeroed
Definition n_network.h:1092
int masked
1 if masked
Definition n_network.h:1074
char * disposition_extra
extra Content-Disposition parameters, appended verbatim after name (and filename) as written,...
Definition n_network.h:905
char * username
NULL if no auth.
Definition n_network.h:936
int status_code
HTTP status code.
Definition n_network.h:1172
SSL * ssl
SSL handle.
Definition n_network.h:446
unsigned long int is_blocking
flag to quickly check socket mode
Definition n_network.h:361
int crypto_algo
if encryption is on, which one (flags NETW_ENCRYPT_*)
Definition n_network.h:407
char content_type[128]
Content-Type header value.
Definition n_network.h:1173
HASH_TABLE * pool
table of clients
Definition n_network.h:627
void * user_data
user data for callback
Definition n_network.h:1141
#define NETW_SOCKET_ERROR
code for a socket error
Definition n_network.h:70
int netw_send_string_to_all(NETWORK *netw, N_STR *name, N_STR *chan, N_STR *txt, int color)
Add a string to the network, aiming all server-side users.
Definition n_network.c:6042
ssize_t send_ssl_data_once(void *netw, char *buf, uint32_t n)
single-attempt TLS send for non-blocking sockets (reactor use).
Definition n_network.c:5388
#define N_URL_MAX_PARAMS
maximum number of parsed query parameters
Definition n_network.h:1021
#define NETW_IO_WANT_READ
single-attempt I/O (send_data_once / recv_data_once): the operation cannot progress until the socket ...
Definition n_network.h:77
#define NETW_COMPRESS_THRESHOLD
Opportunistic compression policy.
Definition n_network.h:342
N_STR * netw_get_msg(NETWORK *netw)
Get a message from aimed NETWORK.
Definition n_network.c:4410
N_STR * n_http_build_multipart(LIST *parts, const char *boundary)
build a multipart/form-data body from a LIST of N_HTTP_MULTIPART_PART* using boundary (without "--");...
Definition n_network.c:6836
int netw_add_msg(NETWORK *netw, N_STR *msg)
Add a message to send in aimed NETWORK.
Definition n_network.c:4313
int netw_ssl_get_verify_result(NETWORK *netw, const char *expected_host, char *errbuf, size_t errsz)
evaluate the peer certificate of a completed TLS client connection
Definition n_network.c:2288
const char * n_netw_get_connect_error(int index)
Get pre-connection error message by index.
Definition n_network.c:126
ssize_t send_ssl_data(void *netw, char *buf, uint32_t n)
send data onto the socket
Definition n_network.c:5172
char * netw_extract_http_request_type(const char *request)
function to extract the request method from an http request
Definition n_network.c:6131
int netw_set_crypto_pem_ctx(NETWORK *netw, const N_STR *key_pem, const N_STR *cert_pem)
install an in-memory cert/key on a single accepted connection's SSL
Definition n_network.c:1853
#define N_WS_MAX_PAYLOAD
Largest WebSocket payload n_ws_recv() will accept from a peer, in bytes.
Definition n_network.h:1068
int netw_get_queue_status(NETWORK *netw, size_t *nb_to_send, size_t *nb_to_read)
retrieve network send queue status
Definition n_network.c:5748
int netw_bind_udp(NETWORK **netw, char *addr, char *port, int ip_version)
Create a UDP bound socket for receiving datagrams.
Definition n_network.c:3735
int netw_set_crypto_pem(NETWORK *netw, const char *key_pem, const char *cert_pem)
activate SSL encryption using PEM-formatted key and certificate strings loaded from memory
Definition n_network.c:1597
ssize_t recv_ssl_data_once(void *netw, char *buf, uint32_t n)
single-attempt TLS recv for non-blocking sockets (reactor use).
Definition n_network.c:5476
#define NETW_THR_EXIT_ERROR
Internal DONE value indicating a send/recv thread observed NETW_ERROR without an in-flight local shut...
Definition n_network.h:98
#define NETW_COMPRESS_MIN_RATIO
Definition n_network.h:343
int netw_init_wsa(int mode, int v1, int v2)
Do not directly use, internal api.
Definition n_network.c:841
int netw_ssl_set_verify(NETWORK *netw, int enable)
enable or disable SSL peer certificate verification
Definition n_network.c:2162
ssize_t send_php(SOCKET s, int _code, char *buf, int n)
send data onto the socket
Definition n_network.c:5561
#define NETW_MSG_MAX_FRAME_SIZE
Maximum accepted size, in bytes, of a single received message frame payload.
Definition n_network.h:93
int netw_stop_thr_engine(NETWORK *netw)
Stop a NETWORK connection sending and receing thread.
Definition n_network.c:4893
void n_ws_close(N_WS_CONN *conn)
Send close frame and close the connection.
Definition n_network.c:7348
char * netw_urlencode(const char *str, size_t len)
function to perform URL encoding
Definition n_network.c:6098
N_STR * n_url_encode(const char *str)
percent-encode a string for use in URLs (delegates to n_str_url_encode())
Definition n_network.c:8317
int n_http_status_class(int status_code)
leading digit of an HTTP status code (1..5), or 0 when outside 100..599
Definition n_network.c:6452
#define SSL_get1_peer_certificate(ssl)
Definition n_network.h:247
void * netw_send_func(void *NET)
Thread send function.
Definition n_network.c:4533
NETWORK * netw_accept_nonblock_from(NETWORK *from, int blocking)
make a normal blocking 'accept' .
Definition n_network.c:4297
int netw_get_url_from_http_request(const char *request, char *url, size_t size)
Helper function to extract the URL from the HTTP request line.
Definition n_network.c:6250
N_PROXY_CFG * n_proxy_cfg_parse(const char *url)
Parse a proxy URL string into an N_PROXY_CFG struct.
Definition n_network.c:8397
#define N_ENUM_netw_code_type(_)
Network codes definition.
Definition n_network.h:296
int netw_set_crypto(NETWORK *netw, char *key, char *certificate)
activate SSL encryption on selected network, using key and certificate
Definition n_network.c:1489
int netw_ssl_server_handshake_ex(NETWORK *netw, netw_sni_pick_cb pick, void *user_data, const char *const *alpn, size_t alpn_count)
upgrade an already-accepted plaintext connection to a TLS server, selecting the certificate per clien...
Definition n_network.c:2047
int netw_set_crypto_chain_pem(NETWORK *netw, const char *key_pem, const char *cert_pem, const char *ca_pem)
activate SSL encryption using PEM strings for key, certificate, and CA
Definition n_network.c:1739
int netw_adopt_client_fd(NETWORK **netw, SOCKET fd, const char *host, const char *port)
Adopt an already-connected socket fd into a fresh client NETWORK.
Definition n_network.c:8840
int netw_ssl_set_ca(NETWORK *netw, const char *ca_file, const char *ca_path)
set custom CA verify location for SSL context
Definition n_network.c:2137
void n_sse_stop(N_SSE_CONN *conn)
Signal the SSE connection to stop reading.
Definition n_network.c:7414
ssize_t recv_data_once(void *netw, char *buf, uint32_t n)
single-attempt recv for non-blocking sockets (reactor use).
Definition n_network.c:5117
#define NETWORK_IPV6
Flag to force IPV6.
Definition n_network.h:52
void n_http_multipart_free(LIST **parts)
free a LIST returned by n_http_parse_multipart and NULL the pointer
Definition n_network.c:6635
void n_ws_unmask(unsigned char *dst, const unsigned char *src, size_t len, const unsigned char mask[4])
XOR-unmask len bytes of src into dst using a 4-byte WebSocket mask key.
Definition n_network.c:7749
int netw_connect_ex_to(NETWORK **netw, char *host, char *port, size_t send_list_limit, size_t recv_list_limit, int ip_version, char *ssl_key_file, char *ssl_cert_file, int connect_timeout_ms)
Use this to connect a NETWORK to any listening one.
Definition n_network.c:2557
#define NETWORK_UDP
Flag for UDP transport.
Definition n_network.h:56
N_STR * n_url_canonicalize_string(const char *url)
parse and canonicalize a URL string in one call
Definition n_network.c:8195
N_STR * n_url_resolve(const char *base, const char *ref)
resolve a (possibly relative) URL reference against an absolute base
Definition n_network.c:8233
ssize_t send_data_once(void *netw, char *buf, uint32_t n)
single-attempt send for non-blocking sockets (reactor use).
Definition n_network.c:5061
int netw_ssl_server_handshake_once(NETWORK *netw, SSL_CTX *ctx)
non-blocking, resumable TLS server handshake against a shared ctx
Definition n_network.c:3202
int netw_get_http_date(char *buffer, size_t buffer_size)
helper function to generate the current date in HTTP format
Definition n_network.c:6865
int netw_connect_nonblock(NETWORK **netw, char *host, char *port, int ip_version)
begin a non-blocking TCP connect without waiting for it to complete
Definition n_network.c:2760
NETWORK_POOL * netw_new_pool(size_t nb_min_element)
return a new network pool of nb_min_element
Definition n_network.c:5767
int netw_set_user_id(NETWORK *netw, int id)
associate an id and a network
Definition n_network.c:5942
void n_mock_server_free(N_MOCK_SERVER **server)
Free a mock server and close the listening socket.
Definition n_network.c:8021
ssize_t recv_data(void *netw, char *buf, uint32_t n)
recv data from the socket
Definition n_network.c:4994
int netw_ssl_handshake_once(NETWORK *netw, const char *sni_hostname)
non-blocking, resumable TLS client handshake
Definition n_network.c:3159
int netw_init_openssl(void)
Do not directly use, internal api.
Definition n_network.c:1335
void n_netw_clear_errors(NETWORK *netw)
Clear captured errors on a NETWORK handle.
Definition n_network.c:116
ssize_t recv_ssl_data(void *netw, char *buf, uint32_t n)
recv data from the socket
Definition n_network.c:5270
int netw_make_listening(NETWORK **netw, char *addr, char *port, int nbpending, int ip_version)
Make a NETWORK be a Listening network.
Definition n_network.c:3602
int netw_ssl_do_handshake(NETWORK *netw, const char *sni_hostname)
Complete the SSL handshake on an already-connected NETWORK.
Definition n_network.c:3057
#define HEAD_SIZE
Size of a HEAD message.
Definition n_network.h:66
ssize_t send_udp_data(void *netw, char *buf, uint32_t n)
send data via UDP on a connected socket
Definition n_network.c:3961
#define netw_atomic_write_state(netw, val)
Lock-free atomic write of the network state field.
Definition n_network.h:607
int netw_set_compression_mode(NETWORK *netw, int mode)
Pick send-side payload compression algorithm.
Definition n_network.c:893
int netw_start_thr_engine(NETWORK *netw)
Start the NETWORK netw Threaded Engine.
Definition n_network.c:4484
int netw_destroy_pool(NETWORK_POOL **netw_pool)
free a NETWORK_POOL *pool
Definition n_network.c:5786
void n_url_free(N_URL **u)
free a N_URL and all its members
Definition n_network.c:8342
#define NETWORK_IPV4
Flag to force IPV4.
Definition n_network.h:50
int netw_build_http_response(N_STR **http_response, int status_code, const char *server_name, const char *content_type, char *additional_headers, N_STR *body)
function to dynamically generate an HTTP response
Definition n_network.c:6897
void * netw_recv_func(void *NET)
To Thread Receiving function.
Definition n_network.c:4716
void n_sse_conn_free(N_SSE_CONN **conn)
Free an SSE connection structure.
Definition n_network.c:7423
int n_proxy_connect_tunnel_ssl(const N_PROXY_CFG *proxy, const char *target_host, int target_port)
Open a TCP connection through an HTTPS proxy using CONNECT tunneling.
Definition n_network.c:8576
N_STR * n_url_decode(const char *str)
decode a percent-encoded string (returns N_STR)
Definition n_network.c:8321
int n_netw_get_error_count(const NETWORK *netw)
Get number of captured errors on a NETWORK handle.
Definition n_network.c:106
int n_ws_frame_parse(const unsigned char *buf, size_t len, N_WS_FRAME *frame, size_t *consumed)
Parse one WebSocket frame from a byte buffer (stateless, no allocation).
Definition n_network.c:7702
N_WS_CONN * n_ws_connect(const char *host, const char *port, const char *path, int use_ssl)
Connect to a WebSocket server (ws:// or wss://).
Definition n_network.c:6995
int n_http_status_is_server_error(int status_code)
1 when status_code is a server error (5xx), else 0
Definition n_network.c:6474
#define SOCKET_SIZE_FORMAT
socket associated printf style
Definition n_network.h:113
__netw_code_type size_t htonst(size_t value)
host to network size_t
Definition n_network.c:145
int netw_unload_openssl(void)
Do not directly use, internal api.
Definition n_network.c:1368
const char * netw_ssl_get_sni(NETWORK *netw)
get the SNI server_name the peer requested in its ClientHello
Definition n_network.c:1839
int n_http_status_is_client_error(int status_code)
1 when status_code is a client error (4xx), else 0
Definition n_network.c:6470
#define HEAD_CODE
Code of a HEAD message.
Definition n_network.h:68
int n_proxy_connect_socks5(const N_PROXY_CFG *proxy, const char *target_host, int target_port)
Open a TCP connection through a SOCKS5 proxy.
Definition n_network.c:8702
size_t ntohst(size_t value)
network to host size_t
Definition n_network.c:162
ssize_t netw_udp_sendto(NETWORK *netw, char *buf, uint32_t n, struct sockaddr *dest_addr, socklen_t dest_len)
send data via UDP to a specific destination address
Definition n_network.c:4038
#define NETWORK_CONSECUTIVE_SEND_WAIT
Flag to set consecutive send waiting timeout.
Definition n_network.h:62
#define netw_atomic_read_reactor_mode(netw)
Lock-free atomic read of the reactor_mode flag.
Definition n_network.h:616
size_t netw_pool_nbclients(NETWORK_POOL *netw_pool)
return the number of networks in netw_pool
Definition n_network.c:5925
int(* netw_sni_pick_cb)(const char *sni, N_STR **cert_pem, N_STR **key_pem, void *user_data)
SNI cert-pick callback for netw_accept_ssl_with_sni_cb: given the client SNI host (may be NULL),...
Definition n_network.h:683
int n_proxy_connect_tunnel(const N_PROXY_CFG *proxy, const char *target_host, int target_port)
Open a TCP connection through an HTTP proxy using CONNECT tunneling.
Definition n_network.c:8503
NETWORK * netw_accept_from_ex(NETWORK *from, size_t send_list_limit, size_t recv_list_limit, int blocking, int *retval)
make a normal 'accept' .
Definition n_network.c:4101
void n_netw_clear_connect_errors(void)
Clear pre-connection errors on this thread.
Definition n_network.c:132
void n_mock_server_stop(N_MOCK_SERVER *server)
Signal the mock server to stop accepting connections.
Definition n_network.c:8012
int netw_connect_ex(NETWORK **netw, char *host, char *port, size_t send_list_limit, size_t recv_list_limit, int ip_version, char *ssl_key_file, char *ssl_cert_file)
Use this to connect a NETWORK to any listening one.
Definition n_network.c:2886
#define NETWORK_IPALL
Flag for auto detection by OS of ip version to use.
Definition n_network.h:48
int SOCKET
default socket declaration
Definition n_network.h:111
#define NETW_SOCKET_DISCONNECTED
Code for a disconnected recv.
Definition n_network.h:72
int netw_pool_broadcast(NETWORK_POOL *netw_pool, const NETWORK *from, N_STR *net_msg)
add net_msg to all network in netork pool
Definition n_network.c:5901
SSL_CTX * netw_ssl_server_ctx_new(const char *key_file, const char *cert_chain_file)
new standalone server SSL_CTX with the library's secure defaults
Definition n_network.c:1449
int n_http_decompress_body(const N_STR *body, const char *encoding, N_STR **out)
decompress an HTTP body per its Content-Encoding ("gzip"/"deflate"; identity/NULL/unknown copies thro...
Definition n_network.c:6535
int netw_ssl_connect_client_to(NETWORK **netw, char *host, char *port, int ip_version, int connect_timeout_ms)
Connect as an SSL client without providing a client certificate.
Definition n_network.c:2948
const char * n_netw_get_error(const NETWORK *netw, int index)
Get captured error message by index (0 = oldest).
Definition n_network.c:110
void n_sse_event_clean(N_SSE_EVENT *event)
Free the contents of an SSE event (does not free the struct itself).
Definition n_network.c:7402
#define NETWORK_WAIT_CLOSE_TIMEOUT
Flag to set network closing wait timeout.
Definition n_network.h:64
int netw_setsockopt(NETWORK *netw, int optname, int value)
Modify common socket options on the given netw.
Definition n_network.c:969
int n_http_multipart_boundary(const char *content_type, char *out, size_t outsz)
copy the boundary token from a Content-Type value into out (without the leading "--").
Definition n_network.c:6595
int netw_ssl_set_alpn(NETWORK *netw, const char *const *protos, size_t count)
offer an ALPN protocol list on a TLS client connection, before its handshake
Definition n_network.c:1934
int netw_set(NETWORK *netw, int flag)
Restart or reset the specified network ability.
Definition n_network.c:3259
ssize_t send_data(void *netw, char *buf, uint32_t n)
send data onto the socket
Definition n_network.c:4933
ssize_t recv_udp_data(void *netw, char *buf, uint32_t n)
recv data via UDP from a connected socket
Definition n_network.c:4002
NETWORK * netw_accept_ssl_with_sni_cb(NETWORK *listen, netw_sni_pick_cb pick, void *user_data)
accept a TLS connection, selecting the server certificate per client SNI
Definition n_network.c:2116
int netw_get_state(NETWORK *netw, uint32_t *state, int *thr_engine_status)
Get the state of a network.
Definition n_network.c:3237
N_SSE_CONN * n_sse_connect(const char *host, const char *port, const char *path, int use_ssl, const char *user_agent, void(*on_event)(N_SSE_EVENT *, N_SSE_CONN *, void *), void *user_data)
Connect to an SSE endpoint and start reading events.
Definition n_network.c:7508
N_URL * n_url_parse(const char *url)
parse a URL string into components
Definition n_network.c:8055
int n_http_status_is_informational(int status_code)
1 when status_code is informational (1xx), else 0
Definition n_network.c:6458
void netw_pool_netw_close(void *netw_ptr)
close a network from a network pool
Definition n_network.c:5805
int netw_connect_check(NETWORK *netw)
advance a non-blocking connect started by netw_connect_nonblock()
Definition n_network.c:2822
int n_netw_get_connect_error_count(void)
Get number of pre-connection errors captured on this thread.
Definition n_network.c:122
size_t netw_calculate_urlencoded_size(const char *str, size_t len)
function to calculate the required size for the URL-encoded string
Definition n_network.c:6075
#define netw_atomic_read_reactor_handle(netw)
Same contract for the back-pointer to the reactor.
Definition n_network.h:621
int deplete_send_buffer(int fd, int timeout)
wait until the socket is empty or timeout, checking each 100 msec.
Definition n_network.c:3336
NETWORK * netw_accept_from(NETWORK *from)
make a normal blocking 'accept' .
Definition n_network.c:4287
static void SSL_set_hostflags(SSL *ssl, unsigned int flags)
1.0.2 stand-in for SSL_set_hostflags(): set the X509_CHECK_FLAG_* host-check flags of ssl
Definition n_network.h:279
N_STR * n_url_canonicalize(const N_URL *u)
produce a canonical URL string for deduplication
Definition n_network.c:8166
#define NETW_IO_WANT_WRITE
single-attempt I/O: the operation cannot progress until the socket is WRITABLE.
Definition n_network.h:81
#define NETW_MAX_RETRIES
Send or recv max number of retries.
Definition n_network.h:83
void n_proxy_cfg_free(N_PROXY_CFG **cfg)
Free an N_PROXY_CFG created by n_proxy_cfg_parse().
Definition n_network.c:8492
int netw_close(NETWORK **netw)
Closing a specified Network, destroy queues, free the structure.
Definition n_network.c:3367
int n_http_status_is_success(int status_code)
1 when status_code is success (2xx), else 0
Definition n_network.c:6462
N_STR * n_url_build(const N_URL *u)
build a URL string from parsed components
Definition n_network.c:8094
void n_mock_server_run(N_MOCK_SERVER *server)
Run the mock server accept loop.
Definition n_network.c:7927
int netw_send_quit(NETWORK *netw)
Add a formatted NETMSG_QUIT message to the specified network.
Definition n_network.c:6058
#define NETW_THR_EXIT_OK
Internal DONE value indicating a send/recv thread reached end-of-life cleanly (peer QUIT or local NET...
Definition n_network.h:96
int netw_ssl_set_ciphers(NETWORK *netw, const char *cipher_list, const char *ciphersuites)
set the cipher list (TLS 1.2 and below) and/or the ciphersuites (TLS 1.3)
Definition n_network.c:2244
int netw_ssl_connect_client(NETWORK **netw, char *host, char *port, int ip_version)
Connect as an SSL client without providing a client certificate.
Definition n_network.c:3020
int netw_ssl_start_client(NETWORK *netw)
Set up a client SSL_CTX on an already-connected NETWORK.
Definition n_network.c:2977
const char * netw_get_http_status_message(int status_code)
helper function to convert status code to a human-readable message
Definition n_network.c:6434
int netw_set_crypto_chain(NETWORK *netw, char *key, char *certificate, char *ca_file)
activate SSL encryption using key/certificate files and a CA file for chain verification
Definition n_network.c:1704
int n_ws_recv(N_WS_CONN *conn, N_WS_MESSAGE *msg_out)
Receive one WebSocket frame.
Definition n_network.c:7266
int netw_set_blocking(NETWORK *netw, unsigned long int is_blocking)
Modify blocking socket mode.
Definition n_network.c:911
N_STR * netw_wait_msg(NETWORK *netw, unsigned int refresh, size_t timeout)
Wait a message from aimed NETWORK.
Definition n_network.c:4432
int n_http_status_is_redirect(int status_code)
1 when status_code is a redirect (3xx), else 0
Definition n_network.c:6466
LIST * n_http_parse_multipart(const N_STR *body, const char *boundary)
parse a multipart body (boundary given without "--") into a LIST of N_HTTP_MULTIPART_PART*; free with...
Definition n_network.c:6695
int netw_send_string_to(NETWORK *netw, int id_to, N_STR *name, N_STR *chan, N_STR *txt, int color)
Add a string to the network, aiming a specific user.
Definition n_network.c:6022
int netw_send_ping(NETWORK *netw, int type, int id_from, int id_to, int time)
Add a ping reply to the network.
Definition n_network.c:5957
int netw_ssl_connect(NETWORK **netw, char *host, char *port, int ip_version, char *ssl_key_file, char *ssl_cert_file)
Use this to connect a NETWORK to any listening one, unrestricted send/recv lists.
Definition n_network.c:2928
NETWORK_HTTP_INFO netw_extract_http_info(char *request)
extract a lot of informations, mostly as pointers, and populate a NETWORK_HTTP_INFO structure
Definition n_network.c:6164
size_t n_ws_frame_build(int fin, int opcode, int do_mask, const unsigned char *payload, size_t len, const unsigned char mask_key[4], unsigned char *out, size_t out_cap)
build a WebSocket frame into out (optionally masking the payload).
Definition n_network.c:7757
int netw_ssl_server_handshake(NETWORK *netw, netw_sni_pick_cb pick, void *user_data)
upgrade an already-accepted plaintext connection to a TLS server, selecting the certificate per clien...
Definition n_network.c:2023
#define netw_atomic_read_state(netw)
Lock-free atomic read of the network state field.
Definition n_network.h:602
int netw_connect(NETWORK **netw, char *host, char *port, int ip_version)
Use this to connect a NETWORK to any listening one, unrestricted send/recv lists.
Definition n_network.c:2898
N_MOCK_SERVER * n_mock_server_start(int port, void(*on_request)(N_HTTP_REQUEST *, N_HTTP_RESPONSE *, void *), void *user_data)
Start a mock HTTP server: set up listener and return immediately.
Definition n_network.c:7893
__netw_code_type
Network codes declaration.
Definition n_network.h:346
#define NETWORK_DEPLETE_SOCKET_TIMEOUT
Flag to set send buffer depletion timeout.
Definition n_network.h:58
int netw_connect_to(NETWORK **netw, char *host, char *port, int ip_version, int connect_timeout_ms)
Connect a NETWORK with a bounded connection-establishment time.
Definition n_network.c:2912
int netw_send_ident(NETWORK *netw, int type, int id, N_STR *name, N_STR *passwd)
Add a formatted NETWMSG_IDENT message to the specified network.
Definition n_network.c:5976
char * netw_urldecode(const char *str)
Function to decode URL-encoded data.
Definition n_network.c:6287
int netw_ssl_set_client_cert(NETWORK *netw, const char *cert_file, const char *key_file)
load a client certificate and private key for mTLS
Definition n_network.c:2355
void n_ws_conn_free(N_WS_CONN **conn)
Free a WebSocket connection structure.
Definition n_network.c:7378
#define NETWORK_DEPLETE_QUEUES_TIMEOUT
Flag to set network queues depletion timeout.
Definition n_network.h:60
int netw_pool_add(NETWORK_POOL *netw_pool, NETWORK *netw)
add a NETWORK *netw to a NETWORK_POOL *pool
Definition n_network.c:5818
int netw_connect_udp(NETWORK **netw, char *host, char *port, int ip_version)
Connect a UDP socket to a remote host.
Definition n_network.c:3856
int netw_info_destroy(NETWORK_HTTP_INFO http_request)
destroy a NETWORK_HTTP_INFO loaded informations
Definition n_network.c:6237
int netw_ssl_get_alpn(NETWORK *netw, char *out, size_t out_len)
get the ALPN protocol the completed handshake selected
Definition n_network.c:1964
int netw_ssl_set_versions(NETWORK *netw, int min_version, int max_version)
set the minimum (and optionally maximum) TLS protocol version on a connection's SSL context
Definition n_network.c:2194
HASH_TABLE * netw_parse_post_data(const char *post_data)
Function to parse POST data.
Definition n_network.c:6324
const char * netw_guess_http_content_type(const char *url)
function to guess the content type based on URL extension
Definition n_network.c:6370
int n_ws_send(N_WS_CONN *conn, const char *payload, size_t len, int opcode)
Send a WebSocket frame (client always masks).
Definition n_network.c:7199
ssize_t recv_php(SOCKET s, int *_code, char **buf)
recv data from the socket
Definition n_network.c:5643
static int SSL_set1_host(SSL *ssl, const char *host)
1.0.2 stand-in for SSL_set1_host(): set the expected peer name of ssl, returning 1 on success and 0 o...
Definition n_network.h:286
int netw_send_position(NETWORK *netw, int id, double X, double Y, double vx, double vy, double acc_x, double acc_y, int time_stamp)
Add a formatted NETWMSG_IDENT message to the specified network.
Definition n_network.c:6000
int netw_pool_remove(NETWORK_POOL *netw_pool, NETWORK *netw)
remove a NETWORK *netw to a NETWORK_POOL *pool
Definition n_network.c:5864
void netw_set_connect_abort_cb(int(*cb)(void *ctx), void *ctx)
Register a process-wide callback polled while a connect is in progress.
Definition n_network.c:2539
int netw_add_msg_ex(NETWORK *netw, char *str, unsigned int length)
Add a message to send in aimed NETWORK.
Definition n_network.c:4379
#define NETWORK_TCP
Flag for TCP transport (default).
Definition n_network.h:54
ssize_t netw_udp_recvfrom(NETWORK *netw, char *buf, uint32_t n, struct sockaddr *src_addr, socklen_t *src_len)
recv data via UDP and capture the source address
Definition n_network.c:4070
#define N_WS_OP_CLOSE
Definition n_network.h:1060
@ NETW_COMPRESS_NONE
no automatic compression on send, still decompresses inbound
Definition n_network.h:328
@ NETW_COMPRESS_ZLIB
compress on send with zlib, decompress either on recv
Definition n_network.h:330
@ NETW_COMPRESS_LZ4
compress on send with LZ4, decompress either on recv
Definition n_network.h:332
@ NETW_COMPRESSED_LZ4
Definition n_network.h:346
@ NETW_DESTROY_RECVBUF
Definition n_network.h:346
@ NETW_ENCRYPT_OPENSSL
Definition n_network.h:346
@ NETW_THR_ENGINE_STARTED
Definition n_network.h:346
@ NETW_COMPRESSED_ZLIB
Definition n_network.h:346
@ NETW_SERVER
Definition n_network.h:346
@ NETW_EMPTY_SENDBUF
Definition n_network.h:346
@ NETW_DESTROY_SENDBUF
Definition n_network.h:346
@ NETW_THR_ENGINE_STOPPED
Definition n_network.h:346
@ NETW_RUN
Definition n_network.h:346
@ NETW_CLIENT
Definition n_network.h:346
@ NETW_EMPTY_RECVBUF
Definition n_network.h:346
@ NETW_EXITED
Definition n_network.h:346
@ NETW_ERROR
Definition n_network.h:346
@ NETW_EXIT_ASKED
Definition n_network.h:346
@ NETW_ENCRYPT_NONE
Definition n_network.h:346
a single part of a parsed multipart/form-data body
Definition n_network.h:900
parsed HTTP request for mock server callback
Definition n_network.h:1162
HTTP response to send from mock server callback.
Definition n_network.h:1171
mock HTTP server handle
Definition n_network.h:1178
Parsed proxy URL components.
Definition n_network.h:932
SSE connection handle.
Definition n_network.h:1137
SSE event received from server.
Definition n_network.h:1127
parsed URL components
Definition n_network.h:1030
WebSocket connection.
Definition n_network.h:1078
A single parsed WebSocket frame (RFC 6455).
Definition n_network.h:1087
WebSocket message.
Definition n_network.h:1071
Structure of a NETWORK.
Definition n_network.h:375
structure for splitting HTTP requests
Definition n_network.h:635
structure of a network pool
Definition n_network.h:625
N_STR * unzip_nstr(N_STR *src)
return an uncompressed version of src
Definition n_zlib.c:217
N_STR * zip_nstr(N_STR *src)
return a compressed version of src
Definition n_zlib.c:166
Base64 encoding and decoding functions using N_STR.
Hash functions and table.
Generic log system.
LZ4 block-compression handler.
static char * netstrerror(int code)
BSD style errno string NO WORKING ON REDHAT.
Definition n_network.c:700
#define NETW_CALL_RETRY(__retvar, __expression, __max_tries)
network-aware retry macro: retries on EINTR and EAGAIN/EWOULDBLOCK
Definition n_network.c:672
netw_sni_pick_cb pick
Definition n_network.c:1868
static size_t _netw_alpn_encode(const char *const *protos, size_t count, unsigned char *out, size_t out_cap)
Definition n_network.c:1907
static void _n_url_normalize_path(const char *path, char *out, size_t outsz)
normalize a path by removing "." and ".." segments (RFC 3986 style)
Definition n_network.c:8114
static int _ssl_use_pem(SSL *ssl, const char *key_pem, const char *cert_pem)
Definition n_network.c:1808
static char * mp_strndup(const char *s, size_t len)
Definition n_network.c:6584
static __thread int s_connect_err_next
Definition n_network.c:79
static int _netw_sni_servername_cb(SSL *ssl, int *al, void *arg)
Definition n_network.c:1984
#define N_WS_FRAME_MAX_PAYLOAD
upper bound on a single parsed WebSocket frame payload, to bound a proxy's reassembly buffer against ...
Definition n_network.c:7691
static ssize_t _ws_read(N_WS_CONN *conn, void *buf, size_t len)
read exactly len bytes from a WebSocket connection
Definition n_network.c:6964
static void mp_put(char *buf, size_t *pos, const void *src, size_t n)
Definition n_network.c:6792
__attribute__((unused))
Definition n_network.c:1288
static void netw_init_locks(void)
Definition n_network.c:1305
void netw_ssl_print_errors(SOCKET socket)
print the queued OpenSSL errors for a given socket
Definition n_network.c:1231
static ssize_t _sse_write(NETWORK *netw, const void *buf, size_t len)
write bytes to an SSE connection (SSL or plain)
Definition n_network.c:7484
#define _Thread_local
thread-local pre-connection error buffer (DNS, socket creation)
Definition n_network.c:75
static int _netw_ssl_server_defaults(SSL_CTX *ctx)
Definition n_network.c:1401
static void _n_parse_query_params(N_URL *u, const char *qs)
Definition n_network.c:8030
static int(* _netw_connect_abort_cb)(void *)
Optional connect-abort callback, or NULL.
Definition n_network.c:2392
static void _n_mock_parse_request(const char *buf, N_HTTP_REQUEST *req)
Parse a raw HTTP request buffer into an N_HTTP_REQUEST.
Definition n_network.c:7803
static ssize_t _ws_write(N_WS_CONN *conn, const void *buf, size_t len)
write bytes to a WebSocket connection (SSL or plain)
Definition n_network.c:6948
static int _netw_ssl_handshake_step(NETWORK *netw)
advance an in-flight TLS handshake by a single non-blocking step
Definition n_network.c:3112
NETWORK * netw_new(size_t send_list_limit, size_t recv_list_limit)
Return an empty allocated network ready to be netw_closed.
Definition n_network.c:714
static ssize_t _sse_read_byte(NETWORK *netw, char *ch, volatile int *stop_flag)
read one byte from an SSE connection (SSL or plain).
Definition n_network.c:7441
static int _netw_start_nonblock_connect(NETWORK *netw)
create a non-blocking socket for netw->link.connect_rp and start connect()
Definition n_network.c:2712
static SOCKET _proxy_tcp_connect(const char *host, int port)
Helper: connect a plain TCP socket to host:port.
Definition n_network.c:8363
long long g_netw_bytes_sent
Add a message to send in aimed NETWORK.
Definition n_network.c:4310
static void * _netw_connect_abort_ctx
Opaque context handed to _netw_connect_abort_cb on each poll.
Definition n_network.c:2394
static void mp_emit(char *buf, size_t *pos, LIST *parts, const char *dash)
Definition n_network.c:6805
static int n_http_inflate(const unsigned char *src, size_t len, int window_bits, N_STR **out)
Definition n_network.c:6481
static int OPENSSL_IS_INITIALIZED
Definition n_network.c:1329
static __thread int s_connect_err_count
Definition n_network.c:78
#define neterrno
get last socket error code, linux version
Definition n_network.c:683
static pthread_mutex_t * netw_ssl_lockarray
Definition n_network.c:1286
static void mp_part_free(void *ptr)
Definition n_network.c:6622
static void _netw_capture_connect_error(const char *fmt,...)
capture a pre-connection error (thread-local)
Definition n_network.c:95
#define NETW_CONNECT_ABORT_POLL_MS
Poll interval (milliseconds) at which an in-progress connect wakes to check the registered connect-ab...
Definition n_network.c:2389
static long mp_find(const unsigned char *hay, size_t hlen, const char *needle, size_t nlen)
Definition n_network.c:6572
char * get_in_addr(struct sockaddr *sa)
get sockaddr, IPv4 or IPv6
Definition n_network.c:828
static int _netw_timed_connect(NETWORK *netw, SOCKET sock, struct addrinfo *rp, int connect_timeout_ms)
Connect a socket, optionally bounding the attempt by a timeout.
Definition n_network.c:2411
static const char * mp_header_value(const char *block, size_t blen, const char *name, size_t *vlen)
Definition n_network.c:6642
void * user_data
Definition n_network.c:1869
static void _n_mock_request_clean(N_HTTP_REQUEST *req)
Free the contents of an N_HTTP_REQUEST (does not free the struct itself).
Definition n_network.c:7880
const char *const * alpn
Definition n_network.c:1870
static int _n_url_has_scheme(const char *s)
test whether a reference string begins with its own URI scheme
Definition n_network.c:8209
long long g_netw_bytes_recv
Definition n_network.c:4311
static char * mp_disp_param(const char *disp, size_t dlen, const char *param)
Definition n_network.c:6670
char * netw_get_openssl_error_string()
get the OpenSSL error string
Definition n_network.c:1200
static __thread char s_connect_errors[8][512]
Definition n_network.c:77
static int _netw_alpn_select_cb(SSL *ssl, const unsigned char **out, unsigned char *outlen, const unsigned char *in, unsigned int inlen, void *arg)
Definition n_network.c:1879
static void _netw_capture_error(NETWORK *netw, const char *fmt,...)
capture an error into a NETWORK handle's ring buffer
Definition n_network.c:83
static void mp_puts(char *buf, size_t *pos, const char *s)
Definition n_network.c:6799
static void netw_kill_locks(void)
Definition n_network.c:1319
static int netw_is_ip_literal(const char *host)
is host a numeric IP literal rather than a DNS name?
Definition n_network.c:3034
static void _netw_crypto_setup_failed(NETWORK *netw)
Definition n_network.c:1384
size_t alpn_count
Definition n_network.c:1871
Network Engine.
Network messages , serialization tools.
void n_reactor_notify_send(NETWORK *netw)
Producer-side wake-up after a netw_add_msg.
Definition n_reactor.c:1279
void n_reactor_close_netw_sync(NETWORK *netw)
Synchronously close a reactor-registered NETWORK from the game thread.
Definition n_reactor.c:1283
Single-threaded epoll reactor for n_network connections.
Timing utilities.
ZLIB compression handler.