Table of Contents
- NETWORK ENGINE: connect, accept, send and recv wrappers. Network Queue, thread-safe add/get message, ssl/tls secured communications
- Structures
- Types
- Functions
- Defines
- Types Documentation
- typedef netw_sni_pick_cb
- typedef netw_func
- enum __netw_code_type
- typedef SOCKET
- enum NETW_COMPRESS_MODE
- Functions Documentation
- function send_udp_data
- function send_ssl_data_once
- function send_ssl_data
- function send_php
- function send_data_once
- function send_data
- function recv_udp_data
- function recv_ssl_data_once
- function recv_ssl_data
- function recv_php
- function recv_data_once
- function recv_data
- function ntohst
- function netw_wait_msg
- function netw_wait_close_timed
- function netw_wait_close
- function netw_urlencode
- function netw_urldecode
- function netw_unload_openssl
- function netw_udp_sendto
- function netw_udp_recvfrom
- function netw_stop_thr_engine
- function netw_start_thr_engine
- function netw_ssl_start_client
- function netw_ssl_set_versions
- function netw_ssl_set_verify
- function netw_ssl_set_client_cert
- function netw_ssl_set_ciphers
- function netw_ssl_set_ca
- function netw_ssl_set_alpn
- function netw_ssl_server_handshake_once
- function netw_ssl_server_handshake_ex
- function netw_ssl_server_handshake
- function netw_ssl_server_ctx_new
- function netw_ssl_handshake_once
- function netw_ssl_get_verify_result
- function netw_ssl_get_sni
- function netw_ssl_get_alpn
- function netw_ssl_do_handshake
- function netw_ssl_connect_client_to
- function netw_ssl_connect_client
- function netw_ssl_connect
- function netw_setsockopt
- function netw_set_user_id
- function netw_set_crypto_pem_ctx
- function netw_set_crypto_pem
- function netw_set_crypto_chain_pem
- function netw_set_crypto_chain
- function netw_set_crypto
- function netw_set_connect_abort_cb
- function netw_set_compression_mode
- function netw_set_blocking
- function netw_set
- function netw_send_string_to_all
- function netw_send_string_to
- function netw_send_quit
- function netw_send_position
- function netw_send_ping
- function netw_send_ident
- function netw_send_func
- function netw_recv_func
- function netw_pool_remove
- function netw_pool_netw_close
- function netw_pool_nbclients
- function netw_pool_broadcast
- function netw_pool_add
- function netw_parse_post_data
- function netw_new_pool
- function netw_make_listening
- function netw_init_wsa
- function netw_init_openssl
- function netw_info_destroy
- function netw_guess_http_content_type
- function netw_get_url_from_http_request
- function netw_get_state
- function netw_get_queue_status
- function netw_get_msg
- function netw_get_http_status_message
- function netw_get_http_date
- function netw_extract_http_request_type
- function netw_extract_http_info
- function netw_destroy_pool
- function netw_connect_udp
- function netw_connect_to
- function netw_connect_nonblock
- function netw_connect_ex_to
- function netw_connect_ex
- function netw_connect_check
- function netw_connect
- function netw_close
- function netw_calculate_urlencoded_size
- function netw_build_http_response
- function netw_bind_udp
- function netw_adopt_client_fd
- function netw_add_msg_ex
- function netw_add_msg
- function netw_accept_ssl_with_sni_cb
- function netw_accept_nonblock_from
- function netw_accept_from_ex
- function netw_accept_from
- function n_ws_unmask
- function n_ws_send
- function n_ws_recv
- function n_ws_frame_parse
- function n_ws_frame_build
- function n_ws_connect
- function n_ws_conn_free
- function n_ws_close
- function n_url_resolve
- function n_url_parse
- function n_url_free
- function n_url_encode
- function n_url_decode
- function n_url_canonicalize_string
- function n_url_canonicalize
- function n_url_build
- function n_sse_stop
- function n_sse_event_clean
- function n_sse_connect
- function n_sse_conn_free
- function n_proxy_connect_tunnel_ssl
- function n_proxy_connect_tunnel
- function n_proxy_connect_socks5
- function n_proxy_cfg_parse
- function n_proxy_cfg_free
- function n_netw_get_error_count
- function n_netw_get_error
- function n_netw_get_connect_error_count
- function n_netw_get_connect_error
- function n_netw_clear_errors
- function n_netw_clear_connect_errors
- function n_mock_server_stop
- function n_mock_server_start
- function n_mock_server_run
- function n_mock_server_free
- function n_http_status_is_success
- function n_http_status_is_server_error
- function n_http_status_is_redirect
- function n_http_status_is_informational
- function n_http_status_is_client_error
- function n_http_status_class
- function n_http_parse_multipart
- function n_http_multipart_free
- function n_http_multipart_boundary
- function n_http_decompress_body
- function n_http_build_multipart
- function htonst
- function deplete_send_buffer
- function SSL_set_hostflags
- function SSL_set1_host
- Macros Documentation
- define netw_atomic_write_state
- define netw_atomic_write_reactor_mode
- define netw_atomic_write_reactor_handle
- define netw_atomic_read_state
- define netw_atomic_read_reactor_mode
- define netw_atomic_read_reactor_handle
- define _OPEN_SYS_SOCK_IPV6
- define SSL_get1_peer_certificate
- define SOCKET_SIZE_FORMAT
- define N_WS_OP_TEXT
- define N_WS_OP_PONG
- define N_WS_OP_PING
- define N_WS_OP_CLOSE
- define N_WS_OP_BINARY
- define N_WS_MAX_PAYLOAD
- define N_URL_MAX_PARAMS
- define N_ENUM_netw_code_type
- define NETW_TLS_MAX_VERSION
- define NETW_THR_EXIT_OK
- define NETW_THR_EXIT_ERROR
- define NETW_SOCKOPT_TIMEO_MS
- define NETW_SOCKET_ERROR
- define NETW_SOCKET_DISCONNECTED
- define NETW_RETRY_DELAY
- define NETW_MSG_MAX_FRAME_SIZE
- define NETW_MAX_RETRIES
- define NETW_IO_WANT_WRITE
- define NETW_IO_WANT_READ
- define NETW_HAVE_TLS13
- define NETW_COMPRESS_THRESHOLD
- define NETW_COMPRESS_MIN_RATIO
- define NETW_COMPRESSED
- define NETWORK_WAIT_CLOSE_TIMEOUT
- define NETWORK_UDP
- define NETWORK_TCP
- define NETWORK_IPV6
- define NETWORK_IPV4
- define NETWORK_IPALL
- define NETWORK_HANDSHAKE_TIMEOUT
- define NETWORK_DISABLE_ZERO_LENGTH_RECV
- define NETWORK_DEPLETE_SOCKET_TIMEOUT
- define NETWORK_DEPLETE_QUEUES_TIMEOUT
- define NETWORK_CONSECUTIVE_SEND_WAIT
- define HEAD_SIZE
- define HEAD_CODE
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
NETWORK ENGINE: connect, accept, send and recv wrappers. Network Queue, thread-safe add/get message, ssl/tls secured communications
Structures
| Name | |
|---|---|
| struct | N_WS_MESSAGE WebSocket message. |
| struct | N_WS_FRAME A single parsed WebSocket frame (RFC 6455). |
| struct | N_WS_CONN WebSocket connection. |
| struct | N_URL_PARAM a single query parameter key=value pair |
| struct | N_URL parsed URL components |
| struct | N_SSE_EVENT SSE event received from server. |
| struct | N_SSE_CONN SSE connection handle. |
| struct | N_SOCKET Structure of a N_SOCKET. |
| struct | N_PROXY_CFG Parsed proxy URL components. |
| struct | N_MOCK_SERVER mock HTTP server handle |
| struct | N_HTTP_RESPONSE HTTP response to send from mock server callback. |
| struct | N_HTTP_REQUEST parsed HTTP request for mock server callback |
| struct | N_HTTP_MULTIPART_PART a single part of a parsed multipart/form-data body |
| struct | NETWORK_POOL structure of a network pool |
| struct | NETWORK_HTTP_INFO structure for splitting HTTP requests |
| struct | NETWORK Structure of a NETWORK. |
Types
| Name | |
|---|---|
| typedef int(*)(const char *sni, N_STR **cert_pem, N_STR **key_pem, void *user_data) | netw_sni_pick_cb SNI cert-pick callback for netw_accept_ssl_with_sni_cb: given the client SNI host (may be NULL), fill *cert_pem and *key_pem with a server certificate and key (newly allocated; n_network frees them). |
| typedef ssize_t(*)(void *, char *, uint32_t) | netw_func send/recv func ptr type |
| enum | __netw_code_type { __netw_code_type_UNKNOWN_VALUE, NETW_THR_ENGINE_STOPPED = 8192, NETW_THR_ENGINE_STARTED = 4096, NETW_SERVER = 4, NETW_RUN = 64, NETW_RESTART_TIMER = 8, NETW_EXIT_ASKED = 128, NETW_EXITED = 256, NETW_ERROR = 512, NETW_ENCRYPT_OPENSSL = 2048, NETW_ENCRYPT_NONE = 1024, NETW_EMPTY_SENDBUF = 16, NETW_EMPTY_RECVBUF = 32, NETW_DESTROY_SENDBUF = 32768, NETW_DESTROY_RECVBUF = 16384, NETW_COMPRESSED_ZLIB = 65536, NETW_COMPRESSED_LZ4 = 131072, NETW_CLIENT = 2} Network codes declaration. |
| typedef int | SOCKET default socket declaration |
| enum | NETW_COMPRESS_MODE { NETW_COMPRESS_ZLIB = 1, NETW_COMPRESS_NONE = 0, NETW_COMPRESS_LZ4 = 2} Compression mode selector for NETWORK.compress_mode. |
Functions
| Name | |
|---|---|
| ssize_t | send_udp_data(void * netw, char * buf, uint32_t n) UDP send data to connected peer or specified addr. |
| ssize_t | send_ssl_data_once(void * netw, char * buf, uint32_t n) SSL single-attempt write (see send_data_once contract). |
| ssize_t | send_ssl_data(void * netw, char * buf, uint32_t n) SSL Writing to a socket. |
| ssize_t | send_php(SOCKET s, int _code, char * buf, int n) sending to php |
| ssize_t | send_data_once(void * netw, char * buf, uint32_t n) Single-attempt write (see NETWORK.send_data_once contract). |
| ssize_t | send_data(void * netw, char * buf, uint32_t n) Writing to a socket. |
| ssize_t | recv_udp_data(void * netw, char * buf, uint32_t n) UDP recv data from socket. |
| ssize_t | recv_ssl_data_once(void * netw, char * buf, uint32_t n) SSL single-attempt read (see recv_data_once contract). |
| ssize_t | recv_ssl_data(void * netw, char * buf, uint32_t n) SSL Reading from a socket. |
| ssize_t | recv_php(SOCKET s, int * _code, char ** buf) receive from php |
| ssize_t | recv_data_once(void * netw, char * buf, uint32_t n) Single-attempt read (see NETWORK.recv_data_once contract). |
| ssize_t | recv_data(void * netw, char * buf, uint32_t n) Reading from a socket. |
| size_t | ntohst(size_t value) network to host size_t |
| N_STR * | netw_wait_msg(NETWORK * netw, unsigned int refresh, size_t timeout) Wait a message from aimed NETWORK. |
| int | netw_wait_close_timed(NETWORK ** netw, size_t timeout) Closing for peer with timeout. |
| int | netw_wait_close(NETWORK ** netw) Closing for peer. |
| char * | netw_urlencode(const char * str, size_t len) URL-encode a string. |
| char * | netw_urldecode(const char * str) URL-decode a string. |
| int | netw_unload_openssl(void ) unload ssl helper |
| ssize_t | netw_udp_sendto(NETWORK * netw, char * buf, uint32_t n, struct sockaddr * dest_addr, socklen_t dest_len) UDP sendto with explicit destination. |
| ssize_t | netw_udp_recvfrom(NETWORK * netw, char * buf, uint32_t n, struct sockaddr * src_addr, socklen_t * src_len) UDP recvfrom with source address capture. |
| int | netw_stop_thr_engine(NETWORK * netw) Stop a NETWORK connection sending and receiving thread. |
| int | netw_start_thr_engine(NETWORK * netw) Create the sending and receiving thread of a NETWORK. |
| int | netw_ssl_start_client(NETWORK * netw) set up a client SSL_CTX on an already-connected NETWORK (no handshake yet) |
| int | netw_ssl_set_versions(NETWORK * netw, int min_version, int max_version) set the minimum/maximum TLS protocol version on the connection's SSL context (0 leaves a default). |
| int | netw_ssl_set_verify(NETWORK * netw, int enable) enable or disable peer certificate verification |
| int | netw_ssl_set_client_cert(NETWORK * netw, const char * cert_file, const char * key_file) load client certificate and private key for mTLS |
| int | netw_ssl_set_ciphers(NETWORK * netw, const char * cipher_list, const char * ciphersuites) set the TLS<=1.2 cipher list and/or the TLS1.3 ciphersuites (NULL leaves a default). |
| int | netw_ssl_set_ca(NETWORK * netw, const char * ca_file, const char * ca_path) set custom CA verify path or file |
| int | netw_ssl_set_alpn(NETWORK * netw, const char *const * protos, size_t count) offer an ALPN protocol list on a TLS client connection, before its handshake |
| int | netw_ssl_server_handshake_once(NETWORK * netw, SSL_CTX * ctx) non-blocking (resumable) TLS server handshake against a caller-owned shared ctx: TRUE done, NETW_IO_WANT_READ/WRITE to retry, FALSE on error |
| int | netw_ssl_server_handshake_ex(NETWORK * netw, netw_sni_pick_cb pick, void * user_data, const char *const * alpn, size_t alpn_count) same, plus an ALPN offer: the first protocol of alpn the client also offered is selected (none when the two lists do not overlap) |
| 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 cert per client SNI via pick() during the handshake (for proxy CONNECT) |
| SSL_CTX * | netw_ssl_server_ctx_new(const char * key_file, const char * cert_chain_file) new standalone server SSL_CTX with the library's secure defaults (TLS 1.2+, forward-secret AEAD, no compression / renegotiation / tickets), the certificate chain and key loaded from PEM files and checked to match. |
| int | netw_ssl_handshake_once(NETWORK * netw, const char * sni_hostname) non-blocking (resumable) TLS client handshake: TRUE done, NETW_IO_WANT_READ/WRITE to retry, FALSE on error |
| int | netw_ssl_get_verify_result(NETWORK * netw, const char * expected_host, char * errbuf, size_t errsz) evaluate the peer certificate (chain trust + host match) against the system trust store, independently of the connection verify mode |
| const char * | netw_ssl_get_sni(NETWORK * netw) get the SNI server_name the peer requested in its ClientHello, or NULL |
| int | netw_ssl_get_alpn(NETWORK * netw, char * out, size_t out_len) get the ALPN protocol the completed handshake selected, on either side of the connection |
| int | netw_ssl_do_handshake(NETWORK * netw, const char * sni_hostname) complete the SSL handshake on a NETWORK whose ctx was already created. |
| int | netw_ssl_connect_client_to(NETWORK ** netw, char * host, char * port, int ip_version, int connect_timeout_ms) like netw_ssl_connect_client but bounds the TCP connect by connect_timeout_ms (0 = OS default) |
| int | netw_ssl_connect_client(NETWORK ** netw, char * host, char * port, int ip_version) connect as SSL client without client certificate (TCP + SSL_CTX, no handshake yet) |
| int | netw_ssl_connect(NETWORK ** netw, char * host, char * port, int ip_version, char * ssl_key_file, char * ssl_cert_file) connect ssl helper |
| int | netw_setsockopt(NETWORK * netw, int optname, int value) Set common socket options (disable naggle, send/recv buf, reuse addr). |
| int | netw_set_user_id(NETWORK * netw, int id) set user id on a netw |
| 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 THIS connection's SSL only (per-connection, unlike the context-wide netw_set_crypto_pem) |
| int | netw_set_crypto_pem(NETWORK * netw, const char * key_pem, const char * cert_pem) set SSL from PEM strings in memory |
| int | netw_set_crypto_chain_pem(NETWORK * netw, const char * key_pem, const char * cert_pem, const char * ca_pem) set SSL certificate chain from PEM strings in memory |
| int | netw_set_crypto_chain(NETWORK * netw, char * key, char * certificate, char * ca_file) set SSL certificate chain from PEM file |
| int | netw_set_crypto(NETWORK * netw, char * key, char * certificate) set SSL |
| void | netw_set_connect_abort_cb(int(*)(void *ctx) cb, void * ctx) register a process-wide callback polled during connect; non-zero aborts the in-progress connect (NULL removes) |
| int | netw_set_compression_mode(NETWORK * netw, int mode) Pick send-side compression algorithm for this NETWORK: NETW_COMPRESS_NONE, _ZLIB, _LZ4. |
| int | netw_set_blocking(NETWORK * netw, unsigned long int is_blocking) set blocking mode |
| int | netw_set(NETWORK * netw, int flag) Set flags on network. |
| int | netw_send_string_to_all(NETWORK * netw, N_STR * name, N_STR * chan, N_STR * txt, int color) send string to all targets |
| int | netw_send_string_to(NETWORK * netw, int id_to, N_STR * name, N_STR * chan, N_STR * txt, int color) send string to a specific target |
| int | netw_send_quit(NETWORK * netw) send quit message |
| 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) send position message |
| int | netw_send_ping(NETWORK * netw, int type, int id_from, int id_to, int time) send ping message |
| int | netw_send_ident(NETWORK * netw, int type, int id, N_STR * name, N_STR * passwd) send ident message |
| void * | netw_send_func(void * NET) Thread Sending management function. |
| void * | netw_recv_func(void * NET) Thread Receiving management function. |
| int | netw_pool_remove(NETWORK_POOL * netw_pool, NETWORK * netw) remove network from pool |
| void | netw_pool_netw_close(void * netw_ptr) close pool |
| size_t | netw_pool_nbclients(NETWORK_POOL * netw_pool) get nb clients |
| int | netw_pool_broadcast(NETWORK_POOL * netw_pool, const NETWORK * from, N_STR * net_msg) broadcast message to pool |
| int | netw_pool_add(NETWORK_POOL * netw_pool, NETWORK * netw) add network to pool |
| HASH_TABLE * | netw_parse_post_data(const char * post_data) parse POST data into hash table |
| NETWORK_POOL * | netw_new_pool(size_t nb_min_element) init pools |
| int | netw_make_listening(NETWORK ** netw, char * addr, char * port, int nbpending, int ip_version) Listening network. |
| int | netw_init_wsa(int mode, int v1, int v2) Used by Init & Close network. |
| int | netw_init_openssl(void ) init ssl helper |
| int | netw_info_destroy(NETWORK_HTTP_INFO http_request) destroy HTTP info structure |
| const char * | netw_guess_http_content_type(const char * url) guess HTTP content type from URL |
| int | netw_get_url_from_http_request(const char * request, char * url, size_t size) get URL from HTTP request |
| int | netw_get_state(NETWORK * netw, uint32_t * state, int * thr_engine_status) Get flags from network. |
| int | netw_get_queue_status(NETWORK * netw, size_t * nb_to_send, size_t * nb_to_read) get queue status |
| N_STR * | netw_get_msg(NETWORK * netw) Get a message from aimed NETWORK. |
| const char * | netw_get_http_status_message(int status_code) get HTTP status message string |
| int | netw_get_http_date(char * buffer, size_t buffer_size) get current HTTP date string |
| char * | netw_extract_http_request_type(const char * request) extract HTTP request type |
| NETWORK_HTTP_INFO | netw_extract_http_info(char * request) extract HTTP info from request |
| int | netw_destroy_pool(NETWORK_POOL ** netw_pool) destroy pool |
| int | netw_connect_udp(NETWORK ** netw, char * host, char * port, int ip_version) Connect a UDP socket to a remote host. |
| int | netw_connect_to(NETWORK ** netw, char * host, char * port, int ip_version, int connect_timeout_ms) Connecting, with a bounded connection-establishment time (connect_timeout_ms, 0 = OS default). |
| int | netw_connect_nonblock(NETWORK ** netw, char * host, char * port, int ip_version) begin a non-blocking TCP connect: resolve and initiate connect() without waiting; drive to completion with netw_connect_check() |
| 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) Connecting, extended, with a bounded connection-establishment time (connect_timeout_ms, 0 = OS default). |
| 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) Connecting, extended. |
| int | netw_connect_check(NETWORK * netw) advance a non-blocking connect: TRUE connected, NETW_IO_WANT_WRITE keep polling for writability, FALSE all addresses failed |
| int | netw_connect(NETWORK ** netw, char * host, char * port, int ip_version) Connecting. |
| int | netw_close(NETWORK ** netw) Closing. |
| size_t | netw_calculate_urlencoded_size(const char * str, size_t len) calculate URL-encoded size |
| 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) build HTTP response |
| int | netw_bind_udp(NETWORK ** netw, char * addr, char * port, int ip_version) Create a UDP bound socket. |
| 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 (plain send/recv) |
| int | netw_add_msg_ex(NETWORK * netw, char * str, unsigned int length) Add a char message to send in the aimed NETWORK. |
| int | netw_add_msg(NETWORK * netw, N_STR * msg) Add a message to send in aimed NETWORK. |
| 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 via pick() during the handshake |
| NETWORK * | netw_accept_nonblock_from(NETWORK * from, int blocking) Accepting routine. |
| NETWORK * | netw_accept_from_ex(NETWORK * from, size_t send_list_limit, size_t recv_list_limit, int blocking, int * retval) Accepting routine extended. |
| NETWORK * | netw_accept_from(NETWORK * from) Accepting routine. |
| 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 | n_ws_send(N_WS_CONN * conn, const char * payload, size_t len, int opcode) send a WebSocket frame (client always masks) |
| int | n_ws_recv(N_WS_CONN * conn, N_WS_MESSAGE * msg_out) receive one WebSocket frame |
| 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). |
| 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). |
| 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://) and perform the HTTP/1.1 upgrade handshake |
| void | n_ws_conn_free(N_WS_CONN ** conn) free a WebSocket connection structure |
| void | n_ws_close(N_WS_CONN * conn) send close frame and close the connection |
| N_STR * | n_url_resolve(const char * base, const char * ref) resolve a (possibly relative) reference against an absolute base URL (RFC 3986 section 5) |
| N_URL * | n_url_parse(const char * url) parse a URL string into components |
| void | n_url_free(N_URL ** u) free a N_URL and all its members |
| N_STR * | n_url_encode(const char * str) percent-encode a string for use in URLs (delegates to n_str_url_encode()) |
| N_STR * | n_url_decode(const char * str) decode a percent-encoded string (returns N_STR) |
| N_STR * | n_url_canonicalize_string(const char * url) parse and canonicalize a URL string in one call |
| N_STR * | n_url_canonicalize(const N_URL * u) produce a canonical URL string for dedup (lowercase scheme/host, drop default port, remove . |
| N_STR * | n_url_build(const N_URL * u) build a URL string from parsed components |
| void | n_sse_stop(N_SSE_CONN * conn) signal the SSE connection to stop reading |
| void | n_sse_event_clean(N_SSE_EVENT * event) free an SSE event's contents (does not free the event struct itself) |
| N_SSE_CONN * | n_sse_connect(const char * host, const char * port, const char * path, int use_ssl, const char * user_agent, void(*)(N_SSE_EVENT *, N_SSE_CONN *, void *) on_event, void * user_data) connect to an SSE endpoint and start reading events (blocks until stopped). |
| void | n_sse_conn_free(N_SSE_CONN ** conn) free an SSE connection |
| 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. |
| 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. |
| 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. |
| N_PROXY_CFG * | n_proxy_cfg_parse(const char * url) Parse a proxy URL string into an N_PROXY_CFG struct. |
| void | n_proxy_cfg_free(N_PROXY_CFG ** cfg) Free an N_PROXY_CFG created by n_proxy_cfg_parse(). |
| int | n_netw_get_error_count(const NETWORK * netw) Get number of captured errors on a NETWORK handle. |
| const char * | n_netw_get_error(const NETWORK * netw, int index) Get captured error message by index (0 = oldest). |
| int | n_netw_get_connect_error_count(void ) Get number of pre-connection errors captured on this thread. |
| const char * | n_netw_get_connect_error(int index) Get pre-connection error message by index. |
| void | n_netw_clear_errors(NETWORK * netw) Clear captured errors on a NETWORK handle. |
| 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 |
| N_MOCK_SERVER * | n_mock_server_start(int port, void(*)(N_HTTP_REQUEST *, N_HTTP_RESPONSE *, void *) on_request, void * user_data) start a mock HTTP server on localhost:port (returns immediately) |
| void | n_mock_server_run(N_MOCK_SERVER * server) run the mock server accept loop (blocks until stop_flag is set) |
| void | n_mock_server_free(N_MOCK_SERVER ** server) free a mock server and close the listening socket |
| int | n_http_status_is_success(int status_code) 1 when status_code is success (2xx), else 0 |
| int | n_http_status_is_server_error(int status_code) 1 when status_code is a server error (5xx), else 0 |
| int | n_http_status_is_redirect(int status_code) 1 when status_code is a redirect (3xx), else 0 |
| int | n_http_status_is_informational(int status_code) 1 when status_code is informational (1xx), else 0 |
| int | n_http_status_is_client_error(int status_code) 1 when status_code is a client error (4xx), else 0 |
| int | n_http_status_class(int status_code) leading digit of an HTTP status code (1..5), or 0 when outside 100..599 |
| 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 n_http_multipart_free. |
| void | n_http_multipart_free(LIST ** parts) free a LIST returned by n_http_parse_multipart and NULL the pointer |
| 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 | 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 through). |
| 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 "--"); returns a new N_STR (free with free_nstr) or NULL. |
| size_t | htonst(size_t value) host to network size_t |
| int | deplete_send_buffer(int fd, int timeout) wait for send buffer to be empty |
| void | SSL_set_hostflags(SSL * ssl, unsigned int flags) 1.0.2 stand-in for SSL_set_hostflags(): set the X509_CHECK_FLAG_* host-check flags of ssl |
| int | SSL_set1_host(SSL * ssl, const char * host) 1.0.2 stand-in for SSL_set1_host(): set the expected peer name of ssl, returning 1 on success and 0 on failure |
Defines
| Name | |
|---|---|
| netw_atomic_write_state(netw, val) Lock-free atomic write of the network state field. |
|
| netw_atomic_write_reactor_mode(netw, val) | |
| netw_atomic_write_reactor_handle(netw, val) | |
| netw_atomic_read_state(netw) Lock-free atomic read of the network state field. |
|
| netw_atomic_read_reactor_mode(netw) Lock-free atomic read of the reactor_mode flag. |
|
| netw_atomic_read_reactor_handle(netw) Same contract for the back-pointer to the reactor. |
|
| _OPEN_SYS_SOCK_IPV6 | |
| SSL_get1_peer_certificate(ssl) | |
| SOCKET_SIZE_FORMAT socket associated printf style |
|
| N_WS_OP_TEXT WebSocket opcodes per RFC 6455. |
|
| N_WS_OP_PONG | |
| N_WS_OP_PING | |
| N_WS_OP_CLOSE | |
| N_WS_OP_BINARY | |
| N_WS_MAX_PAYLOAD Largest WebSocket payload n_ws_recv() will accept from a peer, in bytes. |
|
| N_URL_MAX_PARAMS maximum number of parsed query parameters |
|
| N_ENUM_netw_code_type(_) Network codes definition. |
|
| NETW_TLS_MAX_VERSION highest TLS version the linked TLS library can negotiate, as a TLS*_VERSION constant. |
|
| NETW_THR_EXIT_OK Internal DONE value indicating a send/recv thread reached end-of-life cleanly (peer QUIT or local NETW_EXIT_ASKED ack'd). |
|
| NETW_THR_EXIT_ERROR Internal DONE value indicating a send/recv thread observed NETW_ERROR without an in-flight local shutdown. |
|
| NETW_SOCKOPT_TIMEO_MS Defined when netw_setsockopt() takes SO_RCVTIMEO / SO_SNDTIMEO in msecs on every platform (before, POSIX read seconds and Windows msecs): test it to pick the unit. |
|
| NETW_SOCKET_ERROR code for a socket error |
|
| NETW_SOCKET_DISCONNECTED Code for a disconnected recv. |
|
| NETW_RETRY_DELAY Send or recv delay between retries in usec. |
|
| NETW_MSG_MAX_FRAME_SIZE Maximum accepted size, in bytes, of a single received message frame payload. |
|
| NETW_MAX_RETRIES Send or recv max number of retries. |
|
| NETW_IO_WANT_WRITE single-attempt I/O: the operation cannot progress until the socket is WRITABLE. |
|
| NETW_IO_WANT_READ single-attempt I/O (send_data_once / recv_data_once): the operation cannot progress until the socket is READABLE. |
|
| NETW_HAVE_TLS13 1 when the linked TLS library can negotiate TLS 1.3, 0 otherwise. |
|
| NETW_COMPRESS_THRESHOLD Opportunistic compression policy. |
|
| NETW_COMPRESS_MIN_RATIO | |
| NETW_COMPRESSED Legacy alias, the first compression commit shipped a single NETW_COMPRESSED flag before LZ4 was added. |
|
| NETWORK_WAIT_CLOSE_TIMEOUT Flag to set network closing wait timeout. |
|
| NETWORK_UDP Flag for UDP transport. |
|
| NETWORK_TCP Flag for TCP transport (default). |
|
| NETWORK_IPV6 Flag to force IPV6. |
|
| NETWORK_IPV4 Flag to force IPV4. |
|
| NETWORK_IPALL Flag for auto detection by OS of ip version to use. |
|
| NETWORK_HANDSHAKE_TIMEOUT Flag to set, on a TLS listener, the deadline in msecs for the whole server handshake of each connection netw_accept_from_ex() accepts (0 = none). |
|
| NETWORK_DISABLE_ZERO_LENGTH_RECV Enable/disable recv of length 0. |
|
| NETWORK_DEPLETE_SOCKET_TIMEOUT Flag to set send buffer depletion timeout. |
|
| NETWORK_DEPLETE_QUEUES_TIMEOUT Flag to set network queues depletion timeout. |
|
| NETWORK_CONSECUTIVE_SEND_WAIT Flag to set consecutive send waiting timeout. |
|
| HEAD_SIZE Size of a HEAD message. |
|
| HEAD_CODE Code of a HEAD message. |
Types Documentation
typedef netw_sni_pick_cb
typedef 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), fill *cert_pem and *key_pem with a server certificate and key (newly allocated; n_network frees them).
Return 0 to proceed with the handshake, non-zero to fail it.
typedef netw_func
typedef ssize_t(* netw_func) (void *, char *, uint32_t);
send/recv func ptr type
enum __netw_code_type
| Enumerator | Value | Description |
|---|---|---|
| __netw_code_type_UNKNOWN_VALUE | ||
| NETW_THR_ENGINE_STOPPED | 8192 | |
| NETW_THR_ENGINE_STARTED | 4096 | |
| NETW_SERVER | 4 | |
| NETW_RUN | 64 | |
| NETW_RESTART_TIMER | 8 | |
| NETW_EXIT_ASKED | 128 | |
| NETW_EXITED | 256 | |
| NETW_ERROR | 512 | |
| NETW_ENCRYPT_OPENSSL | 2048 | |
| NETW_ENCRYPT_NONE | 1024 | |
| NETW_EMPTY_SENDBUF | 16 | |
| NETW_EMPTY_RECVBUF | 32 | |
| NETW_DESTROY_SENDBUF | 32768 | |
| NETW_DESTROY_RECVBUF | 16384 | |
| NETW_COMPRESSED_ZLIB | 65536 | |
| NETW_COMPRESSED_LZ4 | 131072 | |
| NETW_CLIENT | 2 |
Network codes declaration.
typedef SOCKET
typedef int SOCKET;
default socket declaration
socket type for POSIX systems
enum NETW_COMPRESS_MODE
| Enumerator | Value | Description |
|---|---|---|
| NETW_COMPRESS_ZLIB | 1 | compress on send with zlib, decompress either on recv |
| NETW_COMPRESS_NONE | 0 | no automatic compression on send, still decompresses inbound |
| NETW_COMPRESS_LZ4 | 2 | compress on send with LZ4, decompress either on recv |
Compression mode selector for NETWORK.compress_mode.
The per-packet state word on the wire carries NETW_COMPRESSED_ZLIB or NETW_COMPRESSED_LZ4 so a receiver in NETW_COMPRESS_AUTO (the default) can decode whichever algorithm the sender chose, while a receiver pinned to a specific algorithm will decode only that flag and pass anything else through uncompressed.
Functions Documentation
function send_udp_data
ssize_t send_udp_data(
void * netw,
char * buf,
uint32_t n
)
UDP send data to connected peer or specified addr.
Parameters:
- netw connected NETWORK
- buf pointer to buffer
- n number of bytes to send
Return: NETW_SOCKET_ERROR on error, n on success
send data via UDP on a connected socket
UDP send data to connected peer or specified addr.
function send_ssl_data_once
ssize_t send_ssl_data_once(
void * netw,
char * buf,
uint32_t n
)
SSL single-attempt write (see send_data_once contract).
Parameters:
- netw the NETWORK to use (crypto must be active)
- buf pointer to buffer
- n number of bytes to try to send (> 0)
Return: > 0 bytes written, NETW_IO_WANT_READ / NETW_IO_WANT_WRITE, NETW_SOCKET_DISCONNECTED, or NETW_SOCKET_ERROR
single-attempt TLS send for non-blocking sockets (reactor use).
SSL single-attempt write (see send_data_once contract).
One SSL_write attempt; WANT_READ/WANT_WRITE are surfaced to the caller's event loop instead of being spun on. Requires SSL_MODE_ENABLE_PARTIAL_WRITE (set at SSL_CTX creation) so a short write can be resumed from the caller's buffer + offset. Note: a TLS send can return NETW_IO_WANT_READ mid-renegotiation, the caller must retry after the next READABLE event.
function send_ssl_data
ssize_t send_ssl_data(
void * netw,
char * buf,
uint32_t n
)
SSL Writing to a socket.
Parameters:
- netw connected NETWORK in SSL mode
- buf pointer to buffer
- n number of characters we want to send
Return: -1 on error, NETW_SOCKET_DISCONNECTED on disconnection, n on success
send data onto the socket
SSL Writing to a socket.
function send_php
ssize_t send_php(
SOCKET s,
int _code,
char * buf,
int n
)
sending to php
Parameters:
- s connected socket
- buf pointer to buffer
- n number of characters we want to send
- _code Code for php decoding rule
Return: -1 on error, n on success
send data onto the socket
sending to php
function send_data_once
ssize_t send_data_once(
void * netw,
char * buf,
uint32_t n
)
Single-attempt write (see NETWORK.send_data_once contract).
Parameters:
- netw the NETWORK to use
- buf pointer to buffer
- n number of bytes to try to send (> 0)
Return: > 0 bytes written, NETW_IO_WANT_WRITE when the socket is not writable, NETW_SOCKET_DISCONNECTED, or NETW_SOCKET_ERROR
single-attempt send for non-blocking sockets (reactor use).
Single-attempt write (see NETWORK.send_data_once contract).
One transport attempt, no loop-until-complete, no retry storm: partial writes are the caller's state machine to handle.
function send_data
ssize_t send_data(
void * netw,
char * buf,
uint32_t n
)
Writing to a socket.
Parameters:
- netw connected NETWORK
- buf pointer to buffer
- n number of characters we want to send
Return: NETW_SOCKET_ERROR on error, NETW_SOCKET_DISCONNECTED on disconnection, 'n' value on success
send data onto the socket
Writing to a socket.
function recv_udp_data
ssize_t recv_udp_data(
void * netw,
char * buf,
uint32_t n
)
UDP recv data from socket.
Parameters:
- netw connected NETWORK
- buf pointer to buffer
- n max number of bytes to receive
Return: NETW_SOCKET_ERROR on error, number of bytes received on success
recv data via UDP from a connected socket
UDP recv data from socket.
function recv_ssl_data_once
ssize_t recv_ssl_data_once(
void * netw,
char * buf,
uint32_t n
)
SSL single-attempt read (see recv_data_once contract).
Parameters:
- netw the NETWORK to use (crypto must be active)
- buf pointer to buffer
- n max number of bytes to read (> 0)
Return: > 0 bytes read, NETW_IO_WANT_READ / NETW_IO_WANT_WRITE, NETW_SOCKET_DISCONNECTED, or NETW_SOCKET_ERROR
single-attempt TLS recv for non-blocking sockets (reactor use).
SSL single-attempt read (see recv_data_once contract).
The caller must loop until NETW_IO_WANT_READ, SSL_read drains its internal plaintext buffer before reporting WANT_READ, so loop-until-WANT_READ also covers the SSL_pending() case that otherwise stalls TLS over edge-triggered epoll.
function recv_ssl_data
ssize_t recv_ssl_data(
void * netw,
char * buf,
uint32_t n
)
SSL Reading from a socket.
Parameters:
- netw connected NETWORK
- buf pointer to buffer
- n number of characters we want
Return: -1 on error, NETW_SOCKET_DISCONNECTED on disconnection n on success
recv data from the socket
SSL Reading from a socket.
function recv_php
ssize_t recv_php(
SOCKET s,
int * _code,
char ** buf
)
receive from php
Parameters:
- s connected socket
- _code pointer to store the code
- buf pointer to buffer
Return: -1 on error, size on success
recv data from the socket
receive from php
function recv_data_once
ssize_t recv_data_once(
void * netw,
char * buf,
uint32_t n
)
Single-attempt read (see NETWORK.recv_data_once contract).
Parameters:
- netw the NETWORK to use
- buf pointer to buffer
- n max number of bytes to read (> 0)
Return: > 0 bytes read, NETW_IO_WANT_READ when no data is available, NETW_SOCKET_DISCONNECTED on orderly EOF / reset, or NETW_SOCKET_ERROR
single-attempt recv for non-blocking sockets (reactor use).
Single-attempt read (see NETWORK.recv_data_once contract).
function recv_data
ssize_t recv_data(
void * netw,
char * buf,
uint32_t n
)
Reading from a socket.
Parameters:
- netw connected NETWORK
- buf pointer to buffer
- n number of characters we want
Return: NETW_SOCKET_ERROR on error, NETW_RECV_DISCONNECTED on disconnection, 'n' value on success
recv data from the socket
Reading from a socket.
function ntohst
size_t ntohst(
size_t value
)
network to host size_t
Parameters:
- value the size_t value to convert to host order
Return: host ordered value
function netw_wait_msg
N_STR * netw_wait_msg(
NETWORK * netw,
unsigned int refresh,
size_t timeout
)
Wait a message from aimed NETWORK.
Parameters:
- netw The link on which we wait a message
- refresh The time in usec between each check until there is a message
- timeout in usecs , maximum amount of time to wait before return. 0 to disable.
Return: NULL or a filled N_STR
Recheck each 'refresh' usec until 'timeout' usec
Recheck each usec until a valid
function netw_wait_close_timed
int netw_wait_close_timed(
NETWORK ** netw,
size_t timeout
)
Closing for peer with timeout.
function netw_wait_close
int netw_wait_close(
NETWORK ** netw
)
Closing for peer.
function netw_urlencode
char * netw_urlencode(
const char * str,
size_t len
)
URL-encode a string.
Parameters:
- str input string
- len input string length
Return: urlencoded char *string or NULL
function to perform URL encoding
URL-encode a string.
function netw_urldecode
char * netw_urldecode(
const char * str
)
URL-decode a string.
Parameters:
- str input string to decode
Return: url decoded string
Function to decode URL-encoded data.
URL-decode a string.
function netw_unload_openssl
int netw_unload_openssl(
void
)
unload ssl helper
Return: TRUE
Do not directly use, internal api.
unload ssl helper
Initialize openssl
function netw_udp_sendto
ssize_t netw_udp_sendto(
NETWORK * netw,
char * buf,
uint32_t n,
struct sockaddr * dest_addr,
socklen_t dest_len
)
UDP sendto with explicit destination.
Parameters:
- netw NETWORK to use for sending
- buf pointer to buffer
- n number of bytes to send
- dest_addr destination sockaddr
- dest_len length of dest_addr
Return: NETW_SOCKET_ERROR on error, bytes sent on success
send data via UDP to a specific destination address
UDP sendto with explicit destination.
function netw_udp_recvfrom
ssize_t netw_udp_recvfrom(
NETWORK * netw,
char * buf,
uint32_t n,
struct sockaddr * src_addr,
socklen_t * src_len
)
UDP recvfrom with source address capture.
Parameters:
- netw NETWORK to use for receiving
- buf pointer to buffer
- n max number of bytes to receive
- src_addr pointer to store source address (can be NULL)
- src_len pointer to length of src_addr (can be NULL)
Return: NETW_SOCKET_ERROR on error, bytes received on success
recv data via UDP and capture the source address
UDP recvfrom with source address capture.
function netw_stop_thr_engine
int netw_stop_thr_engine(
NETWORK * netw
)
Stop a NETWORK connection sending and receiving thread.
Parameters:
- netw The aimed NETWORK conection to stop
Return: TRUE on success FALSE on failure
Stop a NETWORK connection sending and receing thread.
Stop a NETWORK connection sending and receiving thread.
function netw_start_thr_engine
int netw_start_thr_engine(
NETWORK * netw
)
Create the sending and receiving thread of a NETWORK.
Parameters:
- netw The aimed NETWORK connection to start receiving data
Return: TRUE on success FALSE on failure
Start the NETWORK netw Threaded Engine.
Create the sending and receiving thread of a NETWORK.
Create a sending & receiving thread.
function netw_ssl_start_client
int netw_ssl_start_client(
NETWORK * netw
)
set up a client SSL_CTX on an already-connected NETWORK (no handshake yet)
Parameters:
- netw connected NETWORK to promote to SSL. Must not be NULL.
Return: TRUE or FALSE
Set up a client SSL_CTX on an already-connected NETWORK.
set up a client SSL_CTX on an already-connected NETWORK (no handshake yet)
Performs the SSL-context half of netw_ssl_connect_client_to on a NETWORK whose TCP connection is already established (for example one returned by netw_adopt_client_fd after an HTTP CONNECT proxy tunnel): it creates an SSL_CTX with TLS_client_method, loads the default system verify paths, and switches the NETWORK send/recv vtable to the SSL variants. It does NOT perform the handshake. Call netw_ssl_set_ca / netw_ssl_set_verify to configure verification, then netw_ssl_do_handshake to complete the connection. On failure the NETWORK is left untouched (the caller owns it and is responsible for netw_close).
function netw_ssl_set_versions
int netw_ssl_set_versions(
NETWORK * netw,
int min_version,
int max_version
)
set the minimum/maximum TLS protocol version on the connection's SSL context (0 leaves a default).
Parameters:
- netw the network whose SSL context to configure
- min_version minimum version as an OpenSSL TLS*_VERSION constant, or 0 to leave the default
- max_version maximum version likewise, or 0 to leave the default
Return: TRUE on success, FALSE on a bad argument or when OpenSSL refuses the bound
set the minimum (and optionally maximum) TLS protocol version on a connection's SSL context
Pass NETW_TLS_MAX_VERSION rather than TLS1_3_VERSION to stay buildable on OpenSSL 1.0.2
set the minimum/maximum TLS protocol version on the connection's SSL context (0 leaves a default).
A security tool has to be able to say which TLS versions it will speak. Testing whether a host still accepts TLS 1.0, or forcing 1.2 to reproduce a finding, is not possible when the library always negotiates whatever OpenSSL's defaults allow. Call before the handshake; after it, the versions are already agreed and this has no effect.
Below OpenSSL 1.1.0 there is no version-flexible context to bound: the ctx is pinned to TLS 1.2, so a range containing TLS 1.2 is accepted and any other range is refused. Use NETW_TLS_MAX_VERSION rather than naming TLS1_3_VERSION, which does not exist below OpenSSL 1.1.1.
function netw_ssl_set_verify
int netw_ssl_set_verify(
NETWORK * netw,
int enable
)
enable or disable peer certificate verification
Parameters:
- netw the NETWORK to configure
- enable 1 to enable verification, 0 to disable
Return: TRUE or FALSE
enable or disable SSL peer certificate verification
enable or disable peer certificate verification
function netw_ssl_set_client_cert
int netw_ssl_set_client_cert(
NETWORK * netw,
const char * cert_file,
const char * key_file
)
load client certificate and private key for mTLS
Parameters:
- netw the NETWORK to configure
- cert_file path to the client certificate file (PEM)
- key_file path to the client private key file (PEM), or NULL to use cert_file
Return: TRUE or FALSE
load a client certificate and private key for mTLS
load client certificate and private key for mTLS
function netw_ssl_set_ciphers
int netw_ssl_set_ciphers(
NETWORK * netw,
const char * cipher_list,
const char * ciphersuites
)
set the TLS<=1.2 cipher list and/or the TLS1.3 ciphersuites (NULL leaves a default).
Parameters:
- netw the network whose SSL context to configure
- cipher_list OpenSSL cipher-list string for TLS <= 1.2, or NULL to leave the default
- ciphersuites OpenSSL ciphersuite string for TLS 1.3, or NULL to leave the default
Return: TRUE on success, FALSE on a bad argument or when OpenSSL rejects a string
set the cipher list (TLS 1.2 and below) and/or the ciphersuites (TLS 1.3)
The ciphersuites are ignored when NETW_HAVE_TLS13 is 0
set the TLS<=1.2 cipher list and/or the TLS1.3 ciphersuites (NULL leaves a default).
The two are separate knobs in OpenSSL and setting only one silently leaves the other at its default, which is how "I restricted the ciphers" turns into a handshake that used something else entirely. Both are exposed here so a caller can be explicit.
Below OpenSSL 1.1.1 there is no TLS 1.3 to configure, so ciphersuites is logged and ignored while cipher_list still applies; NETW_HAVE_TLS13 tells a caller which of the two it got.
function netw_ssl_set_ca
int netw_ssl_set_ca(
NETWORK * netw,
const char * ca_file,
const char * ca_path
)
set custom CA verify path or file
Parameters:
- netw the NETWORK to configure
- ca_file path to a CA certificate file, or NULL
- ca_path path to a directory of CA certificates, or NULL
Return: TRUE or FALSE
set custom CA verify location for SSL context
set custom CA verify path or file
function netw_ssl_set_alpn
int netw_ssl_set_alpn(
NETWORK * netw,
const char *const * protos,
size_t count
)
offer an ALPN protocol list on a TLS client connection, before its handshake
Parameters:
- netw the NETWORK, with its client SSL_CTX started and its handshake not yet done
- protos the protocol names in client preference order, for example "h2" then "http/1.1"
- count how many protocols
Return: TRUE on success, FALSE on a bad argument or when OpenSSL refused the list
A client that advertises no ALPN is answered with HTTP/1.1 by every modern server, so a proxy or a fetcher that never offers it silently downgrades every connection it makes.
function netw_ssl_server_handshake_once
int netw_ssl_server_handshake_once(
NETWORK * netw,
SSL_CTX * ctx
)
non-blocking (resumable) TLS server handshake against a caller-owned shared ctx: TRUE done, NETW_IO_WANT_READ/WRITE to retry, FALSE on error
Parameters:
- netw an accepted NETWORK (e.g. from netw_accept_nonblock_from)
- ctx the caller-owned server SSL context, shared across connections
Return: TRUE when complete, NETW_IO_WANT_READ / NETW_IO_WANT_WRITE to retry, FALSE on a fatal error
non-blocking, resumable TLS server handshake against a shared ctx
non-blocking (resumable) TLS server handshake against a caller-owned shared ctx: TRUE done, NETW_IO_WANT_READ/WRITE to retry, FALSE on error
The single-attempt counterpart of netw_ssl_server_handshake, for a single-cert server that drives its own poll()/select() loop. Unlike netw_ssl_server_handshake_ex it does NOT create an SSL_CTX or require an SNI pick callback: the caller owns ctx (certificate/key, TLS versions, ...) once and passes it for every accepted connection, typically a NETWORK returned by netw_accept_nonblock_from. On the first call it creates the SSL object from ctx in accept state, binds the socket, installs the SSL send/recv movers, and switches the socket to non-blocking; every call then advances the handshake one step.
The accepted NETWORK keeps netw->ctx == NULL (it borrows ctx, per the accepted-connection convention), so netw_close() frees the SSL object but never the shared context – the caller frees ctx once, after the last connection.
function netw_ssl_server_handshake_ex
int netw_ssl_server_handshake_ex(
NETWORK * netw,
netw_sni_pick_cb pick,
void * user_data,
const char *const * alpn,
size_t alpn_count
)
same, plus an ALPN offer: the first protocol of alpn the client also offered is selected (none when the two lists do not overlap)
Parameters:
- netw an already-accepted plaintext NETWORK
- pick callback that supplies a cert/key for a given SNI host
- user_data opaque pointer passed to pick
- alpn the protocols we accept in server preference order, or NULL for none
- alpn_count how many protocols, 0 for none
Return: TRUE or FALSE
upgrade an already-accepted plaintext connection to a TLS server, selecting the certificate per client SNI and the protocol per ALPN
same, plus an ALPN offer: the first protocol of alpn the client also offered is selected (none when the two lists do not overlap)
Same as netw_ssl_server_handshake(), plus an ALPN offer: the first protocol of alpn that the client also offered is selected, and no ALPN is answered when the two lists do not overlap (the handshake still succeeds, and the peer falls back to whatever it does without ALPN). Read the outcome with netw_ssl_get_alpn(). An intercepting proxy needs this on its client leg: with no ALPN offered, a browser that would have spoken HTTP/2 to the origin speaks HTTP/1.1 to the proxy instead, and the proxy never sees the requests only HTTP/2 can express.
function netw_ssl_server_handshake
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 cert per client SNI via pick() during the handshake (for proxy CONNECT)
Parameters:
- netw an already-accepted plaintext NETWORK
- pick callback that supplies a cert/key for a given SNI host
- user_data opaque pointer passed to pick
Return: TRUE or FALSE
upgrade an already-accepted plaintext connection to a TLS server, selecting the certificate per client SNI
upgrade an already-accepted plaintext connection to a TLS server, selecting the cert per client SNI via pick() during the handshake (for proxy CONNECT)
Sets up a per-connection SSL server context with no default certificate plus an OpenSSL servername callback, then performs SSL_accept on the socket. The callback runs synchronously inside SSL_accept and asks pick() for a certificate matching the requested host, so the handshake completes with a host-specific leaf. Use this when the socket was accepted in the clear first (for example after a proxy CONNECT) and must then become a TLS server.
function netw_ssl_server_ctx_new
SSL_CTX * netw_ssl_server_ctx_new(
const char * key_file,
const char * cert_chain_file
)
new standalone server SSL_CTX with the library's secure defaults (TLS 1.2+, forward-secret AEAD, no compression / renegotiation / tickets), the certificate chain and key loaded from PEM files and checked to match.
Parameters:
- key_file path to the PEM private key
- cert_chain_file path to the PEM certificate chain
Return: the context (free with SSL_CTX_free()), or NULL on error
new standalone server SSL_CTX with the library's secure defaults
For a server that runs its own handshakes (n_http_server); free with SSL_CTX_free().
new standalone server SSL_CTX with the library's secure defaults (TLS 1.2+, forward-secret AEAD, no compression / renegotiation / tickets), the certificate chain and key loaded from PEM files and checked to match.
The certificate file may hold the whole chain (leaf first). The key must match the certificate. For a server that runs its own (non-blocking) handshakes on accepted sockets instead of netw_accept_from_ex().
function netw_ssl_handshake_once
int netw_ssl_handshake_once(
NETWORK * netw,
const char * sni_hostname
)
non-blocking (resumable) TLS client handshake: TRUE done, NETW_IO_WANT_READ/WRITE to retry, FALSE on error
Parameters:
- netw a connected NETWORK carrying a client SSL context (netw->ctx)
- sni_hostname optional SNI server name, or NULL
Return: TRUE when complete, NETW_IO_WANT_READ / NETW_IO_WANT_WRITE to retry, FALSE on a fatal error
non-blocking, resumable TLS client handshake
non-blocking (resumable) TLS client handshake: TRUE done, NETW_IO_WANT_READ/WRITE to retry, FALSE on error
The single-attempt counterpart of netw_ssl_do_handshake, for a caller that drives its own poll()/select() loop instead of the thread engine. Requires a client SSL context already set up on netw (e.g. by netw_ssl_start_client, plus any netw_ssl_set_verify / netw_ssl_set_versions). On the first call it creates the SSL object in connect state, binds the socket, applies SNI, and switches the socket to non-blocking; every call then advances the handshake one step.
function netw_ssl_get_verify_result
int netw_ssl_get_verify_result(
NETWORK * netw,
const char * expected_host,
char * errbuf,
size_t errsz
)
evaluate the peer certificate (chain trust + host match) against the system trust store, independently of the connection verify mode
Parameters:
- netw a NETWORK with a completed client handshake (netw->ssl set)
- expected_host hostname to match against the certificate, or NULL to skip
- errbuf optional buffer that receives a short reason on failure
- errsz size of errbuf
Return: TRUE when the chain is trusted and the host matches, FALSE otherwise
evaluate the peer certificate of a completed TLS client connection
evaluate the peer certificate (chain trust + host match) against the system trust store, independently of the connection verify mode
Verifies the peer certificate chain against the system default trust store and checks that expected_host matches the certificate, independently of the verify mode the handshake ran with. This lets a connection complete with verification disabled (for example an intercepting proxy that must see the traffic regardless) while still reporting whether the real peer certificate would have been trusted.
function netw_ssl_get_sni
const char * netw_ssl_get_sni(
NETWORK * netw
)
get the SNI server_name the peer requested in its ClientHello, or NULL
Parameters:
- netw the accepted NETWORK
Return: the requested host name, or NULL if none / not a TLS connection
get the SNI server_name the peer requested in its ClientHello
get the SNI server_name the peer requested in its ClientHello, or NULL
function netw_ssl_get_alpn
int netw_ssl_get_alpn(
NETWORK * netw,
char * out,
size_t out_len
)
get the ALPN protocol the completed handshake selected, on either side of the connection
Parameters:
- netw the handshaked NETWORK
- out buffer receiving the NUL-terminated protocol name
- out_len capacity of out
Return: TRUE when a protocol was negotiated and copied, FALSE otherwise (out is then set to an empty string when it has room)
get the ALPN protocol the completed handshake selected
get the ALPN protocol the completed handshake selected, on either side of the connection
Works on either side of the connection: the client reads what the server chose from its offer, the server reads what it answered.
function netw_ssl_do_handshake
int netw_ssl_do_handshake(
NETWORK * netw,
const char * sni_hostname
)
complete the SSL handshake on a NETWORK whose ctx was already created.
Parameters:
- netw connected NETWORK with ctx set
- sni_hostname hostname for SNI extension, or NULL to skip
Return: TRUE or FALSE
Complete the SSL handshake on an already-connected NETWORK.
sni_hostname is used for BOTH halves of the identity: it is sent as SNI (so the server picks the right certificate) and set as the name the peer certificate must carry. Without the second half, SSL_VERIFY_PEER checks the chain and nothing else, so any certificate chaining to a trusted root is accepted for any host. An IP literal is matched against the certificate's IP entries, a name against its subjectAltName / CN, and a partial wildcard (w*.example.com) is refused.
With verification on (netw_ssl_set_verify), a mismatch fails the handshake. With it off, the handshake completes and the mismatch is reported by netw_ssl_get_verify_result(), so a caller that deliberately does not verify keeps its previous behaviour. Pass NULL to skip both halves.
complete the SSL handshake on a NETWORK whose ctx was already created.
The NETWORK must have a valid SSL_CTX (from netw_ssl_connect_client or netw_set_crypto). Optionally sets the SNI hostname for virtual hosting support.
function netw_ssl_connect_client_to
int netw_ssl_connect_client_to(
NETWORK ** netw,
char * host,
char * port,
int ip_version,
int connect_timeout_ms
)
like netw_ssl_connect_client but bounds the TCP connect by connect_timeout_ms (0 = OS default)
Parameters:
- netw output: new NETWORK (must be NULL on entry)
- host hostname to connect to
- port port string
- ip_version NETWORK_IPALL, NETWORK_IPV4, or NETWORK_IPV6
- connect_timeout_ms connect timeout in milliseconds, 0 = OS default
Return: TRUE or FALSE
Connect as an SSL client without providing a client certificate.
like netw_ssl_connect_client but bounds the TCP connect by connect_timeout_ms (0 = OS default)
Performs TCP connect, creates an SSL_CTX with TLS_client_method and loads default system verify paths. Does NOT perform the SSL handshake. Call netw_ssl_set_ca / netw_ssl_set_verify to configure verification, then netw_ssl_do_handshake to complete the connection.
function netw_ssl_connect_client
int netw_ssl_connect_client(
NETWORK ** netw,
char * host,
char * port,
int ip_version
)
connect as SSL client without client certificate (TCP + SSL_CTX, no handshake yet)
Parameters:
- netw output: new NETWORK (must be NULL on entry)
- host hostname to connect to
- port port string
- ip_version NETWORK_IPALL, NETWORK_IPV4, or NETWORK_IPV6
Return: TRUE or FALSE
Connect as an SSL client without providing a client certificate.
connect as SSL client without client certificate (TCP + SSL_CTX, no handshake yet)
Equivalent to netw_ssl_connect_client_to with no connect timeout (the OS decides when the TCP connect gives up). See netw_ssl_connect_client_to.
function netw_ssl_connect
int netw_ssl_connect(
NETWORK ** netw,
char * host,
char * port,
int ip_version,
char * ssl_key_file,
char * ssl_cert_file
)
connect ssl helper
Parameters:
- netw a NETWORK *object
- host Host or IP to connect to
- port Port to use to connect
- ip_version NETWORK_IPALL for both ipv4 and ipv6 , NETWORK_IPV4 or NETWORK_IPV6
- ssl_key_file NULL or the path to the SSL key file to use. If set, a ssl_cert_file must also be provided
- ssl_cert_file NULL or the path to the SSL certificate file to use. If set, a ssl_key_file must also be provided
Return: TRUE or FALSE
Use this to connect a NETWORK to any listening one, unrestricted send/recv lists.
connect ssl helper
function netw_setsockopt
int netw_setsockopt(
NETWORK * netw,
int optname,
int value
)
Set common socket options (disable naggle, send/recv buf, reuse addr).
Parameters:
- netw The socket to configure
- optname NETWORK_DEPLETE_SOCKET_TIMEOUT,NETWORK_DEPLETE_QUEUES_TIMEOUT,NETWORK_WAIT_CLOSE_TIMEOUT,NETWORK_CONSECUTIVE_SEND_WAIT,NETWORK_HANDSHAKE_TIMEOUT (msecs, on a listener: deadline for the whole TLS handshake of each accepted connection, 0 = none),SO_REUSEADDR,SO_REUSEPORT,SO_KEEPALIVE,TCP_NODELAY,SO_SNDBUF,SO_RCVBUF,SO_LINGER,SO_RCVTIMEO,SO_SNDTIMEO,TCP_USER_TIMEOUT. Please refer to man setsockopt for details
- value The value of the socket parameter. SO_RCVTIMEO / SO_SNDTIMEO take msecs on every platform (0 = no timeout, < 0 = leave unchanged); until 2026-11-02 POSIX read them as seconds while Windows read msecs. NETW_SOCKOPT_TIMEO_MS is defined from that change on.
Return: TRUE or FALSE
Warning: Beware of TCP_USER_TIMEOUT, it's causing hangs on some systems. It should not be used lightly and tested. It looks like it's messing up with TCP_KEEPALIVE
Modify common socket options on the given netw.
Set common socket options (disable naggle, send/recv buf, reuse addr).
function netw_set_user_id
int netw_set_user_id(
NETWORK * netw,
int id
)
set user id on a netw
Parameters:
- netw targeted network
- id id we want to associated with
Return: TRUE or FALSE
associate an id and a network
set user id on a netw
function netw_set_crypto_pem_ctx
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 THIS connection's SSL only (per-connection, unlike the context-wide netw_set_crypto_pem)
Parameters:
- netw the accepted NETWORK (must already hold an SSL handle)
- key_pem the private key PEM
- cert_pem the certificate PEM
Return: TRUE or FALSE
install an in-memory cert/key on a single accepted connection's SSL
install an in-memory cert/key on THIS connection's SSL only (per-connection, unlike the context-wide netw_set_crypto_pem)
function netw_set_crypto_pem
int netw_set_crypto_pem(
NETWORK * netw,
const char * key_pem,
const char * cert_pem
)
set SSL from PEM strings in memory
Parameters:
- netw the NETWORK to configure
- key_pem PEM-formatted private key string
- cert_pem PEM-formatted certificate string
Return: TRUE or FALSE
activate SSL encryption using PEM-formatted key and certificate strings loaded from memory
set SSL from PEM strings in memory
function netw_set_crypto_chain_pem
int netw_set_crypto_chain_pem(
NETWORK * netw,
const char * key_pem,
const char * cert_pem,
const char * ca_pem
)
set SSL certificate chain from PEM strings in memory
Parameters:
- netw the NETWORK to configure
- key_pem PEM-formatted private key string
- cert_pem PEM-formatted certificate string
- ca_pem PEM-formatted CA certificate string for verification
Return: TRUE or FALSE
activate SSL encryption using PEM strings for key, certificate, and CA
set SSL certificate chain from PEM strings in memory
function netw_set_crypto_chain
int netw_set_crypto_chain(
NETWORK * netw,
char * key,
char * certificate,
char * ca_file
)
set SSL certificate chain from PEM file
Parameters:
- netw the NETWORK to configure
- key path to the key file
- certificate path to the certificate file
- ca_file path to the CA certificate file for chain verification
Return: TRUE or FALSE
activate SSL encryption using key/certificate files and a CA file for chain verification
set SSL certificate chain from PEM file
function netw_set_crypto
int netw_set_crypto(
NETWORK * netw,
char * key,
char * certificate
)
set SSL
Parameters:
- netw the NETWORK instance to configure
- key path to the key file
- certificate path to the certificate file
Return: TRUE of FALSE
activate SSL encryption on selected network, using key and certificate
set SSL
function netw_set_connect_abort_cb
void netw_set_connect_abort_cb(
int(*)(void *ctx) cb,
void * ctx
)
register a process-wide callback polled during connect; non-zero aborts the in-progress connect (NULL removes)
Parameters:
- cb Callback returning non-zero to abort the in-progress connect, or NULL.
- ctx Opaque pointer handed back to
cbon each poll.
Register a process-wide callback polled while a connect is in progress.
register a process-wide callback polled during connect; non-zero aborts the in-progress connect (NULL removes)
When set, netw_connect_ex_to (and every _to / SSL connect variant built on it) wakes every NETW_CONNECT_ABORT_POLL_MS during the connect wait and calls cb; if it returns non-zero the connect is abandoned at once (the connect call returns FALSE) instead of blocking until connect_timeout_ms. This lets an application interrupt a connect to an unresponsive host (a dropped SYN) the way shutdown() already interrupts a blocking read on a connected socket. The callback must be quick and non-blocking. Pass cb = NULL to remove it. The pointer is a single process-global; set it once at startup before concurrent connects (it is read without a lock).
function netw_set_compression_mode
int netw_set_compression_mode(
NETWORK * netw,
int mode
)
Pick send-side compression algorithm for this NETWORK: NETW_COMPRESS_NONE, _ZLIB, _LZ4.
Parameters:
- netw The network to configure (must be non-NULL).
- mode One of NETW_COMPRESS_NONE / NETW_COMPRESS_ZLIB / NETW_COMPRESS_LZ4. Invalid values are rejected.
Return: TRUE on success, FALSE on a NULL netw or unknown mode.
Pick send-side payload compression algorithm.
Independent of the inbound decode path, which always honours whichever flag the sender set.
Pick send-side compression algorithm for this NETWORK: NETW_COMPRESS_NONE, _ZLIB, _LZ4.
Affects outbound packets only. The recv path honours whichever NETW_COMPRESSED_* flag the sender set, so two peers running different modes still interoperate.
function netw_set_blocking
int netw_set_blocking(
NETWORK * netw,
unsigned long int is_blocking
)
set blocking mode
Parameters:
- netw The network to configure
- is_blocking 0 NON BLOCk , 1 BLOCK
Return: TRUE or FALSE
Modify blocking socket mode.
set blocking mode
function netw_set
int netw_set(
NETWORK * netw,
int flag
)
Set flags on network.
Parameters:
- netw The NETWORK *connection to modify
- flag NETW_EMPTY_SENDBUF, NETW_EMPTY_RECVBUF, NETW_RUN , NETW_EXIT_ASKED , NETW_EXITED
Return: TRUE or FALSE
Restart or reset the specified network ability.
Set flags on network.
function netw_send_string_to_all
int netw_send_string_to_all(
NETWORK * netw,
N_STR * name,
N_STR * chan,
N_STR * txt,
int color
)
send string to all targets
Parameters:
- netw The aimed NETWORK where we want to add something to send
- name Name of user
- chan Target Channel, if any. Pass "ALL" to target the default channel
- txt The text to send
- color The color of the text
Return: TRUE or FALSE;
Add a string to the network, aiming all server-side users.
send string to all targets
function netw_send_string_to
int netw_send_string_to(
NETWORK * netw,
int id_to,
N_STR * name,
N_STR * chan,
N_STR * txt,
int color
)
send string to a specific target
Parameters:
- netw The aimed NETWORK where we want to add something to send
- id_to The ID of the targetted client
- name Sender Name
- chan channel to use
- txt Sender text
- color Sender text color
Return: TRUE or FALSE
Add a string to the network, aiming a specific user.
send string to a specific target
function netw_send_quit
int netw_send_quit(
NETWORK * netw
)
send quit message
Parameters:
- netw The aimed NETWORK
Return: TRUE or FALSE
Add a formatted NETMSG_QUIT message to the specified network.
send quit message
function netw_send_position
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
)
send position message
Parameters:
- netw The aimed NETWORK where we want to add something to send
- id The ID of the sending client
- X X position inside a big grid
- Y Y position inside a big grid
- vx X speed
- vy Y speed
- acc_x Y acceleration
- acc_y X acceleration
- time_stamp Current Time when sending (for some delta we would want to compute )
Return: TRUE or FALSE
Add a formatted NETWMSG_IDENT message to the specified network.
send position message
function netw_send_ping
int netw_send_ping(
NETWORK * netw,
int type,
int id_from,
int id_to,
int time
)
send ping message
Parameters:
- netw The aimed NETWORK where we want to add something to send
- id_from Identifiant of the sender
- id_to Identifiant of the destination, -1 if the serveur itslef is targetted
- time The time it was when the ping was sended
- type NETW_PING_REQUEST or NETW_PING_REPLY
Return: TRUE or FALSE
Add a ping reply to the network.
send ping message
function netw_send_ident
int netw_send_ident(
NETWORK * netw,
int type,
int id,
N_STR * name,
N_STR * passwd
)
send ident message
Parameters:
- netw The aimed NETWORK where we want to add something to send
- type type of identification ( NETW_IDENT_REQUEST , NETW_IDENT_NEW )
- id The ID of the sending client
- name Username
- passwd Password
Return: TRUE or FALSE
Add a formatted NETWMSG_IDENT message to the specified network.
send ident message
function netw_send_func
void * netw_send_func(
void * NET
)
Thread Sending management function.
Parameters:
- NET the NETWORK connection to use, casted into (void*)
Return: NULL
Thread send function.
Thread Sending management function.
function netw_recv_func
void * netw_recv_func(
void * NET
)
Thread Receiving management function.
Parameters:
- NET the NETWORK connection to use
Return: NULL ;
To Thread Receiving function.
Thread Receiving management function.
function netw_pool_remove
int netw_pool_remove(
NETWORK_POOL * netw_pool,
NETWORK * netw
)
remove network from pool
Parameters:
- netw_pool targeted network pool
- netw network to remove
Return: TRUE or FALSE
remove a NETWORK *netw to a NETWORK_POOL *pool
remove network from pool
function netw_pool_netw_close
void netw_pool_netw_close(
void * netw_ptr
)
close pool
Parameters:
- netw_ptr NETWORK *network pointer
close a network from a network pool
close pool
function netw_pool_nbclients
size_t netw_pool_nbclients(
NETWORK_POOL * netw_pool
)
get nb clients
Parameters:
- netw_pool targeted network pool
Return: 0 or the number of networks in netw_pool
return the number of networks in netw_pool
get nb clients
function netw_pool_broadcast
int netw_pool_broadcast(
NETWORK_POOL * netw_pool,
const NETWORK * from,
N_STR * net_msg
)
broadcast message to pool
Parameters:
- netw_pool targeted network pool
- from source network
- net_msg mesage to broadcast
Return: TRUE or FALSE
add net_msg to all network in netork pool
broadcast message to pool
function netw_pool_add
int netw_pool_add(
NETWORK_POOL * netw_pool,
NETWORK * netw
)
add network to pool
Parameters:
- netw_pool targeted network pool
- netw network to add
Return: TRUE or FALSE
add a NETWORK *netw to a NETWORK_POOL *pool
add network to pool
function netw_parse_post_data
HASH_TABLE * netw_parse_post_data(
const char * post_data
)
parse POST data into hash table
Parameters:
- post_data the post data to parse
Return: An allocated HASH_TABLE with post data as keys/values, or NULL
Function to parse POST data.
parse POST data into hash table
function netw_new_pool
NETWORK_POOL * netw_new_pool(
size_t nb_min_element
)
init pools
Parameters:
- nb_min_element size of internal hash table for network pool
Return: a new NETWORK_POOL or NULL
return a new network pool of nb_min_element
init pools
function netw_make_listening
int netw_make_listening(
NETWORK ** netw,
char * addr,
char * port,
int nbpending,
int ip_version
)
Listening network.
Parameters:
- netw A NETWORK **network to make listening
- addr Address to bind, NULL for automatic address filling
- port For choosing a PORT to listen to
- nbpending Number of pending connection when listening
- ip_version NETWORK_IPALL for both ipv4 and ipv6 , NETWORK_IPV4 or NETWORK_IPV6
Return: TRUE on success, FALSE on error
Make a NETWORK be a Listening network.
The bind is EXCLUSIVE on every platform: a port another socket already holds is refused, never silently shared. SO_REUSEADDR (so a restarted listener can re-take the port it just released) is set on POSIX only, because on Windows that same option lets an unrelated process bind over a socket already holding the port and leaves which one receives a given connection undefined. Windows refuses the second bind by default, which is the wanted behaviour, so the option is not set there.
Listening network.
function netw_init_wsa
int netw_init_wsa(
int mode,
int v1,
int v2
)
Used by Init & Close network.
Parameters:
- mode 1 for opening 0 for close 2 for status
- v1 First digit of version requested
- v2 Second digit of version requested
Return: TRUE on success FALSE on error
Do not directly use, internal api.
Used by Init & Close network.
Initialize winsock dll loading on windows if needed.
function netw_init_openssl
int netw_init_openssl(
void
)
init ssl helper
Return: TRUE
Do not directly use, internal api.
init ssl helper
Initialize openssl
function netw_info_destroy
int netw_info_destroy(
NETWORK_HTTP_INFO http_request
)
destroy HTTP info structure
Parameters:
- http_request the parsed NETWORK_HTTP_INFO request
Return: TRUE ;
destroy a NETWORK_HTTP_INFO loaded informations
destroy HTTP info structure
function netw_guess_http_content_type
const char * netw_guess_http_content_type(
const char * url
)
guess HTTP content type from URL
Parameters:
- url the url from which we want to guess the content type
Return: a pointer to the detected content type. It will be 'unknown' if no detection worked
function to guess the content type based on URL extension
guess HTTP content type from URL
function netw_get_url_from_http_request
int netw_get_url_from_http_request(
const char * request,
char * url,
size_t size
)
get URL from HTTP request
Parameters:
- request raw http request to decode
- url pointer to an allocated char *holder
- size the size of the url holder
Return: TRUE or FALSE
Helper function to extract the URL from the HTTP request line.
get URL from HTTP request
function netw_get_state
int netw_get_state(
NETWORK * netw,
uint32_t * state,
int * thr_engine_status
)
Get flags from network.
Parameters:
- netw The NETWORK *connection to query
- state pointer to network status storage , NETW_RUN , NETW_EXIT_ASKED , NETW_EXITED
- thr_engine_status pointer to network thread engine status storage ,NETW_THR_ENGINE_STARTED , NETW_THR_ENGINE_STOPPED
Return: TRUE or FALSE
Get the state of a network.
Get flags from network.
function netw_get_queue_status
int netw_get_queue_status(
NETWORK * netw,
size_t * nb_to_send,
size_t * nb_to_read
)
get queue status
Parameters:
- netw NETWORK object
- nb_to_send Number of messages still in send buffer (not yet submitted to kernel)
- nb_to_read Number of message already read by the kernel, waiting in the local message list
Return: TRUE or FALSE
retrieve network send queue status
get queue status
function netw_get_msg
N_STR * netw_get_msg(
NETWORK * netw
)
Get a message from aimed NETWORK.
Parameters:
- netw NETWORK where get the msg
Return: NULL or a filled N_STR
Instant return to NULL if no MSG
function netw_get_http_status_message
const char * netw_get_http_status_message(
int status_code
)
get HTTP status message string
Parameters:
- status_code the code to convert into a human-readable message
Return: a pointer to the human readable message. 'Unknown' is returned if the status code is not supported
helper function to convert status code to a human-readable message
get HTTP status message string
function netw_get_http_date
int netw_get_http_date(
char * buffer,
size_t buffer_size
)
get current HTTP date string
Parameters:
- buffer the target buffer, must be big enough to hold the date
- buffer_size the size of the target buffer
Return: TRUE or FALSE
helper function to generate the current date in HTTP format
get current HTTP date string
function netw_extract_http_request_type
char * netw_extract_http_request_type(
const char * request
)
extract HTTP request type
Parameters:
- request the raw http request
Return: a char *copy of the request type, or NULL
function to extract the request method from an http request
extract HTTP request type
function netw_extract_http_info
NETWORK_HTTP_INFO netw_extract_http_info(
char * request
)
extract HTTP info from request
Parameters:
- request the raw http request string
Return: a NETWORK_HTTP_INFO structure, filled with zeros in case of errors
extract a lot of informations, mostly as pointers, and populate a NETWORK_HTTP_INFO structure
extract HTTP info from request
function netw_destroy_pool
int netw_destroy_pool(
NETWORK_POOL ** netw_pool
)
destroy pool
Parameters:
- netw_pool the address of a NETWORK_POOL *pointer to free
Return: TRUE or FALSE
free a NETWORK_POOL *pool
destroy pool
function netw_connect_udp
int netw_connect_udp(
NETWORK ** netw,
char * host,
char * port,
int ip_version
)
Connect a UDP socket to a remote host.
Parameters:
- netw A NETWORK **network to connect
- host Host or IP to connect to
- port Port to connect to
- ip_version NETWORK_IPALL, NETWORK_IPV4 or NETWORK_IPV6
Return: TRUE on success, FALSE on error
function netw_connect_to
int netw_connect_to(
NETWORK ** netw,
char * host,
char * port,
int ip_version,
int connect_timeout_ms
)
Connecting, with a bounded connection-establishment time (connect_timeout_ms, 0 = OS default).
Parameters:
- netw a NETWORK *object
- host Host or IP to connect to
- port Port to use to connect
- ip_version NETWORK_IPALL for both ipv4 and ipv6 , NETWORK_IPV4 or NETWORK_IPV6
- connect_timeout_ms connect timeout in milliseconds, 0 = OS default
Return: TRUE or FALSE
Connect a NETWORK with a bounded connection-establishment time.
Connecting, with a bounded connection-establishment time (connect_timeout_ms, 0 = OS default).
function netw_connect_nonblock
int netw_connect_nonblock(
NETWORK ** netw,
char * host,
char * port,
int ip_version
)
begin a non-blocking TCP connect: resolve and initiate connect() without waiting; drive to completion with netw_connect_check()
Parameters:
- netw address of an empty (NULL) NETWORK* to fill
- host host or IP to connect to
- port port or service to connect to
- ip_version NETWORK_IPALL / NETWORK_IPV4 / NETWORK_IPV6
Return: TRUE if the connect was initiated, FALSE on resol/allocation failure
begin a non-blocking TCP connect without waiting for it to complete
begin a non-blocking TCP connect: resolve and initiate connect() without waiting; drive to completion with netw_connect_check()
Resolves host : port, creates a non-blocking socket and initiates connect() on the first address, then returns immediately. Drive the connect to completion from a poll()/select() loop with netw_connect_check(); once it returns TRUE, promote the connection with netw_ssl_start_client() + netw_ssl_handshake_once() for TLS, or use it directly for plaintext. This is the non-blocking counterpart of netw_connect_to for callers that must not block a shared thread on a slow or unreachable host.
function netw_connect_ex_to
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
)
Connecting, extended, with a bounded connection-establishment time (connect_timeout_ms, 0 = OS default).
Parameters:
- netw a NETWORK *object
- host Host or IP to connect to
- port Port to use to connect
- send_list_limit Internal sending list maximum number of item. From UNLIMITED_LIST_ITEMS (0) to MAX_LIST_ITEMS (SIZE_MAX).
- recv_list_limit Internal receiving list maximum number of item. From UNLIMITED_LIST_ITEMS (0) to MAX_LIST_ITEMS (SIZE_MAX).
- ip_version NETWORK_IPALL for both ipv4 and ipv6 , NETWORK_IPV4 or NETWORK_IPV6
- ssl_key_file NULL or the path to the SSL key file to use. If set, a ssl_cert_file must also be provided
- ssl_cert_file NULL or the path to the SSL certificate file to use. If set, a ssl_key_file must also be provided
- connect_timeout_ms connect timeout in milliseconds, 0 = OS default
Return: TRUE or FALSE
Use this to connect a NETWORK to any listening one.
Connecting, extended, with a bounded connection-establishment time (connect_timeout_ms, 0 = OS default).
function netw_connect_ex
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
)
Connecting, extended.
Parameters:
- netw a NETWORK *object
- host Host or IP to connect to
- port Port to use to connect
- send_list_limit Internal sending list maximum number of item. From UNLIMITED_LIST_ITEMS (0) to MAX_LIST_ITEMS (SIZE_MAX).
- recv_list_limit Internal receiving list maximum number of item. From UNLIMITED_LIST_ITEMS (0) to MAX_LIST_ITEMS (SIZE_MAX).
- ip_version NETWORK_IPALL for both ipv4 and ipv6 , NETWORK_IPV4 or NETWORK_IPV6
- ssl_key_file NULL or the path to the SSL key file to use. If set, a ssl_cert_file must also be provided
- ssl_cert_file NULL or the path to the SSL certificate file to use. If set, a ssl_key_file must also be provided
Return: TRUE or FALSE
Use this to connect a NETWORK to any listening one.
Connecting, extended.
function netw_connect_check
int netw_connect_check(
NETWORK * netw
)
advance a non-blocking connect: TRUE connected, NETW_IO_WANT_WRITE keep polling for writability, FALSE all addresses failed
Parameters:
- netw a NETWORK from netw_connect_nonblock()
Return: TRUE when connected, NETW_IO_WANT_WRITE while still connecting (keep polling netw->link.sock for POLLOUT), FALSE when every address failed
advance a non-blocking connect started by netw_connect_nonblock()
advance a non-blocking connect: TRUE connected, NETW_IO_WANT_WRITE keep polling for writability, FALSE all addresses failed
Self-contained: it tests the socket for writability (connect completion) without blocking, consults SO_ERROR, and on a failed address transparently moves on to the next resolved address. Call it whenever the socket becomes writable (or on a poll timeout); it never blocks.
function netw_connect
int netw_connect(
NETWORK ** netw,
char * host,
char * port,
int ip_version
)
Connecting.
Parameters:
- netw a NETWORK *object
- host Host or IP to connect to
- port Port to use to connect
- ip_version NETWORK_IPALL for both ipv4 and ipv6 , NETWORK_IPV4 or NETWORK_IPV6
Return: TRUE or FALSE
Use this to connect a NETWORK to any listening one, unrestricted send/recv lists.
Connecting.
function netw_close
int netw_close(
NETWORK ** netw
)
Closing.
Parameters:
- netw A NETWORK *network to close
Return: TRUE on success , FALSE on failure
Closing a specified Network, destroy queues, free the structure.
Closing.
function netw_calculate_urlencoded_size
size_t netw_calculate_urlencoded_size(
const char * str,
size_t len
)
calculate URL-encoded size
Parameters:
- str clear string from which we want to know the urlencoded size
- len length of the input string
Return: the urlencoded size if the string was urlencoded
function to calculate the required size for the URL-encoded string
calculate URL-encoded size
function netw_build_http_response
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
)
build HTTP response
Parameters:
- http_response pointer to a N_STR *response. Will be set to the response, or NULL
- status_code response http status code
- server_name response 'Server' in headers
- content_type response 'Content-Type' in headers
- additional_headers additional response headers, can be "" if no additional headers, else 'backslash r backslash n' separated key: values
- body response 'Server' in headers
Return: TRUE if the http_response was built, FALSE if not
function to dynamically generate an HTTP response
build HTTP response
function netw_bind_udp
int netw_bind_udp(
NETWORK ** netw,
char * addr,
char * port,
int ip_version
)
Create a UDP bound socket.
Parameters:
- netw A NETWORK **network to bind
- addr Address to bind, NULL for wildcard
- port Port to bind to
- ip_version NETWORK_IPALL for both ipv4 and ipv6 , NETWORK_IPV4 or NETWORK_IPV6
Return: TRUE on success, FALSE on error
Create a UDP bound socket for receiving datagrams.
Exclusive on every platform, on the same terms as netw_make_listening: SO_REUSEADDR is POSIX-only because on Windows it permits binding over a port another process already holds.
Create a UDP bound socket.
function netw_adopt_client_fd
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 (plain send/recv)
Parameters:
- netw output: receives the new NETWORK. Must point to NULL on entry.
- fd a connected socket descriptor (must not be INVALID_SOCKET).
- host hostname recorded for logging, or NULL.
- port port string recorded for logging, or NULL.
Return: TRUE on success, FALSE on error.
Adopt an already-connected socket fd into a fresh client NETWORK.
adopt an already-connected socket fd into a fresh client NETWORK (plain send/recv)
Wraps a connected socket file descriptor (for example one returned by n_proxy_connect_tunnel / n_proxy_connect_socks5) in a newly allocated client NETWORK so the blocking send/recv helpers (send_data / netw_read_all / ...) can run over it. The NETWORK is created with the plain (non-SSL) send/recv vtable; promote it with netw_ssl_start_client + netw_ssl_do_handshake to speak TLS over the adopted socket. On success the NETWORK owns fd and closes it in netw_close; on failure fd is left open for the caller to close.
function netw_add_msg_ex
int netw_add_msg_ex(
NETWORK * netw,
char * str,
unsigned int length
)
Add a char message to send in the aimed NETWORK.
Parameters:
- netw NETWORK where add the message
- str the message to add
- length the size of the message to add
Return: TRUE if success FALSE on error
Add a message to send in aimed NETWORK.
Add a char message to send in the aimed NETWORK.
function netw_add_msg
int netw_add_msg(
NETWORK * netw,
N_STR * msg
)
Add a message to send in aimed NETWORK.
function netw_accept_ssl_with_sni_cb
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 via pick() during the handshake
Parameters:
- listen the listening NETWORK from netw_make_listening
- pick callback that supplies a cert/key for a given SNI host
- user_data opaque pointer passed to pick
Return: the accepted NETWORK, or NULL on error
accept a TLS connection, selecting the server certificate per client SNI
accept a TLS connection, selecting the server certificate per client SNI via pick() during the handshake
Accepts a plaintext connection from listen, then upgrades it to a TLS server via netw_ssl_server_handshake(), so the pick callback supplies a leaf matching the client's requested host during the handshake.
function netw_accept_nonblock_from
NETWORK * netw_accept_nonblock_from(
NETWORK * from,
int blocking
)
Accepting routine.
Parameters:
- from The network from which to obtaion the connection
- blocking set to -1 to make it non blocking, to 0 for blocking, else it's the select timeout value in mseconds.
Return: NULL
make a normal blocking 'accept' .
Accepting routine.
Network 'from' must be allocated with netw_make_listening.
function netw_accept_from_ex
NETWORK * netw_accept_from_ex(
NETWORK * from,
size_t send_list_limit,
size_t recv_list_limit,
int blocking,
int * retval
)
Accepting routine extended.
Parameters:
- from the network from where we accept
- send_list_limit Internal sending list maximum number of item. 0 for unrestricted
- recv_list_limit Internal receiving list maximum number of item. 0 for unrestricted
- blocking set to -1 to make it non blocking, to 0 for blocking, else it's the select timeout value in msecs.
- retval EAGAIN ou EWOULDBLOCK or neterrno (use netstrerr( retval) to obtain a string describing the code ), ETIMEDOUT when the TLS handshake ran past the listener's NETWORK_HANDSHAKE_TIMEOUT
Return: NULL on failure, if not a pointer to the connected network
make a normal 'accept' .
Accepting routine extended.
Network 'from' must be allocated with netw_make_listening. On a TLS listener the server handshake runs here, in the caller's thread. By default it is a blocking SSL_accept() with no limit; set netw_setsockopt(listener, NETWORK_HANDSHAKE_TIMEOUT, msecs) to bound it.
function netw_accept_from
NETWORK * netw_accept_from(
NETWORK * from
)
Accepting routine.
Parameters:
- from The network from which to obtaion the connection
Return: NULL
make a normal blocking 'accept' .
Accepting routine.
Network 'from' must be allocated with netw_make_listening.
function n_ws_unmask
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.
function n_ws_send
int n_ws_send(
N_WS_CONN * conn,
const char * payload,
size_t len,
int opcode
)
send a WebSocket frame (client always masks)
Parameters:
- conn WebSocket connection
- payload data to send
- len payload length
- opcode frame opcode (N_WS_OP_TEXT, etc.)
Return: 0 on success, -1 on error
Send a WebSocket frame (client always masks).
send a WebSocket frame (client always masks)
Builds a masked WebSocket frame per RFC 6455 and sends it.
function n_ws_recv
int n_ws_recv(
N_WS_CONN * conn,
N_WS_MESSAGE * msg_out
)
receive one WebSocket frame
Parameters:
- conn WebSocket connection
- msg_out output: populated message. Caller must free payload with free_nstr.
Return: 0 on success, -1 on error or connection closed
Receive one WebSocket frame.
receive one WebSocket frame
Reads the frame header, extended length, optional mask, and payload.
function n_ws_frame_parse
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).
Parameters:
- buf The input bytes (one or more frames, possibly partial).
- len Number of readable bytes in
buf. - frame Receives the parsed header and a payload pointer aliasing
buf. - consumed Receives the total frame size in bytes on a complete frame.
Return: 1 on a complete frame, 0 when more bytes are needed, -1 when malformed or the payload exceeds N_WS_FRAME_MAX_PAYLOAD.
Parse one WebSocket frame from a byte buffer (stateless, no allocation).
Returns 1 and fills frame + *consumed (total frame bytes) on a complete frame, 0 when more bytes are needed, -1 on a malformed or over-large frame. payload aliases buf.
parse one WebSocket frame from a byte buffer (stateless).
function n_ws_frame_build
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).
Returns the number of bytes written, or 0 when out_cap is too small.
function n_ws_connect
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://) and perform the HTTP/1.1 upgrade handshake
Parameters:
- host hostname to connect to
- port port string (e.g. "443")
- path resource path (e.g. "/")
- use_ssl 1 for wss://, 0 for ws://
Return: new N_WS_CONN, or NULL on failure
Connect to a WebSocket server (ws:// or wss://).
connect to a WebSocket server (ws:// or wss://) and perform the HTTP/1.1 upgrade handshake
Performs the HTTP/1.1 upgrade handshake per RFC 6455.
function n_ws_conn_free
void n_ws_conn_free(
N_WS_CONN ** conn
)
free a WebSocket connection structure
Parameters:
- conn pointer to pointer, set to NULL
Free a WebSocket connection structure.
free a WebSocket connection structure
Closes the connection if still open, then frees all members.
function n_ws_close
void n_ws_close(
N_WS_CONN * conn
)
send close frame and close the connection
Parameters:
- conn WebSocket connection
Send close frame and close the connection.
send close frame and close the connection
Sends a close frame (opcode 0x08), attempts to read a close response, then closes the underlying NETWORK.
function n_url_resolve
N_STR * n_url_resolve(
const char * base,
const char * ref
)
resolve a (possibly relative) reference against an absolute base URL (RFC 3986 section 5)
Parameters:
- base an absolute base URL (scheme://host/...). NULL returns NULL.
- ref the reference to resolve. NULL is treated as the empty string.
Return: a newly allocated absolute N_STR URL, or NULL on error.
resolve a (possibly relative) URL reference against an absolute base
resolve a (possibly relative) reference against an absolute base URL (RFC 3986 section 5)
Implements RFC 3986 section 5 reference resolution: a base URL plus a reference found in a document (an href, src, or action) produce an absolute URL. Handles absolute references (returned verbatim), scheme-relative ("//host/path"), absolute-path ("/path"), query-only ("?q"), fragment-only (resolves to the base resource), and relative-path references (merged against the base path). The fragment is dropped (it is not part of the resource identity for crawling) and "." / ".." path segments are removed. The result is not lowercased or otherwise canonicalized; pass it through n_url_canonicalize_string for a dedup key.
function n_url_parse
N_URL * n_url_parse(
const char * url
)
parse a URL string into components
function n_url_free
void n_url_free(
N_URL ** u
)
free a N_URL and all its members
function n_url_encode
N_STR * n_url_encode(
const char * str
)
percent-encode a string for use in URLs (delegates to n_str_url_encode())
function n_url_decode
N_STR * n_url_decode(
const char * str
)
decode a percent-encoded string (returns N_STR)
function n_url_canonicalize_string
N_STR * n_url_canonicalize_string(
const char * url
)
parse and canonicalize a URL string in one call
Parameters:
- url the URL string
Return: a newly allocated N_STR canonical form, or NULL on error
function n_url_canonicalize
N_STR * n_url_canonicalize(
const N_URL * u
)
produce a canonical URL string for dedup (lowercase scheme/host, drop default port, remove .
Parameters:
- u a parsed URL
Return: a newly allocated N_STR canonical form, or NULL on error
produce a canonical URL string for deduplication
/ and ../ segments, keep query)
produce a canonical URL string for dedup (lowercase scheme/host, drop default port, remove .
Lowercases the scheme and host, drops the default port (80 for http, 443 for https), removes "." and ".." path segments, and keeps the query verbatim.
function n_url_build
N_STR * n_url_build(
const N_URL * u
)
build a URL string from parsed components
function n_sse_stop
void n_sse_stop(
N_SSE_CONN * conn
)
signal the SSE connection to stop reading
Parameters:
- conn SSE connection
Signal the SSE connection to stop reading.
signal the SSE connection to stop reading
function n_sse_event_clean
void n_sse_event_clean(
N_SSE_EVENT * event
)
free an SSE event's contents (does not free the event struct itself)
Parameters:
- event the event to clean
Free the contents of an SSE event (does not free the struct itself).
free an SSE event's contents (does not free the event struct itself)
function n_sse_connect
N_SSE_CONN * n_sse_connect(
const char * host,
const char * port,
const char * path,
int use_ssl,
const char * user_agent,
void(*)(N_SSE_EVENT *, N_SSE_CONN *, void *) on_event,
void * user_data
)
connect to an SSE endpoint and start reading events (blocks until stopped).
Parameters:
- user_agent optional User-Agent header value. NULL emits no User-Agent header; some servers (e.g. Wikimedia) reject anonymous clients with 403.
- host hostname
- port port string
- path resource path
- use_ssl 1 for https, 0 for http
- on_event callback for each received event
- user_data passed to callback
Return: new N_SSE_CONN, or NULL on failure
Connect to an SSE endpoint and start reading events.
connect to an SSE endpoint and start reading events (blocks until stopped).
Blocks until stopped or connection closes. Calls on_event for each complete SSE event received.
function n_sse_conn_free
void n_sse_conn_free(
N_SSE_CONN ** conn
)
free an SSE connection
Parameters:
- conn pointer to pointer, set to NULL
Free an SSE connection structure.
free an SSE connection
function n_proxy_connect_tunnel_ssl
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.
Parameters:
- proxy Parsed proxy configuration (scheme must be "https").
- target_host Destination hostname.
- target_port Destination port.
Return: Connected socket fd on success, -1 on failure.
Like n_proxy_connect_tunnel(), but connects to the proxy over TLS first. The CONNECT request and response are exchanged over the encrypted channel. After the tunnel is established, the proxy TLS session is torn down and the raw socket fd is returned, ready for a second TLS handshake to the target or plain HTTP use.
function n_proxy_connect_tunnel
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.
Parameters:
- proxy Parsed proxy configuration. Must not be NULL.
- target_host Destination hostname.
- target_port Destination port.
Return: Connected socket fd on success, -1 on failure.
Connects to the proxy, issues: CONNECT target_host:target_port HTTP/1.1 Host: target_host:target_port Proxy-Authorization: Basic base64(user:pass) (if credentials present)
Verifies the proxy responds with 200 Connection established. Returns the raw socket file descriptor ready for a TLS handshake or plain HTTP use over the tunnel.
function n_proxy_connect_socks5
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.
Parameters:
- proxy Parsed proxy configuration. Must not be NULL.
- target_host Destination hostname.
- target_port Destination port.
Return: Connected socket fd on success, -1 on failure.
Performs the SOCKS5 handshake (no-auth or user/pass auth), requests connection to target_host:target_port. Returns the raw socket fd ready for use.
function n_proxy_cfg_parse
N_PROXY_CFG * n_proxy_cfg_parse(
const char * url
)
Parse a proxy URL string into an N_PROXY_CFG struct.
Parameters:
- url Proxy URL string. Must not be NULL.
Return: Newly allocated N_PROXY_CFG, or NULL on parse failure. Caller must free with n_proxy_cfg_free().
Accepted formats: http://host:porthttp://user:pass@host:port https://host:porthttps://user:pass@host:port socks5://host:port socks5://user:pass@host:port
function n_proxy_cfg_free
void n_proxy_cfg_free(
N_PROXY_CFG ** cfg
)
Free an N_PROXY_CFG created by n_proxy_cfg_parse().
Parameters:
- cfg Pointer to pointer; set to NULL on return.
function n_netw_get_error_count
int n_netw_get_error_count(
const NETWORK * netw
)
Get number of captured errors on a NETWORK handle.
function n_netw_get_error
const char * n_netw_get_error(
const NETWORK * netw,
int index
)
Get captured error message by index (0 = oldest).
Returns NULL if out of range
function n_netw_get_connect_error_count
int n_netw_get_connect_error_count(
void
)
Get number of pre-connection errors captured on this thread.
function n_netw_get_connect_error
const char * n_netw_get_connect_error(
int index
)
Get pre-connection error message by index.
Returns NULL if out of range
function n_netw_clear_errors
void n_netw_clear_errors(
NETWORK * netw
)
Clear captured errors on a NETWORK handle.
function n_netw_clear_connect_errors
void n_netw_clear_connect_errors(
void
)
Clear pre-connection errors on this thread.
function n_mock_server_stop
void n_mock_server_stop(
N_MOCK_SERVER * server
)
signal the mock server to stop accepting connections
Parameters:
- server mock server handle
Signal the mock server to stop accepting connections.
signal the mock server to stop accepting connections
function n_mock_server_start
N_MOCK_SERVER * n_mock_server_start(
int port,
void(*)(N_HTTP_REQUEST *, N_HTTP_RESPONSE *, void *) on_request,
void * user_data
)
start a mock HTTP server on localhost:port (returns immediately)
Parameters:
- port port number to listen on
- on_request callback for each received HTTP request
- user_data arbitrary pointer passed to callback
Return: new N_MOCK_SERVER handle, or NULL on failure
Start a mock HTTP server: set up listener and return immediately.
start a mock HTTP server on localhost:port (returns immediately)
function n_mock_server_run
void n_mock_server_run(
N_MOCK_SERVER * server
)
run the mock server accept loop (blocks until stop_flag is set)
Parameters:
- server mock server handle
Run the mock server accept loop.
run the mock server accept loop (blocks until stop_flag is set)
Blocks until stop_flag is set.
function n_mock_server_free
void n_mock_server_free(
N_MOCK_SERVER ** server
)
free a mock server and close the listening socket
Parameters:
- server pointer to pointer, set to NULL
Free a mock server and close the listening socket.
free a mock server and close the listening socket
function n_http_status_is_success
int n_http_status_is_success(
int status_code
)
1 when status_code is success (2xx), else 0
function n_http_status_is_server_error
int n_http_status_is_server_error(
int status_code
)
1 when status_code is a server error (5xx), else 0
function n_http_status_is_redirect
int n_http_status_is_redirect(
int status_code
)
1 when status_code is a redirect (3xx), else 0
function n_http_status_is_informational
int n_http_status_is_informational(
int status_code
)
1 when status_code is informational (1xx), else 0
function n_http_status_is_client_error
int n_http_status_is_client_error(
int status_code
)
1 when status_code is a client error (4xx), else 0
function n_http_status_class
int n_http_status_class(
int status_code
)
leading digit of an HTTP status code (1..5), or 0 when outside 100..599
function n_http_parse_multipart
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 n_http_multipart_free.
Returns NULL on a bad argument.
function n_http_multipart_free
void n_http_multipart_free(
LIST ** parts
)
free a LIST returned by n_http_parse_multipart and NULL the pointer
function n_http_multipart_boundary
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 "--").
Returns 0 on success, -1 when absent.
function n_http_decompress_body
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 through).
Sets *out to a new N_STR (free with free_nstr). Returns 0 on success, -1 on error.
function n_http_build_multipart
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 "--"); returns a new N_STR (free with free_nstr) or NULL.
function htonst
size_t htonst(
size_t value
)
host to network size_t
Parameters:
- value the size_t value to convert to network order
Return: network ordered value
function deplete_send_buffer
int deplete_send_buffer(
int fd,
int timeout
)
wait for send buffer to be empty
Parameters:
- fd socket descriptor
- timeout timeout value in msec , value <= 0 : disabled
Return: 0 if timeout or unsupported, -1 on error or the amount of remaining datas in bytes
wait until the socket is empty or timeout, checking each 100 msec.
wait for send buffer to be empty
Not as reliable as expected.
function SSL_set_hostflags
static inline void SSL_set_hostflags(
SSL * ssl,
unsigned int flags
)
1.0.2 stand-in for SSL_set_hostflags(): set the X509_CHECK_FLAG_* host-check flags of ssl
function SSL_set1_host
static inline int SSL_set1_host(
SSL * ssl,
const char * host
)
1.0.2 stand-in for SSL_set1_host(): set the expected peer name of ssl, returning 1 on success and 0 on failure
Macros Documentation
define netw_atomic_write_state
#define netw_atomic_write_state(
netw,
val
)
__atomic_store_n(&(netw)->state, (val), __ATOMIC_RELEASE)
Lock-free atomic write of the network state field.
Uses GCC __atomic builtins with release semantics so prior writes are visible to threads performing an acquire load.
define netw_atomic_write_reactor_mode
#define netw_atomic_write_reactor_mode(
netw,
val
)
__atomic_store_n(&(netw)->reactor_mode, (val), __ATOMIC_RELEASE)
define netw_atomic_write_reactor_handle
#define netw_atomic_write_reactor_handle(
netw,
val
)
__atomic_store_n(&(netw)->reactor_handle, (val), __ATOMIC_RELEASE)
define netw_atomic_read_state
#define netw_atomic_read_state(
netw
)
__atomic_load_n(&(netw)->state, __ATOMIC_ACQUIRE)
Lock-free atomic read of the network state field.
Uses GCC __atomic builtins (supported on Linux gcc, Solaris gcc, Windows mingw gcc). Provides acquire semantics so subsequent reads see up-to-date values. For use in send/recv thread hot loops to avoid mutex overhead.
define netw_atomic_read_reactor_mode
#define netw_atomic_read_reactor_mode(
netw
)
__atomic_load_n(&(netw)->reactor_mode, __ATOMIC_ACQUIRE)
Lock-free atomic read of the reactor_mode flag.
The reactor thread clears this flag inside [n_reactor_unregister](n__reactor_8c#user-content-function-n_reactor_unregister) (peer EOF, EXIT_ASKED sweep, or game-thread close handshake), while the game thread reads it from [netw_close](Module-NETWORKING#user-content-function-netw_close) and [netw_add_msg](Module-NETWORKING#user-content-function-netw_add_msg) to decide which dispatch path to take. Both outcomes are correct (the close handshake is designed to be idempotent), but TSan still requires synchronised access to the read/write pair.
define netw_atomic_read_reactor_handle
#define netw_atomic_read_reactor_handle(
netw
)
__atomic_load_n(&(netw)->reactor_handle, __ATOMIC_ACQUIRE)
Same contract for the back-pointer to the reactor.
NULL after unregister. Reads in [netw_add_msg](Module-NETWORKING#user-content-function-netw_add_msg) / [n_reactor_close_netw_sync](n__reactor_8c#user-content-function-n_reactor_close_netw_sync) pair with the write inside [n_reactor_unregister](n__reactor_8c#user-content-function-n_reactor_unregister).
define _OPEN_SYS_SOCK_IPV6
#define _OPEN_SYS_SOCK_IPV6 1
define SSL_get1_peer_certificate
#define SSL_get1_peer_certificate(
ssl
)
SSL_get_peer_certificate(ssl)
define SOCKET_SIZE_FORMAT
#define SOCKET_SIZE_FORMAT "%d"
socket associated printf style
define N_WS_OP_TEXT
#define N_WS_OP_TEXT 0x01
WebSocket opcodes per RFC 6455.
define N_WS_OP_PONG
#define N_WS_OP_PONG 0x0A
define N_WS_OP_PING
#define N_WS_OP_PING 0x09
define N_WS_OP_CLOSE
#define N_WS_OP_CLOSE 0x08
define N_WS_OP_BINARY
#define N_WS_OP_BINARY 0x02
define N_WS_MAX_PAYLOAD
#define N_WS_MAX_PAYLOAD (64 * 1024 * 1024)
Largest WebSocket payload n_ws_recv() will accept from a peer, in bytes.
A frame header declares its payload length in up to 64 bits, so an unvalidated length both invites a peer to ask for an unbounded allocation and, near SIZE_MAX, makes the terminator arithmetic wrap. Anything larger is rejected as a protocol error.
define N_URL_MAX_PARAMS
#define N_URL_MAX_PARAMS 64
maximum number of parsed query parameters
define N_ENUM_netw_code_type
#define N_ENUM_netw_code_type(
_
)
_(NETW_CLIENT, 2) \
_(NETW_SERVER, 4) \
_(NETW_RESTART_TIMER, 8) \
_(NETW_EMPTY_SENDBUF, 16) \
_(NETW_EMPTY_RECVBUF, 32) \
_(NETW_RUN, 64) \
_(NETW_EXIT_ASKED, 128) \
_(NETW_EXITED, 256) \
_(NETW_ERROR, 512) \
_(NETW_ENCRYPT_NONE, 1024) \
_(NETW_ENCRYPT_OPENSSL, 2048) \
_(NETW_THR_ENGINE_STARTED, 4096) \
_(NETW_THR_ENGINE_STOPPED, 8192) \
_(NETW_DESTROY_RECVBUF, 16384) \
_(NETW_DESTROY_SENDBUF, 32768) \
_(NETW_COMPRESSED_ZLIB, 65536) \
_(NETW_COMPRESSED_LZ4, 131072)
Network codes definition.
define NETW_TLS_MAX_VERSION
#define NETW_TLS_MAX_VERSION TLS1_2_VERSION
highest TLS version the linked TLS library can negotiate, as a TLS*_VERSION constant.
Use it instead of naming TLS1_3_VERSION directly: that constant does not exist below OpenSSL 1.1.1 / LibreSSL 3.5, so a literal mention does not compile there.
define NETW_THR_EXIT_OK
#define NETW_THR_EXIT_OK 100
Internal DONE value indicating a send/recv thread reached end-of-life cleanly (peer QUIT or local NETW_EXIT_ASKED ack'd).
define NETW_THR_EXIT_ERROR
#define NETW_THR_EXIT_ERROR 666
Internal DONE value indicating a send/recv thread observed NETW_ERROR without an in-flight local shutdown.
define NETW_SOCKOPT_TIMEO_MS
#define NETW_SOCKOPT_TIMEO_MS 1
Defined when netw_setsockopt() takes SO_RCVTIMEO / SO_SNDTIMEO in msecs on every platform (before, POSIX read seconds and Windows msecs): test it to pick the unit.
define NETW_SOCKET_ERROR
#define NETW_SOCKET_ERROR -1
code for a socket error
define NETW_SOCKET_DISCONNECTED
#define NETW_SOCKET_DISCONNECTED -2
Code for a disconnected recv.
define NETW_RETRY_DELAY
#define NETW_RETRY_DELAY 1000
Send or recv delay between retries in usec.
define NETW_MSG_MAX_FRAME_SIZE
#define NETW_MSG_MAX_FRAME_SIZE (1024UL * 1024UL * 1024UL)
Maximum accepted size, in bytes, of a single received message frame payload.
The on-wire length prefix is an untrusted 32-bit value; any frame claiming more than this is rejected before allocation. This both bounds a hostile peer's memory demand and keeps length + 1 from wrapping a uint32_t. Override at build time if a legitimate deployment needs larger frames. Default: 1 GiB.
define NETW_MAX_RETRIES
#define NETW_MAX_RETRIES 8
Send or recv max number of retries.
define NETW_IO_WANT_WRITE
#define NETW_IO_WANT_WRITE -11
single-attempt I/O: the operation cannot progress until the socket is WRITABLE.
Raw send maps EAGAIN here; TLS maps SSL_ERROR_WANT_WRITE, a TLS recv can also return this.
define NETW_IO_WANT_READ
#define NETW_IO_WANT_READ -10
single-attempt I/O (send_data_once / recv_data_once): the operation cannot progress until the socket is READABLE.
Raw recv maps EAGAIN here; TLS maps SSL_ERROR_WANT_READ, note a TLS send can also return this mid-renegotiation.
define NETW_HAVE_TLS13
#define NETW_HAVE_TLS13 N_OSSL_HAVE_TLS13
1 when the linked TLS library can negotiate TLS 1.3, 0 otherwise.
TLS 1.3 (and with it TLS1_3_VERSION and the SSL_CTX_set_ciphersuites() knob) arrived in OpenSSL 1.1.1 and LibreSSL 3.5; the OpenSSL 1.0.2 this library still supports tops out at TLS 1.2. The test is N_OSSL_HAVE_TLS13 rather than a bare OPENSSL_VERSION_NUMBER comparison because that number is a fixed compatibility value under LibreSSL, see n_openssl_compat.h.
define NETW_COMPRESS_THRESHOLD
#define NETW_COMPRESS_THRESHOLD 256u
Opportunistic compression policy.
Outbound payloads shorter than NETW_COMPRESS_THRESHOLD bytes skip the codec entirely; longer payloads are compressed only if the result is at least NETW_COMPRESS_MIN_RATIO percent smaller than the original (otherwise the original is shipped uncompressed). The reactor's send path (n_reactor_drain_writes) shares these knobs with the thread engine's [netw_send_func](Module-NETWORKING#user-content-function-netw_send_func).
define NETW_COMPRESS_MIN_RATIO
#define NETW_COMPRESS_MIN_RATIO 10u
define NETW_COMPRESSED
#define NETW_COMPRESSED NETW_COMPRESSED_ZLIB
Legacy alias, the first compression commit shipped a single NETW_COMPRESSED flag before LZ4 was added.
Keep the name for any downstream consumer that referenced it before this split.
define NETWORK_WAIT_CLOSE_TIMEOUT
#define NETWORK_WAIT_CLOSE_TIMEOUT 4096
Flag to set network closing wait timeout.
define NETWORK_UDP
#define NETWORK_UDP 1
Flag for UDP transport.
define NETWORK_TCP
#define NETWORK_TCP 0
Flag for TCP transport (default).
define NETWORK_IPV6
#define NETWORK_IPV6 2
Flag to force IPV6.
define NETWORK_IPV4
#define NETWORK_IPV4 1
Flag to force IPV4.
define NETWORK_IPALL
#define NETWORK_IPALL 0
Flag for auto detection by OS of ip version to use.
define NETWORK_HANDSHAKE_TIMEOUT
#define NETWORK_HANDSHAKE_TIMEOUT 8192
Flag to set, on a TLS listener, the deadline in msecs for the whole server handshake of each connection netw_accept_from_ex() accepts (0 = none).
define NETWORK_DISABLE_ZERO_LENGTH_RECV
#define NETWORK_DISABLE_ZERO_LENGTH_RECV FALSE
Enable/disable recv of length 0.
Warning: only enable if you know what you are doing ! (TRUE or FALSE)
define NETWORK_DEPLETE_SOCKET_TIMEOUT
#define NETWORK_DEPLETE_SOCKET_TIMEOUT 512
Flag to set send buffer depletion timeout.
define NETWORK_DEPLETE_QUEUES_TIMEOUT
#define NETWORK_DEPLETE_QUEUES_TIMEOUT 1024
Flag to set network queues depletion timeout.
define NETWORK_CONSECUTIVE_SEND_WAIT
#define NETWORK_CONSECUTIVE_SEND_WAIT 2048
Flag to set consecutive send waiting timeout.
define HEAD_SIZE
#define HEAD_SIZE 10
Size of a HEAD message.
define HEAD_CODE
#define HEAD_CODE 3
Code of a HEAD message.
Modules
- AABB3D
- ACCEPT_POOL
- ALLEGRO4
- ALLEGRO5
- ANIM_LIB
- ASTAR
- ATLAS_LIB
- AVRO
- CLOCK_SYNC
- COMMONS
- CONFIGFILE
- CYPHER_BASE64
- CYPHER_VIGENERE
- DEAD_RECKONING
- ENUMS
- EXCEPTIONS
- GAME_ENV
- GIT
- GUI
- HASH_TABLE
- ISOMETRIC_ENGINE
- LIST
- LOG
- LOGNODUP
- LZ4
- NETWORKING
- NETWORK_MSG
- N_COOKIES
- N_DIFF
- N_DIGEST
- N_DISK_CACHE
- N_DNS
- N_ECC
- N_ENTROPY
- N_FILES
- N_FLUIDS
- N_GUI_COLOR
- N_GUI_COLORWHEEL
- N_GUI_CURVE
- N_GUI_GRID
- N_GUI_POPUP
- N_HEX
- N_HTTP3
- N_HTTP_COOKIE
- N_HTTP_FORM
- N_HTTP_MIME
- N_HTTP_REQ
- N_HTTP_RESP
- N_HTTP_ROUTER
- N_HTTP_SERVER
- N_ICC
- N_JSON
- N_KAFKA
- N_LINALG
- N_MODULE
- N_OPENSSL_COMPAT
- N_PRETTY
- N_PTH
- N_QUERY
- N_RANDOM
- N_SHA256
- N_STR
- N_TIFF
- N_TIME
- N_USER
- N_X509
- N_ZIP
- PARTICLES
- PCRE
- PHYSICS
- SIGNALS
- STACK
- THREADS
- TRAJECTORY
- TREE
- ZLIB