cwist
Modern C web framework with libttak runtime
Loading...
Searching...
No Matches
http.c File Reference

Core HTTP request/response allocation, serialization, socket, and server-loop helpers. More...

#include <cwist/net/http/http.h>
#include <cwist/sys/wasi.h>
#include <cwist/net/http/session.h>
#include <cwist/core/sstring/sstring.h>
#include <cwist/sys/err/cwist_err.h>
#include <cwist/core/mem/alloc.h>
#include <cwist/core/mem/arena.h>
#include <cwist/sys/app/shutdown.h>
#include <cwist/sys/io/reactor.h>
#include "../../sys/io/reactor_rx.h"
#include "../../sys/io/async_debug.h"
#include <cwist/net/http/writer_fast.h>
#include <cwist/core/log.h>
#include <cwist/sys/metrics/metrics.h>
#include <ttak/mols_control.h>
#include <ttak/net/lattice.h>
#include <ttak/priority/scheduler.h>
#include "simd_parser.h"
#include "async_internal.h"
#include "http_live.h"
#include "sockopts.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <strings.h>
#include <errno.h>
#include <cwist/sys/platform.h>
#include <poll.h>
#include <signal.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <pthread.h>
#include <sched.h>
#include <stdatomic.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <sys/stat.h>
#include <sys/resource.h>
#include <fcntl.h>
#include <sys/uio.h>
Include dependency graph for http.c:

Go to the source code of this file.

Macros

#define _POSIX_C_SOURCE   200809L
 
#define HTTP_TASKS_PER_THREAD   32768
 
#define CWIST_HTTP_INFLIGHT_PER_THREAD   32
 
#define CWIST_HTTP_INFLIGHT_FD_RESERVE   4096
 
#define CWIST_POOL_STACK_SIZE   (256 * 1024)
 
#define CWIST_ASYNC_STASH_IDLE_SEC_DEFAULT   10
 
#define CWIST_RX_REARM_MIN_AVAIL   1024
 
#define CWIST_ASYNC_STASH_IDLE   4096
 
#define MAKE_MAGIC4(a, b, c, d)    ((uint32_t)(a) | ((uint32_t)(b) << 8) | ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24))
 
#define MAGIC_GET   MAKE_MAGIC4('G', 'E', 'T', ' ')
 
#define MAGIC_POST   MAKE_MAGIC4('P', 'O', 'S', 'T')
 
#define MAGIC_PUT   MAKE_MAGIC4('P', 'U', 'T', ' ')
 
#define MAGIC_DELE   MAKE_MAGIC4('D', 'E', 'L', 'E')
 
#define MAGIC_HEAD   MAKE_MAGIC4('H', 'E', 'A', 'D')
 
#define CWIST_ASYNC_STASH_MAX   (CWIST_HTTP_READ_BUFFER_SIZE + CWIST_HTTP_MAX_BODY_SIZE)
 
#define CWIST_HTTP_BODY_ZC_MIN   (16 * 1024)
 
#define HTTP_ACCEPT_WAIT_MS   (-1)
 

Typedefs

typedef struct http_pool_task http_pool_task_t
 
typedef struct http_live_conn http_live_conn_t
 

Enumerations

enum  { HTTP_PARK_INLINE = 0 , HTTP_PARK_FILE , HTTP_PARK_BODYREF }
 
enum  cwist_file_begin_result_t { CWIST_FILE_BEGIN_FALLBACK = 0 , CWIST_FILE_BEGIN_HANDLED }
 

Functions

long get_cpu_cores (void)
 Return the number of CPUs available to this process.
 
void cwist_http_pool_limit_core (unsigned int limit)
 Fix the HTTP pool worker count to a specific value.
 
long get_optimal_thread_count (void)
 Compute the HTTP worker/event-loop thread count.
 
uint64_t cwist_http_reactor_generation (void)
 Return the current reactor generation counter.
 
bool cwist_http_reactor_post_live (cwist_reactor_t *reactor, uint64_t gen, cwist_reactor_post_t *node)
 Post a reactor node only while the captured generation is current.
 
long cwist_http_continuation_shed_count (void)
 
long cwist_http_inflight_count (void)
 
bool cwist_http_live_idle_enter (void)
 
void cwist_http_live_idle_leave (void)
 
int cwist_http_pool_init (void)
 Initialize the HTTP connection pool using CWIST_C1M_MODE.
 
int cwist_http_pool_init_mode (bool use_c1m)
 Initialize the HTTP connection pool in the requested mode.
 
void cwist_http_pool_submit (int client_fd, void(*handler)(int, void *), void *ctx)
 Queue a connection for handling on the classic dynamic pool.
 
bool cwist_http_pool_rearm_current (int client_fd, void(*handler)(int, void *), void *ctx)
 Requeue the current connection's next handler turn on the pool.
 
void cwist_http_pool_destroy (void)
 Tear down both pool variants.
 
bool cwist_http_async_rearm (int client_fd, cwist_reactor_t *reactor, cwist_http_async_conn_t *conn)
 Re-arm an async connection for its next event.
 
void cwist_http_async_close_orphan (int client_fd, cwist_http_async_conn_t *conn)
 Close an async connection whose owning worker pool is gone.
 
bool cwist_http_pool_submit_async (int client_fd, cwist_async_handler_t handler, void *ctx)
 Submit a connection to the C1M async reactor pool.
 
const char * cwist_http_method_to_string (cwist_http_method_t method)
 Convert a HTTP method enum into its wire-format token.
 
cwist_http_method_t cwist_http_string_to_method_len (const char *str, size_t len)
 Parse a method token (with explicit length) into a method enum.
 
cwist_http_method_t cwist_http_string_to_method (const char *method_str)
 Parse a NUL-terminated method string into a method enum.
 
cwist_error_t cwist_http_header_add (cwist_http_header_node **head, const char *key, const char *value)
 Prepend one header node to the linked-list header collection.
 
char * cwist_http_header_get (cwist_http_header_node *head, const char *key)
 Find a header value using case-insensitive header-name comparison.
 
size_t cwist_http_header_remove (cwist_http_header_node **head, const char *key)
 Unlink and release every header node matching a name.
 
void cwist_http_response_add_security_headers (cwist_http_response *res)
 Add default security headers to an HTTP response if not already present.
 
void cwist_http_response_add_hsts (cwist_http_response *res)
 Add Strict-Transport-Security to a TLS response (HTTPS only).
 
void cwist_http_header_free_all (cwist_http_header_node *head)
 Destroy every node in a request or response header list.
 
cwist_http_request * cwist_http_request_create (void)
 Allocate and initialize a default HTTP request object.
 
void cwist_http_format_date (time_t t, char *buf, size_t len)
 Resolve the peer IP address for a connected client socket.
 
time_t cwist_http_parse_date (const char *str)
 Parse an HTTP-date string into a time_t.
 
cwist_sstring * cwist_get_client_ip_from_fd (int fd)
 Resolve the peer IP address for a connected client socket.
 
void cwist_http_request_destroy (cwist_http_request *req)
 Destroy a parsed HTTP request and all nested allocations it owns.
 
cwist_http_response * cwist_http_response_create (void)
 Allocate a response backed by its own arena.
 
cwist_http_response * cwist_http_response_create_in_arena (void *arena)
 Allocate a response carved from a caller-owned arena.
 
void cwist_http_response_destroy (cwist_http_response *res)
 Destroy an HTTP response and release any attached body resources.
 
