knaxuslearn · build · ship

Projects / HTTP server / Phase 2

Phase 2 of 4 · about 2.5 hours

Many clients on one thread

You end with a server that answers a small request in under a millisecond while another client is still downloading a 20 MB file.

Step 2.1: One idle client blocks everyone (about 25 minutes)

Our read call blocks: the program stops there until data arrives. If a client connects and then says nothing, handle waits for it, and nobody else gets served. The test below connects one silent client, then asks for a normal page with curl:

python3 slow_test.py
import socket
import subprocess
import time

PORT = 8081

# A client that connects and then says nothing.
idle = socket.create_connection(("localhost", PORT))
time.sleep(0.2)

start = time.time()
out = subprocess.run(
    ["curl", "-s", "-o", "/dev/null", "-w", "%{http_code}", "--max-time", "3", f"localhost:{PORT}/"],
    capture_output=True, text=True,
)
print(f"a normal request while one client sits idle: status {out.stdout}, gave up after {time.time() - start:.1f}s")
idle.close()

With the server running on port 8081:

a normal request while one client sits idle: status 000, gave up after 3.0s

curl gave up after three seconds with status 000, which means "no answer at all". A real attacker needs nothing more than this: open a few connections and stay quiet. The same thing happens, more gently, with slow downloads. Make a 20 MB file and download it slowly while asking for a small one:

head -c 20000000 /dev/urandom > www/big.bin
small file during the big download: 200 in 3.064554s

A 34 byte file took seconds, because the server was busy feeding a slow reader. We need a server that never waits on one client while others have work to do.

Step 2.2: Non-blocking sockets and epoll (about 35 minutes)

Two ideas fix this, and they work together.

A non-blocking socket never waits. If you read and nothing has arrived, the call returns immediately with the error EAGAIN, which means "not now". Setting it takes two fcntl calls:

static int set_nonblocking(int fd) {
  int flags = fcntl(fd, F_GETFL, 0);
  return flags < 0 ? -1 : fcntl(fd, F_SETFL, flags | O_NONBLOCK);
}

But a program that keeps asking "anything yet?" on every socket wastes the CPU. epoll is the answer. You give the kernel a list of sockets you care about, and epoll_wait sleeps until at least one of them is ready, then tells you which. One thread can watch thousands of sockets this way. The loop becomes:

int main(int argc, char **argv) {
  int port = argc > 1 ? atoi(argv[1]) : 8080;
  signal(SIGPIPE, SIG_IGN);
  int server = listen_on(port);
  epoll_fd = epoll_create1(0);
  struct epoll_event ev = {.events = EPOLLIN, .data.fd = server};
  epoll_ctl(epoll_fd, EPOLL_CTL_ADD, server, &ev);
  fprintf(stderr, "listening on port %d\n", port);

  struct epoll_event events[MAX_EVENTS];
  for (;;) {
    int ready = epoll_wait(epoll_fd, events, MAX_EVENTS, -1);
    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) {
        if (on_writable(c) != 0) close_conn(c);  // finished, or the client went away
      }
    }
  }
}

Walk through it:

  • epoll_create1 makes the watch list. epoll_ctl adds, changes or removes a socket on it.
  • epoll_wait returns the ready sockets in events. We handle each one and loop.
  • If the ready socket is the listening one, a client is waiting, so we accept it. If it is a client socket, we look up that client's state in conns[fd].
  • EPOLLIN means "there is data to read". EPOLLOUT means "there is room to write". EPOLLERR and EPOLLHUP mean the connection is broken.

Accepting needs a small loop of its own, because many clients can arrive between two wake-ups:

static void accept_all(int server) {
  for (;;) {  // accept until the queue is empty: one wake-up may mean many waiting clients
    int fd = accept(server, NULL, NULL);
    if (fd < 0) return;  // EAGAIN: nobody else is waiting
    if (fd >= MAX_FDS || set_nonblocking(fd) < 0) { close(fd); continue; }
    Conn *c = calloc(1, sizeof *c);
    if (c == NULL) { close(fd); continue; }
    c->fd = fd;
    c->file = -1;
    conns[fd] = c;
    struct epoll_event ev = {.events = EPOLLIN, .data.fd = fd};
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev);
  }
}

Each new client gets its own Conn, a struct that remembers everything about that connection. We store it in conns[fd], indexed by file descriptor, which is a cheap way to find it again. The listening socket is non-blocking too, so accept returns EAGAIN when the line is empty and the loop ends.

Pitfall: on a non-blocking socket, EAGAIN is not an error to report. It means "not now", so go back to the loop and let epoll say when the socket is ready again.

Step 2.3: A small state machine per connection (about 50 minutes)

