A tiny HTTP server
The accept loop
A server is a loop: accept a connection, serve it, close it, repeat. accept (43) blocks until a client arrives, so one process serves one client at a time:
server_loop: mov rax, 43 ; sys_accept mov rdi, listen_fd xor rsi, rsi xor rdx, rdx syscall mov r12, rax ; connection fd ; serve, then close and loop
Reading the request
Read the request bytes into a buffer. The request line is the first line: METHOD, path, and version separated by spaces. Parse until the first CRLF, then answer - a real server reads headers until a blank line.
Writing the response
A minimal response is a status line, one header, a blank line, and the body. Write it with sys_write on the connection descriptor, close the descriptor, and jump back to accept:
mov rax, 1 mov rdi, r12 mov rsi, response mov rdx, resplen syscall
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does accept do when no client is waiting?
Answer
It blocks until a connection arrives
A blocking listening socket sleeps in accept until the kernel queues a connection.
-
Which syscall number accepts a connection on x86-64 Linux?
Answer
43
accept is 43; socket is 41, connect 42 and listen 50.
-
What does the server do with the descriptor accept returns?
Answer
It serves that connection and closes it
Each accepted descriptor is one connection and is closed after the response.
-
What is the first line of an HTTP request?
Answer
METHOD, path and version separated by spaces
A request line looks like GET / HTTP/1.0.
-
What separates the headers from the body in a response?
Answer
A blank line
The empty line after the last header ends the header block.
-
Why does one process serve one client at a time?
Answer
It blocks in accept and serves the connection in order
A single-threaded loop returns to accept only after it closes the connection.
-
Which descriptor does the response write use?
Answer
The connection descriptor from accept
The response goes to the accepted connection, not to the listening socket.
-
What does the server do after it writes and closes a response?
Answer
It jumps back to accept
The accept loop keeps the server alive for the next client.
-
Which syscall reads the request bytes from the connection?
Answer
read (0)
read takes the connection descriptor, a buffer and a count.
-
Why is the server output not shown on the page?
Answer
The lesson was not run: it needs a network service
The container has no client and no listening network service for a checked run.
The code on this page was not run: it needs a network service. The snippets are fragments of a server, not whole programs.
Article author: Arthur Isaev