knaxuslearn · build · ship

Projects / HTTP server / Phase 4

Phase 4 of 4 · about 2.5 hours

Measure, fix, harden

You end with a benchmark you wrote yourself, a fixed performance bug, a clean leak check and a server that cannot be tricked out of its folder.

Step 4.1: Stop cleanly, then check for leaks (about 35 minutes)

Right now the only way to stop the server is to kill it, so nothing ever frees its memory and we cannot tell whether it leaks. We add a clean exit. A signal handler may only do very little safely, so it just sets a flag, and the main loop checks the flag:

static char docroot[PATH_MAX];  // the real, absolute path of www, with symlinks resolved
static volatile sig_atomic_t stop = 0;  // set by SIGTERM or SIGINT, checked once per loop

static void on_stop(int sig) { (void)sig; stop = 1; }

sig_atomic_t is the one integer type that is safe to write inside a signal handler. In main we install the handler for SIGTERM (what kill sends) and SIGINT (Ctrl+C), and leave out the SA_RESTART flag so that epoll_wait returns early when the signal arrives, instead of sleeping on:

int main(int argc, char **argv) {
  int port = argc > 1 ? atoi(argv[1]) : 8080;
  if (argc > 2) idle_seconds = atoi(argv[2]);
  if (argc > 3) max_conns = atoi(argv[3]);
  if (realpath("www", docroot) == NULL) { perror("www"); return 1; }
  now_s = time(NULL);
  signal(SIGPIPE, SIG_IGN);
  struct sigaction sa = {.sa_handler = on_stop};  // no SA_RESTART: epoll_wait must return when the signal lands
  sigaction(SIGTERM, &sa, NULL);
  sigaction(SIGINT, &sa, NULL);

When the loop ends, we close every connection and the listening socket:

  while (!stop) {
    int ready = epoll_wait(epoll_fd, events, MAX_EVENTS, 1000);  // wake at least once a second
    time_t before = now_s;
    now_s = time(NULL);
    for (int i = 0; i < ready; i++) {
      int fd = events[i].data.fd;
      if (fd == server) { accept_all(server); continue; }
      Conn *c = conns[fd];
      if (c == NULL) continue;
      if (events[i].events & (EPOLLERR | EPOLLHUP)) { close_conn(c); continue; }
      if (events[i].events & EPOLLIN) on_readable(c);
      else if (events[i].events & EPOLLOUT) {
        int done = on_writable(c);
        if (done < 0) close_conn(c);         // the client went away
        else if (done > 0) finish_response(c);
      }
    }
    if (now_s != before) close_idle();
  }

  for (int fd = 0; fd <= max_fd; fd++)
    if (conns[fd] != NULL) close_conn(conns[fd]);
  close(server);
  close(epoll_fd);
  fprintf(stderr, "bye\n");
  return 0;
}

Now a leak check. AddressSanitizer is a compiler feature that watches every memory access, and at exit its LeakSanitizer part reports memory that was allocated and never freed. Build the server with it, drive it with a mix of finished, abandoned and half-finished connections, stop it with SIGTERM and read its verdict:

gcc -std=gnu11 -g -fsanitize=address,undefined -fno-omit-frame-pointer -o server_asan server.c
import signal
import socket
import subprocess
import sys
import time

from helpers import read_response

BINARY = sys.argv[1] if len(sys.argv) > 1 else "server_asan"
proc = subprocess.Popen([f"./{BINARY}", "8090", "30"], stderr=subprocess.PIPE, text=True)
time.sleep(0.5)

# A mix of finished, half-finished and abandoned connections.
for _ in range(200):
    s = socket.create_connection(("localhost", 8090))
    s.sendall(b"GET /style.css HTTP/1.1\r\nHost: x\r\n\r\n")
    read_response(s)
    s.close()
open_ones = [socket.create_connection(("localhost", 8090)) for _ in range(20)]
half = socket.create_connection(("localhost", 8090))
half.sendall(b"GET / HTTP/1.1\r\nHo")
time.sleep(0.3)

