Projects / HTTP server / Phase 1
Phase 1 of 4 · about 2.5 hours
The simplest server that works
You end with a server that answers curl with a real web page, a 404, and a refusal for a path that tries to escape.
First, what is a web server? A socket is a handle the operating system gives your program for one end of a network connection. Your program reads bytes from it and writes bytes to it, the same way it would with a file. A file descriptor is the small integer that names an open file or socket. A server makes one special socket that listens, and every time a client connects, accept hands back a new socket for that one client.
On top of that sits HTTP, which is just agreed-upon text. A request looks like this:
GET /style.css HTTP/1.1
Host: localhost
The first line is the request line: a method, a path and a version. Then come header lines, and a blank line ends them. Each line ends with the two characters carriage return and line feed, written \r\n, so the end of the headers is the four bytes \r\n\r\n. The response has the same shape: a status line, headers, a blank line, then the body. The Content-Length header says how many body bytes follow, so the client knows where the response ends.
Step 1.1: Listen and accept (about 30 minutes)
Create d1/server.c. We will build it in four pieces. The first one turns a port number into a listening socket:
static int listen_on(int port) {
int fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd < 0) { perror("socket"); exit(1); }
int yes = 1;
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes); // restart without "address in use"
struct sockaddr_in addr = {.sin_family = AF_INET, .sin_port = htons(port), .sin_addr.s_addr = htonl(INADDR_ANY)};
if (bind(fd, (struct sockaddr *)&addr, sizeof addr) < 0) { perror("bind"); exit(1); }
if (listen(fd, 128) < 0) { perror("listen"); exit(1); }
return fd;
}
Four system calls do the work:
socketcreates the socket.AF_INETmeans IPv4 andSOCK_STREAMmeans TCP.setsockoptwithSO_REUSEADDRlets you restart the server right away. Without it,bindcan fail with "address in use" for a minute after you stop the server.bindattaches the socket to a port.INADDR_ANYmeans "on every network interface" andhtonsputs the port number into network byte order.listenturns it into a listening socket. The128is how many clients may wait in line before we callaccept.
The main loop, which comes last in the file, is the whole server in four lines: accept a client, handle it, close it, repeat.
int main(int argc, char **argv) {
int port = argc > 1 ? atoi(argv[1]) : 8080;
signal(SIGPIPE, SIG_IGN); // a client that hangs up must not kill the server
int server = listen_on(port);
fprintf(stderr, "listening on port %d\n", port);
for (;;) {
int client = accept(server, NULL, NULL);
if (client < 0) continue;
handle(client);
close(client);
}
}
Nothing here is clever yet. One client is served at a time, and we will see what that costs in Phase 2.
Step 1.2: Writing all the bytes (about 30 minutes)
Here is a trap that catches almost every first server. write(fd, buf, len) is allowed to send fewer bytes than you asked for, and tells you how many it took. A large response, or a slow client, makes that happen. The fix is a loop:
// write() may send fewer bytes than asked. Keep going until everything is out, or the peer is gone.
static int write_all(int fd, const char *buf, size_t len) {
while (len > 0) {
ssize_t n = write(fd, buf, len);
if (n < 0) {
if (errno == EINTR) continue;
return -1;
}
buf += n;
len -= (size_t)n;
}
return 0;
}
Walk through it:
n < 0is an error.EINTRmeans a signal interrupted the call before it did anything, so we just try again. Any other error means the client is gone, and we give up on it.- Otherwise we move
bufforward bynbytes and shortenlenby the same amount.
The second trap is in main: signal(SIGPIPE, SIG_IGN). If a client hangs up and we write to its socket anyway, the kernel sends our process the SIGPIPE signal, and the default action is to kill it. One impolite client would take the whole server down. Ignoring the signal turns it into a plain error (EPIPE) from write, which write_all already handles.
Pitfall: if the server vanishes the moment a client hangs up in the middle of an answer, look for a missing signal(SIGPIPE, SIG_IGN) first.
Step 1.3: Read and understand the request (about 45 minutes)
First two small helpers. send_text writes a complete small response, which we use for every error, and content_type picks the Content-Type header from the file extension, so a browser knows whether it got a page or a stylesheet.
static void send_text(int fd, int code, const char *reason, const char *body) {
char head[256];
int n = snprintf(head, sizeof head,
"HTTP/1.1 %d %s\r\nContent-Type: text/plain\r\nContent-Length: %zu\r\nConnection: close\r\n\r\n",
code, reason, strlen(body));
if (write_all(fd, head, (size_t)n) == 0) write_all(fd, body, strlen(body));
}
static const char *content_type(const char *path) {
const char *dot = strrchr(path, '.');
if (dot == NULL) return "application/octet-stream";
if (strcmp(dot, ".html") == 0) return "text/html";
if (strcmp(dot, ".css") == 0) return "text/css";
if (strcmp(dot, ".txt") == 0) return "text/plain";
return "application/octet-stream";
}
Now the part that makes it a web server. handle reads from the client until it has seen the blank line that ends the headers, then looks at the first line.
static void handle(int fd) {
char req[MAX_REQUEST + 1];
size_t len = 0;
while (len < MAX_REQUEST) { // read until the blank line that ends the headers
ssize_t n = read(fd, req + len, MAX_REQUEST - len);
if (n <= 0) return;
len += (size_t)n;
req[len] = '\0';
if (strstr(req, "\r\n\r\n") != NULL) break;
}
if (strstr(req, "\r\n\r\n") == NULL) { send_text(fd, 431, "Request Header Fields Too Large", "too big\n"); return; }
char method[16], target[1024], version[16];
if (sscanf(req, "%15s %1023s %15s", method, target, version) != 3) {
send_text(fd, 400, "Bad Request", "bad request line\n");
return;
}
if (strcmp(method, "GET") != 0) { send_text(fd, 405, "Method Not Allowed", "GET only\n"); return; }
if (target[0] != '/' || strstr(target, "..") != NULL) { send_text(fd, 400, "Bad Request", "bad path\n"); return; }
Take it in order:
- We read into a buffer of 8 KB. One
readcan return half a request, so we keep reading and checking for\r\n\r\n. If 8 KB go by without one, the client gets431 Request Header Fields Too Large. Without that limit a client could make us buffer forever. sscanfsplits the request line into method, target and version. The size limits in the format (%15s,%1023s) stop it from writing past the end of our small arrays. If it does not find three words, the answer is400 Bad Request.- We only know
GET. Anything else gets405 Method Not Allowed. - The path must start with
/, and it must not contain... That second rule matters: without it, a request for/../server.cwould walk out of thewwwfolder and read any file the server can read. This is called path traversal, and it is one of the oldest ways to break a file server.
Step 1.4: Send the file and try it (about 45 minutes)
The rest of handle finds the file, learns its size with fstat, sends a header and copies the bytes across:
char *query = strchr(target, '?');
if (query != NULL) *query = '\0';
char path[1100];
snprintf(path, sizeof path, "www%s%s", target, strcmp(target, "/") == 0 ? "index.html" : "");
struct stat st;
int file = open(path, O_RDONLY);
if (file < 0 || fstat(file, &st) < 0 || !S_ISREG(st.st_mode)) {
if (file >= 0) close(file);
send_text(fd, 404, "Not Found", "not found\n");
return;
}
char head[256];
int n = snprintf(head, sizeof head,
"HTTP/1.1 200 OK\r\nContent-Type: %s\r\nContent-Length: %lld\r\nConnection: close\r\n\r\n",
content_type(path), (long long)st.st_size);
if (write_all(fd, head, (size_t)n) == 0) {
char buf[16384];
ssize_t r;
while ((r = read(file, buf, sizeof buf)) > 0)
if (write_all(fd, buf, (size_t)r) < 0) break;
}
close(file);
}
A few details:
- A
?starts a query string such as/page?x=1. We cut the target off there, because we serve files and have no use for the query. - The path
/is mapped toindex.html. - We check
S_ISREGso that asking for a directory gives 404 and not a confusing read error. - Every response says
Connection: close: we send one answer and hang up. That keeps the server simple, and we will change it in Phase 3.
Build it and try it. Start the server in one terminal, and in another run these requests:
cd d1
gcc -std=gnu11 -O2 -Wall -Wextra -o server server.c
./server 8081
$ curl -si localhost:8081/
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 70
Connection: close
<!doctype html><title>tiny</title><h1>Hello from the tiny server</h1>
$ curl -si localhost:8081/nope | head -1
HTTP/1.1 404 Not Found
$ curl -si --path-as-is localhost:8081/../server.c | head -1
HTTP/1.1 400 Bad Request
$ curl -si -X POST localhost:8081/ | head -1
HTTP/1.1 405 Method Not Allowed
The --path-as-is flag stops curl from tidying the .. away before it sends the request, so our check really is the one answering. You can also open http://localhost:8081/ in a browser.
Phase 1 done
You have a working web server in about 110 lines of C. It speaks real HTTP, it refuses the obvious attacks, and it handles partial reads and writes. It also has a serious weakness, which Phase 2 begins with.