With threads, the program's place in handle was kept for free: the stack remembered it was halfway through reading. With one thread and a loop, we must keep that memory ourselves. That is what Conn is for:

typedef struct {
  int fd;
  char in[MAX_REQUEST + 1];  // bytes read so far
  size_t in_len;
  char head[1536];  // the response header, or a whole small response
  size_t head_len, head_sent;
  const char *body;  // small fixed body for errors (may be NULL)
  size_t body_len, body_sent;
  int file;  // open file to send, or -1
  off_t file_off, file_len;
} Conn;

It holds the bytes read so far (in, in_len), the response being sent (head, body, file) and how far we have got with each (head_sent, body_sent, file_off). A connection is always in one of three states: reading a request, sending a response, or finished. Reading comes first:

static void on_readable(Conn *c) {
  for (;;) {
    ssize_t n = read(c->fd, c->in + c->in_len, MAX_REQUEST - c->in_len);
    if (n == 0) { close_conn(c); return; }  // the client hung up
    if (n < 0) {
      if (errno == EAGAIN || errno == EWOULDBLOCK) break;
      if (errno == EINTR) continue;
      close_conn(c);
      return;
    }
    c->in_len += (size_t)n;
    c->in[c->in_len] = '\0';
    if (strstr(c->in, "\r\n\r\n") != NULL) break;
    if (c->in_len == MAX_REQUEST) break;
  }
  if (strstr(c->in, "\r\n\r\n") == NULL) {
    if (c->in_len < MAX_REQUEST) return;  // keep waiting for the rest of the headers
    respond_text(c, 431, "Request Header Fields Too Large", "too big\n");
  } else {
    build_response(c);
  }
  watch(c, EPOLLOUT);  // now we have something to say: wake us when the socket can take it
}
  • We read until EAGAIN, which means we have everything the kernel has for us right now.
  • A read that returns 0 means the client closed its end, so we clean up.
  • If the headers are not complete yet, we just return. The next time more bytes arrive, epoll wakes us and we pick up where we left off. That is the whole trick.
  • Once the request is complete, build_response decides what to say (it is the old handle logic, but it only fills in fields and never touches the socket), and watch(c, EPOLLOUT) asks to be woken when the socket can accept data.

We switch to EPOLLOUT only now because a socket with room in its send buffer is almost always writable. Watching for it all the time would wake the loop constantly with nothing to do.

Writing is the mirror image:

// Returns 1 when the whole response has been sent.
static int on_writable(Conn *c) {
  while (c->head_sent < c->head_len) {
    ssize_t n = send(c->fd, c->head + c->head_sent, c->head_len - c->head_sent, MSG_NOSIGNAL);
    if (n < 0) return (errno == EAGAIN || errno == EINTR) ? 0 : -1;
    c->head_sent += (size_t)n;
  }
  while (c->body_sent < c->body_len) {
    ssize_t n = send(c->fd, c->body + c->body_sent, c->body_len - c->body_sent, MSG_NOSIGNAL);
    if (n < 0) return (errno == EAGAIN || errno == EINTR) ? 0 : -1;
    c->body_sent += (size_t)n;
  }
  while (c->file >= 0 && c->file_off < c->file_len) {
    ssize_t n = sendfile(c->fd, c->file, &c->file_off, (size_t)(c->file_len - c->file_off));
    if (n < 0) return (errno == EAGAIN || errno == EINTR) ? 0 : -1;
    if (n == 0) break;
  }
  return 1;
}

Each send may take only part of the data. We record how much went out and, on EAGAIN, return 0 so the loop can come back when the socket drains. We use MSG_NOSIGNAL on send as a second guard against SIGPIPE, so a hang-up cannot kill us even if the signal handling were removed. close_conn removes the socket from the watch list, frees the Conn, and closes the descriptor.

Step 2.4: sendfile, and the same test again (about 40 minutes)

The last loop in on_writable uses sendfile. Instead of reading a file into our buffer and then writing the buffer to the socket, sendfile asks the kernel to copy straight from the file to the socket. That saves a trip of the data through our program, which is why web servers use it for static files. Like send, it may move only part of the file, and file_off remembers how far it got.

Now repeat both tests against the new server:

a normal request while one client sits idle: status 200, took 0.01s
small file during the big download: 200 in 0.000330s
big.bin arrived byte for byte

The idle client no longer matters, the small file arrives while the big download is still running, and the 20 MB file is identical to the original, so none of the partial sends lost or repeated a byte.

Phase 2 done

One thread now serves many clients, because no step ever waits on a single one. The price is that the code is harder to read: the straight line of handle became a state machine spread over a few functions. That trade is the core of event-driven servers, and it is the same one nginx and Node.js make.