Nilorea Library
C utilities for networking, threading, graphics
Loading...
Searching...
No Matches
ex_http_server.c

n_http_server over real sockets, plain and TLS: keep-alive, pipelining, HEAD, HTTP/1.0, bodies in memory and in a file, unread bodies, 413 / 417 / 400 / 501 / 431 / 408 / 503 / 500, Expect: 100-continue, deadlines against slow peers, the connection cap, a clean stop

n_http_server over real sockets, plain and TLS: keep-alive, pipelining, HEAD, HTTP/1.0, bodies in memory and in a file, unread bodies, 413 / 417 / 400 / 501 / 431 / 408 / 503 / 500, Expect: 100-continue, deadlines against slow peers, the connection cap, a clean stop

Author
Castagnier Mickael
Version
1.0
Date
23/10/2026
/*
* Nilorea Library
* Copyright (C) 2005-2026 Castagnier Mickael
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
#include "nilorea/n_log.h"
#include "nilorea/n_str.h"
#ifdef HAVE_OPENSSL
#include "nilorea/n_x509.h"
#include <openssl/err.h>
#include <openssl/ssl.h>
#endif
#include <fcntl.h>
#include <poll.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <time.h>
#include <unistd.h>
static int failures = 0;
static void expect_true(const char* what, int ok) {
if (!ok) {
n_log(LOG_ERR, "FAIL: %s", what);
} else {
n_log(LOG_INFO, "ok: %s", what);
}
}
static void process_args(int argc, char** argv) {
int opt = 0;
while ((opt = getopt(argc, argv, "V:")) != EOF) {
if (opt == 'V') {
if (!strncmp("LOG_NULL", optarg, 8))
else if (!strncmp("LOG_NOTICE", optarg, 10))
else if (!strncmp("LOG_INFO", optarg, 8))
else if (!strncmp("LOG_ERR", optarg, 7))
else if (!strncmp("LOG_DEBUG", optarg, 9))
}
}
}
static N_HTTP_RESP* text(int status, const char* body) {
n_http_response_set_header(r, "Content-Type", "text/plain");
n_http_response_append(r, body, strlen(body));
return r;
}
static N_HTTP_RESP* handler(N_HTTP_SERVER_REQUEST* req, void* user) {
(void)user;
if (strcmp(req->path, "/hello") == 0)
return text(200, "hello");
if (strcmp(req->path, "/null") == 0)
return NULL;
if (strcmp(req->path, "/info") == 0) {
char b[256];
snprintf(b, sizeof(b), "path=%s query=%s tls=%d peer=%s", req->path, req->query, req->tls, req->peer_ip);
return text(200, b);
}
if (strcmp(req->path, "/echo") == 0) {
N_STR* body = NULL;
if (!n_http_server_read_body(req, 1024, &body)) {
free_nstr(&body);
return text(req->body_status, "body refused");
}
free_nstr(&body);
return r;
}
if (strcmp(req->path, "/file") == 0) {
char path[] = "ex_http_server_body_XXXXXX";
int fd = mkstemp(path);
char b[64];
int ok = fd >= 0 && n_http_server_read_body_to_fd(req, 65536, fd);
long long size = fd >= 0 ? (long long)lseek(fd, 0, SEEK_END) : -1;
if (fd >= 0) {
close(fd);
unlink(path);
}
if (!ok)
return text(req->body_status ? req->body_status : 500, "file refused");
snprintf(b, sizeof(b), "stored %lld", size);
return text(200, b);
}
if (strcmp(req->path, "/nobody") == 0)
return text(200, "ignored");
return text(404, "not found");
}
typedef struct {
#ifdef HAVE_OPENSSL
SSL* ssl;
#endif
static int cl_connect(const char* port, client* c) {
memset(c, 0, sizeof(*c));
if (netw_connect(&c->netw, "127.0.0.1", (char*)port, NETWORK_IPALL) != TRUE || !c->netw)
return 0;
netw_setsockopt(c->netw, SO_RCVTIMEO, 3000);
return 1;
}
#ifdef HAVE_OPENSSL
static int cl_tls(client* c, SSL_CTX* ctx) {
c->ssl = SSL_new(ctx);
SSL_set_fd(c->ssl, (int)c->netw->link.sock);
SSL_set_tlsext_host_name(c->ssl, "localhost");
return SSL_connect(c->ssl) == 1;
}
#endif
static void cl_send(client* c, const char* s, size_t n) {
#ifdef HAVE_OPENSSL
if (c->ssl) {
SSL_write(c->ssl, s, (int)n);
return;
}
#endif
while (n > 0) {
ssize_t w = send(c->netw->link.sock, s, n, MSG_NOSIGNAL);
if (w <= 0)
return;
s += w;
n -= (size_t)w;
}
}
static void cl_sends(client* c, const char* s) {
cl_send(c, s, strlen(s));
}
static long cl_recv(client* c, char* b, size_t n) {
#ifdef HAVE_OPENSSL
if (c->ssl) {
int r = SSL_read(c->ssl, b, (int)n);
if (r > 0)
return r;
r = SSL_get_error(c->ssl, r);
ERR_clear_error();
return r == SSL_ERROR_ZERO_RETURN || r == SSL_ERROR_SYSCALL ? 0 : -1;
}
#endif
return (long)recv(c->netw->link.sock, b, n, 0);
}
static void cl_close(client* c) {
if (!c->netw)
return;
#ifdef HAVE_OPENSSL
if (c->ssl) {
SSL_shutdown(c->ssl);
SSL_free(c->ssl);
c->ssl = NULL;
ERR_clear_error();
}
#endif
}
typedef struct {
int status;
char head[4096];
char body[70000];
long body_len;
static char pending[200000];
static size_t npending = 0;
static int read_reply(client* c, int head_only, reply* r) {
const char* end = NULL;
memset(r, 0, sizeof(*r));
while (!(end = strstr(pending, "\r\n\r\n"))) {
long n;
if (npending >= sizeof(pending) - 1)
return 0;
n = cl_recv(c, pending + npending, sizeof(pending) - 1 - npending);
if (n <= 0)
return 0;
npending += (size_t)n;
pending[npending] = '\0';
}
{
size_t hl = (size_t)(end - pending) + 4;
long clen = 0;
const char* cl;
memcpy(r->head, pending, hl < sizeof(r->head) - 1 ? hl : sizeof(r->head) - 1);
sscanf(pending, "HTTP/1.1 %d", &r->status);
cl = strstr(r->head, "Content-Length: ");
if (cl)
clen = atol(cl + 16);
if (head_only || r->status == 100 || r->status == 204 || r->status == 304)
clen = 0;
while ((long)(npending - hl) < clen) {
long n = cl_recv(c, pending + npending, sizeof(pending) - 1 - npending);
if (n <= 0)
return 0;
npending += (size_t)n;
pending[npending] = '\0';
}
memcpy(r->body, pending + hl, (size_t)clen);
r->body[clen] = '\0';
r->body_len = clen;
memmove(pending, pending + hl + clen, npending - hl - (size_t)clen + 1);
npending -= hl + (size_t)clen;
}
return r->status;
}
static int closed_by_server(client* c, int ms) {
char b[64];
struct pollfd p;
p.fd = (int)c->netw->link.sock;
p.events = POLLIN;
if (npending > 0)
return 0;
#ifdef HAVE_OPENSSL
if (c->ssl && SSL_pending(c->ssl) > 0)
return 0;
#endif
if (poll(&p, 1, ms) <= 0)
return 0;
return cl_recv(c, b, sizeof(b)) == 0;
}
typedef struct {
N_HTTP_SERVER* srv;
int ok;
static void* run_server(void* p) {
runner* r = (runner*)p;
return NULL;
}
static N_HTTP_SERVER* start(N_HTTP_SERVER_CONFIG* cfg, char* port, int base) {
int p;
for (p = base; p < base + 100; p++) {
snprintf(port, 16, "%d", p);
cfg->port = port;
if (s)
return s;
}
return NULL;
}
static void test_plain(void) {
pthread_t th;
char port[16];
client c;
static reply r;
long long t0;
cfg.workers = 2;
cfg.header_timeout_ms = 300;
cfg.idle_timeout_ms = 300;
cfg.body_timeout_ms = 300;
cfg.write_timeout_ms = 1000;
cfg.max_body = 100000;
srv = start(&cfg, port, 18600);
expect_true("server bound", srv != NULL);
if (!srv)
return;
run.srv = srv;
run.ok = 0;
pthread_create(&th, NULL, run_server, &run);
/* keep-alive, pipelining, HEAD */
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "GET /hello HTTP/1.1\r\nHost: t\r\n\r\n");
expect_true("GET 200", read_reply(&c, 0, &r) == 200 && strcmp(r.body, "hello") == 0);
expect_true("keep-alive: no Connection: close", strstr(r.head, "Connection: close") == NULL);
expect_true("Date sent", strstr(r.head, "\r\nDate: ") != NULL);
cl_sends(&c, "GET /info?a=1&b=2 HTTP/1.1\r\nHost: t\r\n\r\n");
expect_true("second request on the same connection", read_reply(&c, 0, &r) == 200 && strstr(r.body, "path=/info query=a=1&b=2 tls=0 peer=127.0.0.1"));
cl_sends(&c, "HEAD /hello HTTP/1.1\r\nHost: t\r\n\r\nGET /hello HTTP/1.1\r\nHost: t\r\n\r\n");
expect_true("pipelined HEAD: length, no body", read_reply(&c, 1, &r) == 200 && strstr(r.head, "Content-Length: 5\r\n") && r.body_len == 0);
expect_true("pipelined GET after it", read_reply(&c, 0, &r) == 200 && strcmp(r.body, "hello") == 0);
cl_sends(&c, "POST /echo HTTP/1.1\r\nHost: t\r\nContent-Length: 3\r\n\r\nabc");
expect_true("POST body echoed", read_reply(&c, 0, &r) == 200 && strcmp(r.body, "abc") == 0);
cl_sends(&c, "GET /null HTTP/1.1\r\nHost: t\r\n\r\n");
expect_true("NULL response: 500", read_reply(&c, 0, &r) == 500);
cl_sends(&c, "GET /hello HTTP/1.1\r\nHost: t\r\nConnection: close\r\n\r\n");
expect_true("Connection: close honoured", read_reply(&c, 0, &r) == 200 && strstr(r.head, "Connection: close") && closed_by_server(&c, 1000));
cl_close(&c);
}
/* idle timeout after a keep-alive response */
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "GET /hello HTTP/1.1\r\nHost: t\r\n\r\n");
read_reply(&c, 0, &r);
t0 = (long long)time(NULL);
expect_true("idle connection closed after the idle timeout", closed_by_server(&c, 2000) && (long long)time(NULL) - t0 <= 2);
cl_close(&c);
}
/* HTTP/1.0 */
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "GET /hello HTTP/1.0\r\n\r\n");
expect_true("HTTP/1.0 without keep-alive closes", read_reply(&c, 0, &r) == 200 && strstr(r.head, "Connection: close") && closed_by_server(&c, 1000));
cl_close(&c);
}
/* bodies */
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "POST /echo HTTP/1.1\r\nHost: t\r\nContent-Length: 2000\r\n\r\n");
expect_true("body over the handler's cap: 413 and close", read_reply(&c, 0, &r) == 413 && closed_by_server(&c, 1000));
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "POST /echo HTTP/1.1\r\nHost: t\r\nContent-Length: 200000\r\n\r\n");
expect_true("body over max_body: 413 before the handler", read_reply(&c, 0, &r) == 413 && strstr(r.body, "413") && closed_by_server(&c, 1000));
cl_close(&c);
}
if (cl_connect(port, &c)) {
static char big[60000 + 128];
size_t i, hl;
npending = 0;
hl = (size_t)snprintf(big, sizeof(big), "POST /file HTTP/1.1\r\nHost: t\r\nContent-Length: 60000\r\n\r\n");
for (i = 0; i < 60000; i++)
big[hl + i] = (char)('a' + i % 26);
cl_send(&c, big, hl + 60000);
expect_true("60000-byte body stored in a file", read_reply(&c, 0, &r) == 200 && strcmp(r.body, "stored 60000") == 0);
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "POST /nobody HTTP/1.1\r\nHost: t\r\nContent-Length: 4\r\n\r\nabcd");
expect_true("unread body: answered, then closed", read_reply(&c, 0, &r) == 200 && strstr(r.head, "Connection: close") && closed_by_server(&c, 1000));
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "POST /echo HTTP/1.1\r\nHost: t\r\nContent-Length: 10\r\n\r\nabc");
expect_true("body cut short: 408 after the body deadline", read_reply(&c, 0, &r) == 408);
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "POST /echo HTTP/1.1\r\nHost: t\r\nContent-Length: 5\r\nExpect: 100-continue\r\n\r\n");
expect_true("100 Continue sent when the body is read", read_reply(&c, 0, &r) == 100);
cl_sends(&c, "hello");
expect_true("then the final response", read_reply(&c, 0, &r) == 200 && strcmp(r.body, "hello") == 0);
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "POST /echo HTTP/1.1\r\nHost: t\r\nContent-Length: 5\r\nExpect: something-else\r\n\r\n");
expect_true("unknown Expect: 417", read_reply(&c, 0, &r) == 417);
cl_close(&c);
}
/* bad requests */
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "BREW /pot HTTP/1.1\r\nHost: t\r\n\r\n");
expect_true("unknown method: 501 and close", read_reply(&c, 0, &r) == 501 && closed_by_server(&c, 1000));
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "TRACE / HTTP/1.1\r\nHost: t\r\n\r\n");
expect_true("TRACE: 501", read_reply(&c, 0, &r) == 501);
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "POST /echo HTTP/1.1\r\nHost: t\r\nContent-Length: 1073742300\r\n\r\n");
expect_true("Content-Length above every cap: 413", read_reply(&c, 0, &r) == 413);
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "POST /echo HTTP/1.1\r\nHost: t\r\ncontent-length: 99999999999999999999999 \r\n\r\n");
expect_true("Content-Length of 23 digits: 413", read_reply(&c, 0, &r) == 413);
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "POST /echo HTTP/1.1\r\nHost: t\r\nContent-Length: 1073742300\r\nContent-Length: 1073742300\r\n\r\n");
expect_true("two huge Content-Length headers: 400", read_reply(&c, 0, &r) == 400);
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "POST /echo HTTP/1.1\r\nHost: t\r\nContent-Length: 12x\r\n\r\n");
expect_true("malformed Content-Length: 400", read_reply(&c, 0, &r) == 400);
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "get / HTTP/1.1\r\nHost: t\r\n\r\n");
expect_true("lowercase method: 400", read_reply(&c, 0, &r) == 400);
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "GET\t/ HTTP/1.1\r\nHost: t\r\n\r\n");
expect_true("malformed request line: 400", read_reply(&c, 0, &r) == 400);
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "GET /hello HTTP/1.1\r\n\r\n");
expect_true("HTTP/1.1 without Host: 400", read_reply(&c, 0, &r) == 400);
cl_close(&c);
}
if (cl_connect(port, &c)) {
static char huge[20000];
npending = 0;
memset(huge, 'a', sizeof(huge));
memcpy(huge, "GET /hello HTTP/1.1\r\nHost: t\r\nX-Big: ", 37);
cl_send(&c, huge, sizeof(huge));
expect_true("head over 16 KiB: 431", read_reply(&c, 0, &r) == 431);
cl_close(&c);
}
/* slow peers */
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "GET /hello HTTP/1.1\r\nHo");
expect_true("head not finished in time: 408", read_reply(&c, 0, &r) == 408 && closed_by_server(&c, 1000));
cl_close(&c);
}
if (cl_connect(port, &c)) {
int i;
struct timespec ts0, ts1;
long elapsed;
struct pollfd p;
npending = 0;
p.fd = (int)c.netw->link.sock;
p.events = POLLIN;
clock_gettime(CLOCK_MONOTONIC, &ts0);
/* one byte every 100 ms for 600 ms: every single read is quick, so
* only a TOTAL head deadline (300 ms) stops it; stop sending as soon
* as the answer is readable, without reading it */
for (i = 0; i < 6; i++) {
if (poll(&p, 1, 0) > 0)
break;
cl_send(&c, "G", 1);
usleep(100000);
}
expect_true("byte-at-a-time head: 408", read_reply(&c, 0, &r) == 408);
clock_gettime(CLOCK_MONOTONIC, &ts1);
elapsed = (ts1.tv_sec - ts0.tv_sec) * 1000 + (ts1.tv_nsec - ts0.tv_nsec) / 1000000;
expect_true("byte-at-a-time head: stopped by the total deadline, not per read", elapsed < 550);
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
expect_true("silent connection closed after the header timeout", closed_by_server(&c, 2000));
cl_close(&c);
}
t0 = (long long)time(NULL);
pthread_join(th, NULL);
expect_true("run() returns after stop", run.ok == TRUE && (long long)time(NULL) - t0 <= 2);
n_log(LOG_INFO, "stats: accepted %llu refused %llu active %llu requests %llu timeouts %llu bad %llu", st.accepted, st.refused, st.active, st.requests, st.timeouts, st.bad_requests);
expect_true("stats", st.requests >= 10 && st.timeouts >= 3 && st.bad_requests >= 4 && st.active == 0);
expect_true("free sets NULL", srv == NULL);
}
static void test_capacity(void) {
pthread_t th;
char port[16];
client c, c2, c3, c4, c5;
static reply r;
cfg.workers = 2;
cfg.header_timeout_ms = 5000;
srv = start(&cfg, port, 18800);
expect_true("capacity server bound", srv != NULL);
if (!srv)
return;
run.srv = srv;
run.ok = 0;
pthread_create(&th, NULL, run_server, &run);
/* 2 workers hold c and c2, c3 and c4 fill the queue of 2, c5 is refused */
memset(&c3, 0, sizeof(c3));
memset(&c4, 0, sizeof(c4));
/* let the workers take c and c2 before the queue is filled */
if (cl_connect(port, &c) && cl_connect(port, &c2)) {
usleep(300000);
if (cl_connect(port, &c3) && cl_connect(port, &c4)) {
usleep(300000);
npending = 0;
if (cl_connect(port, &c5)) {
expect_true("over capacity: 503", read_reply(&c5, 0, &r) == 503);
cl_close(&c5);
}
}
}
cl_close(&c4);
cl_close(&c3);
cl_close(&c2);
cl_close(&c);
pthread_join(th, NULL);
expect_true("capacity server stopped while connections were held", run.ok == TRUE);
}
#ifdef HAVE_OPENSSL
static int write_pem(const N_STR* pem, char* path) {
int fd = mkstemp(path);
int ok = fd >= 0 && write(fd, pem->data, pem->written) == (ssize_t)pem->written;
if (fd >= 0)
close(fd);
return ok;
}
static void test_tls(void) {
N_STR *ca_cert = NULL, *ca_key = NULL, *cert = NULL, *key = NULL;
char cert_path[] = "ex_http_server_cert_XXXXXX", key_path[] = "ex_http_server_key_XXXXXX";
pthread_t th;
char port[16];
client c;
static reply r;
if (n_x509_generate_ca("ex_http_server CA", 2, &ca_cert, &ca_key) != 0 ||
n_x509_mint_host_cert("localhost", ca_cert, ca_key, 2, &cert, &key) != 0 || !write_pem(cert, cert_path) || !write_pem(key, key_path)) {
expect_true("test certificate", 0);
return;
}
cfg.workers = 4;
cfg.tls_key_file = key_path;
cfg.tls_cert_file = cert_path;
srv = start(&cfg, port, 18700);
expect_true("TLS server bound", srv != NULL);
cfg.tls_cert_file = NULL;
expect_true("key without certificate refused", n_http_server_new(&cfg) == NULL);
if (srv) {
run.srv = srv;
run.ok = 0;
pthread_create(&th, NULL, run_server, &run);
SSL_CTX* cctx = SSL_CTX_new(TLS_client_method());
SSL_CTX_set_verify(cctx, SSL_VERIFY_NONE, NULL);
if (cl_connect(port, &c) && cl_tls(&c, cctx)) {
npending = 0;
expect_true("TLS 1.3 negotiated", strcmp(SSL_get_version(c.ssl), "TLSv1.3") == 0);
cl_sends(&c, "GET /info HTTP/1.1\r\nHost: t\r\n\r\n");
expect_true("GET over TLS", read_reply(&c, 0, &r) == 200 && strstr(r.body, "tls=1"));
cl_sends(&c, "GET /hello HTTP/1.1\r\nHost: t\r\n\r\n");
expect_true("keep-alive over TLS", read_reply(&c, 0, &r) == 200 && strcmp(r.body, "hello") == 0);
} else {
expect_true("TLS client handshake", 0);
}
cl_close(&c);
if (cl_connect(port, &c)) {
npending = 0;
expect_true("no handshake: closed after the handshake timeout", closed_by_server(&c, 2000));
cl_close(&c);
}
if (cl_connect(port, &c)) {
npending = 0;
cl_sends(&c, "GET /hello HTTP/1.1\r\nHost: t\r\n\r\n");
expect_true("plain HTTP on the TLS port: closed", read_reply(&c, 0, &r) == 0);
cl_close(&c);
}
SSL_CTX_free(cctx);
pthread_join(th, NULL);
expect_true("TLS failures counted", st.tls_failures >= 2);
}
unlink(cert_path);
unlink(key_path);
free_nstr(&ca_cert);
free_nstr(&ca_key);
}
#endif
int main(int argc, char** argv) {
process_args(argc, argv);
#ifdef HAVE_OPENSSL
#endif
expect_true("config without handler refused", n_http_server_new(&bad) == NULL);
bad.workers = 0;
expect_true("config without workers refused", n_http_server_new(&bad) == NULL);
#ifdef HAVE_OPENSSL
#endif
if (failures) {
n_log(LOG_ERR, "ex_http_server: %d failure(s)", failures);
return 1;
}
n_log(LOG_NOTICE, "ex_http_server: all checks passed");
return 0;
}
void process_args(int argc, char **argv)
static int failures
Definition ex_atlas.c:51
int main(void)
Definition ex_atlas.c:117
static void expect_true(const char *label, int cond)
Definition ex_atlas.c:53
static void run_server(char *port, double fake_offset, int nb_rounds)
N_HTTP_SERVER * srv
the server
static char pending[200000]
leftover bytes between responses on one connection
int ok
run() result
char head[4096]
the head
static long cl_recv(client *c, char *b, size_t n)
receive some bytes (3 s socket timeout)
static int read_reply(client *c, int head_only, reply *r)
read one response
NETWORK * netw
the socket
static N_HTTP_RESP * handler(N_HTTP_SERVER_REQUEST *req, void *user)
the application under test
long body_len
body length
static N_HTTP_RESP * text(int status, const char *body)
text response
static int closed_by_server(client *c, int ms)
has the server closed the connection (within ms)?
static size_t npending
number of leftover bytes
SSL * ssl
TLS, or NULL.
static void test_plain(void)
the plain HTTP server
static void test_tls(void)
the TLS server
int status
status code, 0 when none
static void cl_sends(client *c, const char *s)
send a NUL-terminated string
static N_HTTP_SERVER * start(N_HTTP_SERVER_CONFIG *cfg, char *port, int base)
start a server on the first free port from base
static void test_capacity(void)
the connection cap, on a server whose deadlines are long enough for the held connections to stay open...
static int write_pem(const N_STR *pem, char *path)
write a PEM string to a temp file
static int cl_tls(client *c, SSL_CTX *ctx)
upgrade a client connection to TLS
static int cl_connect(const char *port, client *c)
connect to the server
static void cl_send(client *c, const char *s, size_t n)
send all bytes
char body[70000]
the body
static void cl_close(client *c)
close a client connection
a test client connection, plain or TLS
a parsed response as the client saw it
server thread state
int run
Definition ex_kafka.c:56
NETWORK * netw
Network for server mode, accepting incomming.
Definition ex_network.c:39
char * cert
char * port
volatile char key[227]
TRUE while the key is held.
#define n_log(__LEVEL__,...)
Logging function wrapper to get line and func.
Definition n_log.h:113
#define LOG_DEBUG
debug-level messages
Definition n_log.h:108
#define LOG_ERR
error conditions
Definition n_log.h:100
void set_log_level(const int log_level)
Set the global log level value ( static int LOG_LEVEL ).
Definition n_log.c:123
#define LOG_NOTICE
normal but significant condition
Definition n_log.h:104
#define LOG_NULL
no log output
Definition n_log.h:70
#define LOG_INFO
informational
Definition n_log.h:106
int n_http_response_append(N_HTTP_RESP *r, const void *data, size_t len)
append bytes to the memory body (drops a file body)
int n_http_response_set_header(N_HTTP_RESP *r, const char *name, const char *value)
set a header: remove every header of that name, then add it
N_HTTP_RESP * n_http_response_new(int status)
new response with a status, keep-alive off, HTTP/1.1
a response under construction (fields are private, use the functions)
int body_timeout_ms
body deadline, ms (default 60000)
int header_timeout_ms
request head deadline from its first byte, ms (default 10000)
unsigned long long requests
requests answered
int tls
non-zero over TLS
unsigned long long timeouts
connections ended by a deadline
int body_status
after a failed body read: the status to answer (408, 413...)
unsigned long long active
connections being served now
size_t workers
worker threads = most concurrent connections (default 32)
const char * port
port to bind ("7430")
int write_timeout_ms
deadline to write one response, ms (default 60000)
unsigned long long accepted
connections accepted
long long max_body
largest Content-Length accepted at all (default 32 MiB); handlers pass their own, lower cap to the bo...
const char * tls_key_file
PEM private key, NULL for plain HTTP.
const char * tls_cert_file
PEM certificate chain, NULL for plain HTTP.
const char * path
the path, without the query string, still percent-encoded
n_http_server_handler handler
the application
unsigned long long refused
connections refused (queue full, per-IP cap)
const char * peer_ip
peer address as text
const char * query
the query string without '?
int idle_timeout_ms
wait for the next request on a kept-alive connection, ms (default 15000)
unsigned long long tls_failures
failed TLS handshakes
unsigned long long bad_requests
400 / 413 / 417 / 431 answered by the server
int handshake_timeout_ms
TLS handshake deadline, ms (default 10000).
void n_http_server_stats(N_HTTP_SERVER *srv, N_HTTP_SERVER_STATS *out)
copy of the counters
int n_http_server_read_body_to_fd(N_HTTP_SERVER_REQUEST *req, long long max, int fd)
read the whole body into an open file descriptor, refusing more than max
int n_http_server_run(N_HTTP_SERVER *srv)
serve until n_http_server_stop()
N_HTTP_SERVER * n_http_server_new(const N_HTTP_SERVER_CONFIG *cfg)
bind the listening socket and load the TLS context
void n_http_server_stop(N_HTTP_SERVER *srv)
ask the server to stop (async-signal-safe)
int n_http_server_read_body(N_HTTP_SERVER_REQUEST *req, long long max, N_STR **out)
read the whole body into memory, refusing more than max
void n_http_server_free(N_HTTP_SERVER **srv)
free a stopped server and set *srv to NULL
void n_http_server_config_defaults(N_HTTP_SERVER_CONFIG *cfg)
fill a config with the documented defaults
server settings; start from n_http_server_config_defaults()
a request as the handler sees it (fields are read-only)
counters, see n_http_server_stats()
size_t written
number of meaningful bytes in data, excluding the null terminator; the size including the null termin...
Definition n_str.h:68
char * data
the string
Definition n_str.h:63
#define free_nstr(__ptr)
free a N_STR structure and set the pointer to NULL
Definition n_str.h:203
A box including a string and his lenght.
Definition n_str.h:61
int n_x509_generate_ca(const char *cn, int days, N_STR **ca_cert_pem, N_STR **ca_key_pem)
Generate a self-signed certificate authority (CA) keypair and cert.
Definition n_x509.c:226
int n_x509_mint_host_cert(const char *host, const N_STR *ca_cert_pem, const N_STR *ca_key_pem, int days, N_STR **leaf_cert_pem, N_STR **leaf_key_pem)
Mint a per-host leaf certificate signed by the given CA.
Definition n_x509.c:285
N_SOCKET link
networking socket
Definition n_network.h:454
SOCKET sock
a normal socket
Definition n_network.h:356
int netw_init_openssl(void)
Do not directly use, internal api.
Definition n_network.c:1335
int netw_unload_openssl(void)
Do not directly use, internal api.
Definition n_network.c:1368
#define NETWORK_IPALL
Flag for auto detection by OS of ip version to use.
Definition n_network.h:48
int netw_setsockopt(NETWORK *netw, int optname, int value)
Modify common socket options on the given netw.
Definition n_network.c:969
int netw_close(NETWORK **netw)
Closing a specified Network, destroy queues, free the structure.
Definition n_network.c:3367
int netw_connect(NETWORK **netw, char *host, char *port, int ip_version)
Use this to connect a NETWORK to any listening one, unrestricted send/recv lists.
Definition n_network.c:2898
Structure of a NETWORK.
Definition n_network.h:375
Common headers and low-level functions & define.
HTTP/1.1 response: validated headers, memory or file body, framing.
a server (opaque)
HTTP/1.1 server: TLS or plain, deadlines, limits, keep-alive.
Generic log system.
Network Engine.
N_STR and string function declaration.
X.509 helpers: self-signed CA generation and per-host leaf minting.