52static char* _n_strndup(
const char* s,
size_t n) {
53 size_t len = strlen(s);
55 char* p = (
char*)malloc(len + 1);
62#define strndup _n_strndup
66#include <openssl/sha.h>
67#include <openssl/rand.h>
68#include <openssl/x509v3.h>
75#define _Thread_local __thread
144#if __BYTE_ORDER == __LITTLE_ENDIAN
145 if (
sizeof(
size_t) == 4) {
146 return (
size_t)htonl((uint32_t)value);
147 }
else if (
sizeof(
size_t) == 8) {
148 return ((
size_t)htonl((uint32_t)(value >> 32)) |
149 ((
size_t)htonl((uint32_t)value) << 32));
161#if __BYTE_ORDER == __LITTLE_ENDIAN
162 if (
sizeof(
size_t) == 4) {
163 return (
size_t)ntohl((uint32_t)value);
164 }
else if (
sizeof(
size_t) == 8) {
165 return ((
size_t)ntohl((uint32_t)(value >> 32)) |
166 ((
size_t)ntohl((uint32_t)value) << 32));
179char* wchar_to_char(
const wchar_t* pwchar) {
183 int currentCharIndex = 0;
184 char currentChar = (char)pwchar[currentCharIndex];
185 char* filePathC = NULL;
187 while (currentChar !=
'\0') {
189 currentChar = (char)pwchar[currentCharIndex];
192 const int charCount = currentCharIndex + 1;
195 Malloc(filePathC,
char, (
size_t)charCount);
198 for (
int i = 0; i < charCount; i++) {
200 char character = (char)pwchar[i];
202 *filePathC = character;
204 filePathC +=
sizeof(char);
208 filePathC -= (
sizeof(char) * (
size_t)charCount);
214#define NETW_CALL_RETRY(__retvar, __expression, __max_tries) \
216 int __nb_retries = 0; \
218 __retvar = (__expression); \
220 } while (__retvar == -1 && (WSAGetLastError() == WSAEINTR || WSAGetLastError() == WSAEWOULDBLOCK) && __nb_retries < (__max_tries)); \
221 if (__retvar == -1 && __nb_retries >= (__max_tries)) __retvar = -2; \
225#define neterrno WSAGetLastError()
232 FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
234 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
235 (LPWSTR)&ws, 0, NULL);
236 char* netstr = wchar_to_char(ws);
241#if __GNUC__ <= 6 && __GNUC_MINOR__ <= 3
277size_t strlcpy(
char* dst,
const char* src,
size_t siz) {
285 if ((*d++ = *s++) ==
'\0')
297 return (s - src - 1);
322static char* inet_ntop4(
const unsigned char* src,
char* dst, socklen_t size);
323static char* inet_ntop6(
const unsigned char* src,
char* dst, socklen_t size);
333char* inet_ntop(
int af,
const void* src,
char* dst, socklen_t size) {
336 return (inet_ntop4((
const unsigned char*)src, dst, size));
338 return (inet_ntop6((
const unsigned char*)src, dst, size));
356static char* inet_ntop4(
const unsigned char* src,
char* dst, socklen_t size) {
357 static const char fmt[] =
"%u.%u.%u.%u";
358 char tmp[
sizeof "255.255.255.255"];
361 l = snprintf(tmp,
sizeof(tmp), fmt, src[0], src[1], src[2], src[3]);
362 if (l <= 0 || (socklen_t)l >= size) {
365 strlcpy(dst, tmp, size);
375static char* inet_ntop6(
const unsigned char* src,
char* dst, socklen_t size) {
383 char tmp[
sizeof "ffff:ffff:ffff:ffff:ffff:ffff:255.255.255.255"], *tp;
388#define NS_IN6ADDRSZ 16
390 u_int words[NS_IN6ADDRSZ / NS_INT16SZ];
398 memset(words,
'\0',
sizeof words);
399 for (i = 0; i < NS_IN6ADDRSZ; i++)
400 words[i / 2] |= (src[i] << ((1 - (i % 2)) << 3));
405 for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
408 cur.base = i, cur.len = 1;
412 if (cur.base != -1) {
413 if (best.base == -1 || cur.len > best.len)
419 if (cur.base != -1) {
420 if (best.base == -1 || cur.len > best.len)
423 if (best.base != -1 && best.len < 2)
430 for (i = 0; i < (NS_IN6ADDRSZ / NS_INT16SZ); i++) {
432 if (best.base != -1 && i >= best.base &&
433 i < (best.base + best.len)) {
442 if (i == 6 && best.base == 0 && (best.len == 6 || (best.len == 7 && words[7] != 0x0001) || (best.len == 5 && words[5] == 0xffff))) {
443 if (!inet_ntop4(src + 12, tp,
sizeof tmp - (tp - tmp)))
448 tp += sprintf(tp,
"%x", words[i]);
451 if (best.base != -1 && (best.base + best.len) ==
452 (NS_IN6ADDRSZ / NS_INT16SZ))
459 if ((socklen_t)(tp - tmp) > size) {
488static int inet_pton4(
const char* src, u_char* dst);
489static int inet_pton6(
const char* src, u_char* dst);
498int inet_pton(
int af,
const char* src,
void* dst) {
501 return (inet_pton4(src, (
unsigned char*)dst));
503 return (inet_pton6(src, (
unsigned char*)dst));
520static int inet_pton4(
const char* src, u_char* dst) {
521 static const char digits[] =
"0123456789";
522 int saw_digit, octets, ch;
528 u_char tmp[NS_INADDRSZ] = {0}, *tp;
533 while ((ch = *src++) !=
'\0') {
536 if ((pch = strchr(digits, ch)) != NULL) {
537 u_int uiNew = *tp * 10 + (pch - digits);
539 if (saw_digit && *tp == 0)
549 }
else if (ch ==
'.' && saw_digit) {
559 memcpy(dst, tmp, NS_INADDRSZ);
576static int inet_pton6(
const char* src, u_char* dst) {
577 static const char xdigits_l[] =
"0123456789abcdef",
578 xdigits_u[] =
"0123456789ABCDEF";
579#define NS_IN6ADDRSZ 16
581 u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp;
583 int ch, seen_xdigits;
586 memset((tp = tmp),
'\0', NS_IN6ADDRSZ);
587 endp = tp + NS_IN6ADDRSZ;
596 while ((ch = *src++) !=
'\0') {
597 const char* xdigits :
const char* pch;
599 if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL)
600 pch = strchr((xdigits = xdigits_u), ch);
603 val |= (pch - xdigits);
604 if (++seen_xdigits > 4)
615 }
else if (*src ==
'\0') {
618 if (tp + NS_INT16SZ > endp)
620 *tp++ = (u_char)(val >> 8) & 0xff;
621 *tp++ = (u_char)val & 0xff;
626 if (ch ==
'.' && ((tp + NS_INADDRSZ) <= endp) &&
627 inet_pton4(curtok, tp) > 0) {
635 if (tp + NS_INT16SZ > endp)
637 *tp++ = (u_char)(val >> 8) & 0xff;
638 *tp++ = (u_char)val & 0xff;
640 if (colonp != NULL) {
645 const int n = tp - colonp;
650 for (i = 1; i <= n; i++) {
651 endp[-i] = colonp[n - i];
658 memcpy(dst, tmp, NS_IN6ADDRSZ);
666#include <sys/types.h>
670#define NETW_CALL_RETRY(__retvar, __expression, __max_tries) \
672 int __nb_retries = 0; \
674 __retvar = (__expression); \
676 } while (__retvar == -1 && (errno == EINTR || errno == EAGAIN || errno == EWOULDBLOCK) && __nb_retries < (__max_tries)); \
677 if (__retvar == -1 && __nb_retries >= (__max_tries)) __retvar = -2; \
681#define neterrno errno
701 return strdup(strerror(code));
735 memset(&
netw->
link.
raddr, 0,
sizeof(
struct sockaddr_storage));
770 n_log(
LOG_ERR,
"Error when creating receive list with %d item limit", recv_list_limit);
776 n_log(
LOG_ERR,
"Error when creating send list with %d item limit", send_list_limit);
827 return sa->sa_family == AF_INET
828 ? (
char*)&(((
struct sockaddr_in*)sa)->sin_addr)
829 : (
char*)&(((
struct sockaddr_in6*)sa)->sin6_addr);
840 int compiler_warning_suppressor = 0;
841#if !defined(__linux__) && !defined(__sun) && !defined(_AIX)
842 static WSADATA WSAdata;
843 static int WSA_IS_INITIALIZED = 0;
849 return WSA_IS_INITIALIZED;
853 if (WSA_IS_INITIALIZED == 1)
855 if ((WSAStartup(MAKEWORD(v1, v2), &WSAdata)) != 0) {
856 WSA_IS_INITIALIZED = 0;
859 WSA_IS_INITIALIZED = 1;
865 if (WSA_IS_INITIALIZED == 0)
867 if (WSACleanup() == 0) {
868 WSA_IS_INITIALIZED = 0;
874 compiler_warning_suppressor =
mode + v1 + v2;
875 (void)compiler_warning_suppressor;
876 compiler_warning_suppressor = TRUE;
877 return compiler_warning_suppressor;
916#if defined(__linux__) || defined(__sun)
920 if (flags & O_NONBLOCK) {
927 if (!(flags & O_NONBLOCK)) {
934 if (fcntl(
netw->
link.
sock, F_SETFL, is_blocking ? flags & ~O_NONBLOCK : flags | O_NONBLOCK) == -1) {
943 unsigned long int blocking = 1 - is_blocking;
944 int res = ioctlsocket(
netw->
link.
sock, (
long)FIONBIO, &blocking);
946 if (res != NO_ERROR) {
949 n_log(
LOG_ERR,
"ioctlsocket failed with error: %ld , neterrno: %s", res,
_str(errmsg));
977 if (setsockopt(
netw->
link.
sock, IPPROTO_TCP, TCP_NODELAY, (
const char*)&value,
sizeof(value)) == -1) {
991 if (setsockopt(
netw->
link.
sock, SOL_SOCKET, SO_SNDBUF, (
const char*)&value,
sizeof(value)) == -1) {
1005 if (setsockopt(
netw->
link.
sock, SOL_SOCKET, SO_RCVBUF, (
const char*)&value,
sizeof(value)) == -1) {
1018 if (setsockopt(
netw->
link.
sock, SOL_SOCKET, SO_REUSEADDR, (
char*)&value,
sizeof(value)) == -1) {
1045 }
else if (value == 0) {
1051 ling.l_linger = (u_short)value;
1053 ling.l_linger = value;
1057 if (setsockopt(
netw->
link.
sock, SOL_SOCKET, SO_LINGER, &ling,
sizeof(ling)) == -1) {
1066 if (setsockopt(
netw->
link.
sock, SOL_SOCKET, SO_LINGER, (
const char*)&ling,
sizeof(ling)) == -1) {
1084 if (setsockopt(
netw->
link.
sock, SOL_SOCKET, SO_RCVTIMEO, (
const char*)&tv,
sizeof tv) == -1) {
1094 if (setsockopt(
netw->
link.
sock, SOL_SOCKET, SO_RCVTIMEO, (
const char*)&value,
sizeof value) == -1) {
1114 if (setsockopt(
netw->
link.
sock, SOL_SOCKET, SO_SNDTIMEO, (
const char*)&tv,
sizeof tv) == -1) {
1124 if (setsockopt(
netw->
link.
sock, SOL_SOCKET, SO_SNDTIMEO, (
const char*)&value,
sizeof value) == -1) {
1149 case TCP_USER_TIMEOUT:
1151 if (setsockopt(
netw->
link.
sock, IPPROTO_TCP, TCP_USER_TIMEOUT, (
const char*)&value,
sizeof value) == -1) {
1162 if (setsockopt(
netw->
link.
sock, IPPROTO_TCP, TCP_QUICKACK, &value,
sizeof(value)) < 0) {
1173 if (setsockopt(
netw->
link.
sock, SOL_SOCKET, SO_KEEPALIVE, (
const char*)&value,
sizeof value) == -1) {
1186 n_log(
LOG_ERR,
"%d is not a supported setsockopt", optname);
1199 BIO* bio = BIO_new(BIO_s_mem());
1204 ERR_print_errors(bio);
1207 size_t len = (size_t)BIO_get_mem_data(bio, &buf);
1210 char* error_str = malloc(len + 1);
1212 memcpy(error_str, buf, len);
1213 error_str[len] =
'\0';
1230 unsigned long error = 0;
1231 while ((error = ERR_get_error())) {
1233#ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING
1240 if (ERR_GET_REASON(error) == SSL_R_UNEXPECTED_EOF_WHILE_READING)
1243 n_log(level,
"socket %d: %s", socket, ERR_reason_error_string(error));
1286__attribute__((unused))
static void netw_ssl_lock_callback(
int mode,
int type,
char* file,
int line) {
1289 if (
mode & CRYPTO_LOCK) {
1296__attribute__((unused))
static unsigned long thread_id(
void) {
1299 ret = (
unsigned long)pthread_self();
1306 size_t lock_count = (size_t)CRYPTO_num_locks();
1307 netw_ssl_lockarray = (pthread_mutex_t*)OPENSSL_malloc((
size_t)(lock_count *
sizeof(pthread_mutex_t)));
1309 for (i = 0; i < CRYPTO_num_locks(); i++) {
1313 CRYPTO_set_id_callback((
unsigned long (*)())thread_id);
1314 CRYPTO_set_locking_callback((
void (*)())netw_ssl_lock_callback);
1320 CRYPTO_set_locking_callback(NULL);
1321 for (i = 0; i < CRYPTO_num_locks(); i++)
1338 SSL_load_error_strings();
1340#if OPENSSL_VERSION_NUMBER < 0x10100000L
1341 ERR_load_BIO_strings();
1343 OpenSSL_add_all_algorithms();
1354 signal(SIGPIPE, SIG_IGN);
1388 char* tmp_key = NULL;
1389 char* tmp_cert = NULL;
1390 if (
key && strlen(
key) > 0) {
1391 tmp_key = strdup(
key);
1393 n_log(
LOG_ERR,
"strdup failed for key in netw_set_crypto");
1397 if (certificate && strlen(certificate) > 0) {
1398 tmp_cert = strdup(certificate);
1400 n_log(
LOG_ERR,
"strdup failed for certificate in netw_set_crypto");
1413 if (
key && certificate) {
1415#if OPENSSL_VERSION_NUMBER >= 0x10100000L
1432 SSL_CTX_set_mode(
netw->
ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1434#if OPENSSL_VERSION_NUMBER >= 0x10101000L
1449 SSL_CTX_set_num_tickets(
netw->
ctx, 0);
1453 if (SSL_CTX_load_verify_locations(
netw->
ctx, NULL,
"/etc/ssl/certs/") != 1) {
1458 if (SSL_CTX_use_certificate_file(
netw->
ctx, certificate, SSL_FILETYPE_PEM) <= 0) {
1462 if (SSL_CTX_use_PrivateKey_file(
netw->
ctx,
key, SSL_FILETYPE_PEM) <= 0) {
1491#if OPENSSL_VERSION_NUMBER >= 0x10100000L
1506 SSL_CTX_set_mode(
netw->
ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1508#if OPENSSL_VERSION_NUMBER >= 0x10101000L
1514 SSL_CTX_set_num_tickets(
netw->
ctx, 0);
1518 BIO* cert_bio = BIO_new_mem_buf(cert_pem, -1);
1520 n_log(
LOG_ERR,
"Failed to create BIO for certificate PEM");
1523 X509*
cert = PEM_read_bio_X509(cert_bio, NULL, NULL, NULL);
1530 if (SSL_CTX_use_certificate(
netw->
ctx,
cert) <= 0) {
1538 BIO* key_bio = BIO_new_mem_buf(key_pem, -1);
1543 EVP_PKEY* pkey = PEM_read_bio_PrivateKey(key_bio, NULL, NULL, NULL);
1550 if (SSL_CTX_use_PrivateKey(
netw->
ctx, pkey) <= 0) {
1551 EVP_PKEY_free(pkey);
1555 EVP_PKEY_free(pkey);
1558 if (!SSL_CTX_check_private_key(
netw->
ctx)) {
1559 n_log(
LOG_ERR,
"Private key does not match the certificate");
1591 if (SSL_CTX_use_certificate_chain_file(
netw->
ctx, certificate) <= 0) {
1592 n_log(
LOG_ERR,
"Failed to load certificate chain from %s", certificate);
1598 if (SSL_CTX_load_verify_locations(
netw->
ctx,
ca_file, NULL) != 1) {
1626 BIO* ca_bio = BIO_new_mem_buf(ca_pem, -1);
1632 X509_STORE* store = SSL_CTX_get_cert_store(
netw->
ctx);
1635 n_log(
LOG_ERR,
"Failed to get certificate store from SSL context");
1639 X509* ca_cert = NULL;
1641 while ((ca_cert = PEM_read_bio_X509(ca_bio, NULL, NULL, NULL)) != NULL) {
1642 if (X509_STORE_add_cert(store, ca_cert) != 1) {
1643 n_log(
LOG_ERR,
"Failed to add CA certificate to store");
1653 if (ca_loaded == 0) {
1654 n_log(
LOG_ERR,
"No CA certificates were loaded from PEM string");
1659 BIO* chain_bio = BIO_new_mem_buf(cert_pem, -1);
1662 X509* skip_cert = PEM_read_bio_X509(chain_bio, NULL, NULL, NULL);
1664 X509_free(skip_cert);
1667 X509* chain_cert = NULL;
1668 while ((chain_cert = PEM_read_bio_X509(chain_bio, NULL, NULL, NULL)) != NULL) {
1669 if (SSL_CTX_add_extra_chain_cert(
netw->
ctx, chain_cert) != 1) {
1671 X509_free(chain_cert);
1675 BIO_free(chain_bio);
1684static int _ssl_use_pem(SSL* ssl,
const char* key_pem,
const char* cert_pem) {
1685 BIO* cbio = BIO_new_mem_buf(cert_pem, -1);
1690 cert = PEM_read_bio_X509(cbio, NULL, NULL, NULL);
1694 if (SSL_use_certificate(ssl,
cert) == 1) {
1695 BIO* kbio = BIO_new_mem_buf(key_pem, -1);
1697 EVP_PKEY* pkey = PEM_read_bio_PrivateKey(kbio, NULL, NULL, NULL);
1700 if (SSL_use_PrivateKey(ssl, pkey) == 1 && SSL_check_private_key(ssl) == 1)
1702 EVP_PKEY_free(pkey);
1719 return SSL_get_servername(
netw->
ssl, TLSEXT_NAMETYPE_host_name);
1754 N_STR* cert_pem = NULL;
1755 N_STR* key_pem = NULL;
1759 return SSL_TLSEXT_ERR_OK;
1760 sni = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name);
1761 if (a->
pick(sni, &cert_pem, &key_pem, a->
user_data) != 0 || !cert_pem || !key_pem) {
1766 return SSL_TLSEXT_ERR_ALERT_FATAL;
1771 return ok ? SSL_TLSEXT_ERR_OK : SSL_TLSEXT_ERR_ALERT_FATAL;
1796#if OPENSSL_VERSION_NUMBER >= 0x10100000L
1806 SSL_CTX_set_mode(
netw->
ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
1813 SSL_CTX_set_tlsext_servername_arg(
netw->
ctx, &arg);
1827 if (SSL_accept(
netw->
ssl) <= 0) {
1872 n_log(
LOG_ERR,
"At least one of ca_file or ca_path must be specified");
1876 if (SSL_CTX_load_verify_locations(
netw->
ctx,
ca_file, ca_path) != 1) {
1897 SSL_CTX_set_verify(
netw->
ctx, SSL_VERIFY_PEER, NULL);
1899 SSL_CTX_set_verify(
netw->
ctx, SSL_VERIFY_NONE, NULL);
1923 STACK_OF(X509)* chain = NULL;
1924 X509_STORE* store = NULL;
1925 X509_STORE_CTX* store_ctx = NULL;
1930 if (errbuf && errsz > 0)
1937 if (errbuf && errsz > 0)
1938 snprintf(errbuf, errsz,
"no peer certificate");
1941 chain = SSL_get_peer_cert_chain(
netw->
ssl);
1943 store = X509_STORE_new();
1944 store_ctx = X509_STORE_CTX_new();
1945 if (!store || !store_ctx) {
1946 if (errbuf && errsz > 0)
1947 snprintf(errbuf, errsz,
"out of memory");
1950 X509_STORE_set_default_paths(store);
1951 if (X509_STORE_CTX_init(store_ctx, store,
cert, chain) != 1) {
1952 if (errbuf && errsz > 0)
1953 snprintf(errbuf, errsz,
"verify init failed");
1956 if (X509_verify_cert(store_ctx) == 1) {
1959 int verr = X509_STORE_CTX_get_error(store_ctx);
1960 if (errbuf && errsz > 0)
1961 snprintf(errbuf, errsz,
"%s", X509_verify_cert_error_string(verr));
1963 if (expected_host && expected_host[0]) {
1964 if (X509_check_host(
cert, expected_host, 0, 0, NULL) != 1) {
1966 if (errbuf && errsz > 0 && chain_ok)
1967 snprintf(errbuf, errsz,
"hostname mismatch for %s", expected_host);
1970 result = (chain_ok && host_ok) ? TRUE : FALSE;
1974 X509_STORE_CTX_free(store_ctx);
1976 X509_STORE_free(store);
1993 if (SSL_CTX_use_certificate_file(
netw->
ctx, cert_file, SSL_FILETYPE_PEM) != 1) {
1994 n_log(
LOG_ERR,
"Failed to load client certificate from %s", cert_file);
2000 const char* kf = key_file ? key_file : cert_file;
2001 if (SSL_CTX_use_PrivateKey_file(
netw->
ctx, kf, SSL_FILETYPE_PEM) != 1) {
2002 n_log(
LOG_ERR,
"Failed to load client private key from %s", kf);
2008 if (SSL_CTX_check_private_key(
netw->
ctx) != 1) {
2009 n_log(
LOG_ERR,
"Client certificate and private key do not match");
2022#define NETW_CONNECT_ABORT_POLL_MS 100
2045 if (connect_timeout_ms <= 0) {
2046 return connect(sock, rp->ai_addr, (socklen_t)rp->ai_addrlen);
2051 return connect(sock, rp->ai_addr, (socklen_t)rp->ai_addrlen);
2054 int rc = connect(sock, rp->ai_addr, (socklen_t)rp->ai_addrlen);
2060 int in_progress = 0;
2062 if (
neterrno == WSAEWOULDBLOCK ||
neterrno == WSAEINPROGRESS) in_progress = 1;
2064 if (
neterrno == EINPROGRESS) in_progress = 1;
2082 time_t remaining_us = (time_t)connect_timeout_ms * 1000;
2098 FD_SET(sock, &wset);
2100 FD_SET(sock, &eset);
2101 time_t wait_us = remaining_us;
2102 if (poll_us > 0 && wait_us > poll_us)
2105 tv.tv_sec = (long)(wait_us / 1000000);
2106 tv.tv_usec = (long)(wait_us % 1000000);
2108 int sel = select((
int)sock + 1, NULL, &wset, &eset, &tv);
2119 if (remaining_us <= 0)
2125 int interrupted = (
neterrno == WSAEINTR);
2127 int interrupted = (
neterrno == EINTR);
2135 if (remaining_us <= 0) {
2140 if (aborted || !connected) {
2146 socklen_t slen =
sizeof(so_error);
2147 if (getsockopt(sock, SOL_SOCKET, SO_ERROR, (
char*)&so_error, &slen) == -1 || so_error != 0) {
2193 (void)ssl_cert_file;
2194 int error = 0, net_status = 0;
2195 char* errmsg = NULL;
2199 n_log(
LOG_ERR,
"Unable to allocate (*netw), already existing. You must use empty NETWORK *structs.");
2204 (*netw) =
netw_new(send_list_limit, recv_list_limit);
2216 (*netw)->link.hints.ai_family = AF_INET;
2218 (*netw)->link.hints.ai_family = AF_INET6;
2221 (*netw)->link.hints.ai_family = AF_UNSPEC;
2224 (*netw)->link.hints.ai_socktype = SOCK_STREAM;
2225 (*netw)->link.hints.ai_protocol = IPPROTO_TCP;
2226 (*netw)->link.hints.ai_flags = AI_PASSIVE;
2227 (*netw)->link.hints.ai_canonname = NULL;
2228 (*netw)->link.hints.ai_next = NULL;
2240 error = getaddrinfo(host,
port, &(*netw)->link.hints, &(*netw)->link.rhost);
2243 n_log(
LOG_ERR,
"Error when resolving %s:%s getaddrinfo: %s", host,
port, gai_strerror(error));
2248 (*netw)->addr_infos_loaded = 1;
2249 (*netw)->connect_dns_usec = (
long long)
get_usec(&connect_timer);
2250 Malloc((*netw)->link.ip,
char, 64);
2254 struct addrinfo* rp = NULL;
2255 for (rp = (*netw)->link.rhost; rp != NULL; rp = rp->ai_next) {
2256 SOCKET sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
2257 if (sock == INVALID_SOCKET) {
2265 (*netw)->link.sock = sock;
2268 if (net_status == -1) {
2274 (*netw)->link.sock = INVALID_SOCKET;
2278 if (!inet_ntop(rp->ai_family,
get_in_addr(rp->ai_addr), (*netw)->link.ip, 64)) {
2290 n_log(
LOG_ERR,
"Couldn't connect to %s:%s : no address succeeded", host,
port);
2295 (*netw)->connect_tcp_usec = (
long long)
get_usec(&connect_timer);
2297 (*netw)->link.port = strdup(
port);
2300 if (ssl_key_file && ssl_cert_file) {
2310 (*netw)->ssl = SSL_new((*netw)->ctx);
2311 SSL_set_fd((*netw)->ssl, (
int)(*netw)->link.sock);
2314 if (SSL_connect((*netw)->ssl) <= 0) {
2321 n_log(
LOG_DEBUG,
"SSL-Connected to %s:%s", (*netw)->link.ip, (*netw)->link.port);
2323 _netw_capture_error(*
netw,
"%s:%s trying to configure SSL but application was compiled without SSL support !", (*netw)->
link.
ip, (*netw)->link.port);
2324 n_log(
LOG_ERR,
"%s:%s trying to configure SSL but application was compiled without SSL support !", (*netw)->link.ip, (*netw)->link.port);
2327 n_log(
LOG_DEBUG,
"Connected to %s:%s", (*netw)->link.ip, (*netw)->link.port);
2442#if OPENSSL_VERSION_NUMBER >= 0x10100000L
2457 SSL_CTX_set_mode(
netw->
ctx, SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
2459 SSL_CTX_set_default_verify_paths(
netw->
ctx);
2508 SSL_set_tlsext_host_name(
netw->
ssl, sni_hostname);
2510 if (SSL_connect(
netw->
ssl) <= 0) {
2512 unsigned long err = ERR_peek_error();
2515 err ? ERR_reason_error_string(err) :
"unknown error");
2538 if (thr_engine_status)
2632#if defined(__linux__)
2633 int outstanding = 0;
2637 for (
int it = 0; it < timeout; it += 100) {
2639 if (ioctl(fd, SIOCOUTQ, &outstanding) == -1) {
2641 n_log(
LOG_ERR,
"ioctl SIOCOUTQ returned -1: %s for socket %d", strerror(error), fd);
2665 int thr_engine_status = 0;
2688#if N_REACTOR_AVAILABLE
2689 if (__atomic_load_n(&(*netw)->reactor_registered, __ATOMIC_ACQUIRE)) {
2694 if ((*netw)->deplete_queues_timeout > 0) {
2696 int max_iterations = (*netw)->deplete_queues_timeout * 10;
2701 pthread_mutex_lock(&(*netw)->eventbolt);
2702 nb_running = (*netw)->nb_running_threads;
2703 pthread_mutex_unlock(&(*netw)->eventbolt);
2706 }
while (nb_running > 0 && it < max_iterations);
2708 if (it >= max_iterations && nb_running > 0) {
2709 n_log(
LOG_ERR,
"netw %d: %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);
2714 if ((*netw)->link.sock != INVALID_SOCKET) {
2715 int remaining =
deplete_send_buffer((
int)(*netw)->link.sock, (*netw)->deplete_socket_timeout);
2717 if (remaining > 0) {
2718 n_log(
LOG_ERR,
"socket %d (%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);
2735 pthread_mutex_lock(&(*netw)->eventbolt);
2736 nb_running = (*netw)->nb_running_threads;
2737 pthread_mutex_unlock(&(*netw)->eventbolt);
2739 if ((*netw)->link.sock != INVALID_SOCKET) {
2745 if (nb_running == 0) {
2746 int shutdown_res = SSL_shutdown((*netw)->ssl);
2747 if (shutdown_res == 0) {
2751 shutdown_res = SSL_shutdown((*netw)->ssl);
2753 if (shutdown_res < 0) {
2754 int err = SSL_get_error((*netw)->ssl, shutdown_res);
2755 if (err != SSL_ERROR_SYSCALL && err != SSL_ERROR_SSL) {
2762 n_log(
LOG_WARNING,
"netw %d: forcing bidirectional SSL_shutdown with %d threads still running", (*netw)->link.sock, nb_running);
2763 int shutdown_res = SSL_shutdown((*netw)->ssl);
2764 if (shutdown_res == 0) {
2766 shutdown_res = SSL_shutdown((*netw)->ssl);
2768 if (shutdown_res < 0) {
2769 int err = SSL_get_error((*netw)->ssl, shutdown_res);
2770 n_log(
LOG_ERR,
"netw %d: SSL_shutdown() failed with %d threads still running: %d", (*netw)->link.sock, nb_running, err);
2773 SSL_free((*netw)->ssl);
2776 n_log(
LOG_ERR,
"SSL handle of socket %d was already NULL", (*netw)->link.sock);
2778 n_log(
LOG_DEBUG,
"listening socket %d has no SSL handle (expected)", (*netw)->link.sock);
2785 shutdown((*netw)->link.sock, SHUT_WR);
2787 if ((*netw)->wait_close_timeout > 0) {
2790 char buffer[4096] =
"";
2791 int max_iters = (*netw)->wait_close_timeout * 10;
2792 for (
int it = 0; it < max_iters; it++) {
2796#pragma GCC diagnostic push
2797#pragma GCC diagnostic ignored "-Wsign-conversion"
2798 FD_SET((*netw)->link.sock, &rfds);
2799#pragma GCC diagnostic pop
2801 tv.tv_usec = 100000;
2802 int sel = select((
int)(*netw)->link.sock + 1, &rfds, NULL, NULL, &tv);
2804 ssize_t res = recv((*netw)->link.sock, buffer, 4096, NETFLAGS);
2809 if (error != ENOTCONN && error != EINTR && error != ECONNRESET
2811 && error != WSAENOTCONN && error != WSAECONNRESET && error != WSAESHUTDOWN && error != WSAEWOULDBLOCK && error != WSAEINTR
2815 n_log(
LOG_ERR,
"read returned error %d when closing socket %d (%s:%s): %s", error, (*netw)->link.sock,
_str((*netw)->link.ip), (*netw)->link.port,
_str(errmsg));
2818 n_log(
LOG_DEBUG,
"wait close: connection gracefully closed on socket %d (%s:%s)", (*netw)->link.sock,
_str((*netw)->link.ip), (*netw)->link.port);
2822 }
else if (sel < 0) {
2827 && error != WSAEINTR
2831 n_log(
LOG_ERR,
"select() error on socket %d during close: %s", (*netw)->link.sock,
_str(errmsg));
2841 closesocket((*netw)->link.sock);
2848 SSL_CTX_free((*netw)->ctx);
2859 if ((*netw)->link.rhost) {
2860 freeaddrinfo((*netw)->link.rhost);
2866 pthread_mutex_destroy(&(*netw)->recvbolt);
2867 pthread_mutex_destroy(&(*netw)->sendbolt);
2868 pthread_mutex_destroy(&(*netw)->eventbolt);
2869 sem_destroy(&(*netw)->send_blocker);
2889 char* errmsg = NULL;
2892 n_log(
LOG_ERR,
"Cannot use an allocated network. Please pass a NULL network to modify");
2904 (*netw)->link.port = strdup(
port);
2907 (*netw)->link.hints.ai_family = AF_INET;
2909 (*netw)->link.hints.ai_family = AF_INET6;
2912 (*netw)->link.hints.ai_family = AF_UNSPEC;
2915 (*netw)->link.hints.ai_flags = AI_PASSIVE;
2917 (*netw)->link.hints.ai_socktype = SOCK_STREAM;
2918 (*netw)->link.hints.ai_protocol = IPPROTO_TCP;
2919 (*netw)->link.hints.ai_canonname = NULL;
2920 (*netw)->link.hints.ai_next = NULL;
2922 error = getaddrinfo(
addr,
port, &(*netw)->link.hints, &(*netw)->link.rhost);
2929 (*netw)->addr_infos_loaded = 1;
2935 struct addrinfo* rp = NULL;
2936 for (rp = (*netw)->link.rhost; rp != NULL; rp = rp->ai_next) {
2937 (*netw)->link.sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
2938 if ((*netw)->link.sock == INVALID_SOCKET) {
2947 if (bind((*netw)->link.sock, rp->ai_addr, (socklen_t)rp->ai_addrlen) == 0) {
2955 if (!inet_ntop(rp->ai_family,
get_in_addr(rp->ai_addr), ip, 64)) {
2962 (*netw)->link.ip = ip;
2970 closesocket((*netw)->link.sock);
2981 (*netw)->nb_pending = nbpending;
2982 if (listen((*netw)->link.sock, (*netw)->nb_pending) != 0) {
3009 char* errmsg = NULL;
3012 n_log(
LOG_ERR,
"Cannot use an allocated network. Please pass a NULL network to modify");
3024 (*netw)->link.port = strdup(
port);
3029 (*netw)->link.hints.ai_family = AF_INET;
3031 (*netw)->link.hints.ai_family = AF_INET6;
3033 (*netw)->link.hints.ai_family = AF_UNSPEC;
3036 (*netw)->link.hints.ai_flags = AI_PASSIVE;
3038 (*netw)->link.hints.ai_socktype = SOCK_DGRAM;
3039 (*netw)->link.hints.ai_protocol = IPPROTO_UDP;
3040 (*netw)->link.hints.ai_canonname = NULL;
3041 (*netw)->link.hints.ai_next = NULL;
3043 error = getaddrinfo(
addr,
port, &(*netw)->link.hints, &(*netw)->link.rhost);
3050 (*netw)->addr_infos_loaded = 1;
3052 struct addrinfo* rp = NULL;
3053 for (rp = (*netw)->link.rhost; rp != NULL; rp = rp->ai_next) {
3054 (*netw)->link.sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
3055 if ((*netw)->link.sock == INVALID_SOCKET) {
3058 n_log(
LOG_ERR,
"Error while trying to make a UDP socket: %s",
_str(errmsg));
3063 if (bind((*netw)->link.sock, rp->ai_addr, (socklen_t)rp->ai_addrlen) == 0) {
3071 if (!inet_ntop(rp->ai_family,
get_in_addr(rp->ai_addr), ip, 64)) {
3077 (*netw)->link.ip = ip;
3083 n_log(
LOG_ERR,
"Error from bind() on UDP port %s neterrno: %s",
port, errmsg);
3085 closesocket((*netw)->link.sock);
3115 char* errmsg = NULL;
3118 n_log(
LOG_ERR,
"Unable to allocate (*netw), already existing. You must use empty NETWORK *structs.");
3134 (*netw)->link.hints.ai_family = AF_INET;
3136 (*netw)->link.hints.ai_family = AF_INET6;
3138 (*netw)->link.hints.ai_family = AF_UNSPEC;
3141 (*netw)->link.hints.ai_socktype = SOCK_DGRAM;
3142 (*netw)->link.hints.ai_protocol = IPPROTO_UDP;
3143 (*netw)->link.hints.ai_flags = AI_PASSIVE;
3144 (*netw)->link.hints.ai_canonname = NULL;
3145 (*netw)->link.hints.ai_next = NULL;
3147 error = getaddrinfo(host,
port, &(*netw)->link.hints, &(*netw)->link.rhost);
3150 n_log(
LOG_ERR,
"Error when resolving %s:%s getaddrinfo: %s", host,
port, gai_strerror(error));
3154 (*netw)->addr_infos_loaded = 1;
3155 Malloc((*netw)->link.ip,
char, 64);
3158 struct addrinfo* rp = NULL;
3159 for (rp = (*netw)->link.rhost; rp != NULL; rp = rp->ai_next) {
3160 SOCKET sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
3161 if (sock == INVALID_SOCKET) {
3164 n_log(
LOG_ERR,
"Error while trying to make a UDP socket: %s",
_str(errmsg));
3169 (*netw)->link.sock = sock;
3172 if (connect(sock, rp->ai_addr, (socklen_t)rp->ai_addrlen) == -1) {
3178 (*netw)->link.sock = INVALID_SOCKET;
3181 if (!inet_ntop(rp->ai_family,
get_in_addr(rp->ai_addr), (*netw)->link.ip, 64)) {
3192 n_log(
LOG_ERR,
"Couldn't connect UDP to %s:%s : no address succeeded", host,
port);
3197 (*netw)->link.port = strdup(
port);
3206 n_log(
LOG_DEBUG,
"UDP-Connected to %s:%s", (*netw)->link.ip, (*netw)->link.port);
3224 char* errmsg = NULL;
3232 ssize_t bs = send(s, buf, NETW_BUFLEN_CAST(n), NETFLAGS);
3235 if (error == ECONNRESET || error == ENOTCONN
3237 || error == WSAECONNRESET || error == WSAENOTCONN
3271 ssize_t br = recv(s, buf, NETW_BUFLEN_CAST(n), NETFLAGS);
3276 n_log(
LOG_ERR,
"UDP socket %d recv returned %zd, error: %s", s, br,
_str(errmsg));
3306 ssize_t bs = sendto(
netw->
link.
sock, buf, NETW_BUFLEN_CAST(n), NETFLAGS, dest_addr, dest_len);
3337 ssize_t br = recvfrom(
netw->
link.
sock, buf, NETW_BUFLEN_CAST(n), NETFLAGS, src_addr, src_len);
3359 SOCKET tmp = INVALID_SOCKET;
3361 char* errmsg = NULL;
3363#if defined(__linux__) || defined(__sun) || defined(_AIX)
3364 socklen_t sin_size = 0;
3384 int secs = blocking / 1000;
3385 int usecs = (blocking % 1000) * 1000;
3386 struct timeval select_timeout = {secs, usecs};
3389 FD_ZERO(&accept_set);
3390#pragma GCC diagnostic push
3391#pragma GCC diagnostic ignored "-Wsign-conversion"
3392 FD_SET(from->
link.
sock, &accept_set);
3393#pragma GCC diagnostic pop
3395 int ret = select((
int)(from->
link.
sock + 1), &accept_set, NULL, NULL, &select_timeout);
3401 n_log(
LOG_DEBUG,
"error on select with timeout %ds (%d.%ds), neterrno: %s", blocking, secs, usecs,
_str(errmsg));
3405 }
else if (ret == 0) {
3411#pragma GCC diagnostic push
3412#pragma GCC diagnostic ignored "-Wsign-conversion"
3413 if (FD_ISSET(from->
link.
sock, &accept_set)) {
3414#pragma GCC diagnostic pop
3417 if (tmp == INVALID_SOCKET) {
3434 }
else if (blocking == -1) {
3442 if (tmp == INVALID_SOCKET) {
3443 if (error != EINTR && error != EAGAIN
3445 && error != WSAEWOULDBLOCK
3463 if (tmp == INVALID_SOCKET) {
3521 if (SSL_accept(
netw->
ssl) <= 0) {
3576 n_log(
LOG_ERR,
"Empty messages are not supported. msg(%p)->length=%zu", msg, msg->
length);
3588 long long bytes_for_counter = (
long long)msg->
written;
3613#if N_REACTOR_AVAILABLE
3690 unsigned int secs = 0;
3691 unsigned int usecs = 0;
3696 if (refresh > 999999) {
3697 secs = refresh / 1000000;
3698 usecs = refresh % 1000000;
3704 n_log(
LOG_DEBUG,
"wait from socket %d, refresh: %zu usec (%zu secs, %zu usecs), timeout %zu usec",
netw->
link.
sock, refresh, secs, usecs, timeout);
3713 if (timed >= refresh)
3715 if (timed == 0 || timed < refresh) {
3784 ssize_t net_status = 0;
3799 int message_sent = 0;
3800 while (message_sent == 0 && !
DONE) {
3810 memcpy(nboct, &nboctet,
sizeof(uint32_t));
3827 if (ptr->
written <= UINT_MAX - 2 *
sizeof(uint32_t)) {
3836 uint32_t pkt_state = state;
3839 N_STR* zipped = NULL;
3840 uint32_t flag_bit = 0;
3848 if (zipped && zipped->
written > 0 &&
3854 pkt_state |= flag_bit;
3855 }
else if (zipped) {
3874 size_t frame_len = 2 *
sizeof(uint32_t) + ptr->
written;
3876 Malloc(frame,
char, frame_len);
3878 nboctet = htonl(pkt_state);
3879 memcpy(frame, &nboctet,
sizeof(uint32_t));
3880 nboctet = htonl((uint32_t)ptr->
written);
3881 memcpy(frame +
sizeof(uint32_t), &nboctet,
sizeof(uint32_t));
3882 memcpy(frame + 2 *
sizeof(uint32_t), ptr->
data, ptr->
written);
3893 n_log(
LOG_ERR,
"could not allocate %zu byte send frame, packet dropped", frame_len);
3902 n_log(
LOG_ERR,
"discarded packet of size %zu which is greater than %" PRIu32, ptr->
written, UINT_MAX);
3925 }
else if (
DONE == 2) {
3928 }
else if (
DONE == 3)
3930 else if (
DONE == 4) {
3933 }
else if (
DONE == 5) {
3954#if !defined(__linux__)
3966 ssize_t net_status = 0;
3974 N_STR* recvdmsg = NULL;
3992 if (net_status < 0) {
4001 memcpy(&nboctet, nboct,
sizeof(uint32_t));
4002 tmpstate = ntohl(nboctet);
4008 uint32_t pkt_state = tmpstate;
4016 if (net_status < 0) {
4019 memcpy(&nboctet, nboct,
sizeof(uint32_t));
4020 tmpstate = ntohl(nboctet);
4029 if (!recvdmsg->
data) {
4033 recvdmsg->
length = nboctet + 1;
4038 if (net_status < 0) {
4051 if (want_zlib || want_lz4) {
4052 recvdmsg->
data[nboctet] =
'\0';
4053 N_STR* plain = want_lz4
4061 "socket %d : failed to decompress payload (%" PRIu32
" bytes, codec=%s); dropping",
4063 want_lz4 ?
"lz4" :
"zlib");
4087 }
else if (
DONE == 2) {
4090 }
else if (
DONE == 3) {
4093 }
else if (
DONE == 4) {
4096 }
else if (
DONE == 5) {
4099 }
else if (
DONE == 6) {
4120#if !defined(__linux__)
4133 int thr_engine_status = 0;
4141 n_log(
LOG_ERR,
"Thread engine status already stopped for network %p",
netw);
4148 for (
int it = 0; it < 10; it++) {
4177 char* errmsg = NULL;
4185 char* tmp_buf = buf;
4196 }
else if (error == ECONNRESET || error == ENOTCONN || error == EPIPE
4198 || error == WSAECONNRESET || error == WSAENOTCONN || error == WSAESHUTDOWN
4203 }
else if (bs == -1) {
4210 }
else if (bs == -2) {
4215 }
else if (bs == 0) {
4238 char* errmsg = NULL;
4240#if defined(NETWORK_DISABLE_ZERO_LENGTH_RECV) && (NETWORK_DISABLE_ZERO_LENGTH_RECV == TRUE)
4248 char* tmp_buf = buf;
4259 }
else if (br == 0) {
4263 }
else if (error == ECONNRESET || error == ENOTCONN
4265 || error == WSAECONNRESET || error == WSAENOTCONN || error == WSAESHUTDOWN
4271 }
else if (br == -1) {
4278 }
else if (br == -2) {
4309 ssize_t bs = send(s, buf, NETW_BUFLEN_CAST(n), NETFLAGS);
4311 if (bs > 0)
return bs;
4319 || error == WSAEINTR
4323 if (error == EAGAIN || error == EWOULDBLOCK
4325 || error == WSAEWOULDBLOCK
4329 if (error == ECONNRESET || error == ENOTCONN || error == EPIPE
4331 || error == WSAECONNRESET || error == WSAENOTCONN || error == WSAESHUTDOWN
4365 ssize_t br = recv(s, buf, NETW_BUFLEN_CAST(n), NETFLAGS);
4367 if (br > 0)
return br;
4375 || error == WSAEINTR
4379 if (error == EAGAIN || error == EWOULDBLOCK
4381 || error == WSAEWOULDBLOCK
4385 if (error == ECONNRESET || error == ENOTCONN
4387 || error == WSAECONNRESET || error == WSAENOTCONN
4420 char* errmsg = NULL;
4431#if OPENSSL_VERSION_NUMBER < 0x1010107fL
4432 int status = SSL_write(ssl, buf, (
int)(n - bcount));
4433 bs = (status > 0) ? (
size_t)status : 0;
4435 int status = SSL_write_ex(ssl, buf, (
size_t)(n - bcount), &bs);
4439 bcount += (ssize_t)bs;
4442 int ssl_error = SSL_get_error(ssl, status);
4443 if (ssl_error == SSL_ERROR_WANT_READ || ssl_error == SSL_ERROR_WANT_WRITE) {
4462 if (ssl_error == SSL_ERROR_ZERO_RETURN ||
4463 (ssl_error == SSL_ERROR_SYSCALL &&
4464 (error == 0 || error == EPIPE || error == ECONNRESET || error == ENOTCONN
4466 || error == WSAECONNRESET || error == WSAENOTCONN || error == WSAESHUTDOWN
4469 n_log(
LOG_DEBUG,
"socket %d disconnected during SSL_write !", s);
4473 switch (ssl_error) {
4474 case SSL_ERROR_SYSCALL:
4482 n_log(
LOG_ERR,
"socket %d SSL_write returned %zu, error: %s", s, bs, ERR_reason_error_string(ERR_get_error()));
4487 n_log(
LOG_ERR,
"socket %d SSL_write returned %zu, errno: %s", s, bs,
_str(errmsg));
4514 char* errmsg = NULL;
4522 while (bcount < n) {
4525#if OPENSSL_VERSION_NUMBER < 0x10101000L
4526 int status = SSL_read(ssl, buf, (
int)(n - bcount));
4527 br = (status > 0) ? (
size_t)status : 0;
4529 int status = SSL_read_ex(ssl, buf, (
size_t)(n - bcount), &br);
4533 bcount += (ssize_t)br;
4536 int ssl_error = SSL_get_error(ssl, status);
4537 if (ssl_error == SSL_ERROR_WANT_READ || ssl_error == SSL_ERROR_WANT_WRITE) {
4553 if (ssl_error == SSL_ERROR_ZERO_RETURN) {
4555 n_log(
LOG_DEBUG,
"socket %d : TLS session closed by peer (close_notify)", s);
4558 if (ssl_error == SSL_ERROR_SYSCALL && (error == 0 || error == ECONNRESET || error == ENOTCONN
4560 || error == WSAECONNRESET || error == WSAENOTCONN || error == WSAESHUTDOWN
4564 n_log(
LOG_DEBUG,
"socket %d : peer closed connection (TLS, no close_notify)", s);
4571 unsigned long ssl_reason = ERR_get_error();
4572#ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING
4573 if (ssl_error == SSL_ERROR_SSL && ERR_GET_REASON(ssl_reason) == SSL_R_UNEXPECTED_EOF_WHILE_READING) {
4577 n_log(
LOG_DEBUG,
"socket %d : peer closed connection (TLS unexpected EOF)", s);
4582 switch (ssl_error) {
4583 case SSL_ERROR_SYSCALL:
4591 n_log(
LOG_ERR,
"socket %d SSL_read protocol error: %s", s,
_str((
char*)ERR_reason_error_string(ssl_reason)));
4596 n_log(
LOG_ERR,
"socket %d SSL_read returned %zu, errno: %s", s, br,
_str(errmsg));
4635#if OPENSSL_VERSION_NUMBER < 0x1010107fL
4636 int status = SSL_write(ssl, buf, (
int)n);
4637 bs = (status > 0) ? (
size_t)status : 0;
4639 int status = SSL_write_ex(ssl, buf, (
size_t)n, &bs);
4642 if (status > 0)
return (ssize_t)bs;
4644 int ssl_error = SSL_get_error(ssl, status);
4645 switch (ssl_error) {
4646 case SSL_ERROR_WANT_READ:
4648 case SSL_ERROR_WANT_WRITE:
4650 case SSL_ERROR_ZERO_RETURN:
4653 case SSL_ERROR_SYSCALL:
4654 if (error == 0 || error == ECONNRESET || error == EPIPE || error == ENOTCONN
4656 || error == WSAECONNRESET || error == WSAENOTCONN
4659 n_log(
LOG_DEBUG,
"socket %d SSL_write syscall: connection closed by peer", s);
4662 if (error == EINTR || error == EAGAIN || error == EWOULDBLOCK
4664 || error == WSAEINTR || error == WSAEWOULDBLOCK
4671 n_log(
LOG_ERR,
"socket %d SSL_write_once syscall error: %s", s,
_str(errmsg));
4677 n_log(
LOG_ERR,
"socket %d SSL_write_once error: %s", s, ERR_reason_error_string(ERR_get_error()));
4709#if OPENSSL_VERSION_NUMBER < 0x10101000L
4710 int status = SSL_read(ssl, buf, (
int)n);
4711 br = (status > 0) ? (
size_t)status : 0;
4713 int status = SSL_read_ex(ssl, buf, (
size_t)n, &br);
4716 if (status > 0)
return (ssize_t)br;
4718 int ssl_error = SSL_get_error(ssl, status);
4719 switch (ssl_error) {
4720 case SSL_ERROR_WANT_READ:
4722 case SSL_ERROR_WANT_WRITE:
4724 case SSL_ERROR_ZERO_RETURN:
4727 case SSL_ERROR_SYSCALL:
4728 if (error == 0 || error == ECONNRESET || error == ENOTCONN
4730 || error == WSAECONNRESET || error == WSAENOTCONN
4733 n_log(
LOG_DEBUG,
"socket %d SSL_read syscall: connection closed by peer", s);
4736 if (error == EINTR || error == EAGAIN || error == EWOULDBLOCK
4738 || error == WSAEINTR || error == WSAEWOULDBLOCK
4745 n_log(
LOG_ERR,
"socket %d SSL_read_once syscall error: %s", s,
_str(errmsg));
4754 unsigned long ssl_reason = ERR_get_error();
4755#ifdef SSL_R_UNEXPECTED_EOF_WHILE_READING
4756 if (ssl_error == SSL_ERROR_SSL && ERR_GET_REASON(ssl_reason) == SSL_R_UNEXPECTED_EOF_WHILE_READING) {
4757 n_log(
LOG_DEBUG,
"socket %d : peer closed connection (TLS unexpected EOF)", s);
4762 n_log(
LOG_ERR,
"socket %d SSL_read_once error: %s", s,
_str((
char*)ERR_reason_error_string(ssl_reason)));
4782 char* errmsg = NULL;
4798 bs = send(s, ptr, NETW_BUFLEN_CAST(
HEAD_SIZE - bcount), NETFLAGS);
4806 n_log(
LOG_ERR,
"Socket %d sending Error %d when sending head size, neterrno: %s", s, bs,
_str(errmsg));
4817 bs = send(s, ptr, NETW_BUFLEN_CAST(
HEAD_CODE - bcount), NETFLAGS);
4824 n_log(
LOG_ERR,
"Socket %d sending Error %d when sending head code, neterrno: %s", s, bs,
_str(errmsg));
4834 bs = send(s, buf, NETW_BUFLEN_CAST(n - bcount), NETFLAGS);
4842 n_log(
LOG_ERR,
"Socket %d sending Error %d when sending message of size %d, neterrno: %s", s, bs, n,
_str(errmsg));
4862 long int tmpnb = 0, size = 0;
4866 char* errmsg = NULL;
4876 br = recv(s, ptr, NETW_BUFLEN_CAST(
HEAD_SIZE - bcount), NETFLAGS);
4890 tmpnb = strtol(head, NULL, 10);
4891 if (tmpnb == LONG_MIN || tmpnb == LONG_MAX) {
4892 n_log(
LOG_ERR,
"Size received ( %ld ) can not be determined on socket %d", tmpnb, s);
4903 br = recv(s, ptr, NETW_BUFLEN_CAST(
HEAD_CODE - bcount), NETFLAGS);
4911 n_log(
LOG_ERR,
"Socket %d receive %d Error , neterrno: %s", s, br,
_str(errmsg));
4917 tmpnb = strtol(code, NULL, 10);
4918 if (tmpnb <= INT_MIN || tmpnb >= INT_MAX) {
4919 n_log(
LOG_ERR,
"Code received ( %ld ) too big or too little to be valid code on socket %d", tmpnb, s);
4923 (*_code) = (int)tmpnb;
4930 Malloc((*buf),
char, (
size_t)(size + 1));
4938 while (bcount < size) {
4940 br = recv(s, ptr, NETW_BUFLEN_CAST(size - bcount), NETFLAGS);
4948 n_log(
LOG_ERR,
"Socket %d receive %d Error neterrno: %s", s, br,
_str(errmsg));
5003 __n_assert(netw_pool && (*netw_pool),
return FALSE);
5006 if ((*netw_pool)->pool)
5008 unlock((*netw_pool)->rwlock);
5174 N_STR* tmpstr = NULL;
5193 N_STR* tmpstr = NULL;
5217 N_STR* tmpstr = NULL;
5239 N_STR* tmpstr = NULL;
5259 N_STR* tmpstr = NULL;
5277 N_STR* tmpstr = NULL;
5294 size_t encoded_size = 0;
5296 for (
size_t i = 0; i < len; i++) {
5297 unsigned char c = (
unsigned char)str[i];
5298 if (isalnum(c) || c ==
'-' || c ==
'_' || c ==
'.' || c ==
'~') {
5305 return encoded_size;
5317 static const char* hex =
"0123456789ABCDEF";
5319 char* encoded = (
char*)malloc(encoded_size + 1);
5325 char* pbuf = encoded;
5327 for (
size_t i = 0; i < len; i++) {
5328 unsigned char c = (
unsigned char)str[i];
5329 if (isalnum(c) || c ==
'-' || c ==
'_' || c ==
'.' || c ==
'~') {
5333 *pbuf++ = hex[c >> 4];
5334 *pbuf++ = hex[c & 0xF];
5350 const char* space = strchr(request,
' ');
5352 if (space == NULL) {
5358 size_t method_length = (size_t)(space - request);
5361 char* method = (
char*)malloc(method_length + 1);
5363 if (method == NULL) {
5369 strncpy(method, request, method_length);
5370 method[method_length] =
'\0';
5393 const char* content_type_header = strstr(request,
"Content-Type:");
5394 if (content_type_header) {
5395 const char* start = content_type_header + strlen(
"Content-Type: ");
5396 const char* end = strstr(start,
"\r\n");
5398 size_t length = (size_t)(end - start);
5399 if (length > 255) length = 255;
5409 const char* content_length_header = strstr(request,
"Content-Length:");
5410 if (content_length_header) {
5411 const char* start = content_length_header + strlen(
"Content-Length: ");
5413 unsigned long tmp_cl = strtoul(start, NULL, 10);
5417#if ULONG_MAX > SIZE_MAX
5418 if (error == ERANGE || tmp_cl > SIZE_MAX) {
5420 if (error == ERANGE) {
5422 n_log(
LOG_ERR,
"could not get content_length for request %p, returned %s", request, strerror(error));
5430 const char* body_start = strstr(request,
"\r\n\r\n");
5444 info.
type = request_type;
5467 __n_assert(request && strlen(request) > 0,
return FALSE);
5471 strncpy(url,
"/", size - 1);
5472 url[size - 1] =
'\0';
5475 const char* first_space = strchr(request,
' ');
5481 const char* second_space = strchr(first_space + 1,
' ');
5482 if (!second_space) {
5487 size_t len = (size_t)(second_space - first_space - 1);
5492 strncpy(url, first_space + 1, len);
5505 char* decoded = malloc(strlen(str) + 1);
5511 if (isxdigit((
unsigned char)str[1]) && isxdigit((
unsigned char)str[2])) {
5513 if (sscanf(str + 1,
"%2x", &value) >= 1) {
5517 n_log(
LOG_ERR,
"sscanf could not parse char *str (%p) for a %%2x", str);
5524 }
else if (*str ==
'+') {
5544 char* data = strdup(post_data);
5551 while (pair != NULL) {
5553 char* ampersand_pos = strchr(pair,
'&');
5556 if (ampersand_pos != NULL) {
5557 *ampersand_pos =
'\0';
5561 char* equal_pos = strchr(pair,
'=');
5562 if (equal_pos != NULL) {
5564 const char*
key = pair;
5565 const char* value = equal_pos + 1;
5571 free(decoded_value);
5574 pair = (ampersand_pos != NULL) ? (ampersand_pos + 1) : NULL;
5578 return post_data_table;
5590 char url_copy[1024];
5591 strncpy(url_copy, url,
sizeof(url_copy) - 1);
5592 url_copy[
sizeof(url_copy) - 1] =
'\0';
5595 char* query_start = strchr(url_copy,
'?');
5597 *query_start =
'\0';
5601 const char* ext = strrchr(url_copy,
'.');
5609 if (strcmp(ext,
".html") == 0 || strcmp(ext,
".htm") == 0) {
5611 }
else if (strcmp(ext,
".txt") == 0) {
5612 return "text/plain";
5613 }
else if (strcmp(ext,
".jpg") == 0 || strcmp(ext,
".jpeg") == 0) {
5614 return "image/jpeg";
5615 }
else if (strcmp(ext,
".png") == 0) {
5617 }
else if (strcmp(ext,
".gif") == 0) {
5619 }
else if (strcmp(ext,
".css") == 0) {
5621 }
else if (strcmp(ext,
".js") == 0) {
5622 return "application/javascript";
5623 }
else if (strcmp(ext,
".json") == 0) {
5624 return "application/json";
5625 }
else if (strcmp(ext,
".xml") == 0) {
5626 return "application/xml";
5627 }
else if (strcmp(ext,
".pdf") == 0) {
5628 return "application/pdf";
5629 }
else if (strcmp(ext,
".zip") == 0) {
5630 return "application/zip";
5631 }
else if (strcmp(ext,
".mp4") == 0) {
5633 }
else if (strcmp(ext,
".mp3") == 0) {
5634 return "audio/mpeg";
5635 }
else if (strcmp(ext,
".wav") == 0) {
5637 }
else if (strcmp(ext,
".ogg") == 0) {
5651 switch (status_code) {
5655 return "No Content";
5657 return "Not Modified";
5661 return "Internal Server Error";
5669 if (status_code < 100 || status_code > 599)
5671 return status_code / 100;
5699 size_t alloc, total = 0;
5703 memset(&strm, 0,
sizeof(strm));
5704 if (inflateInit2(&strm, window_bits) != Z_OK)
5709 buf = malloc(alloc);
5714 strm.next_in = (Bytef*)src;
5715 strm.avail_in = (uInt)len;
5717 if (total >= alloc - 1) {
5720 tmp = realloc(buf, alloc);
5728 strm.next_out = (Bytef*)(buf + total);
5729 strm.avail_out = (uInt)(alloc - total - 1);
5730 ret = inflate(&strm, Z_NO_FLUSH);
5731 if (ret == Z_STREAM_ERROR || ret == Z_DATA_ERROR || ret == Z_MEM_ERROR || ret == Z_NEED_DICT) {
5736 total = alloc - 1 - strm.avail_out;
5737 }
while (ret != Z_STREAM_END);
5753 int is_gzip = 0, is_deflate = 0;
5761 for (i = 0; i <
sizeof(enc) - 1 && encoding[i]; i++)
5762 enc[i] = (
char)tolower((
unsigned char)encoding[i]);
5765 if (strstr(enc,
"gzip"))
5767 else if (strstr(enc,
"deflate"))
5771 if ((!is_gzip && !is_deflate) || !body->
data || body->
written == 0) {
5788static long mp_find(
const unsigned char* hay,
size_t hlen,
const char* needle,
size_t nlen) {
5790 if (nlen == 0 || nlen > hlen)
5792 for (i = 0; i + nlen <= hlen; i++) {
5793 if (hay[i] == (
unsigned char)needle[0] && memcmp(hay + i, needle, nlen) == 0)
5802 Malloc(r,
char, len + 1);
5814 if (!content_type || !out || outsz == 0)
5817 for (p = content_type; *p; p++) {
5818 if (strncasecmp(p,
"boundary=", 9) == 0)
5827 while (*p && *p !=
'"' && i + 1 < outsz)
5830 while (*p && *p !=
';' && *p !=
' ' && *p !=
'\r' && *p !=
'\n' && i + 1 < outsz)
5834 return i > 0 ? 0 : -1;
5851 if (parts && *parts)
5857static const char*
mp_header_value(
const char* block,
size_t blen,
const char* name,
size_t* vlen) {
5858 size_t nlen = strlen(name);
5862 size_t line_end = i;
5863 while (line_end < blen && block[line_end] !=
'\n')
5866 if (line_end - i > nlen + 1 && strncasecmp(block + i, name, nlen) == 0 && block[i + nlen] ==
':') {
5867 const char* v = block + i + nlen + 1;
5868 size_t vl = line_end - (i + nlen + 1);
5869 while (vl > 0 && (*v ==
' ' || *v ==
'\t')) {
5873 while (vl > 0 && (v[vl - 1] ==
'\r' || v[vl - 1] ==
' ' || v[vl - 1] ==
'\t'))
5888 snprintf(
key,
sizeof(
key),
"%s=", param);
5890 for (i = 0; i + klen <= dlen; i++) {
5891 if (strncasecmp(disp + i,
key, klen) == 0) {
5892 const char* v = disp + i + klen;
5893 size_t avail = dlen - (i + klen);
5895 if (avail > 0 && *v ==
'"') {
5898 while (j < avail && v[j] !=
'"')
5901 while (j < avail && v[j] !=
';' && v[j] !=
' ')
5912 char crlf_dash[260];
5913 const unsigned char* data;
5914 size_t len, dlen, cdlen, cursor;
5918 if (!body || !body->
data || !boundary || !boundary[0])
5920 if (strlen(boundary) + 2 >=
sizeof(dash))
5922 snprintf(dash,
sizeof(dash),
"--%s", boundary);
5923 snprintf(crlf_dash,
sizeof(crlf_dash),
"\r\n--%s", boundary);
5924 dlen = strlen(dash);
5925 cdlen = strlen(crlf_dash);
5931 data = (
const unsigned char*)body->
data;
5933 first =
mp_find(data, len, dash, dlen);
5936 cursor = (size_t)first + dlen;
5940 size_t part_start, part_end;
5944 if (cursor + 2 <= len && data[cursor] ==
'-' && data[cursor + 1] ==
'-')
5947 if (cursor + 2 <= len && data[cursor] ==
'\r' && data[cursor + 1] ==
'\n')
5949 else if (cursor < len && data[cursor] ==
'\n')
5951 part_start = cursor;
5952 rel =
mp_find(data + part_start, len - part_start, crlf_dash, cdlen);
5955 part_end = part_start + (size_t)rel;
5966 long s =
mp_find(data + part_start, part_end - part_start,
"\r\n\r\n", 4);
5968 size_t hlen = (size_t)s;
5969 size_t bbeg = part_start + (size_t)s + 4;
5970 const char* hblock = (
const char*)(data + part_start);
5971 const char* hv =
mp_header_value(hblock, hlen,
"Content-Disposition", &hvl);
5980 size_t blen = part_end - bbeg;
5984 memcpy(mp->
body->
data, data + bbeg, blen);
6001 cursor = part_end + cdlen;
6007static void mp_put(
char* buf,
size_t* pos,
const void* src,
size_t n) {
6009 memcpy(buf + *pos, src, n);
6014static void mp_puts(
char* buf,
size_t* pos,
const char* s) {
6016 mp_put(buf, pos, s, strlen(s));
6020static void mp_emit(
char* buf,
size_t* pos,
LIST* parts,
const char* dash) {
6026 mp_puts(buf, pos,
"\r\nContent-Disposition: form-data; name=\"");
6030 mp_puts(buf, pos,
"; filename=\"");
6036 mp_puts(buf, pos,
"Content-Type: ");
6054 if (!parts || !boundary || !boundary[0])
6056 if (strlen(boundary) + 2 >=
sizeof(dash))
6058 snprintf(dash,
sizeof(dash),
"--%s", boundary);
6060 mp_emit(NULL, &total, parts, dash);
6061 Malloc(buf,
char, total + 1);
6065 mp_emit(buf, &total, parts, dash);
6080 const time_t now = time(NULL);
6083 if (gmtime_s(&gmt, &now) != 0) {
6088 if (!gmtime_r(&now, &gmt)) {
6093 if (strftime(buffer, buffer_size,
"%a, %d %b %Y %H:%M:%S GMT", &gmt) == 0) {
6113 __n_assert(additional_headers,
return FALSE);
6116 const char* connection_type =
"close";
6119 char date_buffer[128] =
"";
6122 if ((*http_response)) {
6123 (*http_response)->written = 0;
6126 if (!body || body->
written == 0) {
6129 "HTTP/1.1 %d %s\r\n"
6132 "Content-Length: 0\r\n"
6134 "Connection: %s\r\n\r\n",
6135 status_code, status_message, date_buffer, server_name, additional_headers, connection_type);
6140 "HTTP/1.1 %d %s\r\n"
6143 "Content-Type: %s\r\n"
6144 "Content-Length: %zu\r\n"
6146 "Connection: %s\r\n\r\n",
6147 status_code, status_message, date_buffer, server_name, content_type, body->
written, additional_headers, connection_type);
6148 nstrcat((*http_response), body);
6165 int ret = SSL_write(conn->
netw->
ssl, buf, (
int)len);
6166 return (ret > 0) ? (ssize_t)ret : -1;
6168 ssize_t ret = send(conn->
netw->
link.
sock, buf, NETW_BUFLEN_CAST(len), NETFLAGS);
6181 char* p = (
char*)buf;
6182 while (total < len) {
6185 ret = SSL_read(conn->
netw->
ssl, p + total, (
int)(len - total));
6187 ret = recv(conn->
netw->
link.
sock, p + total, NETW_BUFLEN_CAST(len - total), 0);
6192 total += (size_t)ret;
6194 return (ssize_t)total;
6219 conn->
host = strdup(host);
6220 conn->
path = strdup(path);
6223 goto ws_connect_fail;
6229 n_log(
LOG_ERR,
"n_ws_connect: TCP+SSL context setup failed for %s:%s", host,
port);
6230 goto ws_connect_fail;
6234 n_log(
LOG_ERR,
"n_ws_connect: SSL handshake failed for %s:%s", host,
port);
6235 goto ws_connect_fail;
6240 goto ws_connect_fail;
6245 unsigned char rand_bytes[16];
6246 if (RAND_bytes(rand_bytes, 16) != 1) {
6249 goto ws_connect_fail;
6254 memcpy(rand_nstr->
data, rand_bytes, 16);
6259 __n_assert(ws_key_nstr,
goto ws_connect_fail);
6261 while (ws_key_nstr->
written > 0 &&
6262 (ws_key_nstr->
data[ws_key_nstr->
written - 1] ==
'\n' ||
6263 ws_key_nstr->
data[ws_key_nstr->
written - 1] ==
'\r' ||
6264 ws_key_nstr->
data[ws_key_nstr->
written - 1] ==
' ')) {
6269 char upgrade_req[2048];
6270 int req_len = snprintf(upgrade_req,
sizeof(upgrade_req),
6271 "GET %s HTTP/1.1\r\n"
6273 "Upgrade: websocket\r\n"
6274 "Connection: Upgrade\r\n"
6275 "Sec-WebSocket-Key: %s\r\n"
6276 "Sec-WebSocket-Version: 13\r\n"
6278 path, host, ws_key_nstr->
data);
6280 if (req_len < 0 || (
size_t)req_len >=
sizeof(upgrade_req)) {
6282 n_log(
LOG_ERR,
"n_ws_connect: upgrade request too large");
6284 goto ws_connect_fail;
6288 if (
_ws_write(conn, upgrade_req, (
size_t)req_len) < 0) {
6290 n_log(
LOG_ERR,
"n_ws_connect: failed to send upgrade request");
6292 goto ws_connect_fail;
6296 char resp_buf[4096];
6297 memset(resp_buf, 0,
sizeof(resp_buf));
6298 size_t resp_len = 0;
6299 while (resp_len <
sizeof(resp_buf) - 1) {
6302 r = SSL_read(conn->
netw->
ssl, resp_buf + resp_len, 1);
6304 r = recv(conn->
netw->
link.
sock, resp_buf + resp_len, 1, 0);
6308 n_log(
LOG_ERR,
"n_ws_connect: failed reading handshake response");
6310 goto ws_connect_fail;
6312 resp_len += (size_t)r;
6313 if (resp_len >= 4 &&
6314 resp_buf[resp_len - 4] ==
'\r' && resp_buf[resp_len - 3] ==
'\n' &&
6315 resp_buf[resp_len - 2] ==
'\r' && resp_buf[resp_len - 1] ==
'\n') {
6319 resp_buf[resp_len] =
'\0';
6322 if (strstr(resp_buf,
"101") == NULL) {
6324 n_log(
LOG_ERR,
"n_ws_connect: server did not return 101: %.128s", resp_buf);
6326 goto ws_connect_fail;
6330 static const char ws_magic[] =
"258EAFA5-E914-47DA-95CA-5AB5FE44F513";
6331 char concat_key[256];
6332 snprintf(concat_key,
sizeof(concat_key),
"%s%s", ws_key_nstr->
data, ws_magic);
6337 unsigned char sha1_hash[SHA_DIGEST_LENGTH];
6338 SHA1((
const unsigned char*)concat_key, strlen(concat_key), sha1_hash);
6342 memcpy(sha1_nstr->
data, sha1_hash, SHA_DIGEST_LENGTH);
6343 sha1_nstr->
written = SHA_DIGEST_LENGTH;
6347 __n_assert(expected_accept,
goto ws_connect_fail);
6349 while (expected_accept->
written > 0 &&
6350 (expected_accept->
data[expected_accept->
written - 1] ==
'\n' ||
6351 expected_accept->
data[expected_accept->
written - 1] ==
'\r' ||
6352 expected_accept->
data[expected_accept->
written - 1] ==
' ')) {
6353 expected_accept->
data[--expected_accept->
written] =
'\0';
6357 const char* accept_hdr = NULL;
6358 char* search_pos = resp_buf;
6359 while (*search_pos) {
6360 if (strncasecmp(search_pos,
"Sec-WebSocket-Accept:", 21) == 0) {
6361 accept_hdr = search_pos + 21;
6368 n_log(
LOG_ERR,
"n_ws_connect: no Sec-WebSocket-Accept header in response");
6370 goto ws_connect_fail;
6373 while (*accept_hdr ==
' ') accept_hdr++;
6375 char accept_val[128];
6378 while (ai < (
int)
sizeof(accept_val) - 1 && accept_hdr[ai] && accept_hdr[ai] !=
'\r' && accept_hdr[ai] !=
'\n') {
6379 accept_val[ai] = accept_hdr[ai];
6382 accept_val[ai] =
'\0';
6384 if (strcmp(accept_val, expected_accept->
data) != 0) {
6387 n_log(
LOG_DEBUG,
"n_ws_connect: Sec-WebSocket-Accept mismatch (proxy?): got [%s] expected [%s]",
6388 accept_val, expected_accept->
data);
6393 n_log(
LOG_INFO,
"n_ws_connect: WebSocket handshake completed with %s:%s%s", host,
port, path);
6417 size_t frame_max = 14 + len;
6418 unsigned char* frame = NULL;
6419 Malloc(frame,
unsigned char, frame_max);
6425 frame[pos++] = (
unsigned char)(0x80 | (opcode & 0x0F));
6429 frame[pos++] = (
unsigned char)(0x80 | len);
6430 }
else if (len <= 65535) {
6431 frame[pos++] = (
unsigned char)(0x80 | 126);
6432 frame[pos++] = (
unsigned char)((len >> 8) & 0xFF);
6433 frame[pos++] = (
unsigned char)(len & 0xFF);
6435 frame[pos++] = (
unsigned char)(0x80 | 127);
6436 for (
int i = 7; i >= 0; i--) {
6437 frame[pos++] = (
unsigned char)((len >> (8 * i)) & 0xFF);
6442 unsigned char mask_key[4];
6443 if (RAND_bytes(mask_key, 4) != 1) {
6445 n_log(
LOG_ERR,
"n_ws_send: RAND_bytes failed for mask key");
6449 memcpy(frame + pos, mask_key, 4);
6453 if (payload && len > 0) {
6454 for (
size_t i = 0; i < len; i++) {
6455 frame[pos + i] = (
unsigned char)((
unsigned char)payload[i] ^ mask_key[i % 4]);
6460 ssize_t written =
_ws_write(conn, frame, pos);
6462 if (written < 0 || (
size_t)written != pos) {
6464 n_log(
LOG_ERR,
"n_ws_send: write failed (wrote %zd of %zu)", written, pos);
6484 memset(msg_out, 0,
sizeof(*msg_out));
6487 unsigned char hdr[2];
6493 int opcode = hdr[0] & 0x0F;
6494 int mask_bit = (hdr[1] >> 7) & 1;
6495 uint64_t payload_len = hdr[1] & 0x7F;
6498 if (payload_len == 126) {
6499 unsigned char ext[2];
6500 if (
_ws_read(conn, ext, 2) < 0)
return -1;
6501 payload_len = ((uint64_t)ext[0] << 8) | (uint64_t)ext[1];
6502 }
else if (payload_len == 127) {
6503 unsigned char ext[8];
6504 if (
_ws_read(conn, ext, 8) < 0)
return -1;
6506 for (
int i = 0; i < 8; i++) {
6507 payload_len = (payload_len << 8) | (uint64_t)ext[i];
6512 unsigned char mask_key[4] = {0};
6514 if (
_ws_read(conn, mask_key, 4) < 0)
return -1;
6521 if (payload_len > 0) {
6522 if (
_ws_read(conn, payload->
data, (
size_t)payload_len) < 0) {
6528 for (uint64_t i = 0; i < payload_len; i++) {
6529 payload->
data[i] = (char)((
unsigned char)payload->
data[i] ^ mask_key[i % 4]);
6533 payload->
written = (size_t)payload_len;
6534 payload->
data[payload_len] =
'\0';
6536 msg_out->
opcode = opcode;
6538 msg_out->
masked = mask_bit;
6561 memset(&msg, 0,
sizeof(msg));
6619 __atomic_store_n(&conn->
stop_flag, 1, __ATOMIC_RELEASE);
6649 if (stop_flag && __atomic_load_n(stop_flag, __ATOMIC_ACQUIRE)) {
6654 tv.tv_usec = 500000;
6662 if (SSL_pending(
netw->
ssl) > 0) {
6667 int sel = select((
int)
netw->
link.
sock + 1, &fds, NULL, NULL, &tv);
6668 if (sel < 0)
return -1;
6669 if (sel == 0)
continue;
6674 ret = SSL_read(
netw->
ssl, ch, 1);
6678 return (ret == 1) ? 1 : -1;
6690 int ret = SSL_write(
netw->
ssl, buf, (
int)len);
6691 return (ret > 0) ? (ssize_t)ret : -1;
6693 ssize_t ret = send(
netw->
link.
sock, buf, NETW_BUFLEN_CAST(len), NETFLAGS);
6729 n_log(
LOG_ERR,
"n_sse_connect: TCP+SSL context setup failed for %s:%s", host,
port);
6730 goto sse_connect_fail;
6734 n_log(
LOG_ERR,
"n_sse_connect: SSL handshake failed for %s:%s", host,
port);
6735 goto sse_connect_fail;
6740 goto sse_connect_fail;
6747 if (user_agent && user_agent[0]) {
6748 req_len = snprintf(request,
sizeof(request),
6749 "GET %s HTTP/1.1\r\n"
6751 "Accept: text/event-stream\r\n"
6752 "Cache-Control: no-cache\r\n"
6753 "Connection: keep-alive\r\n"
6754 "User-Agent: %s\r\n"
6756 path, host, user_agent);
6758 req_len = snprintf(request,
sizeof(request),
6759 "GET %s HTTP/1.1\r\n"
6761 "Accept: text/event-stream\r\n"
6762 "Cache-Control: no-cache\r\n"
6763 "Connection: keep-alive\r\n"
6768 if (req_len < 0 || (
size_t)req_len >=
sizeof(request)) {
6771 goto sse_connect_fail;
6776 n_log(
LOG_ERR,
"n_sse_connect: failed to send HTTP request");
6777 goto sse_connect_fail;
6781 char resp_buf[8192];
6782 size_t resp_len = 0;
6783 while (resp_len <
sizeof(resp_buf) - 1) {
6787 n_log(
LOG_ERR,
"n_sse_connect: failed reading HTTP response");
6788 goto sse_connect_fail;
6790 resp_buf[resp_len++] = ch;
6791 if (resp_len >= 4 &&
6792 resp_buf[resp_len - 4] ==
'\r' && resp_buf[resp_len - 3] ==
'\n' &&
6793 resp_buf[resp_len - 2] ==
'\r' && resp_buf[resp_len - 1] ==
'\n') {
6797 resp_buf[resp_len] =
'\0';
6800 if (strstr(resp_buf,
"200") == NULL) {
6802 n_log(
LOG_ERR,
"n_sse_connect: server did not return 200: %.128s", resp_buf);
6803 goto sse_connect_fail;
6811 memset(¤t, 0,
sizeof(current));
6815 size_t line_len = 0;
6817 while (!__atomic_load_n(&conn->
stop_flag, __ATOMIC_ACQUIRE)) {
6820 n_log(
LOG_DEBUG,
"n_sse_connect: connection closed or read error");
6826 if (line_len > 0 && line[line_len - 1] ==
'\r') {
6829 line[line_len] =
'\0';
6831 if (line_len == 0) {
6836 memset(¤t, 0,
sizeof(current));
6838 }
else if (line[0] ==
':') {
6843 char* colon = strchr(line,
':');
6844 const char* field = line;
6845 const char* value =
"";
6850 if (*value ==
' ') value++;
6853 if (strcmp(field,
"data") == 0) {
6860 }
else if (strcmp(field,
"event") == 0) {
6863 }
else if (strcmp(field,
"id") == 0) {
6866 }
else if (strcmp(field,
"retry") == 0) {
6867 current.
retry = atoi(value);
6873 if (line_len <
sizeof(line) - 1) {
6874 line[line_len++] = ch;
6894#define N_WS_FRAME_MAX_PAYLOAD (16U * 1024U * 1024U)
6909 if (!buf || !frame || !consumed)
6913 frame->
fin = (buf[0] & 0x80) ? 1 : 0;
6914 frame->
rsv = (buf[0] >> 4) & 0x07;
6915 frame->
opcode = buf[0] & 0x0F;
6916 frame->
masked = (buf[1] & 0x80) ? 1 : 0;
6917 len7 = buf[1] & 0x7F;
6919 plen = (uint64_t)len7;
6920 }
else if (len7 == 126) {
6923 plen = ((uint64_t)buf[2] << 8) | (uint64_t)buf[3];
6930 for (i = 0; i < 8; i++)
6931 plen = (plen << 8) | (uint64_t)buf[2 + i];
6939 memcpy(frame->
mask, buf + hdr, 4);
6942 memset(frame->
mask, 0, 4);
6944 if (len < hdr + plen)
6948 *consumed = hdr + (size_t)plen;
6952void n_ws_unmask(
unsigned char* dst,
const unsigned char* src,
size_t len,
const unsigned char mask[4]) {
6954 if (!dst || !src || !mask)
6956 for (i = 0; i < len; i++)
6957 dst[i] = (
unsigned char)(src[i] ^ mask[i & 3]);
6960size_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) {
6962 unsigned char b1 = (
unsigned char)(do_mask ? 0x80 : 0);
6963 if (!out || out_cap < 2)
6965 out[pos++] = (
unsigned char)((fin ? 0x80 : 0) | (opcode & 0x0F));
6967 out[pos++] = (
unsigned char)(b1 | (
unsigned char)len);
6968 }
else if (len <= 65535) {
6969 if (out_cap < pos + 3)
6971 out[pos++] = (
unsigned char)(b1 | 126);
6972 out[pos++] = (
unsigned char)((len >> 8) & 0xFF);
6973 out[pos++] = (
unsigned char)(len & 0xFF);
6976 if (out_cap < pos + 9)
6978 out[pos++] = (
unsigned char)(b1 | 127);
6979 for (i = 7; i >= 0; i--)
6980 out[pos++] = (
unsigned char)((len >> (8 * i)) & 0xFF);
6983 if (!mask_key || out_cap < pos + 4)
6985 memcpy(out + pos, mask_key, 4);
6988 if (out_cap < pos + len)
6990 if (do_mask && mask_key) {
6992 for (i = 0; i < len; i++)
6993 out[pos + i] = (
unsigned char)((payload ? payload[i] : 0) ^ mask_key[i & 3]);
6994 }
else if (payload && len > 0) {
6995 memcpy(out + pos, payload, len);
7007 if (!buf || !req)
return;
7010 const char* line_end = strstr(buf,
"\r\n");
7011 if (!line_end) line_end = strchr(buf,
'\n');
7012 if (!line_end)
return;
7014 size_t line_len = (size_t)(line_end - buf);
7016 if (line_len >=
sizeof(line)) line_len =
sizeof(line) - 1;
7017 memcpy(line, buf, line_len);
7018 line[line_len] =
'\0';
7021 char* sp1 = strchr(line,
' ');
7023 size_t mlen = (size_t)(sp1 - line);
7024 if (mlen >=
sizeof(req->
method)) mlen =
sizeof(req->
method) - 1;
7025 memcpy(req->
method, line, mlen);
7026 req->
method[mlen] =
'\0';
7030 char* sp2 = strchr(sp1,
' ');
7031 if (sp2) *sp2 =
'\0';
7032 char* qmark = strchr(sp1,
'?');
7035 strncpy(req->
query, qmark + 1,
sizeof(req->
query) - 1);
7038 strncpy(req->
path, sp1,
sizeof(req->
path) - 1);
7039 req->
path[
sizeof(req->
path) - 1] =
'\0';
7042 const char* hdr_start = line_end;
7043 if (*hdr_start ==
'\r') hdr_start++;
7044 if (*hdr_start ==
'\n') hdr_start++;
7048 const char* body_start = NULL;
7049 while (hdr_start && *hdr_start) {
7050 const char* next = strstr(hdr_start,
"\r\n");
7051 if (!next) next = strchr(hdr_start,
'\n');
7054 size_t hlen = (size_t)(next - hdr_start);
7058 if (*body_start ==
'\r') body_start++;
7059 if (*body_start ==
'\n') body_start++;
7063 char* header_line = strndup(hdr_start, hlen);
7069 if (*hdr_start ==
'\r') hdr_start++;
7070 if (*hdr_start ==
'\n') hdr_start++;
7074 if (body_start && *body_start) {
7107 server->user_data = user_data;
7120 server->listener = listener;
7134 while (!__atomic_load_n(&
server->stop_flag, __ATOMIC_ACQUIRE)) {
7141 tv.tv_usec = 200000;
7142 int sel = select((
int)(
server->listener->
link.
sock + 1), &readfds, NULL, NULL, &tv);
7143 if (sel <= 0)
continue;
7148 if (!client)
continue;
7152 ssize_t n = recv(client->
link.
sock, buf,
sizeof(buf) - 1, 0);
7161 memset(&req, 0,
sizeof(req));
7166 memset(&resp, 0,
sizeof(resp));
7175 if (!status_msg) status_msg =
"Unknown";
7177 size_t body_len = 0;
7178 const char* body_data =
"";
7184 char header_buf[1024];
7185 int hlen = snprintf(header_buf,
sizeof(header_buf),
7186 "HTTP/1.1 %d %s\r\n"
7187 "Content-Type: %s\r\n"
7188 "Content-Length: %zu\r\n"
7189 "Connection: close\r\n"
7196 send(client->
link.
sock, header_buf, NETW_BUFLEN_CAST(hlen), NETFLAGS);
7199 send(client->
link.
sock, body_data, NETW_BUFLEN_CAST(body_len), NETFLAGS);
7217 __atomic_store_n(&
server->stop_flag, 1, __ATOMIC_RELEASE);
7226 if ((*server)->listener) {
7234 if (!u || !qs || !qs[0])
return;
7235 char* buf = strdup(qs);
7237 char* saveptr = NULL;
7238 const char* tok = strtok_r(buf,
"&", &saveptr);
7240 char* eq = strchr(tok,
'=');
7250 tok = strtok_r(NULL,
"&", &saveptr);
7256 if (!url)
return NULL;
7259 if (!u)
return NULL;
7260 memset(u, 0,
sizeof(*u));
7261 const char* p = url;
7262 const char* scheme_end = strstr(p,
"://");
7264 u->
scheme = strndup(p, (
size_t)(scheme_end - p));
7267 u->
scheme = strdup(
"http");
7269 const char* host_end = p;
7270 while (*host_end && *host_end !=
'/' && *host_end !=
'?' && *host_end !=
':') host_end++;
7271 u->
host = strndup(p, (
size_t)(host_end - p));
7276 while (*p && *p !=
'/' && *p !=
'?') p++;
7280 while (*pe && *pe !=
'?') pe++;
7281 u->
path = strndup(p, (
size_t)(pe - p));
7284 u->
path = strdup(
"/");
7288 u->
query = strdup(p);
7295 if (!u)
return NULL;
7297 if (!result)
return NULL;
7300 int dp = (u->
scheme && strcmp(u->
scheme,
"https") == 0) ? 443 : 80;
7315 const char* seg_starts[256];
7316 size_t seg_lens[256];
7318 const char* p = (path && path[0]) ? path :
"/";
7329 slash = strchr(p,
'/');
7330 slen = slash ? (size_t)(slash - p) : strlen(p);
7331 if (slen == 1 && p[0] ==
'.') {
7333 }
else if (slen == 2 && p[0] ==
'.' && p[1] ==
'.') {
7335 }
else if (nb < 256) {
7337 seg_lens[nb] = slen;
7343 if (outsz == 0)
return;
7345 for (i = 0; i < nb && pos < outsz - 1; i++) {
7347 if (i > 0 && pos < outsz - 1) out[pos++] =
'/';
7348 for (k = 0; k < seg_lens[i] && pos < outsz - 1; k++)
7349 out[pos++] = seg_starts[i][k];
7352 if (path && path[0] && path[strlen(path) - 1] ==
'/' && pos < outsz - 1 && (nb > 0))
7367 N_STR* result = NULL;
7372 if (!u)
return NULL;
7373 snprintf(scheme,
sizeof(scheme),
"%s", u->
scheme ? u->
scheme :
"http");
7374 snprintf(host,
sizeof(host),
"%s", u->
host ? u->
host :
"");
7375 for (i = 0; scheme[i]; i++) scheme[i] = (
char)tolower((
unsigned char)scheme[i]);
7376 for (i = 0; host[i]; i++) host[i] = (
char)tolower((
unsigned char)host[i]);
7379 if (!result)
return NULL;
7382 int dp = (strcmp(scheme,
"https") == 0) ? 443 : 80;
7398 if (!u)
return NULL;
7410 if (!s || !isalpha((
unsigned char)s[0]))
return 0;
7412 while (s[i] && (isalnum((
unsigned char)s[i]) || s[i] ==
'+' || s[i] ==
'-' || s[i] ==
'.')) i++;
7434 if (!base)
return NULL;
7437 char* refbuf = strdup(ref ? ref :
"");
7438 if (!refbuf)
return NULL;
7439 char* frag = strchr(refbuf,
'#');
7440 if (frag) *frag =
'\0';
7457 char* refq = strchr(refbuf,
'?');
7458 const char* ref_query = NULL;
7461 ref_query = refq + 1;
7465 char authority[300];
7467 snprintf(authority,
sizeof(authority),
"%s:%d", b->
host ? b->
host :
"", b->
port);
7469 snprintf(authority,
sizeof(authority),
"%s", b->
host ? b->
host :
"");
7473 const char* t_query = NULL;
7475 if (refbuf[0] ==
'\0') {
7477 snprintf(rawpath,
sizeof(rawpath),
"%s", b->
path ? b->
path :
"/");
7478 t_query = refq ? ref_query : b->
query;
7479 }
else if (refbuf[0] ==
'/' && refbuf[1] ==
'/') {
7481 const char* a = refbuf + 2;
7482 const char* slash = strchr(a,
'/');
7484 snprintf(authority,
sizeof(authority),
"%.*s", (
int)(slash - a), a);
7485 snprintf(rawpath,
sizeof(rawpath),
"%s", slash);
7487 snprintf(authority,
sizeof(authority),
"%s", a);
7488 snprintf(rawpath,
sizeof(rawpath),
"/");
7490 t_query = ref_query;
7491 }
else if (refbuf[0] ==
'/') {
7493 snprintf(rawpath,
sizeof(rawpath),
"%s", refbuf);
7494 t_query = ref_query;
7497 const char* bp = (b->
path && b->
path[0]) ? b->
path :
"/";
7498 const char* lastslash = strrchr(bp,
'/');
7499 size_t prefixlen = lastslash ? (size_t)(lastslash - bp) + 1 : 0;
7500 snprintf(rawpath,
sizeof(rawpath),
"%.*s%s", (
int)prefixlen, bp, refbuf);
7501 t_query = ref_query;
7504 char normpath[4096];
7507 N_STR* out =
new_nstr(strlen(authority) +
sizeof(normpath) + 32);
7509 nstrprintf(out,
"%s://%s%s", t_scheme, authority, normpath);
7522 if (!str)
return NULL;
7523 size_t len = strlen(str);
7525 if (!result)
return NULL;
7526 for (
size_t i = 0; i < len; i++) {
7527 if (str[i] ==
'%' && i + 2 < len && isxdigit((
unsigned char)str[i + 1]) && isxdigit((
unsigned char)str[i + 2])) {
7528 const char hex[3] = {str[i + 1], str[i + 2],
'\0'};
7529 unsigned int val = 0;
7530 sscanf(hex,
"%x", &val);
7533 }
else if (str[i] ==
'+') {
7543 if (!u || !*u)
return;
7549 for (
int i = 0; i < p->
nb_params; i++) {
7567 struct addrinfo hints;
7568 memset(&hints, 0,
sizeof(hints));
7569 hints.ai_family = AF_UNSPEC;
7570 hints.ai_socktype = SOCK_STREAM;
7572 struct addrinfo* res = NULL;
7573 int gai_rc = getaddrinfo(host,
port_str, &hints, &res);
7574 if (gai_rc != 0 || !res) {
7575 n_log(
LOG_ERR,
"n_proxy: DNS lookup failed for %s:%d: %s",
7576 host,
port, gai_strerror(gai_rc));
7577 return INVALID_SOCKET;
7580 SOCKET fd = INVALID_SOCKET;
7581 struct addrinfo* rp = NULL;
7582 for (rp = res; rp; rp = rp->ai_next) {
7583 fd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
7584 if (fd == INVALID_SOCKET)
continue;
7585 if (connect(fd, rp->ai_addr, (socklen_t)rp->ai_addrlen) == 0)
break;
7587 fd = INVALID_SOCKET;
7591 if (fd == INVALID_SOCKET) {
7598 if (!url)
return NULL;
7601 const char* sep = strstr(url,
"://");
7603 n_log(
LOG_ERR,
"n_proxy_cfg_parse: no scheme in '%s'", url);
7607 size_t scheme_len = (size_t)(sep - url);
7608 if (scheme_len == 0 || scheme_len > 16)
return NULL;
7611 memcpy(scheme, url, scheme_len);
7612 scheme[scheme_len] =
'\0';
7615 if (strcmp(scheme,
"http") != 0 && strcmp(scheme,
"https") != 0 && strcmp(scheme,
"socks5") != 0) {
7616 n_log(
LOG_ERR,
"n_proxy_cfg_parse: unsupported scheme '%s'", scheme);
7620 const char* after = sep + 3;
7621 if (!*after)
return NULL;
7624 const char* at = strchr(after,
'@');
7625 const char* host_start = NULL;
7626 char* username = NULL;
7627 char* password = NULL;
7631 const char* colon = strchr(after,
':');
7632 if (colon && colon < at) {
7633 username = strndup(after, (
size_t)(colon - after));
7634 password = strndup(colon + 1, (
size_t)(at - colon - 1));
7636 username = strndup(after, (
size_t)(at - after));
7638 host_start = at + 1;
7645 char* hostname = NULL;
7648 if (host_start[0] ==
'[') {
7649 const char* bracket = strchr(host_start,
']');
7650 if (!bracket)
goto fail;
7651 hostname = strndup(host_start + 1, (
size_t)(bracket - host_start - 1));
7652 if (bracket[1] ==
':') {
7653 port = atoi(bracket + 2);
7656 const char* colon = strchr(host_start,
':');
7658 hostname = strndup(host_start, (
size_t)(colon - host_start));
7659 port = atoi(colon + 1);
7661 hostname = strdup(host_start);
7665 if (!hostname || !hostname[0])
goto fail;
7666 if (port <= 0 || port > 65535) {
7668 if (strcmp(scheme,
"http") == 0 || strcmp(scheme,
"https") == 0)
7670 else if (strcmp(scheme,
"socks5") == 0)
7676 if (!cfg)
goto fail;
7677 memset(cfg, 0,
sizeof(*cfg));
7678 cfg->
scheme = strdup(scheme);
7679 cfg->
host = hostname;
7693 if (!cfg || !*cfg)
return;
7704 const char* target_host,
7706 if (!proxy || !target_host)
return -1;
7709 if (fd == INVALID_SOCKET)
return -1;
7712 char connect_req[2048];
7715 len = snprintf(connect_req,
sizeof(connect_req),
7716 "CONNECT %s:%d HTTP/1.1\r\n"
7718 target_host, target_port,
7719 target_host, target_port);
7724 snprintf(cred,
sizeof(cred),
"%s:%s",
7729 if (b64 && b64->
data) {
7730 len += snprintf(connect_req + len,
7731 sizeof(connect_req) - (
size_t)len,
7732 "Proxy-Authorization: Basic %s\r\n",
7740 len += snprintf(connect_req + len,
sizeof(connect_req) - (
size_t)len,
7744 ssize_t sent = send(fd, connect_req, NETW_BUFLEN_CAST(len), 0);
7745 if (sent != (ssize_t)len) {
7746 n_log(
LOG_ERR,
"n_proxy_connect_tunnel: send CONNECT failed");
7752 char resp_buf[4096];
7753 ssize_t nr = recv(fd, resp_buf, NETW_BUFLEN_CAST(
sizeof(resp_buf) - 1), 0);
7755 n_log(
LOG_ERR,
"n_proxy_connect_tunnel: no response from proxy");
7759 resp_buf[nr] =
'\0';
7762 if (strstr(resp_buf,
" 200 ") == NULL) {
7763 n_log(
LOG_ERR,
"n_proxy_connect_tunnel: proxy rejected CONNECT: %.*s",
7764 (
int)(strchr(resp_buf,
'\r') ? strchr(resp_buf,
'\r') - resp_buf : nr),
7770 n_log(
LOG_DEBUG,
"n_proxy_connect_tunnel: tunnel established to %s:%d via %s:%d",
7771 target_host, target_port, proxy->
host, proxy->
port);
7777 const char* target_host,
7779 if (!proxy || !target_host)
return -1;
7782 if (fd == INVALID_SOCKET)
return -1;
7787#if OPENSSL_VERSION_NUMBER >= 0x10100000L
7788 const SSL_METHOD* method = TLS_client_method();
7790 const SSL_METHOD* method = TLSv1_2_client_method();
7792 SSL_CTX* ctx = SSL_CTX_new(method);
7794 n_log(
LOG_ERR,
"n_proxy_connect_tunnel_ssl: SSL_CTX_new failed");
7798 SSL_CTX_set_default_verify_paths(ctx);
7800 SSL* ssl = SSL_new(ctx);
7802 n_log(
LOG_ERR,
"n_proxy_connect_tunnel_ssl: SSL_new failed");
7807 SSL_set_fd(ssl, (
int)fd);
7808 SSL_set_tlsext_host_name(ssl, proxy->
host);
7810 if (SSL_connect(ssl) <= 0) {
7811 n_log(
LOG_ERR,
"n_proxy_connect_tunnel_ssl: TLS handshake to proxy %s:%d failed",
7819 n_log(
LOG_DEBUG,
"n_proxy_connect_tunnel_ssl: TLS established to proxy %s:%d",
7823 char connect_req[2048];
7826 len = snprintf(connect_req,
sizeof(connect_req),
7827 "CONNECT %s:%d HTTP/1.1\r\n"
7829 target_host, target_port,
7830 target_host, target_port);
7835 snprintf(cred,
sizeof(cred),
"%s:%s",
7840 if (b64 && b64->
data) {
7841 len += snprintf(connect_req + len,
7842 sizeof(connect_req) - (
size_t)len,
7843 "Proxy-Authorization: Basic %s\r\n",
7851 len += snprintf(connect_req + len,
sizeof(connect_req) - (
size_t)len,
7855 if (SSL_write(ssl, connect_req, len) != len) {
7856 n_log(
LOG_ERR,
"n_proxy_connect_tunnel_ssl: send CONNECT failed");
7864 char resp_buf[4096];
7865 int nr = SSL_read(ssl, resp_buf, (
int)(
sizeof(resp_buf) - 1));
7867 n_log(
LOG_ERR,
"n_proxy_connect_tunnel_ssl: no response from proxy");
7873 resp_buf[nr] =
'\0';
7876 if (strstr(resp_buf,
" 200 ") == NULL) {
7877 n_log(
LOG_ERR,
"n_proxy_connect_tunnel_ssl: proxy rejected CONNECT: %.*s",
7878 (
int)(strchr(resp_buf,
'\r') ? strchr(resp_buf,
'\r') - resp_buf : nr),
7891 SSL_set_quiet_shutdown(ssl, 1);
7896 n_log(
LOG_DEBUG,
"n_proxy_connect_tunnel_ssl: tunnel established to %s:%d via https://%s:%d",
7897 target_host, target_port, proxy->
host, proxy->
port);
7903 const char* target_host,
7905 if (!proxy || !target_host)
return -1;
7908 if (fd == INVALID_SOCKET)
return -1;
7919 if (send(fd, greeting, 4, 0) != 4)
goto fail;
7924 if (send(fd, greeting, 3, 0) != 3)
goto fail;
7928 char method_resp[2];
7929 if (recv(fd, method_resp, 2, 0) != 2)
goto fail;
7930 if (method_resp[0] != 0x05)
goto fail;
7932 if (method_resp[1] == 0x02 && use_auth) {
7934 size_t ulen = strlen(proxy->
username);
7936 if (ulen > 255 || plen > 255)
goto fail;
7940 auth_req[pos++] = 0x01;
7941 auth_req[pos++] = (char)ulen;
7942 memcpy(auth_req + pos, proxy->
username, ulen);
7944 auth_req[pos++] = (char)plen;
7946 memcpy(auth_req + pos, proxy->
password, plen);
7953 if (send(fd, auth_req, NETW_BUFLEN_CAST(pos), 0) != (ssize_t)pos)
goto fail;
7956 if (recv(fd, auth_resp, 2, 0) != 2)
goto fail;
7957 if (auth_resp[1] != 0x00) {
7958 n_log(
LOG_ERR,
"n_proxy_connect_socks5: auth rejected");
7961 }
else if (method_resp[1] != 0x00) {
7962 n_log(
LOG_ERR,
"n_proxy_connect_socks5: no acceptable method");
7968 size_t hlen = strlen(target_host);
7969 if (hlen > 255)
goto fail;
7973 conn_req[pos++] = 0x05;
7974 conn_req[pos++] = 0x01;
7975 conn_req[pos++] = 0x00;
7976 conn_req[pos++] = 0x03;
7977 conn_req[pos++] = (char)hlen;
7978 memcpy(conn_req + pos, target_host, hlen);
7980 conn_req[pos++] = (char)((target_port >> 8) & 0xFF);
7981 conn_req[pos++] = (char)(target_port & 0xFF);
7983 if (send(fd, conn_req, NETW_BUFLEN_CAST(pos), 0) != (ssize_t)pos)
goto fail;
7990 ssize_t nr = recv(fd, conn_resp, NETW_BUFLEN_CAST(
sizeof(conn_resp)), 0);
7991 if (nr < 4)
goto fail;
7992 if (conn_resp[0] != 0x05 || conn_resp[1] != 0x00) {
7993 n_log(
LOG_ERR,
"n_proxy_connect_socks5: connect failed, reply=%02x",
7999 if (conn_resp[3] == 0x03 && nr < 5) {
8002 recv(fd, extra, NETW_BUFLEN_CAST(
sizeof(extra)), 0);
8003 }
else if (conn_resp[3] == 0x04 && nr < 10) {
8006 size_t need = 22 - (size_t)nr;
8007 if (need <=
sizeof(extra)) {
8008 recv(fd, extra, NETW_BUFLEN_CAST(need), 0);
8013 n_log(
LOG_DEBUG,
"n_proxy_connect_socks5: tunnel established to %s:%d via %s:%d",
8014 target_host, target_port, proxy->
host, proxy->
port);
8018 n_log(
LOG_ERR,
"n_proxy_connect_socks5: handshake failed");
8043 n_log(
LOG_ERR,
"netw_adopt_client_fd: target NETWORK must be empty");
8046 if (fd == INVALID_SOCKET) {
8047 n_log(
LOG_ERR,
"netw_adopt_client_fd: invalid socket");
8051 n_log(
LOG_ERR,
"netw_adopt_client_fd: unable to load WSA dll's");
8057 (*netw)->link.sock = fd;
8058 (*netw)->link.ip = strdup(host ? host :
"");
8059 if (!(*netw)->link.ip) {
8063 (*netw)->link.port = strdup(
port ?
port :
"");
8064 if (!(*netw)->link.port) {
8070 n_log(
LOG_DEBUG,
"netw_adopt_client_fd: adopted socket %d for %s:%s", (
int)fd, (*netw)->link.ip, (*netw)->link.port);
static NETWORK_POOL * pool
NETWORK * netw
Network for server mode, accepting incomming.
static void on_request(N_HTTP_REQUEST *req, N_HTTP_RESPONSE *resp, void *user_data)
Request handler: returns JSON for GET /api/test, 404 otherwise.
#define init_lock(__rwlock_mutex)
Macro for initializing a rwlock.
#define FreeNoLog(__ptr)
Free Handler without log.
#define Malloc(__ptr, __struct, __size)
Malloc Handler to get errors and set to 0.
#define __n_assert(__ptr, __ret)
macro to assert things
#define _str(__PTR)
define true
#define rw_lock_destroy(__rwlock_mutex)
Macro to destroy rwlock mutex.
#define unlock(__rwlock_mutex)
Macro for releasing read/write lock a rwlock mutex.
#define endif
close a ifwhatever block
#define write_lock(__rwlock_mutex)
Macro for acquiring a write lock on a rwlock mutex.
#define Free(__ptr)
Free Handler to get errors.
#define read_lock(__rwlock_mutex)
Macro for acquiring a read lock on a rwlock mutex.
#define _nstr(__PTR)
N_STR or "NULL" string for logging purposes.
N_STR * n_base64_encode(N_STR *input)
encode a N_STR *string
#define N_ENUM_DEFINE(MACRO_DEFINITION, enum_name)
Macro to define an N_ENUM.
#define N_ENUM_ENTRY(class, method)
helper to build an N_ENUM
size_t nb_keys
total number of used keys in the table
int ht_get_ptr(HASH_TABLE *table, const char *key, void **val)
get pointer at 'key' from 'table'
#define ht_foreach(__ITEM_, __HASH_)
ForEach macro helper (classic / old)
int destroy_ht(HASH_TABLE **table)
empty a table and destroy it
int ht_remove(HASH_TABLE *table, const char *key)
remove and delete node at key in table
HASH_TABLE * new_ht(size_t size)
Create a hash table with the given size.
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
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
#define hash_val(node, type)
Cast a HASH_NODE element.
structure of a hash table node
structure of a hash table
size_t nb_items
number of item currently in the list
#define list_shift(__LIST_, __TYPE_)
Shift macro helper for void pointer casting.
int list_empty(LIST *list)
Empty a LIST list of pointers.
LIST_NODE * list_search(LIST *list, const void *ptr)
search ptr in list
int list_push(LIST *list, void *ptr, void(*destructor)(void *ptr))
Add a pointer to the end of the list.
#define list_foreach(__ITEM_, __LIST_)
ForEach macro helper, safe for node removal during iteration.
#define remove_list_node(__LIST_, __NODE_, __TYPE_)
Remove macro helper for void pointer casting.
int list_destroy(LIST **list)
Empty and Free a list container.
LIST * new_generic_list(size_t max_items)
Initialiaze a generic list container to max_items pointers.
#define MAX_LIST_ITEMS
flag to pass to new_generic_list for the maximum possible number of item in a list
Structure of a generic LIST container.
Structure of a generic list node.
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
#define LOG_DEBUG
debug-level messages
#define LOG_ERR
error conditions
#define LOG_WARNING
warning conditions
#define LOG_INFO
informational
N_STR * zip4_nstr(N_STR *src)
Compress src with LZ4 block format.
N_STR * unzip4_nstr(N_STR *src)
Decompress an N_STR produced by zip4_nstr.
size_t written
number of meaningful bytes in data, excluding the null terminator; the size including the null termin...
size_t length
total allocation (in bytes) of the data buffer, padding included
void free_nstr_ptr(void *ptr)
Free a N_STR pointer structure.
N_STR * n_str_url_encode(const char *src)
Percent-encode a C string per RFC 3986 (unreserved set kept as-is).
size_t NSTRBYTE
N_STR base unit.
#define free_nstr(__ptr)
free a N_STR structure and set the pointer to NULL
#define nstrcat(__nstr_dst, __nstr_src)
Macro to quickly concatenate two N_STR.
N_STR * nstrdup(N_STR *str)
Duplicate a N_STR.
#define nstrprintf_cat(__nstr_var, __format,...)
Macro to quickly allocate and sprintf and cat to a N_STR.
N_STR * char_to_nstr(const char *src)
Convert a char into a N_STR, short version.
N_STR * new_nstr(NSTRBYTE size)
create a new N_STR string
#define nstrprintf(__nstr_var, __format,...)
Macro to quickly allocate and sprintf to N_STR.
int char_to_nstr_ex(const char *from, NSTRBYTE nboct, N_STR **to)
Convert a char into a N_STR, extended version.
A box including a string and his lenght.
void u_sleep(unsigned int usec)
wrapper around usleep for API consistency
int start_HiTimer(N_TIME *timer)
Initialize or restart from zero any N_TIME HiTimer.
time_t get_usec(N_TIME *timer)
Poll any N_TIME HiTimer, returning usec, and moving currentTime to startTime.
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
char query[2048]
query string (or empty)
char * ip
ip of the connected socket
N_SOCKET link
networking socket
char * certificate
openssl certificate file
char netw_errors[8][512]
per-connection error capture ring buffer (max 8 entries, 512 chars each)
int threaded_engine_status
Threaded network engine state for this network.
size_t content_length
Store content length.
char * type
Type of request.
pthread_t send_thr
sending thread
int compress_mode
Per-packet compression mode, see NETW_COMPRESS_MODE.
int nb_pending
Nb pending connection,if listening.
char * filename
Content-Disposition filename, or "".
int so_reuseaddr
so reuseaddr state
pthread_t recv_thr
receiving thread
int port
port number (0 if not specified)
int masked
MASK bit (client-to-server frames are masked)
char * host
proxy hostname
pthread_rwlock_t rwlock
thread safety
NETWORK * netw
underlying network connection
struct sockaddr_storage raddr
connected remote addr
char * path
path starting with "/", or "/" if empty
pthread_mutex_t eventbolt
mutex for threaded access of state event
char * content_type
the part's Content-Type, or ""
const SSL_METHOD * method
SSL method container.
N_STR * body
response body
int netw_err_next
next write slot in ring buffer
int deplete_socket_timeout
deplete socket send buffer timeout ( 0 disabled, > 0 wait for timeout and check unset/unack datas)
char * scheme
"http" or "https"
int deplete_queues_timeout
deplete network queues timeout ( 0 disabled, > 0 wait for timeout and check unset/unack datas)
int nb_running_threads
nb running threads, if > 0 thread engine is still running
int opcode
opcode (N_WS_OP_*)
pthread_mutex_t recvbolt
mutex for threaded access of recv buf
NETWORK * netw
underlying network connection
void(* on_event)(N_SSE_EVENT *event, struct N_SSE_CONN *conn, void *user_data)
callback
pthread_mutex_t sendbolt
mutex for threaded access of send_buf
N_STR * body
the part's raw body bytes (binary-safe), or NULL
int send_queue_consecutive_wait
send queue consecutive pool interval, used when there are still items to send, in usec
int fin
FIN bit (1 = final fragment)
N_STR * event
event type (or NULL for default)
int connected
1 if handshake completed
N_STR * body
request body (or NULL)
int so_rcvtimeo
send timeout value
uint64_t payload_len
payload length in bytes
char * password
NULL if no auth.
char * query
raw query string without leading '?', or NULL
N_URL_PARAM params[64]
parsed key=value pairs
int tcpnodelay
state of naggle algorythm, 0 untouched, 1 forcibly disabled
char * body
Pointer to the body data.
LIST * headers
list of char* "Name: Value" strings
char * value
parameter value
char * host
remote hostname
int netw_err_count
number of captured errors
SOCKET sock
a normal socket
char path[2048]
request path
char * scheme
"http", "https", or "socks5"
char * port
port of socket
netw_func recv_data_once
single-attempt recv, same contract as send_data_once.
LIST * recv_buf
reveicing buffer (for incomming usage)
int transport_type
transport type: NETWORK_TCP (0) or NETWORK_UDP (1)
int nb_params
number of parsed parameters
char * name
Content-Disposition form-field name, or "".
int user_id
if part of a user property, id of the user
sem_t send_blocker
block sending func
SSL_CTX * ctx
SSL context holder.
int so_sndbuf
size of the socket send buffer, 0 untouched, else size in bytes
int so_sndtimeo
send timeout value
const unsigned char * payload
pointer into the input buffer (still masked)
int retry
retry interval in ms (0 if not set)
char content_type[256]
Store content type.
N_STR * id
last event ID (or NULL)
struct addrinfo hints
address of local machine
int so_keepalive
so keepalive state
netw_func send_data
send func ptr
int addr_infos_loaded
Internal flag to know if we have to free addr infos.
int rsv
the three reserved bits, rsv1<<2 | rsv2<<1 | rsv3
N_STR * payload
message payload
char method[16]
HTTP method.
unsigned char mask[4]
masking key when masked, else zeroed
LIST * pools
pointers to network pools if members of any
char * username
NULL if no auth.
netw_func send_data_once
single-attempt send (non-blocking / reactor use).
int status_code
HTTP status code.
char * key
openssl key file
int so_linger
close lingering value (-1 disabled, 0 force close, >0 linger )
unsigned long int is_blocking
flag to quickly check socket mode
int crypto_algo
if encryption is on, which one (flags NETW_ENCRYPT_*)
char content_type[128]
Content-Type header value.
HASH_TABLE * pool
table of clients
LIST * send_buf
sending buffer (for outgoing queuing )
int mode
NETWORK mode , 1 listening, 0 connecting.
int so_rcvbuf
size of the socket recv buffer, 0 untouched, else size in bytes
void * user_data
user data for callback
netw_func recv_data
receive func ptr
int wait_close_timeout
network wait close timeout value ( < 1 disabled, >= 1 timeout sec )
#define NETW_SOCKET_ERROR
code for a socket error
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.
ssize_t send_ssl_data_once(void *netw, char *buf, uint32_t n)
single-attempt TLS send for non-blocking sockets (reactor use).
#define N_URL_MAX_PARAMS
maximum number of parsed query parameters
#define NETW_IO_WANT_READ
single-attempt I/O (send_data_once / recv_data_once): the operation cannot progress until the socket ...
#define NETW_COMPRESS_THRESHOLD
Opportunistic compression policy.
N_STR * netw_get_msg(NETWORK *netw)
Get a message from aimed NETWORK.
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 "--");...
int netw_add_msg(NETWORK *netw, N_STR *msg)
Add a message to send in aimed NETWORK.
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
const char * n_netw_get_connect_error(int index)
Get pre-connection error message by index.
ssize_t send_ssl_data(void *netw, char *buf, uint32_t n)
send data onto the socket
char * netw_extract_http_request_type(const char *request)
function to extract the request method from an http request
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
int netw_get_queue_status(NETWORK *netw, size_t *nb_to_send, size_t *nb_to_read)
retrieve network send queue status
int netw_bind_udp(NETWORK **netw, char *addr, char *port, int ip_version)
Create a UDP bound socket for receiving datagrams.
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
ssize_t recv_ssl_data_once(void *netw, char *buf, uint32_t n)
single-attempt TLS recv for non-blocking sockets (reactor use).
#define NETW_THR_EXIT_ERROR
Internal DONE value indicating a send/recv thread observed NETW_ERROR without an in-flight local shut...
#define NETW_COMPRESS_MIN_RATIO
int netw_init_wsa(int mode, int v1, int v2)
Do not directly use, internal api.
int netw_ssl_set_verify(NETWORK *netw, int enable)
enable or disable SSL peer certificate verification
ssize_t send_php(SOCKET s, int _code, char *buf, int n)
send data onto the socket
int netw_stop_thr_engine(NETWORK *netw)
Stop a NETWORK connection sending and receing thread.
void n_ws_close(N_WS_CONN *conn)
Send close frame and close the connection.
char * netw_urlencode(const char *str, size_t len)
function to perform URL encoding
N_STR * n_url_encode(const char *str)
percent-encode a string for use in URLs (delegates to n_str_url_encode())
int n_http_status_class(int status_code)
leading digit of an HTTP status code (1..5), or 0 when outside 100..599
void * netw_send_func(void *NET)
Thread send function.
NETWORK * netw_accept_nonblock_from(NETWORK *from, int blocking)
make a normal blocking 'accept' .
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.
N_PROXY_CFG * n_proxy_cfg_parse(const char *url)
Parse a proxy URL string into an N_PROXY_CFG struct.
int netw_set_crypto(NETWORK *netw, char *key, char *certificate)
activate SSL encryption on selected network, using key and certificate
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
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.
int netw_ssl_set_ca(NETWORK *netw, const char *ca_file, const char *ca_path)
set custom CA verify location for SSL context
void n_sse_stop(N_SSE_CONN *conn)
Signal the SSE connection to stop reading.
ssize_t recv_data_once(void *netw, char *buf, uint32_t n)
single-attempt recv for non-blocking sockets (reactor use).
#define NETWORK_IPV6
Flag to force IPV6
void n_http_multipart_free(LIST **parts)
free a LIST returned by n_http_parse_multipart and NULL the pointer
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.
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.
#define NETWORK_UDP
Flag for UDP transport.
N_STR * n_url_canonicalize_string(const char *url)
parse and canonicalize a URL string in one call
N_STR * n_url_resolve(const char *base, const char *ref)
resolve a (possibly relative) URL reference against an absolute base
ssize_t send_data_once(void *netw, char *buf, uint32_t n)
single-attempt send for non-blocking sockets (reactor use).
int netw_get_http_date(char *buffer, size_t buffer_size)
helper function to generate the current date in HTTP format
NETWORK_POOL * netw_new_pool(size_t nb_min_element)
return a new network pool of nb_min_element
int netw_set_user_id(NETWORK *netw, int id)
associate an id and a network
void n_mock_server_free(N_MOCK_SERVER **server)
Free a mock server and close the listening socket.
ssize_t recv_data(void *netw, char *buf, uint32_t n)
recv data from the socket
int netw_init_openssl(void)
Do not directly use, internal api.
void n_netw_clear_errors(NETWORK *netw)
Clear captured errors on a NETWORK handle.
ssize_t recv_ssl_data(void *netw, char *buf, uint32_t n)
recv data from the socket
int netw_make_listening(NETWORK **netw, char *addr, char *port, int nbpending, int ip_version)
Make a NETWORK be a Listening network.
int netw_ssl_do_handshake(NETWORK *netw, const char *sni_hostname)
Complete the SSL handshake on an already-connected NETWORK.
#define HEAD_SIZE
Size of a HEAD message.
ssize_t send_udp_data(void *netw, char *buf, uint32_t n)
send data via UDP on a connected socket
#define netw_atomic_write_state(netw, val)
Lock-free atomic write of the network state field.
int netw_set_compression_mode(NETWORK *netw, int mode)
Pick send-side payload compression algorithm.
int netw_start_thr_engine(NETWORK *netw)
Start the NETWORK netw Threaded Engine.
int netw_destroy_pool(NETWORK_POOL **netw_pool)
free a NETWORK_POOL *pool
void n_url_free(N_URL **u)
free a N_URL and all its members
#define NETWORK_IPV4
Flag to force IPV4
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
void * netw_recv_func(void *NET)
To Thread Receiving function.
void n_sse_conn_free(N_SSE_CONN **conn)
Free an SSE connection structure.
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.
N_STR * n_url_decode(const char *str)
decode a percent-encoded string (returns N_STR)
int n_netw_get_error_count(const NETWORK *netw)
Get number of captured errors on a NETWORK handle.
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).
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://).
int n_http_status_is_server_error(int status_code)
1 when status_code is a server error (5xx), else 0
#define SOCKET_SIZE_FORMAT
socket associated printf style
__netw_code_type size_t htonst(size_t value)
host to network size_t
int netw_unload_openssl(void)
Do not directly use, internal api.
const char * netw_ssl_get_sni(NETWORK *netw)
get the SNI server_name the peer requested in its ClientHello
int n_http_status_is_client_error(int status_code)
1 when status_code is a client error (4xx), else 0
#define HEAD_CODE
Code of a HEAD message.
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.
size_t ntohst(size_t value)
network to host size_t
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
#define NETWORK_CONSECUTIVE_SEND_WAIT
Flag to set consecutive send waiting timeout
#define netw_atomic_read_reactor_mode(netw)
Lock-free atomic read of the reactor_mode flag.
size_t netw_pool_nbclients(NETWORK_POOL *netw_pool)
return the number of networks in netw_pool
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),...
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.
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' .
void n_netw_clear_connect_errors(void)
Clear pre-connection errors on this thread.
void n_mock_server_stop(N_MOCK_SERVER *server)
Signal the mock server to stop accepting connections.
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.
#define NETWORK_IPALL
Flag for auto detection by OS of ip version to use.
int SOCKET
default socket declaration
#define NETW_SOCKET_DISCONNECTED
Code for a disconnected recv.
int netw_pool_broadcast(NETWORK_POOL *netw_pool, const NETWORK *from, N_STR *net_msg)
add net_msg to all network in netork pool
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...
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.
const char * n_netw_get_error(const NETWORK *netw, int index)
Get captured error message by index (0 = oldest).
void n_sse_event_clean(N_SSE_EVENT *event)
Free the contents of an SSE event (does not free the struct itself).
#define NETWORK_WAIT_CLOSE_TIMEOUT
Flag to set network closing wait timeout.
int netw_setsockopt(NETWORK *netw, int optname, int value)
Modify common socket options on the given netw.
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 "--").
int netw_set(NETWORK *netw, int flag)
Restart or reset the specified network ability.
ssize_t send_data(void *netw, char *buf, uint32_t n)
send data onto the socket
ssize_t recv_udp_data(void *netw, char *buf, uint32_t n)
recv data via UDP from a connected socket
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
int netw_get_state(NETWORK *netw, uint32_t *state, int *thr_engine_status)
Get the state of a network.
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.
N_URL * n_url_parse(const char *url)
parse a URL string into components
int n_http_status_is_informational(int status_code)
1 when status_code is informational (1xx), else 0
void netw_pool_netw_close(void *netw_ptr)
close a network from a network pool
int n_netw_get_connect_error_count(void)
Get number of pre-connection errors captured on this thread.
size_t netw_calculate_urlencoded_size(const char *str, size_t len)
function to calculate the required size for the URL-encoded string
#define netw_atomic_read_reactor_handle(netw)
Same contract for the back-pointer to the reactor.
int deplete_send_buffer(int fd, int timeout)
wait until the socket is empty or timeout, checking each 100 msec.
NETWORK * netw_accept_from(NETWORK *from)
make a normal blocking 'accept' .
N_STR * n_url_canonicalize(const N_URL *u)
produce a canonical URL string for deduplication
#define NETW_IO_WANT_WRITE
single-attempt I/O: the operation cannot progress until the socket is WRITABLE.
#define NETW_MAX_RETRIES
Send or recv max number of retries.
void n_proxy_cfg_free(N_PROXY_CFG **cfg)
Free an N_PROXY_CFG created by n_proxy_cfg_parse().
int netw_close(NETWORK **netw)
Closing a specified Network, destroy queues, free the structure.
int n_http_status_is_success(int status_code)
1 when status_code is success (2xx), else 0
N_STR * n_url_build(const N_URL *u)
build a URL string from parsed components
void n_mock_server_run(N_MOCK_SERVER *server)
Run the mock server accept loop.
int netw_send_quit(NETWORK *netw)
Add a formatted NETMSG_QUIT message to the specified network.
#define NETW_THR_EXIT_OK
Internal DONE value indicating a send/recv thread reached end-of-life cleanly (peer QUIT or local NET...
int netw_ssl_connect_client(NETWORK **netw, char *host, char *port, int ip_version)
Connect as an SSL client without providing a client certificate.
int netw_ssl_start_client(NETWORK *netw)
Set up a client SSL_CTX on an already-connected NETWORK.
const char * netw_get_http_status_message(int status_code)
helper function to convert status code to a human-readable message
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
int n_ws_recv(N_WS_CONN *conn, N_WS_MESSAGE *msg_out)
Receive one WebSocket frame.
int netw_set_blocking(NETWORK *netw, unsigned long int is_blocking)
Modify blocking socket mode.
N_STR * netw_wait_msg(NETWORK *netw, unsigned int refresh, size_t timeout)
Wait a message from aimed NETWORK.
int n_http_status_is_redirect(int status_code)
1 when status_code is a redirect (3xx), else 0
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...
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.
int netw_send_ping(NETWORK *netw, int type, int id_from, int id_to, int time)
Add a ping reply to the network.
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.
NETWORK_HTTP_INFO netw_extract_http_info(char *request)
extract a lot of informations, mostly as pointers, and populate a NETWORK_HTTP_INFO structure
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).
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...
#define netw_atomic_read_state(netw)
Lock-free atomic read of the network state field.
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.
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.
__netw_code_type
Network codes declaration.
#define NETWORK_DEPLETE_SOCKET_TIMEOUT
Flag to set send buffer depletion timeout
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.
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.
char * netw_urldecode(const char *str)
Function to decode URL-encoded data.
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
void n_ws_conn_free(N_WS_CONN **conn)
Free a WebSocket connection structure.
#define NETWORK_DEPLETE_QUEUES_TIMEOUT
Flag to set network queues depletion timeout
int netw_pool_add(NETWORK_POOL *netw_pool, NETWORK *netw)
add a NETWORK *netw to a NETWORK_POOL *pool
int netw_connect_udp(NETWORK **netw, char *host, char *port, int ip_version)
Connect a UDP socket to a remote host.
int netw_info_destroy(NETWORK_HTTP_INFO http_request)
destroy a NETWORK_HTTP_INFO loaded informations
HASH_TABLE * netw_parse_post_data(const char *post_data)
Function to parse POST data.
const char * netw_guess_http_content_type(const char *url)
function to guess the content type based on URL extension
int n_ws_send(N_WS_CONN *conn, const char *payload, size_t len, int opcode)
Send a WebSocket frame (client always masks).
ssize_t recv_php(SOCKET s, int *_code, char **buf)
recv data from the socket
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.
int netw_pool_remove(NETWORK_POOL *netw_pool, NETWORK *netw)
remove a NETWORK *netw to a NETWORK_POOL *pool
void netw_set_connect_abort_cb(int(*cb)(void *ctx), void *ctx)
Register a process-wide callback polled while a connect is in progress.
int netw_add_msg_ex(NETWORK *netw, char *str, unsigned int length)
Add a message to send in aimed NETWORK.
#define NETWORK_TCP
Flag for TCP transport (default)
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
@ NETW_COMPRESS_NONE
no automatic compression on send, still decompresses inbound
@ NETW_COMPRESS_ZLIB
compress on send with zlib, decompress either on recv
@ NETW_COMPRESS_LZ4
compress on send with LZ4, decompress either on recv
@ NETW_THR_ENGINE_STARTED
@ NETW_THR_ENGINE_STOPPED
a single part of a parsed multipart/form-data body
parsed HTTP request for mock server callback
HTTP response to send from mock server callback.
Parsed proxy URL components.
SSE event received from server.
A single parsed WebSocket frame (RFC 6455).
structure for splitting HTTP requests
structure of a network pool
N_STR * unzip_nstr(N_STR *src)
return an uncompressed version of src
N_STR * zip_nstr(N_STR *src)
return a compressed version of src
Base64 encoding and decoding functions using N_STR.
Hash functions and table.
LZ4 block-compression handler.
static char * netstrerror(int code)
BSD style errno string NO WORKING ON REDHAT.
#define NETW_CALL_RETRY(__retvar, __expression, __max_tries)
network-aware retry macro: retries on EINTR and EAGAIN/EWOULDBLOCK
static void _n_url_normalize_path(const char *path, char *out, size_t outsz)
normalize a path by removing "." and ".." segments (RFC 3986 style)
static int _ssl_use_pem(SSL *ssl, const char *key_pem, const char *cert_pem)
static char * mp_strndup(const char *s, size_t len)
static __thread int s_connect_err_next
static int _netw_sni_servername_cb(SSL *ssl, int *al, void *arg)
#define N_WS_FRAME_MAX_PAYLOAD
upper bound on a single parsed WebSocket frame payload, to bound a proxy's reassembly buffer against ...
static ssize_t _ws_read(N_WS_CONN *conn, void *buf, size_t len)
read exactly len bytes from a WebSocket connection
static void mp_put(char *buf, size_t *pos, const void *src, size_t n)
static void netw_init_locks(void)
void netw_ssl_print_errors(SOCKET socket)
print the queued OpenSSL errors for a given socket
static ssize_t _sse_write(NETWORK *netw, const void *buf, size_t len)
write bytes to an SSE connection (SSL or plain)
#define _Thread_local
thread-local pre-connection error buffer (DNS, socket creation)
static void _n_parse_query_params(N_URL *u, const char *qs)
static int(* _netw_connect_abort_cb)(void *)
Optional connect-abort callback, or NULL.
static void _n_mock_parse_request(const char *buf, N_HTTP_REQUEST *req)
Parse a raw HTTP request buffer into an N_HTTP_REQUEST.
static ssize_t _ws_write(N_WS_CONN *conn, const void *buf, size_t len)
write bytes to a WebSocket connection (SSL or plain)
NETWORK * netw_new(size_t send_list_limit, size_t recv_list_limit)
Return an empty allocated network ready to be netw_closed.
static ssize_t _sse_read_byte(NETWORK *netw, char *ch, volatile int *stop_flag)
read one byte from an SSE connection (SSL or plain).
static SOCKET _proxy_tcp_connect(const char *host, int port)
Helper: connect a plain TCP socket to host:port.
long long g_netw_bytes_sent
Add a message to send in aimed NETWORK.
static void * _netw_connect_abort_ctx
Opaque context handed to _netw_connect_abort_cb on each poll.
N_ENUM_netw_code_type
network error code
static void mp_emit(char *buf, size_t *pos, LIST *parts, const char *dash)
static int n_http_inflate(const unsigned char *src, size_t len, int window_bits, N_STR **out)
static int OPENSSL_IS_INITIALIZED
static __thread int s_connect_err_count
#define neterrno
get last socket error code, linux version
static pthread_mutex_t * netw_ssl_lockarray
static void mp_part_free(void *ptr)
static void _netw_capture_connect_error(const char *fmt,...)
capture a pre-connection error (thread-local)
#define NETW_CONNECT_ABORT_POLL_MS
Poll interval (milliseconds) at which an in-progress connect wakes to check the registered connect-ab...
static long mp_find(const unsigned char *hay, size_t hlen, const char *needle, size_t nlen)
char * get_in_addr(struct sockaddr *sa)
get sockaddr, IPv4 or IPv6
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.
static const char * mp_header_value(const char *block, size_t blen, const char *name, size_t *vlen)
static void _n_mock_request_clean(N_HTTP_REQUEST *req)
Free the contents of an N_HTTP_REQUEST (does not free the struct itself).
static int _n_url_has_scheme(const char *s)
test whether a reference string begins with its own URI scheme
long long g_netw_bytes_recv
static char * mp_disp_param(const char *disp, size_t dlen, const char *param)
char * netw_get_openssl_error_string()
get the OpenSSL error string
static __thread char s_connect_errors[8][512]
static void _netw_capture_error(NETWORK *netw, const char *fmt,...)
capture an error into a NETWORK handle's ring buffer
static void mp_puts(char *buf, size_t *pos, const char *s)
static void netw_kill_locks(void)
Network messages , serialization tools.
void n_reactor_notify_send(NETWORK *netw)
Producer-side wake-up after a netw_add_msg.
void n_reactor_close_netw_sync(NETWORK *netw)
Synchronously close a reactor-registered NETWORK from the game thread.
Single-threaded epoll reactor for n_network connections.
ZLIB compression handler.