DEV Community

Cover image for http-from-scratch: one HTTP/1.1 server in Rust, built twice
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

http-from-scratch: one HTTP/1.1 server in Rust, built twice

Most of us use HTTP every day through a framework. We write a handler, return a response, and the framework deals with the rest. That is the right way to ship software, and it also means many developers have never seen what "the rest" is: how a request is cut out of a stream of bytes, what keep-alive really asks of the server, why Content-Length and Transfer-Encoding together are a security problem.

http-from-scratch is my answer to that gap. It is an HTTP/1.1 server written from the socket up in Rust, twice: once on std::net::TcpListener with a hand-made thread pool, and once on Tokio. Both versions share the same I/O-free parser, handler and connection state machine, so the only difference between them is how bytes move. It is a learning project, not a production server, and this post is about what building it teaches.

What I built

An incremental parser. parser.rs never touches a socket. You feed it the bytes received so far. It returns Ok(None) until a full request (head and body) is there, then it returns the request and the number of bytes it consumed. Because it reports how much it used, pipelined requests stay in the buffer for the next round.

The parser handles Content-Length and Transfer-Encoding: chunked, including chunk extensions and trailers. It rejects malformed request lines and headers, obsolete line folding, conflicting Content-Length values, and requests that carry both Content-Length and Transfer-Encoding. That last check is the request-smuggling guard. Size limits answer with 431 or 413.

Responses. response.rs writes the status line and headers, with either a Content-Length body or a chunked one, and handles HEAD, where the headers go out and the body does not.

Routing and static files. app.rs serves three kinds of routes: GET/HEAD /<path> serves files under --root (with index.html for directories), POST /echo echoes the body, and GET /chunked streams a chunked response. File paths are percent-decoded and protected against path traversal: .., the encoded form %2e%2e, backslashes and NUL bytes are refused. MIME types come from the file extension.

One shared connection step. lib.rs::next_response is the per-connection step: parse, handle, serialize, and decide whether the connection stays open. Both servers call it in a loop.

A thread pool by hand. threadpool.rs is a fixed pool over an mpsc channel. It shuts down gracefully on drop, and a job that panics does not kill its worker.

Two servers. server_std.rs and server_tokio.rs are the read loops. Each has a 5 second idle keep-alive timeout.

How to use it

Clone the repository and run it with Cargo. The repository ships a public folder to serve.

git clone https://github.com/AbdeldjalilChougui/http-from-scratch
cd http-from-scratch

cargo run --release -- --root public --port 8080            # std + thread pool
cargo run --release -- --tokio --root public --port 8080    # Tokio
Enter fullscreen mode Exit fullscreen mode

Then talk to it with curl:

curl -v http://127.0.0.1:8080/
curl -d 'hello' http://127.0.0.1:8080/echo
curl -H 'Transfer-Encoding: chunked' -d @README.md http://127.0.0.1:8080/echo
curl --raw http://127.0.0.1:8080/chunked
Enter fullscreen mode Exit fullscreen mode

The first command fetches a static file and shows the headers. The second posts a body with Content-Length. The third sends the request body chunked, so you exercise the chunked decoder. The last one uses --raw so curl prints the chunked response as it is on the wire, chunk sizes included.

A good exercise is to run the same four commands against both servers and check that the answers are identical. They should be, since both servers run the same parser and handler.

What it teaches

HTTP is a framing problem first. TCP gives you a stream, not messages. A read can return half a request line, or one request and a third of the next. The parser's contract ("here are all the bytes so far, tell me if there is a full request and how long it was") is the cleanest way I know to handle that. One of the unit tests states the rule directly: every prefix of a valid request is incomplete, never an error.

Keeping I/O out of the parser pays off. Because the parser, the handler and the connection step do no I/O, they are tested with plain byte slices. And the same code runs under blocking sockets and under Tokio without a single async in it. Writing the server twice is what proves the separation is real: if the shared part needed to know how bytes arrive, the second server would not have fit.

Two length headers are a trap. If one proxy trusts Content-Length and the server behind it trusts Transfer-Encoding, they disagree on where a request ends, and an attacker can hide a second request inside the first. Rejecting requests that carry both, and requests with conflicting Content-Length values, is a small check with a large effect.

Keep-alive has a cost in the thread model. In the std server, a keep-alive connection occupies a pool thread until it closes or idles out. Seeing that in your own code makes the case for async I/O better than any diagram.

A thread pool is small. A channel, a few workers, a drop implementation that joins them. The details that take thought are shutdown and panics, not the happy path.

Things to know

The README is clear: this is a learning project, not a production server.

  • No TLS, no HTTP/2, no Expect: 100-continue, no compression, no range requests, and no caching headers (ETag, Last-Modified).
  • Whole bodies and files are buffered in memory. The request body limit is 8 MiB.
  • In the std server, a keep-alive connection holds a pool thread until it closes or idles out (5 s), so slow clients can exhaust the pool.
  • The Tokio server reads files with blocking std::fs inside the async task.

What was tested. cargo test runs unit tests for the parser, the response writer and path handling. Then tests/servers.rs starts both servers on ephemeral ports and checks static files, the 301, 403, 404, 405, 400 and 505 answers, HEAD, keep-alive, pipelining, HTTP/1.0, chunked requests sent in pieces, chunked responses, and 16 concurrent keep-alive clients.

Why I built it

I wanted to understand HTTP/1.1 at the level of bytes on a socket, not at the level of a framework's API. Reading the specification gets you part of the way. Having to decide what your own code does with a folded header, a second Content-Length or a half-received chunk gets you the rest.

Building it twice had its own purpose. People often present "threads versus async" as two different worlds. Here the protocol logic is written once, and the two servers differ only in their read loops. That makes it easy to see what async changes (how you wait for bytes) and what it does not change (everything else).

If you are learning Rust networking, the repository is small enough to read in order: parser.rs, response.rs, app.rs, then lib.rs, the thread pool and the two servers.

Get the code

The source and the tests are on GitHub: https://github.com/AbdeldjalilChougui/http-from-scratch. It's MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

Building it twice is the detail that makes this more than a tutorial — sharing one I/O-free parser across a hand-rolled thread pool and a Tokio server is the only honest way to compare threads versus async, because otherwise you are comparing two different parsers wearing the same name. The request-smuggling guard is the part I would point every backend dev at: rejecting a request that carries both Content-Length and Transfer-Encoding is a tiny check, but it is exactly the kind of thing a framework hides until a proxy in front of you disagrees about where a request ends. Your honest accounting of the trade-offs is refreshing too — the 5-second keep-alive holding a pool thread, the blocking std::fs reads inside async tasks, the 8 MiB body cap. Those are the real costs, and most writeups bury them. One question: when the Tokio server reads files with blocking std::fs, did you measure how much that actually hurts under concurrent slow downloads, or is it still on the list to move to tokio::fs? And did writing the parser I/O-free change how you test — are the byte-string unit tests the thing that caught the chunk-extension edge cases?