void cwist_http_response_set_body_ptr (cwist_http_response *res, const void *ptr, size_t len)
 Attach an unmanaged zero-copy body pointer to a response.
 
void cwist_http_response_set_body_ptr_managed (cwist_http_response *res, const void *ptr, size_t len, cwist_http_body_cleanup_fn cleanup, void *ctx)
 Attach a managed zero-copy body pointer and optional cleanup hook to a response.
 
void cwist_http_response_set_alt_svc (cwist_http_response *res, const char *alt_svc)
 Set the Alt-Svc header value for HTTP/3 upgrade advertisement.
 
int headers_have_content_length (cwist_http_header_node *headers)
 Detect whether a header list already defines Content-Length.
 
size_t cwist_http_serialize_headers (cwist_http_response *res, char *buf, size_t buf_size)
 Serialize the status line and headers into a caller-provided buffer.
 
bool cwist_tcp_cork_enabled (void)
 TCP_CORK coalescing stub for platforms without TCP_CORK.
 
cwist_error_t cwist_http_send_response (int client_fd, cwist_http_response *res)
 Serialize and send an HTTP response to a connected client socket.
 
cwist_error_t cwist_http_send_response_head (int client_fd, cwist_http_response *res)
 Send only the status line and headers of a response (RFC 9110 section 9.3.2 HEAD semantics): Content-Length reflects the would-be body, but no body bytes are written. Body resources are released as in the full send path.
 
void cwist_http_async_send_response (int client_fd, cwist_http_response *res, cwist_reactor_t *reactor, cwist_http_async_conn_t *conn, bool keep_alive, bool head_only)
 Send a response on the async path, parking the unsent remainder on EAGAIN instead of blocking the reactor thread.
 
cwist_async_send_status_t cwist_http_send_response_async (int client_fd, cwist_http_response *res, cwist_http_async_conn_t *conn, bool keep_alive, bool head_only)
 Async send variant that reports the outcome to the caller instead of re-arming or closing the connection itself (deferred-completion handoff).
 
int cwist_http_coalesce_append (cwist_http_async_conn_t *conn, const void *data, size_t len)
 Append bytes to a connection's coalesced-output stash.
 
cwist_coalesce_flush_status_t cwist_http_coalesce_flush (int client_fd, cwist_http_async_conn_t *conn, bool keep_alive)
 Flush the coalesced-output stash with one speculative write.
 
int cwist_http_coalesce_flush_blocking (int client_fd, cwist_http_async_conn_t *conn)
 Flush the coalesced-output stash, blocking in poll() until drained.
 
int cwist_http_coalesce_error_response (cwist_http_async_conn_t *conn, int status)
 Build a minimal text error response into the coalesce stash.
 
cwist_async_send_status_t cwist_http_send_response_coalesced (int client_fd, cwist_http_response *res, cwist_http_async_conn_t *conn, bool keep_alive, bool head_only)
 Coalescing variant of the async send: serialize small responses directly into the connection's output stash so one reactor turn flushes many responses with a single write.
 
const char * cwist_http_status_reason (int status)
 Map an HTTP status code to its RFC reason phrase.
 
void cwist_http_send_error_response (int fd, int status, const char *msg)
 Send a minimal error response with Connection: close, used to answer malformed requests (400/413/417/431/501) before the connection is dropped.
 
cwist_sstring * cwist_http_stringify_response (cwist_http_response *res)
 Materialize an HTTP response into a contiguous string for debugging or TLS writes.
 
cwist_http_request * cwist_http_parse_request (const char *raw_request)
 Parse a NUL-terminated raw HTTP request buffer.
 
cwist_http_request * cwist_http_parse_request_len (const char *buf, size_t len)
 Parse a raw HTTP request buffer with an explicit length.
 
int cwist_http_response_serialize (cwist_http_response *res, char **out, size_t *out_len)
 Serialize a full response (headers + body) into a heap buffer.
 
int cwist_http_response_stream_begin (cwist_http_response *res)
 Switch a response to chunked streaming mode.
 
int cwist_http_response_stream_write (cwist_http_response *res, const char *data, size_t len)
 Append one data chunk to a streaming response.
 
int cwist_http_response_stream_end (cwist_http_response *res)
 Terminate a streaming response with the final zero-length chunk and flush.
 
cwist_http_request * cwist_http_receive_request (int client_fd, char *read_buf, size_t buf_size, size_t *buf_len, cwist_http_parse_error_t *err_out)
 Blocking read of one full request from a classic-pool connection.
 
int cwist_http_async_conn_fill (cwist_http_async_conn_t *conn)
 Drain the socket into the connection stash. Stops at EAGAIN, and also after a short read: poll is level-triggered, so if bytes remain after a short recv the one-shot re-arm fires again immediately. This skips the guaranteed-EAGAIN second recv that otherwise costs one wasted syscall per request on non-pipelined keep-alive traffic.
 
cwist_recv_status_t cwist_http_receive_request_nb (cwist_http_async_conn_t *conn, cwist_http_request **out, cwist_http_parse_error_t *err_out)
 Try to assemble one complete request from the stash without any blocking IO. On CWIST_RECV_OK the consumed bytes are removed from the stash and *out holds a fully parsed request.
 
cwist_error_t cwist_http_response_send_file (cwist_http_response *res, const char *file_path, const char *content_type_hint, size_t *out_size)
 Prepare a response to serve a file either by buffering or direct streaming.
 
bool cwist_reuseport_enabled (void)
 
int cwist_make_socket_ipv4 (struct sockaddr_in *sockv4, const char *address, uint16_t port, uint16_t backlog)
 Create, configure, bind, and listen on an IPv4 TCP socket.
 
cwist_error_t cwist_accept_socket (int server_fd, struct sockaddr *sockv4, void(*handler_func)(int client_fd, void *), void *ctx)
 Accept one client connection and dispatch it according to the current server strategy.
 
cwist_error_t cwist_http_server_loop (int server_fd, cwist_server_config *config, void(*handler)(int, void *), void *ctx)
 Run the main HTTP accept loop using the configured concurrency strategy.
 

Variables

const int CWIST_CREATE_SOCKET_FAILED = -1
 
const int CWIST_HTTP_UNAVAILABLE_ADDRESS = -2
 
const int CWIST_HTTP_BIND_FAILED = -3
 
const int CWIST_HTTP_SETSOCKOPT_FAILED = -4
 
const int CWIST_HTTP_LISTEN_FAILED = -5
 
const char CWIST_BLOB_200_OK []
 
const char CWIST_BLOB_404 []
 
const char CWIST_BLOB_500 []
 

Detailed Description

Core HTTP request/response allocation, serialization, socket, and server-loop helpers.

Definition in file http.c.

Macro Definition Documentation

◆ _POSIX_C_SOURCE

#define _POSIX_C_SOURCE   200809L

Definition at line 7 of file http.c.

◆ CWIST_ASYNC_STASH_IDLE

#define CWIST_ASYNC_STASH_IDLE   4096

Definition at line 1012 of file http.c.

◆ CWIST_ASYNC_STASH_IDLE_SEC_DEFAULT

#define CWIST_ASYNC_STASH_IDLE_SEC_DEFAULT   10

Definition at line 960 of file http.c.

◆ CWIST_ASYNC_STASH_MAX

Definition at line 4908 of file http.c.

◆ CWIST_HTTP_BODY_ZC_MIN