proc.send_signal(signal.SIGTERM)
err = proc.communicate(timeout=5)[1]
print("exit code:", proc.returncode)
print("sanitizer reports:", err.count("ERROR: "))
last = err.strip().splitlines()[-1] if err.strip() else "(nothing)"
print("last line the server printed:", last)
exit code: 0
sanitizer reports: 0
last line the server printed: bye

Exit code 0 and no reports. But a check that has never failed proves nothing, so break the server on purpose by commenting out the free(c) in close_conn and run the same test:

sed 's|  free(c);|  /* free(c); */|' server.c > leaky.c
gcc -std=gnu11 -g -fsanitize=address,undefined -o server_leaky leaky.c
python3 try_leaks.py server_leaky
exit code: 1
sanitizer reports: 1
last line the server printed: SUMMARY: AddressSanitizer: 2171104 byte(s) leaked in 221 allocation(s).

Now the sanitizer reports the missing frees, so the clean result above means something. We also ran all three Phase 3 tests against the sanitizer build and they gave the same answers with no reports.

Step 4.2: A load generator (about 30 minutes)

To say how fast the server is, we need something that asks for pages as fast as it can. wrk and ab are the usual tools, but a 70 line program of our own keeps the project self-contained and shows exactly what is measured. It starts N threads. Each thread sends a request, reads the whole response using Content-Length, counts it and repeats, either on one connection (keep-alive) or on a new connection every time.

// A tiny load generator: N threads, each sends requests as fast as it can for a few seconds.
#define _GNU_SOURCE
#include <arpa/inet.h>
#include <netinet/in.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 port, seconds, keep_alive;
static const char *path;
static volatile int stop;
static long done[256];  // requests finished, one slot per thread, so threads never share a counter

static int connect_to_server(void) {
  int fd = socket(AF_INET, SOCK_STREAM, 0);
  struct sockaddr_in addr = {.sin_family = AF_INET, .sin_port = htons(port)};
  inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  if (connect(fd, (struct sockaddr *)&addr, sizeof addr) < 0) { close(fd); return -1; }
  return fd;
}

// Send one request and read the whole response. Returns 0 on success.
static int one_request(int fd) {
  char req[256];
  int n = snprintf(req, sizeof req, "GET %s HTTP/1.1\r\nHost: bench\r\nConnection: %s\r\n\r\n", path,
                   keep_alive ? "keep-alive" : "close");
  if (write(fd, req, (size_t)n) != n) return -1;
  char buf[65536];
  size_t have = 0, head_len = 0, body_len = 0;
  for (;;) {
    ssize_t r = read(fd, buf + have, sizeof buf - 1 - have);
    if (r <= 0) return -1;
    have += (size_t)r;
    buf[have] = '\0';
    char *end = strstr(buf, "\r\n\r\n");
    if (end == NULL) continue;
    if (head_len == 0) {
      head_len = (size_t)(end - buf) + 4;
      char *cl = strcasestr(buf, "Content-Length:");
      body_len = cl ? (size_t)atol(cl + 15) : 0;
    }
    if (have >= head_len + body_len) return 0;
    if (have == sizeof buf - 1) have = head_len;  // big body: keep counting, forget the bytes
  }
}

static void *worker(void *arg) {
  long id = (long)arg;
  int fd = -1;
  while (!stop) {
    if (fd < 0 && (fd = connect_to_server()) < 0) continue;
    if (one_request(fd) == 0) done[id]++;
    else { close(fd); fd = -1; continue; }
    if (!keep_alive) { close(fd); fd = -1; }
  }
  if (fd >= 0) close(fd);
  return NULL;
}

