# The story of mini_serv — from the exam's `main.c` to a working server > Read this once from top to bottom. It is chronological: each chapter adds one piece to the > file, explains why it goes *there*, and what each condition means. The final code is > `exam-answer/mini_serv.c` (proven: 13/13 behavioral tests + real Grademe passed). --- ## Prologue — what the exam hands you, and what it hides You open the exam and get two things: a subject and a file called `main.c`. The file contains two finished helpers and a **demo**: ```c sockfd = socket(AF_INET, SOCK_STREAM, 0); /* create a socket */ bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; /* IPv4 */ servaddr.sin_addr.s_addr = htonl(2130706433); /* 127.0.0.1 */ servaddr.sin_port = htons(8081); /* hardcoded port! */ bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)); listen(sockfd, 10); connfd = accept(sockfd, (struct sockaddr *)&cli, &len); /* ONE client, then END */ ``` That demo creates a door, opens it, lets **one** person in — and the program ends. It has no ids, no messages, no loop. Its job is to show you the shape of the socket calls (and to warn you, in the subject, that it uses forbidden functions and hardcoded values). So the story is: **keep the door, throw away the demo's ending, and build the room behind it.** --- ## Chapter 1 — First, decide what the program must remember Before writing a loop, ask: between one event and the next, what do I need to know? 1. Who is connected → for every fd, a name. `g_id[fd]`: `-1` means "nobody", otherwise the client's public id. 2. What did they type that isn't a full line yet → `g_buf[fd]`. 3. Where is the door → `g_server`. 4. How far do I have to scan → `g_maxfd` (the highest fd in use). 5. What name do I give the next person → `g_nextid` (0, 1, 2, …). ```c static int g_id[FD_SETSIZE]; /* -1 = free slot, else client id */ static char *g_buf[FD_SETSIZE]; /* unfinished line for that client */ static int g_server; /* the listening fd */ static int g_maxfd; /* highest fd in use */ static int g_nextid; /* next client id */ ``` **Why arrays indexed by fd?** Because the kernel hands you an fd with every `accept`, and the fd *is* the slot number. `g_id[5]` is "the client whose socket is fd 5" — no search, no list, no struct to keep in sync. **Why `-1` and not `0`?** Because `0` is a real client id (the first one). The empty-slot marker must be a value that can never be a client id. `-1` is that value. **Why globals?** The handlers below are separate functions; they all need this state. Globals are the simplest way to share it in a single-file exam program. And a helper for the two fatal paths: ```c static void fatal(void) { write(2, "Fatal error\n", 12); exit(1); } ``` stderr is fd 2, the `\n` is inside the string, the length counts it (12), and the exit status is 1. The subject asks for exactly those bytes. --- ## Chapter 2 — The two gifts: `str_join` and `extract_message` The demo file also gives you two functions. They exist because of one fact: > **TCP is a byte stream, not a message service.** If a client writes `"hello\nworld\n"`, your `recv` might deliver `"hello\nworld\n"`, or `"hel"`, then `"lo\nworld\n"`, or `"hello\nw"`, then `"orld\n"`, or any other split. The kernel decides. The network decides. You don't. So every client needs a buffer of bytes that are not yet a complete line, and two operations: - **append**: `g_buf[fd] = str_join(g_buf[fd], chunk);` `str_join` makes a bigger heap string, copies old + new, **frees the old buffer**, and returns the new one. `NULL` on allocation failure (→ `fatal()`). - **cut one line**: `extract_message(&g_buf[fd], &line)` - returns `1`: `line` points at one `\n`-terminated line (**you must free it**), and `g_buf[fd]` now holds the remainder; - returns `0`: no newline yet — keep waiting; - returns `-1`: allocation failure. You copy both **verbatim** from the exam file. They are not the exam's lesson; the lesson is the loop around them. --- ## Chapter 3 — Keep the door, but make it *your* door The demo's `main` is a demo: no arguments, hardcoded port, `printf`, `exit(0)`. Replace the frame, keep the socket lines. **First condition: did they give me a port?** ```c if (argc != 2) { write(2, "Wrong number of arguments\n", 26); return (1); } ``` `argc` counts the program name too: `./mini_serv 8081` → `argc == 2`. Any other count means "no port" or "too many arguments" → the subject's exact stderr line, status 1. **Create the socket:** ```c g_server = socket(AF_INET, SOCK_STREAM, 0); if (g_server < 0) fatal(); ``` `AF_INET` = IPv4, `SOCK_STREAM` = TCP, `0` = default protocol. On success the kernel returns a small fd (usually 3, because 0/1/2 are stdin/stdout/stderr). On failure → the subject's `Fatal error`. **Fill the address — carefully:** ```c memset(&addr, 0, sizeof(addr)); /* zero FIRST: bind reads every field */ addr.sin_family = AF_INET; /* IPv4 */ addr.sin_addr.s_addr = htonl(2130706433); /* 127.0.0.1 */ addr.sin_port = htons(atoi(argv[1])); /* port from the argument */ ``` - `memset` first: a struct on the stack contains garbage; `bind` reads all of it. - `2130706433` = `0x7F000001` = the four bytes `127.0.0.1`. `htonl` converts to network byte order. The subject says "only listen on 127.0.0.1", so this exact address is required. - The port arrives as text (`"8081"`), so `atoi` turns it into a number, and `htons` converts a 16-bit port to network byte order. **Claim the port, then open the door:** ```c if (bind(g_server, (struct sockaddr *)&addr, sizeof(addr)) < 0) fatal(); if (listen(g_server, 10) < 0) fatal(); ``` `bind` = "this program owns 127.0.0.1:8081". Failure here (e.g. port already in use) happens *before* accepting — the subject wants `Fatal error` and exit 1. `listen` = "turn this socket into a door with a queue". The kernel will complete TCP handshakes for you and park up to 10 finished connections (the backlog). Nobody is accepted yet; `accept` is what dequeues them, one per call. --- ## Chapter 4 — Prepare the ledger ```c i = 0; while (i < FD_SETSIZE) { g_id[i] = -1; /* every slot starts empty */ i++; } g_maxfd = g_server; /* the highest fd so far is the door */ ``` `FD_SETSIZE` is 1024: `select`'s bitmap has one bit per fd, so fds 0..1023 is the whole universe. Empty must be written explicitly because static memory starts at zero, and `0` looks like "client 0". `g_maxfd` starts at the listener because that is the highest fd that exists. Every scan in the program goes `0..g_maxfd`; forgetting to raise it later is the classic "only the first client works" bug. --- ## Chapter 5 — The heartbeat: one `select` to hear everyone The demo did one `accept` and quit. A server must wait **forever**, on **many** sockets, in **one** process. `select` is the waiting room: give it a bitmap of fds, it sleeps until at least one is ready. ```c while (1) { FD_ZERO(&readfds); /* 1. clean clipboard */ FD_SET(g_server, &readfds); /* 2. always watch the door */ i = 0; while (i <= g_maxfd) /* 3. watch every live client */ { if (g_id[i] != -1) FD_SET(i, &readfds); i++; } if (select(g_maxfd + 1, &readfds, NULL, NULL, NULL) < 0) /* 4. sleep */ continue ; if (FD_ISSET(g_server, &readfds)) /* 5. someone at the door? */ on_accept(); i = 0; while (i <= g_maxfd) /* 6. someone talking? */ { if (i != g_server && g_id[i] != -1 && FD_ISSET(i, &readfds)) on_read(i); i++; } } ``` Why each piece is here, in this order: - **`FD_ZERO` first** — the set is a bitmap; leftovers from the previous round would watch dead fds. A fresh clipboard every heartbeat. - **`FD_SET(g_server)` always** — the door is a permanent source of events ("new connection"). - **`FD_SET(i)` for live slots** — these are the sources of "data" and "EOF". - **`g_maxfd + 1`** — `select`'s first argument is "watch fds 0..nfds−1". It must be the highest fd + 1, not `FD_SETSIZE` and not a stale number. Too small → the newest client is invisible forever. - **`< 0 → continue`** — a syscall can be interrupted by a signal (`EINTR`); the server must not die for that. Anything else (e.g. a bad fd) would repeat, but in this program the set is rebuilt every round, so retrying is safe. - **`select` overwrites the set** — on return, only ready fds still have their bit. That is why we rebuild it from scratch, and why `FD_ISSET` is meaningful only *after* the call. - **door first, then clients** — accepting first keeps the order of events intuitive; the new fd is not in this round's bitmap anyway, so its data is read next round. - **`i != g_server`** — the listening fd is not a chat client; it must never be read as one. What does "ready" mean? | fd | ready means | handler | |---|---|---| | `g_server` | a connection is waiting to be dequeued | `accept` | | client | bytes arrived **or EOF is pending** | `recv` (which tells you which) | --- ## Chapter 6 — Letting someone in: `on_accept` ```c static void on_accept(void) { char msg[64]; int fd = accept(g_server, NULL, NULL); if (fd < 0) return ; /* nothing to dequeue: never die */ if (fd >= FD_SETSIZE) { close(fd); return ; } /* select can't watch it */ g_id[fd] = g_nextid++; /* public name, forever increasing */ g_buf[fd] = NULL; /* new client, no pending text */ if (fd > g_maxfd) g_maxfd = fd; /* extend the scan window */ sprintf(msg, "server: client %d just arrived\n", g_id[fd]); send_all(fd, msg); /* tell the OTHERS, not the newcomer */ } ``` The kernel already finished the TCP handshake when the client connected; `accept` simply dequeues that finished connection and returns a **new fd** for it. The door keeps its own fd and keeps listening. - `fd < 0`: the connection may have been removed between `select` and `accept` (or the call was interrupted). The server's job is to keep running, not to exit. - `fd >= FD_SETSIZE`: `select` cannot watch fds ≥ 1024; close this one rather than overflow the arrays. (In practice you will never get here in the exam.) - `id = g_nextid++`: ids are *yours*. The kernel recycles fds; you must not recycle ids. - `g_buf[fd] = NULL`: an fd can be reused by a new client after an old one left — clear the old buffer *before* it can be reused. (`on_leave` also frees it.) - `g_maxfd` must rise, or the new client is never watched. - `send_all(fd, …)`: everyone **except** the newcomer. The grader's expected trace contains no line where a client hears about itself. --- ## Chapter 7 — The loudspeaker: `send_all` Three different messages need the same rule — "to everybody else": ```c static void send_all(int skip_fd, const char *s) { int fd = 0; while (fd <= g_maxfd) { if (fd != skip_fd && g_id[fd] != -1) send(fd, s, strlen(s), 0); fd++; } } ``` - `fd != skip_fd`: don't send it to the author. Arrival messages pass the new fd; relayed chat passes the sender; departures pass `-1`, meaning "nobody to skip". - `g_id[fd] != -1`: only live clients. Dead slots and the listener are skipped. - `send(fd, s, strlen(s), 0)`: one call per message, exact byte count. No retry loops — the subject says the fds won't block if you only call `send` after `select`, and the official test always drains what it receives. This is the line that enforces every "others only" rule in the exam. --- ## Chapter 8 — A message arrives: `on_read` `select` woke us because fd is readable. But "readable" means "there are bytes **or** the peer has closed". Only `recv` knows which: ```c static void on_read(int fd) { char chunk[4096]; char *line; char *out; ssize_t n; n = recv(fd, chunk, sizeof(chunk) - 1, 0); if (n <= 0) { on_leave(fd); return ; } /* 0 = EOF, -1 = error */ chunk[n] = 0; /* make it a C string */ g_buf[fd] = str_join(g_buf[fd], chunk); /* append FIRST */ if (!g_buf[fd]) fatal(); /* out of memory */ while (extract_message(&g_buf[fd], &line) == 1) /* then cut lines */ { out = malloc(strlen(line) + 64); /* "client N: " + line + \0 */ if (!out) { free(line); fatal(); } sprintf(out, "client %d: %s", g_id[fd], line); send_all(fd, out); /* to the others only */ free(out); free(line); } } ``` The story of one `recv` call: 1. **Read up to 4095 bytes** (`sizeof − 1`, leaving room for the terminator). `recv` returns how many it got; it does not care about lines. 2. **`n <= 0` means the client is gone.** `0` is EOF (the peer closed its writing side); `-1` is an error (e.g. connection reset). Both are handled the same way: `on_leave`. 3. **Terminate the chunk** (`chunk[n] = 0`) so the string helpers work. 4. **Append to that client's buffer.** Why append, not replace? Because the previous `recv` may have ended in the middle of a line: `"hel"` + `"lo\n"`. 5. **Extract in a loop.** One chunk can contain zero, one, or many complete lines, and it can end with a partial one. Each `extract_message == 1` gives exactly one complete line. 6. **Build the outbound string.** `"client %d: "` + the line (which already ends with `\n`). Size: `strlen(line) + 64` is plenty for the prefix and the id. Then send it to the others and free both heap strings. 7. When `extract_message` returns `0`, the remainder stays in `g_buf[fd]` for the next chunk. Why not just `send` the chunk? Because a chunk is not a message. Sending it raw would produce half a line, lose the prefix, or concatenate several lines without their own prefix. The exam grader compares exact bytes; "almost right" is wrong. --- ## Chapter 9 — Cutting a line, in slow motion `extract_message` is the only subtle function, and it is given to you. Here is what it does with the buffer `"hi\nhow\nare"`: - scan from the start until the first `'\n'` (index 2); - allocate a new string for everything after it: `"how\nare"`; - null-terminate the old buffer right after the newline: `"hi\n"` — that's your `line`; - make `*buf` point at the new remainder: `"how\nare"`; - return `1`. Next call: line `"how\n"`, remainder `"are"`; next call: no `'\n'` → return `0`, remainder stays. When the rest of the line arrives later, append it and call again. Ownership is the trap: the line it returns is a **slice of the old buffer**, and the old buffer is no longer referenced. You must free the line after using it. The remainder is a fresh allocation that belongs to the buffer. --- ## Chapter 10 — Goodbye: `on_leave` ```c static void on_leave(int fd) { char msg[64]; int id = g_id[fd]; /* save the name BEFORE clearing the slot */ close(fd); /* release the kernel socket */ g_id[fd] = -1; /* slot empty: broadcasts will skip it */ free(g_buf[fd]); /* DROP the unfinished line (never flush) */ g_buf[fd] = NULL; sprintf(msg, "server: client %d just left\n", id); send_all(-1, msg); /* tell everyone who is left */ while (g_maxfd > g_server && g_id[g_maxfd] == -1) g_maxfd--; /* shrink the scan window, keep the door */ } ``` The order matters: - **save the id first** — after `g_id[fd] = -1` you can no longer name the client in the message. The grader's line uses the id, not the fd. - **free the buffer without sending it** — a half-typed line is not a message. The expected trace shows `arrived` + `left` and nothing in between for a client that closed mid-line. - **`send_all(-1, …)` after clearing the slot** — the dead client is skipped automatically, and everyone else hears the news. - **shrink `g_maxfd`** — if the highest client left, no reason to scan up to its old fd. The condition `g_maxfd > g_server` protects the door: never shrink below the listener. --- ## Chapter 11 — One full session, event by event The grader connects a **listener** (call it L) and then short-lived senders. Watch the state: | Event | Code path | State changes | L sees | |---|---|---|---| | L connects | `select` → door → `accept` | L: fd 4, id 0, buf NULL | nothing (nobody else yet) | | Alice connects | door → `accept` | Alice: fd 5, id 1 | `server: client 1 just arrived` | | Alice types `hello\n` | Alice's fd ready → `recv` 6 → append → extract | buf `"hello\n"` → line → buf empty | `client 1: hello` | | Alice types `par` (no Enter) | `recv` 3 → append → extract returns 0 | buf `"par"` | nothing | | Alice types `tial\n` | `recv` 5 → append → buf `"partial\n"` → extract | buf empty | `client 1: partial` | | Alice closes (Ctrl-C) | `recv` 0 → `on_leave` | fd 5 closed, slot -1, buf freed, id 1 remembered | `server: client 1 just left` | | Bob connects | `accept` may reuse fd 5 | Bob: fd 5, **id 2** | `server: client 2 just arrived` | That table is the entire exam. Every rule in the subject is one of those rows: - ids increment and are never reused (Bob gets 2 although he has Alice's old fd); - arrival/relay/left go to others only (L sees them, the involved client does not); - a partial line stays invisible until completion; - a disconnect drops the partial line but announces the departure. --- ## Chapter 12 — Why this order of code C reads top to bottom, so a function must exist before the function that calls it: - globals first → every function below can use them; - `fatal` first → everyone can die cleanly; - `str_join`, `extract_message` next → `on_read` uses them; - `send_all` next → `on_accept`/`on_leave`/`on_read` use it; - `on_leave` before `on_read` → `on_read` calls `on_leave`; - `on_accept` after that; - `main` last → everything is defined by then. Inside `main`, the same logic: create the door → claim the address → listen → initialize the ledger → loop forever (rebuild watch list → sleep → dispatch). --- ## Chapter 13 — Every condition, and what it is really asking | Condition | The question it asks | If true | If false | |---|---|---|---| | `argc != 2` | did the user forget/over-supply the port? | exact args error, exit 1 | continue | | `g_server < 0` | did the kernel refuse a socket? | `Fatal error`, exit 1 | continue | | `bind(...) < 0` | is the address already taken / invalid? | `Fatal error`, exit 1 | continue | | `listen(...) < 0` | did the kernel refuse the queue? | `Fatal error`, exit 1 | continue | | `select(...) < 0` | was the wait interrupted? | retry the loop | process readiness | | `FD_ISSET(g_server)` | is there a new connection? | `on_accept` | check clients | | `i != g_server` | is this fd a chat client? | might call `on_read` | skip (it's the door) | | `g_id[i] != -1` | is this slot occupied? | watch/relay to it | skip | | `accept(...) < 0` | was the pending connection gone? | return, keep serving | continue | | `fd >= FD_SETSIZE` | is the fd outside select's universe? | close it | use it | | `recv(...) <= 0` | did the peer close or error? | `on_leave` | process bytes | | `!g_buf[fd]` | did the append run out of memory? | `Fatal error` | continue | | `extract_message(...) == 1` | is there a complete line? | relay it | keep the remainder | | `!out` | did the relay allocation fail? | free line, `Fatal error` | continue | | `fd > g_maxfd` | is this the highest fd so far? | raise the ceiling | leave it | | `fd != skip_fd` | is this the author/newcomer? | skip | send | | `g_maxfd > g_server && g_id[g_maxfd] == -1` | can the scan window shrink safely? | lower it | stop | --- ## Chapter 14 — What the grader really compares The grader is not checking your functions; it is checking the **listener's byte stream**. Each chapter produces one kind of line in it: ``` server: client 1 just arrived <- Chapter 6 (accept + announce) client 1: hello <- Chapters 8-9 (recv + extract + relay) server: client 1 just left <- Chapter 10 (EOF + announce) ``` The expected file in `tester/grademe/normal.output` is exactly those lines, in order. If your program produces them, byte for byte, you pass. Every rule in this story exists to produce the right line at the right time — nothing more, nothing less. --- ## Epilogue — the four sentences to remember 1. **The kernel gives you fds; you give clients ids — and ids are never reused.** 2. **`select` is a rebuilt watch list; a ready client may be data or EOF, and only `recv` knows.** 3. **Append first, cut complete lines second; a partial line is never a message — not even at goodbye.** 4. **Everything is announced to the others, with `"client %d: "` in front of every line.**