#define CWIST_HTTP_BODY_ZC_MIN   (16 * 1024)

Definition at line 4913 of file http.c.

◆ CWIST_HTTP_INFLIGHT_FD_RESERVE

#define CWIST_HTTP_INFLIGHT_FD_RESERVE   4096

Definition at line 305 of file http.c.

◆ CWIST_HTTP_INFLIGHT_PER_THREAD

#define CWIST_HTTP_INFLIGHT_PER_THREAD   32

Definition at line 304 of file http.c.

◆ CWIST_POOL_STACK_SIZE

#define CWIST_POOL_STACK_SIZE   (256 * 1024)

Definition at line 353 of file http.c.

◆ CWIST_RX_REARM_MIN_AVAIL

#define CWIST_RX_REARM_MIN_AVAIL   1024

Definition at line 1006 of file http.c.

◆ HTTP_ACCEPT_WAIT_MS

#define HTTP_ACCEPT_WAIT_MS   (-1)

Definition at line 5513 of file http.c.

◆ HTTP_TASKS_PER_THREAD

#define HTTP_TASKS_PER_THREAD   32768

Definition at line 234 of file http.c.

◆ MAGIC_DELE

#define MAGIC_DELE   MAKE_MAGIC4('D', 'E', 'L', 'E')

Definition at line 1574 of file http.c.

◆ MAGIC_GET

#define MAGIC_GET   MAKE_MAGIC4('G', 'E', 'T', ' ')

Definition at line 1571 of file http.c.

◆ MAGIC_HEAD

#define MAGIC_HEAD   MAKE_MAGIC4('H', 'E', 'A', 'D')

Definition at line 1575 of file http.c.

◆ MAGIC_POST

#define MAGIC_POST   MAKE_MAGIC4('P', 'O', 'S', 'T')

Definition at line 1572 of file http.c.

◆ MAGIC_PUT

#define MAGIC_PUT   MAKE_MAGIC4('P', 'U', 'T', ' ')

Definition at line 1573 of file http.c.

◆ MAKE_MAGIC4

#define MAKE_MAGIC4 (   a,
  b,
  c,
  d 
)     ((uint32_t)(a) | ((uint32_t)(b) << 8) | ((uint32_t)(c) << 16) | ((uint32_t)(d) << 24))

Definition at line 1568 of file http.c.

Typedef Documentation

◆ http_live_conn_t

◆ http_pool_task_t

Enumeration Type Documentation

◆ anonymous enum

Enumerator
HTTP_PARK_INLINE 
HTTP_PARK_FILE 
HTTP_PARK_BODYREF 

Definition at line 3009 of file http.c.

◆ cwist_file_begin_result_t

Enumerator
CWIST_FILE_BEGIN_FALLBACK 
CWIST_FILE_BEGIN_HANDLED 

Definition at line 3261 of file http.c.

Function Documentation

◆ cwist_accept_socket()

cwist_error_t cwist_accept_socket ( int  server_fd,
struct sockaddr *  sockv4,
void(*)(int client_fd, void *)  handler_func,
void *  ctx 
)

Accept one client connection and dispatch it according to the current server strategy.

Parameters
server_fdListening server socket.
sockv4Scratch sockaddr buffer for accept(2).
handler_funcCallback that handles one accepted client.
ctxOpaque callback context.
Returns
Tagged CWIST error describing success or failure.

Definition at line 5550 of file http.c.

References cap, CWIST_ERR_INT16, and make_error().

Referenced by cwist_http_server_loop().

◆ cwist_get_client_ip_from_fd()

cwist_sstring * cwist_get_client_ip_from_fd ( int  fd)

Resolve the peer IP address for a connected client socket.

Parameters
fdConnected client socket descriptor.
Returns
New sstring with the textual IP; "127.0.0.1" when unavailable.

Definition at line 2141 of file http.c.

References cap, cwist_sstring_assign(), and cwist_sstring_create().

◆ cwist_http_async_close_orphan()

void cwist_http_async_close_orphan ( int  client_fd,
cwist_http_async_conn_t *  conn 
)

Close an async connection whose owning worker pool is gone.

Marks the load slot index invalid so the teardown does not touch load counters that may belong to a later pool generation.

Definition at line 1453 of file http.c.

References cap, and cwist_http_async_conn::worker_id.

◆ cwist_http_async_conn_fill()

int cwist_http_async_conn_fill ( cwist_http_async_conn_t *  conn)

Drain the socket into the connection stash. Stops at EAGAIN, and also after a short read: poll is level-triggered, so if bytes remain after a short recv the one-shot re-arm fires again immediately. This skips the guaranteed-EAGAIN second recv that otherwise costs one wasted syscall per request on non-pipelined keep-alive traffic.

Returns
0 on data, EAGAIN, or EOF (recorded in peer_eof); -1 on fatal error.

Definition at line 4956 of file http.c.

References cwist_http_async_conn::cap, cap, cwist_http_async_conn::fd, cwist_http_async_conn::len, cwist_http_async_conn::peer_eof, cwist_http_async_conn::rbuf, cwist_http_async_conn::rx_data_ready, cwist_http_async_conn::rx_recv_inflight, and cwist_http_async_conn::virgin.

Referenced by cwist_app_http_handler_async().

◆ cwist_http_async_rearm()

bool cwist_http_async_rearm ( int  client_fd,
cwist_reactor_t *  reactor,
cwist_http_async_conn_t *  conn 
)

Re-arm an async connection for its next event.

Handles deferred-completion shutdown races, peer EOF, pipelined bytes (posted as a continuation so other connections run between batches), and RECV-first re-arm with a POLL fallback.

Returns
false when the connection was closed or the re-arm failed.

Definition at line 1357 of file http.c.

References cap, cwist_alloc(), cwist_fast_monotonic_sec(), cwist_free(), CWIST_METRIC_HTTP_CONTINUATION_SHED, cwist_metric_inc(), cwist_metrics_registry(), cwist_http_async_conn::handler, cwist_http_async_conn::last_active_sec, cwist_http_async_conn::len, cwist_http_async_conn::peer_eof, and cwist_http_async_conn::user_ctx.

Referenced by cwist_app_http_handler_async(), and cwist_http_async_send_response().

◆ cwist_http_async_send_response()

void cwist_http_async_send_response ( int  client_fd,
cwist_http_response *  res,
cwist_reactor_t *  reactor,
cwist_http_async_conn_t *  conn,
bool  keep_alive,
bool  head_only 
)

Send a response on the async path, parking the unsent remainder on EAGAIN instead of blocking the reactor thread.

Pointer bodies park by reference (ownership moves to the park state); other bodies deep-copy the unsent remainder. File streams use the non-blocking sendfile path. On completion the connection is re-armed for keep-alive or closed.

Definition at line 3413 of file http.c.

References cwist_http_response::body, cap, cwist_alloc(), CWIST_FILE_BEGIN_HANDLED, cwist_free(), cwist_http_async_rearm(), CWIST_HTTP_MAX_HEADER_SIZE, cwist_http_send_response(), cwist_http_sendmsg_speculative(), cwist_reactor_add_out(), CWIST_WRITE_DONE, CWIST_WRITE_PENDING, cwist_sstring::data, g_cwist_running, cwist_http_response::is_ptr_body, cwist_http_async_conn::len, MSG_DONTWAIT, cwist_http_response::ptr_body, cwist_http_response::ptr_body_len, cwist_sstring::size, and cwist_http_response::use_file_stream.