int main(int argc, char **argv) {
  if (argc < 6) { fprintf(stderr, "usage: bench port threads seconds keepalive(0|1) path\n"); return 1; }
  port = atoi(argv[1]);
  int threads = atoi(argv[2]);
  seconds = atoi(argv[3]);
  keep_alive = atoi(argv[4]);
  path = argv[5];
  pthread_t t[256];
  for (long i = 0; i < threads; i++) pthread_create(&t[i], NULL, worker, (void *)i);
  sleep((unsigned)seconds);
  stop = 1;
  long total = 0;
  for (int i = 0; i < threads; i++) { pthread_join(t[i], NULL); total += done[i]; }
  printf("%ld requests in %d s = %ld requests/s\n", total, seconds, total / seconds);
  return 0;
}

Each thread has its own slot in done, so threads never write to the same counter. The main thread sleeps for the test duration, sets stop, joins the threads and prints the total. Build it with gcc -std=gnu11 -O2 -Wall -Wextra -pthread -o bench bench.c.

Step 4.3: Measure, and find a 40 millisecond stall (about 50 minutes)

Run each version of the server for three seconds with 20 client threads asking for /style.css. This script starts a server, runs bench and stops the server:

#!/bin/sh
# Starts each server, hits /style.css for 3 seconds with the load generator, prints requests per second.
pidfile="$PWD/server.pid"
bench() {  # label, directory, keep-alive flag, threads
  (cd "$2" && ./server 9100 >/dev/null 2>&1 & echo $! > "$pidfile")
  sleep 0.5
  printf '%-38s' "$1"
  ./bench 9100 "$4" 3 "$3" /style.css
  kill "$(cat "$pidfile")"; sleep 0.3
}
bench "d1 blocking, new connection each"      ../d1 0 20
bench "d2 epoll, new connection each"         ../d2 0 20
bench "d3 epoll, keep-alive (no NODELAY)"     ../d3 1 20
bench "d4 epoll, new connection each"         .     0 20
bench "d4 epoll, keep-alive"                  .     1 20
bench "d4 epoll, keep-alive, 200 clients"     .     1 200
rm -f "$pidfile"
d1 blocking, new connection each      122118 requests in 3 s = 40706 requests/s
d2 epoll, new connection each         117639 requests in 3 s = 39213 requests/s
d3 epoll, keep-alive (no NODELAY)     1400 requests in 3 s = 466 requests/s
d4 epoll, new connection each         105826 requests in 3 s = 35275 requests/s
d4 epoll, keep-alive                  187557 requests in 3 s = 62519 requests/s
d4 epoll, keep-alive, 200 clients     183150 requests in 3 s = 61050 requests/s

Your numbers will differ, and they move by ten or twenty percent between runs (the load generator and the server share the same CPUs, and the file is tiny, so this measures the connection handling and not the disk). Read the shapes, not the digits:

  • The first and second rows are close. With fast clients and a 34 byte file, the blocking server of Phase 1 keeps up with the epoll server. Their difference is not speed. It is that epoll stays responsive when a client is slow, which Phase 2 showed and this benchmark does not exercise.
  • The fourth row is about the same as the second. Connecting and closing dominates the cost, and nothing in Phase 3 changes that.
  • Keep-alive raises the rate by more than half (row five against row four), because 20 sockets now carry thousands of requests each, with no connect and no close in between.
  • The third row is wrong. The Phase 3 server with keep-alive manages only a few hundred requests a second, far below even the version that closes every connection.

That third row is a real bug, and no test in the earlier phases could find it, because every one of them checked that answers were correct or that slow clients were handled, and none measured throughput. Divide it out: about 460 requests a second spread over 20 clients is roughly 23 requests per client per second, or one request every 43 milliseconds. Something waits about that long on every request.

The cause is an interaction between two sensible TCP rules. Nagle's algorithm says that if you have sent a small packet that has not been acknowledged yet, hold the next small packet back and send it together with others. The receiver's delayed ACK rule says to wait a short while before acknowledging, hoping to attach the acknowledgement to a reply. Our server sends the response header with send, and then the body in a second call to sendfile. The second small piece waits for the acknowledgement of the first, and the client waits to send that acknowledgement, until its delay timer expires. When we close the connection after each response this never matters, because closing flushes everything. With keep-alive, it happens on every request.