◆ cwist_http_coalesce_append()

int cwist_http_coalesce_append ( cwist_http_async_conn_t *  conn,
const void *  data,
size_t  len 
)

Append bytes to a connection's coalesced-output stash.

Returns
0 on success, -1 when the data would exceed the coalesce cap or the stash could not be grown.

Definition at line 3653 of file http.c.

References cap, cwist_alloc(), cwist_fast_monotonic_sec(), cwist_free(), CWIST_HTTP_COALESCE_MAX, cwist_http_async_conn::obuf, cwist_http_async_conn::ocap, cwist_http_async_conn::olen, and cwist_http_async_conn::stash_grown_sec.

Referenced by cwist_http_coalesce_error_response().

◆ cwist_http_coalesce_error_response()

int cwist_http_coalesce_error_response ( cwist_http_async_conn_t *  conn,
int  status 
)

Build a minimal text error response into the coalesce stash.

Returns
0 on success, -1 when the response could not be appended.

Definition at line 3756 of file http.c.

References cap, cwist_http_coalesce_append(), and cwist_http_status_reason().

◆ cwist_http_coalesce_flush()

cwist_coalesce_flush_status_t cwist_http_coalesce_flush ( int  client_fd,
cwist_http_async_conn_t *  conn,
bool  keep_alive 
)

Flush the coalesced-output stash with one speculative write.

On a partial write the unsent remainder is deep-copied into the parked writer, which re-arms or closes the connection when it drains.

Returns
DONE when fully written, PARKED when deferred, ERROR otherwise.

Definition at line 3682 of file http.c.

References cap, cwist_alloc(), CWIST_COALESCE_FLUSH_DONE, CWIST_COALESCE_FLUSH_ERROR, CWIST_COALESCE_FLUSH_PARKED, cwist_free(), cwist_http_sendmsg_speculative(), cwist_reactor_add_out(), CWIST_WRITE_DONE, CWIST_WRITE_PENDING, g_cwist_running, cwist_http_async_conn::len, MSG_DONTWAIT, cwist_http_async_conn::obuf, cwist_http_async_conn::olen, and cwist_http_async_conn::reactor.

Referenced by cwist_app_http_handler_async().

◆ cwist_http_coalesce_flush_blocking()

int cwist_http_coalesce_flush_blocking ( int  client_fd,
cwist_http_async_conn_t *  conn 
)

Flush the coalesced-output stash, blocking in poll() until drained.

Returns
0 on success, -1 on send failure.

Definition at line 3737 of file http.c.

References cap, MSG_DONTWAIT, cwist_http_async_conn::obuf, and cwist_http_async_conn::olen.

Referenced by cwist_http_receive_request_nb(), and cwist_http_send_response_coalesced().

◆ cwist_http_continuation_shed_count()

long cwist_http_continuation_shed_count ( void  )

Continuations dropped because the reactor post queue was full; each one closed its connection. Exported for metrics/observability.

Definition at line 293 of file http.c.

References cap.

Referenced by cwist_metric_load(), and cwist_metrics_render_prometheus().

◆ cwist_http_format_date()

void cwist_http_format_date ( time_t  t,
char *  buf,
size_t  len 
)

Resolve the peer IP address for a connected client socket.

Format a time_t as an HTTP-date (RFC 7231).

Parameters
fdConnected client socket descriptor.
Returns
Heap-allocated string containing the textual IP address.

Format a time_t as an HTTP-date (RFC 7231).

Parameters
tUnix timestamp.
bufOutput buffer.
lenBuffer capacity.

Definition at line 2108 of file http.c.

References cap.

◆ cwist_http_header_add()

cwist_error_t cwist_http_header_add ( cwist_http_header_node **  head,
const char *  key,
const char *  value 
)

Prepend one header node to the linked-list header collection.

Prepend a header to the list.

Add a header to the list.

Parameters
headHeader-list head pointer to update.
keyHeader name to store.
valueHeader value to store.
Returns
Tagged CWIST error: INT16 0 on success, INT16 -1 when head is NULL or key/value contains CR or LF (nothing is added), or a JSON error on allocation failure.

Definition at line 1861 of file http.c.

References cap, CWIST_ERR_INT16, head, and make_error().

Referenced by cwist_app_healthz(), cwist_async_abort(), cwist_async_respond(), cwist_bind_write_error_response(), cwist_graphql_serve(), cwist_grpc_set_response(), cwist_grpc_stream_close(), cwist_grpc_stream_set_retry_pushback(), cwist_http2_push_resource(), cwist_http_response_send_file(), cwist_https_send_response(), cwist_https_send_response_head(), cwist_metrics_serve_http(), cwist_mw_cors_handler(), cwist_mw_request_id_handler(), cwist_sse_response_init(), and cwist_websocket_upgrade_response().

◆ cwist_http_header_free_all()

void cwist_http_header_free_all ( cwist_http_header_node *  head)

Destroy every node in a request or response header list.

Free all headers.

Parameters
headHead of the header linked list.

Definition at line 2006 of file http.c.

References cap, cwist_free(), cwist_sstring_destroy(), head, and cwist_http_header_node::next.

Referenced by cwist_http_client_request(), cwist_http_request_destroy(), and cwist_http_response_destroy().

◆ cwist_http_header_get()

char * cwist_http_header_get ( cwist_http_header_node *  head,
const char *  key 
)

Find a header value using case-insensitive header-name comparison.

Finds a header value by key.

Find a header value by key.

Parameters
headHead of the header linked list.
keyHeader name to search for.
Returns
Raw header value string, or NULL when absent.

Definition at line 1880 of file http.c.

References cap, cwist_sstring::data, head, and cwist_http_header_node::value.

Referenced by cwist_assets_respond(), cwist_http3_push_resource(), cwist_http_response_add_hsts(), cwist_http_response_add_security_headers(), cwist_http_response_send_file(), cwist_https_send_response(), cwist_https_send_response_head(), cwist_mw_request_id_handler(), cwist_session_start(), and cwist_websocket_upgrade_response().

◆ cwist_http_header_remove()

size_t cwist_http_header_remove ( cwist_http_header_node **  head,
const char *  key 
)

Unlink and release every header node matching a name.

Remove all headers matching a name, honoring per-node ownership (heap vs arena vs borrowed buffers).

Parameters
headPointer to the header-list head; updated as nodes are removed.
keyHeader name (case-insensitive) to remove; all duplicates go.
Returns
Number of nodes removed.

Ownership is handled per node: heap-owned nodes are freed, arena-owned nodes are left for the arena to reclaim, and borrowed key/value buffers are never freed individually. Applications should call this instead of hand-rolling unlink loops, which have repeatedly gotten that bookkeeping wrong.

Definition at line 1907 of file http.c.

References cwist_http_header_node::arena_owned, cap, cwist_free(), cwist_sstring_destroy(), cwist_sstring::data, head, cwist_http_header_node::key, cwist_http_header_node::next, and cwist_http_header_node::value.

Referenced by cwist_http_response_html_redirect().

◆ cwist_http_inflight_count()

long cwist_http_inflight_count ( void  )

Live C1M connections (accepted, not yet closed). The shutdown drain in cwist_app_listen_ex polls this to exit early once nothing is left. Acquire pairs with the handlers' release decrement, so once the drain sees zero, everything those handlers did happens before cwist_app_destroy().

Definition at line 301 of file http.c.

References cap.

◆ cwist_http_live_idle_enter()

bool cwist_http_live_idle_enter ( void  )

Mark the calling worker's connection idle (waiting for a new request).

Returns
false when the pool is shutting down: the caller must treat the connection as closed by the peer instead of waiting on it.

Definition at line 423 of file http.c.

References cap.

Referenced by cwist_app_http_handler(), and cwist_http_receive_request().

◆ cwist_http_live_idle_leave()

void cwist_http_live_idle_leave ( void  )

The connection received request bytes; it is no longer idle.

Definition at line 434 of file http.c.

References cap.

Referenced by cwist_app_http_handler(), and cwist_http_receive_request().

◆ cwist_http_method_to_string()

const char * cwist_http_method_to_string ( cwist_http_method_t  method)

Convert a HTTP method enum into its wire-format token.

Convert method enum to string.

Parameters
methodHTTP method enum value.
Returns
Static string name for the method.

Definition at line 1554 of file http.c.

References CWIST_HTTP_CONNECT, CWIST_HTTP_DELETE, CWIST_HTTP_GET, CWIST_HTTP_HEAD, CWIST_HTTP_OPTIONS, CWIST_HTTP_PATCH, CWIST_HTTP_POST, and CWIST_HTTP_PUT.

Referenced by cwist_http_client_request().

◆ cwist_http_parse_date()

time_t cwist_http_parse_date ( const char *  str)

Parse an HTTP-date string into a time_t.

Parameters
strHTTP-date string.
Returns
Parsed timestamp, or (time_t)-1 on failure.

Definition at line 2119 of file http.c.

References cap.

◆ cwist_http_parse_request()

cwist_http_request * cwist_http_parse_request ( const char *  raw_request)

Parse a NUL-terminated raw HTTP request buffer.

Parse a raw HTTP request string.

Returns
Parsed request, or NULL when no header terminator exists.

Definition at line 4412 of file http.c.

References cap.

Referenced by cwist_https_receive_request().

◆ cwist_http_parse_request_len()

cwist_http_request * cwist_http_parse_request_len ( const char *  buf,
size_t  len 
)

Parse a raw HTTP request buffer with an explicit length.

Parse an HTTP/1.x request held in a memory buffer (length-based; the buffer may contain a binary body and need not be NUL-terminated).

Returns
Parsed request, or NULL when no header terminator exists.

Definition at line 4424 of file http.c.

References cap.

Referenced by cwist_app_dispatch_memory(), and cwist_app_dispatch_stream().

◆ cwist_http_pool_destroy()

void cwist_http_pool_destroy ( void  )

Tear down both pool variants.

Stops new work, drains queued tasks, retires the reactor generation and waits for in-flight posters, then stops, joins, and frees the C1M reactors.

Definition at line 836 of file http.c.

References cap, cwist_free(), cwist_reactor_destroy(), and cwist_reactor_stop().

Referenced by cwist_async_server_loop(), and cwist_http_server_loop().

◆ cwist_http_pool_init()

int cwist_http_pool_init ( void  )

Initialize the HTTP connection pool using CWIST_C1M_MODE.

Initialize the handler pool in the mode CWIST_C1M_MODE selects.

Returns
0 on success, -1 on failure.

Definition at line 678 of file http.c.

References cap, and cwist_http_pool_init_mode().

◆ cwist_http_pool_init_mode()

int cwist_http_pool_init_mode ( bool  use_c1m)

Initialize the HTTP connection pool in the requested mode.

Initialize the handler pool as reactor workers (use_c1m) or the classic thread pool, without reading CWIST_C1M_MODE.

Parameters
use_c1mtrue for the event-driven reactor (C1M) pool, false for the classic dynamic thread pool.
Returns
0 on success, -1 on failure (partially created state is cleaned up by cwist_http_pool_destroy()).

Definition at line 696 of file http.c.

References cap, cwist_alloc(), cwist_free(), cwist_reactor_create(), and get_optimal_thread_count().

Referenced by cwist_async_server_loop(), cwist_http_pool_init(), and cwist_http_server_loop().

◆ cwist_http_pool_limit_core()

void cwist_http_pool_limit_core ( unsigned int  limit)

Fix the HTTP pool worker count to a specific value.

Parameters
limitFixed thread count; 0 restores automatic sizing.

Definition at line 145 of file http.c.

References cap.

◆ cwist_http_pool_rearm_current()

bool cwist_http_pool_rearm_current ( int  client_fd,
void(*)(int, void *)  handler,
void *  ctx 
)

Requeue the current connection's next handler turn on the pool.

Returns
false for invalid arguments (fd < 0 or NULL handler).

Definition at line 824 of file http.c.

References cwist_http_pool_submit().

◆ cwist_http_pool_submit()

void cwist_http_pool_submit ( int  client_fd,
void(*)(int, void *)  handler,
void *  ctx 
)

Queue a connection for handling on the classic dynamic pool.

Enforces the inflight limit (over-limit connections get a bare 503 and are closed) and spawns an extra worker when queued demand exceeds idle capacity.

Definition at line 772 of file http.c.

References cap, cwist_alloc(), and MSG_DONTWAIT.

Referenced by cwist_http_pool_rearm_current(), and cwist_http_server_loop().

◆ cwist_http_pool_submit_async()

bool cwist_http_pool_submit_async ( int  client_fd,
cwist_async_handler_t  handler,
void *  ctx 
)

Submit a connection to the C1M async reactor pool.

Enforces the inflight limit (503 + close on overflow), sets the socket non-blocking, allocates the connection shell, and load-balances with power-of-two-choices over the per-worker load counters.

Returns
false when the connection was rejected or the initial arm failed.

Definition at line 1468 of file http.c.

References cap, cwist_alloc(), cwist_fast_monotonic_sec(), cwist_sched_p2c_select_worker(), cwist_http_async_conn::fd, cwist_http_async_conn::handler, cwist_http_async_conn::last_active_sec, MSG_DONTWAIT, cwist_http_async_conn::reactor, cwist_http_async_conn::stash_grown_sec, cwist_http_async_conn::user_ctx, cwist_http_async_conn::virgin, and cwist_http_async_conn::worker_id.

◆ cwist_http_reactor_generation()

uint64_t cwist_http_reactor_generation ( void  )

Return the current reactor generation counter.

Deferred completions capture the generation so they can detect pool teardown; see g_reactor_gen for the protocol.

Definition at line 268 of file http.c.

References cap.

Referenced by cwist_async_defer().

◆ cwist_http_reactor_post_live()

bool cwist_http_reactor_post_live ( cwist_reactor_t *  reactor,
uint64_t  gen,
cwist_reactor_post_t *  node 
)

Post a reactor node only while the captured generation is current.

Counts the caller in g_reactor_posters around the generation check and the post so cwist_http_pool_destroy() cannot free the reactor in between.

Parameters
reactorReactor to post into.
genGeneration the completion was created under.
nodePost node to enqueue.
Returns
true when the node was posted; false when the generation moved or the post failed (the caller must close instead).

Definition at line 283 of file http.c.

References cap.

◆ cwist_http_receive_request()

cwist_http_request * cwist_http_receive_request ( int  client_fd,
char *  read_buf,
size_t  buf_size,
size_t *  buf_len,
cwist_http_parse_error_t *  err_out 
)

Blocking read of one full request from a classic-pool connection.

Receive and parse an HTTP request from a socket.