The usual fix is the socket option TCP_NODELAY, which turns Nagle's algorithm off for a socket so that small writes leave at once. We set it for each accepted client:

    int yes = 1;
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof yes);  // send small writes at once, do not wait to batch them

Rows four to six use the fixed server. The same design that did a few hundred requests a second now does tens of thousands, and nothing about the answers changed. The lesson is bigger than the option: a correct server can be slow for reasons that no functional test sees, so measure it.

Step 4.4: Stay inside the www folder (about 35 minutes)

Our .. check blocks the obvious traversal. But a file inside www can be a symbolic link that points somewhere else, and open follows links without asking. If someone ever puts www/leak.c -> ../server.c in place (by accident, or through another bug), the server would hand out the file. Let us see whether it does. This test asks for several tricky paths:

import socket

from helpers import read_response, start_server

server = start_server(8091)


def get(target):
    s = socket.create_connection(("localhost", 8091))
    s.sendall(f"GET {target} HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n".encode())
    status, body = read_response(s)
    s.close()
    return status, len(body)


for target in ["/style.css", "/../server.c", "/%2e%2e/server.c", "//style.css", "/leak.c", "/nope", "/?x=1"]:
    print(f"{target:20} -> {get(target)}")
server.kill()

First against the Phase 3 server, in a folder where www/leak.c is a link to ../server.c:

ln -s ../server.c www/leak.c
/style.css           -> ('HTTP/1.1 200 OK', 34)
/../server.c         -> ('HTTP/1.1 400 Bad Request', 9)
/%2e%2e/server.c     -> ('HTTP/1.1 404 Not Found', 10)
//style.css          -> ('HTTP/1.1 200 OK', 34)
/leak.c              -> ('HTTP/1.1 200 OK', 10039)
/nope                -> ('HTTP/1.1 404 Not Found', 10)
/?x=1                -> ('HTTP/1.1 200 OK', 70)

The line for /leak.c is the problem: it returned 200 OK and about 10 KB of source code. Percent-encoded dots (%2e%2e) are harmless here, because we never decode them, so the server looks for a file with that literal name and finds nothing.

The fix is realpath, which resolves every link and every . and .. and returns the real absolute path. We compute the real path of www once at startup, and for each request we compute the real path of the file and insist that it still begins with the www path followed by a slash:

  char real[PATH_MAX];  // resolve symlinks and "." parts, then insist the result is still inside www
  size_t root_len = strlen(docroot);
  if (realpath(path, real) == NULL || strncmp(real, docroot, root_len) != 0 || real[root_len] != '/') {
    respond_text(c, 404, "Not Found", "not found\n");
    return;
  }

  struct stat st;
  int file = open(real, O_RDONLY);
  if (file < 0 || fstat(file, &st) < 0 || !S_ISREG(st.st_mode)) {
    if (file >= 0) close(file);
    respond_text(c, 404, "Not Found", "not found\n");
    return;
  }

The extra check on the character after the prefix matters. Without it, a folder called www-secrets would pass a test for the prefix www. We also open the resolved path and not the original one, so a link cannot be swapped between the check and the open. The reply is 404 and not 403, so the server does not confirm that the file exists. Run the same test against the new server:

/style.css           -> ('HTTP/1.1 200 OK', 34)
/../server.c         -> ('HTTP/1.1 400 Bad Request', 9)
/%2e%2e/server.c     -> ('HTTP/1.1 404 Not Found', 10)
//style.css          -> ('HTTP/1.1 200 OK', 34)
/leak.c              -> ('HTTP/1.1 404 Not Found', 10)
/nope                -> ('HTTP/1.1 404 Not Found', 10)
/?x=1                -> ('HTTP/1.1 200 OK', 70)

Now /leak.c gets 404 and the normal files are unchanged.

Phase 4 done

You wrote about 290 lines of server, a load generator, and a handful of small test programs. You measured the server, found and fixed a performance bug that only measurement could show, proved that connections do not leak, and closed a path-handling hole.