Bounds the header read by CWIST_HTTP_HEADERS_TIMEOUT_MS, answers a validated Expect: 100-continue, then completes the body per Content-Length or chunked framing. Leftover pipelined bytes are compacted into read_buf and *buf_len is updated.

Returns
Parsed request, or NULL with *err_out set (defaults to CWIST_HTTP_PARSE_EOF).

Definition at line 4722 of file http.c.

References cwist_http_request::body, cap, cwist_http_request::content_length, cwist_alloc(), cwist_free(), CWIST_HTTP_HEADERS_TIMEOUT_MS, cwist_http_live_idle_enter(), cwist_http_live_idle_leave(), CWIST_HTTP_MAX_BODY_SIZE, CWIST_HTTP_PARSE_BODY_TOO_LARGE, CWIST_HTTP_PARSE_EOF, CWIST_HTTP_PARSE_HEADER_OVERFLOW, CWIST_HTTP_PARSE_MALFORMED, CWIST_HTTP_PARSE_OK, cwist_http_request_destroy(), CWIST_HTTP_TIMEOUT_MS, CWIST_LOG_WARN, CWIST_METRIC_HTTP_HEADER_OVERFLOW, cwist_metric_inc(), cwist_metrics_registry(), cwist_sstring_adopt_len(), cwist_sstring_create(), cwist_sstring_destroy(), cwist_http_request::expect_100_seen, and cwist_http_request::te_chunked_seen.

Referenced by cwist_app_http_handler().

◆ cwist_http_receive_request_nb()

◆ cwist_http_request_create()

◆ cwist_http_request_destroy()

◆ cwist_http_response_add_hsts()

void cwist_http_response_add_hsts ( cwist_http_response *  res)

Add Strict-Transport-Security to a TLS response (HTTPS only).

RFC 6797 section 7.2 prohibits HSTS over plain HTTP. Call this only from an HTTPS handler, after cwist_http_response_add_security_headers(). No-op when the header is already present.

Parameters
resResponse object to populate.

Definition at line 1993 of file http.c.

References cwist_http_response::arena, cwist_http_header_get(), and cwist_http_response::headers.

◆ cwist_http_response_add_security_headers()

void cwist_http_response_add_security_headers ( cwist_http_response *  res)

Add default security headers to an HTTP response if not already present.

Add default security headers (CSP, X-Frame-Options, Permissions-Policy, etc.) if missing.

Add default security headers (CSP, X-Frame-Options, etc.) if missing.

Safe to call for both HTTP and HTTPS responses. HSTS is intentionally omitted here because RFC 6797 section 7.2 forbids sending it over plain HTTP; browsers ignore it on non-TLS connections anyway. Use cwist_http_response_add_hsts() from your HTTPS handler to add it there.

Parameters
resResponse object to populate.

Definition at line 1935 of file http.c.

References cwist_http_response::arena, cwist_http_header_get(), and cwist_http_response::headers.

◆ cwist_http_response_create()

cwist_http_response * cwist_http_response_create ( void  )

Allocate a response backed by its own arena.

Create a new HTTP response object.

Returns
Newly allocated response, or NULL on failure.

Definition at line 2291 of file http.c.

References cap, cwist_arena_create(), and cwist_arena_destroy().

Referenced by cwist_app_dispatch_memory(), cwist_app_dispatch_stream(), cwist_http_client_request(), cwist_http_response_create_in_arena(), and cwist_websocket_upgrade().

◆ cwist_http_response_create_in_arena()

cwist_http_response * cwist_http_response_create_in_arena ( void *  arena)

Allocate a response carved from a caller-owned arena.

Create a response inside an existing (request) arena. The response is bump-allocated from arena and shares its lifetime: cwist_http_response_destroy releases body/header resources but leaves the arena itself to the owner. arena must outlive the response.

Parameters
arenaArena to allocate from; NULL falls back to cwist_http_response_create().

Definition at line 2306 of file http.c.

References cwist_http_response_create().

Referenced by cwist_http2_push_resource(), and cwist_http2_serve_connection_ex().

◆ cwist_http_response_destroy()

◆ cwist_http_response_send_file()

cwist_error_t cwist_http_response_send_file ( cwist_http_response *  res,
const char *  file_path,
const char *  content_type_hint,
size_t *  out_size 
)

Prepare a response to serve a file either by buffering or direct streaming.

Parameters
resResponse object to populate.
file_pathFilesystem path to the file that should be served.
content_type_hintOptional MIME type override.
out_sizeOptional output pointer receiving the file size in bytes.
Returns
Tagged CWIST error describing success or failure.

Definition at line 5223 of file http.c.

References cwist_http_response::body, cap, cwist_alloc(), CWIST_ENDPOINT_FILE, CWIST_ERR_INT16, cwist_free(), cwist_http_header_add(), cwist_http_header_get(), CWIST_HTTP_MAX_BODY_SIZE, CWIST_HTTP_OK, cwist_sstring_adopt_len(), cwist_sstring_borrow(), cwist_http_response::endpoint_opts, cwist_http_response::file_stream_auto_close, cwist_http_response::file_stream_fd, cwist_http_response::file_stream_len, cwist_http_response::file_stream_offset, cwist_http_response::headers, make_error(), cwist_http_response::status_code, and cwist_http_response::use_file_stream.

◆ cwist_http_response_serialize()

int cwist_http_response_serialize ( cwist_http_response *  res,
char **  out,
size_t *  out_len 
)

Serialize a full response (headers + body) into a heap buffer.

Serialize a response into a freshly allocated HTTP/1.x buffer (status line + headers + body). Caller frees out with cwist_free(). File-streaming bodies cannot be serialized; the call fails for them.

Streaming responses are auto-finalized so the chunked terminator is present even when the handler skipped cwist_http_response_stream_end().

Returns
0 with out and out_len set, or -1 (invalid input, file-stream body, or allocation failure).

Definition at line 4439 of file http.c.

References cwist_http_response::body, cap, cwist_alloc(), CWIST_HTTP_MAX_HEADER_SIZE, cwist_http_response_stream_end(), cwist_sstring::data, cwist_http_response::is_ptr_body, cwist_http_response::ptr_body, cwist_http_response::ptr_body_len, cwist_sstring::size, cwist_http_response::stream_buf, cwist_http_response::stream_ended, cwist_http_response::stream_mode, and cwist_http_response::use_file_stream.

Referenced by cwist_app_dispatch_memory().

◆ cwist_http_response_set_alt_svc()

void cwist_http_response_set_alt_svc ( cwist_http_response *  res,
const char *  alt_svc 
)

Set the Alt-Svc header value for HTTP/3 upgrade advertisement.

Parameters
resResponse object to modify.
alt_svcAlt-Svc header value (e.g., h3=":443"; ma=86400). Pass NULL to clear any previously set value.

Definition at line 2376 of file http.c.

References cwist_http_response::alt_svc, cap, cwist_free(), and cwist_strdup().

◆ cwist_http_response_set_body_ptr()

void cwist_http_response_set_body_ptr ( cwist_http_response *  res,
const void *  ptr,
size_t  len 
)

Attach an unmanaged zero-copy body pointer to a response.

Sets a direct pointer for the response body (Zero Copy). Use this when serving large files from memory mapped regions. The pointer must remain valid until the response is sent.

Parameters
resResponse object to modify.
ptrExternal body pointer.
lenLength of the external body in bytes.

Definition at line 2346 of file http.c.

References cap, and cwist_http_response_set_body_ptr_managed().

Referenced by cwist_assets_respond().

◆ cwist_http_response_set_body_ptr_managed()

void cwist_http_response_set_body_ptr_managed ( cwist_http_response *  res,
const void *  ptr,
size_t  len,
cwist_http_body_cleanup_fn  cleanup,
void *  ctx 
)

Attach a managed zero-copy body pointer and optional cleanup hook to a response.

Parameters
resResponse object to modify.
ptrExternal body pointer.
lenLength of the external body in bytes.
cleanupOptional cleanup callback for the body pointer.
ctxOpaque context forwarded to the cleanup callback.

Definition at line 2358 of file http.c.

References cwist_http_response::is_ptr_body, cwist_http_response::ptr_body, cwist_http_response::ptr_body_cleanup, cwist_http_response::ptr_body_cleanup_ctx, and cwist_http_response::ptr_body_len.

Referenced by cwist_http_response_set_body_ptr().

◆ cwist_http_response_stream_begin()

int cwist_http_response_stream_begin ( cwist_http_response *  res)

Switch a response to chunked streaming mode.

Discards any body assigned before the switch. Incompatible with pointer or file-stream bodies.

Returns
0 on success, -1 otherwise.

Definition at line 4503 of file http.c.

References cwist_http_response::body, cwist_http_response::is_ptr_body, cwist_sstring::size, cwist_http_response::stream_mode, and cwist_http_response::use_file_stream.

◆ cwist_http_response_stream_end()

int cwist_http_response_stream_end ( cwist_http_response *  res)

Terminate a streaming response with the final zero-length chunk and flush.

Returns
0 on success, -1 on error.

Definition at line 4549 of file http.c.

References cwist_http_response::arena, cap, cwist_sstring_append_len(), cwist_http_response::stream_buf, cwist_http_response::stream_ended, cwist_http_response::stream_failed, and cwist_http_response::stream_mode.

Referenced by cwist_app_dispatch_memory(), cwist_app_dispatch_stream(), and cwist_http_response_serialize().

◆ cwist_http_response_stream_write()

int cwist_http_response_stream_write ( cwist_http_response *  res,
const char *  data,
size_t  len 
)

Append one data chunk to a streaming response.

Frames the chunk (hex length prefix / CRLF suffix) and flushes through the sink. A sink failure marks the stream failed.

Returns
0 on success, -1 on error.

Definition at line 4519 of file http.c.

References cwist_http_response::arena, cap, cwist_sstring_append_len(), cwist_http_response::stream_buf, cwist_http_response::stream_ended, cwist_http_response::stream_failed, and cwist_http_response::stream_mode.

◆ cwist_http_send_error_response()

void cwist_http_send_error_response ( int  fd,
int  status,
const char *  msg 
)

Send a minimal error response with Connection: close, used to answer malformed requests (400/413/417/431/501) before the connection is dropped.

Send a minimal HTTP/1.x error response (Connection: close) on a socket, used to answer malformed requests before dropping them.

Send a minimal error response (Connection: close) for a failed request.

Parameters
fdConnected client socket descriptor.
statusHTTP status code (reason phrase is derived from it).
msgPlain-text body; NULL falls back to the reason phrase.

Definition at line 4046 of file http.c.

References cap, cwist_http_status_reason(), and MSG_DONTWAIT.

◆ cwist_http_send_response()

cwist_error_t cwist_http_send_response ( int  client_fd,
cwist_http_response *  res 
)

Serialize and send an HTTP response to a connected client socket.

Send a response over a socket.

Parameters
client_fdConnected client socket descriptor.
resResponse object to send.
Returns
Tagged CWIST error describing success or transmission failure.

Definition at line 2878 of file http.c.

References cwist_http_response::body, cap, CWIST_ERR_INT16, CWIST_HTTP_MAX_HEADER_SIZE, cwist_tcp_cork_enabled(), cwist_sstring::data, cwist_http_response::is_ptr_body, make_error(), MSG_DONTWAIT, cwist_http_response::ptr_body, cwist_http_response::ptr_body_len, cwist_sstring::size, and cwist_http_response::use_file_stream.

Referenced by cwist_http_async_send_response(), cwist_http_send_response_async(), cwist_http_send_response_coalesced(), and cwist_websocket_upgrade().

◆ cwist_http_send_response_async()

◆ cwist_http_send_response_coalesced()

cwist_async_send_status_t cwist_http_send_response_coalesced ( int  client_fd,
cwist_http_response *  res,
cwist_http_async_conn_t *  conn,
bool  keep_alive,
bool  head_only 
)

◆ cwist_http_send_response_head()

cwist_error_t cwist_http_send_response_head ( int  client_fd,
cwist_http_response *  res 
)

Send only the status line and headers of a response (RFC 9110 section 9.3.2 HEAD semantics): Content-Length reflects the would-be body, but no body bytes are written. Body resources are released as in the full send path.

Send only the status line and headers of a response (HEAD replies). Content-Length still reflects the would-be body; body resources are released without being transmitted.

Send only the status line and headers (HEAD replies).

Definition at line 2961 of file http.c.

References cap, CWIST_ERR_INT16, CWIST_HTTP_MAX_HEADER_SIZE, make_error(), and MSG_DONTWAIT.

◆ cwist_http_serialize_headers()

size_t cwist_http_serialize_headers ( cwist_http_response *  res,
char *  buf,
size_t  buf_size 
)

Serialize the status line and headers into a caller-provided buffer.

Serialize only the status line and headers into a caller buffer. Used by the TLS send path to stream header block and body separately.

Serialize only the status line and headers into a caller buffer.

Non-static wrapper around serialize_headers() so the TLS send path can stream headers and body separately instead of materializing one blob.

Parameters
resResponse object to serialize.
bufDestination buffer for the header block.
buf_sizeTotal capacity of buf in bytes.
Returns
Number of bytes written into the buffer.

Definition at line 2609 of file http.c.

References cap.

Referenced by cwist_app_dispatch_stream(), cwist_https_send_response(), and cwist_https_send_response_head().

◆ cwist_http_server_loop()

cwist_error_t cwist_http_server_loop ( int  server_fd,
cwist_server_config *  config,
void(*)(int, void *)  handler,
void *  ctx 
)

Run the main HTTP accept loop using the configured concurrency strategy.

Parameters
server_fdListening server socket.
configServer concurrency configuration flags.
handlerCallback that handles one accepted client.
ctxOpaque callback context.
Returns
Tagged CWIST error describing success or failure.

Definition at line 5590 of file http.c.

References cap, count, cwist_accept_socket(), CWIST_ERR_INT16, cwist_http_pool_destroy(), cwist_http_pool_init_mode(), cwist_http_pool_submit(), g_cwist_running, HTTP_ACCEPT_WAIT_MS, make_error(), cwist_server_config::use_epoll, cwist_server_config::use_forking, and cwist_server_config::use_threading.

◆ cwist_http_status_reason()

const char * cwist_http_status_reason ( int  status)

Map an HTTP status code to its RFC reason phrase.

Return the standard reason phrase for an HTTP status code (e.g. 404 -> "Not Found"). Unknown codes return NULL; applications may also assign any int to a response status_code for non-standard codes.

Returns
Static reason phrase, or NULL for unknown codes.

Definition at line 3970 of file http.c.

References cap.

Referenced by cwist_http_coalesce_error_response(), and cwist_http_send_error_response().

◆ cwist_http_string_to_method()

cwist_http_method_t cwist_http_string_to_method ( const char *  method_str)

Parse a NUL-terminated method string into a method enum.

Convert method string to enum.

Returns
Matching method, or CWIST_HTTP_UNKNOWN for NULL/unrecognized input.

Definition at line 1629 of file http.c.

References cap, cwist_http_string_to_method_len(), and CWIST_HTTP_UNKNOWN.

Referenced by cwist_http3_method_is_idempotent().

◆ cwist_http_string_to_method_len()

cwist_http_method_t cwist_http_string_to_method_len ( const char *  str,
size_t  len 
)

Parse a method token (with explicit length) into a method enum.

Uses a SWAR 4-byte magic fast path for GET/POST/PUT/DELETE/HEAD, then exact-length comparisons.

Returns
Matching method, or CWIST_HTTP_UNKNOWN.

Definition at line 1584 of file http.c.

References cap, CWIST_HTTP_DELETE, CWIST_HTTP_GET, CWIST_HTTP_HEAD, CWIST_HTTP_OPTIONS, CWIST_HTTP_PATCH, CWIST_HTTP_POST, CWIST_HTTP_PUT, CWIST_HTTP_UNKNOWN, MAGIC_DELE, MAGIC_GET, MAGIC_HEAD, MAGIC_POST, and MAGIC_PUT.

Referenced by cwist_http_string_to_method().

◆ cwist_http_stringify_response()

cwist_sstring * cwist_http_stringify_response ( cwist_http_response *  res)

Materialize an HTTP response into a contiguous string for debugging or TLS writes.

Serialize a response to a string.

Parameters
resResponse object to stringify.
Returns
Heap-allocated response string, or NULL on invalid input.

Definition at line 4099 of file http.c.

References cwist_http_response::body, cap, CWIST_HTTP_MAX_HEADER_SIZE, cwist_sstring_append_len(), cwist_sstring_assign_len(), cwist_sstring_create(), cwist_sstring::data, cwist_http_response::is_ptr_body, cwist_http_response::ptr_body, cwist_http_response::ptr_body_len, and cwist_sstring::size.

◆ cwist_make_socket_ipv4()

int cwist_make_socket_ipv4 ( struct sockaddr_in *  sockv4,
const char *  address,
uint16_t  port,
uint16_t  backlog 
)

Create, configure, bind, and listen on an IPv4 TCP socket.

Create an IPv4 socket and perform bind/listen.

Create an IPv4 socket and bind/listen.

Parameters
sockv4Output sockaddr structure populated for the bind call.
addressIPv4 address string to bind.
portTCP port to listen on.
backlogListen backlog passed to listen(2).
Returns
Listening socket fd on success, or a negative CWIST socket error code.

Definition at line 5361 of file http.c.

References cap, CWIST_CREATE_SOCKET_FAILED, cwist_free(), CWIST_HTTP_BIND_FAILED, CWIST_HTTP_LISTEN_FAILED, CWIST_HTTP_SETSOCKOPT_FAILED, CWIST_HTTP_UNAVAILABLE_ADDRESS, and cwist_reuseport_enabled().

◆ cwist_reuseport_enabled()

bool cwist_reuseport_enabled ( void  )

Whether listen sockets get SO_REUSEPORT where the OS has it. Default on; CWIST_REUSEPORT=0/false disables, which restores bind() failure on a port conflict (and therefore requires a single worker process). Read at every bind, so worker children re-created after fork honor the same environment.

Definition at line 5347 of file http.c.

References cap.

Referenced by cwist_async_server_loop(), and cwist_make_socket_ipv4().

◆ cwist_tcp_cork_enabled()

bool cwist_tcp_cork_enabled ( void  )

TCP_CORK coalescing stub for platforms without TCP_CORK.

Whether the TCP_CORK coalescing layer is active for cleartext HTTP/1.1 responses. Enabled at runtime with CWIST_USE_TCP_CORK=1 (burst size via CWIST_TCP_CORK_BURST, default 256 KiB); always false off-Linux.

Returns
Always false.

Definition at line 2684 of file http.c.

Referenced by cwist_http_send_response().

◆ get_cpu_cores()

long get_cpu_cores ( void  )

Return the number of CPUs available to this process.

Honors the process CPU affinity mask where the platform supports it (sched_getaffinity on Linux); falls back to sysconf(3)/sysctl and ultimately 1 when the count cannot be determined.

Returns
Number of usable CPUs, at least 1.

Definition at line 99 of file http.c.

References cap, and count.

Referenced by get_optimal_thread_count().

◆ get_optimal_thread_count()

long get_optimal_thread_count ( void  )

Compute the HTTP worker/event-loop thread count.

Resolution order: a value fixed with cwist_http_pool_limit_core(), then the CWIST_WORKER_THREADS environment override, then CPU-core based sizing modified by CWIST_WORKERS (worker-process count) and CWIST_C1M_MODE. C1M mode divides the core budget across worker processes (one event loop per CPU); classic mode multiplies it to cover blocking keep-alive handlers.

Returns
Computed thread count, clamped to the mode-specific range.

Definition at line 159 of file http.c.

References cap, count, and get_cpu_cores().

Referenced by cwist_http_pool_init_mode(), https_pool_destroy(), and https_pool_init().

◆ headers_have_content_length()

int headers_have_content_length ( cwist_http_header_node *  headers)

Detect whether a header list already defines Content-Length.

Parameters
headersHeader linked list to scan.
Returns
1 when a Content-Length header is present, otherwise 0.

Definition at line 2394 of file http.c.

References cap, and cwist_http_header_node::next.

Variable Documentation

◆ CWIST_BLOB_200_OK

const char CWIST_BLOB_200_OK[]
Initial value:
=
"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: keep-alive\r\n\r\n"

Definition at line 5334 of file http.c.

◆ CWIST_BLOB_404

const char CWIST_BLOB_404[]
Initial value:
=
"HTTP/1.1 404 Not Found\r\nContent-Length: 13\r\nConnection: keep-alive\r\n\r\n404 Not Found"

Definition at line 5336 of file http.c.

◆ CWIST_BLOB_500

const char CWIST_BLOB_500[]
Initial value:
=
"HTTP/1.1 500 Internal Server Error\r\nContent-Length: 21\r\nConnection: close\r\n\r\nInternal Server Error"

Definition at line 5338 of file http.c.

◆ CWIST_CREATE_SOCKET_FAILED

const int CWIST_CREATE_SOCKET_FAILED = -1

Definition at line 1541 of file http.c.

Referenced by cwist_make_socket_ipv4().

◆ CWIST_HTTP_BIND_FAILED

const int CWIST_HTTP_BIND_FAILED = -3

Definition at line 1543 of file http.c.

Referenced by cwist_make_socket_ipv4().

◆ CWIST_HTTP_LISTEN_FAILED

const int CWIST_HTTP_LISTEN_FAILED = -5

Definition at line 1545 of file http.c.

Referenced by cwist_make_socket_ipv4().

◆ CWIST_HTTP_SETSOCKOPT_FAILED

const int CWIST_HTTP_SETSOCKOPT_FAILED = -4

Definition at line 1544 of file http.c.

Referenced by cwist_make_socket_ipv4().

◆ CWIST_HTTP_UNAVAILABLE_ADDRESS

const int CWIST_HTTP_UNAVAILABLE_ADDRESS = -2

Definition at line 1542 of file http.c.

Referenced by cwist_make_socket_ipv4().