# mini_serv — how the machine works, piece by piece
> The files in this gym: `reference/variant_friend.c` (the code your friend passed with)
> and `reference/mini_serv.c` (the canonical gym version). This document annotates the
> friend's variant and flags where the canonical one differs. Both pass the real grader.
---
## 0. One sentence
`mini_serv` is a **switchboard**: every client is a socket (an fd), the server waits for
"someone wants to say something" with `select()`, and when a **complete line** arrives it
copies it to everyone else with a name tag — plus announcements when people join/leave.
---
## 1. Map of the whole program
```mermaid
flowchart TD
A([start]) --> ARG{"argc == 2 ?"}
ARG -- no --> E1["write(2, 'Wrong number of arguments\n')
exit(1)"]
ARG -- yes --> S["socket(AF_INET, SOCK_STREAM, 0)"]
S --> SET["fill sockaddr_in:
127.0.0.1 = htonl(2130706433)
port = htons(atoi(argv[1]))"]
SET --> BL["bind + listen"]
BL -- error --> E2["write(2, 'Fatal error\n')
exit(1)"]
BL --> MASTER["active_fds = { listen fd }
max_fd = listen fd"]
MASTER --> LOOP["LOOP"]
LOOP --> CP["read_fds = write_fds = active_fds"]
CP --> SEL{"select(max_fd + 1) — sleep until something is ready"}
SEL --> SCAN["scan fd = 0 .. max_fd"]
SCAN --> SRV{"listen fd readable?"}
SRV -- yes --> ACC["accept() → new client
id = next_id++
FD_SET into active_fds
broadcast 'just arrived' to OTHERS"]
SRV -- no --> CLI{"some client fd readable?"}
CLI -- no --> LOOP
CLI -- yes --> RC{"recv(fd) > 0 ?"}
RC -- "<= 0 → EOF / error" --> DISC["broadcast 'just left'
FD_CLR, close(fd), free its buffer"]
RC -- yes --> APP["append chunk to that client's buffer"]
APP --> EX{"complete line in buffer?"}
EX -- yes --> REL["broadcast 'client N: ' + line to OTHERS
(repeat while lines remain)"]
EX -- no --> LOOP
REL --> LOOP
ACC --> LOOP
DISC --> LOOP
```
**The fd_set lifecycle — the single most-tested idea in this exam:**
```mermaid
flowchart LR
M["active_fds (the master)
server + every client
never passed to select"] -->|copy before every select| C["read_fds / write_fds (the copies)
select() modifies them:
bits for NON-ready fds are cleared"]
C -->|"FD_ISSET(fd, &read_fds) == true"| H["that fd has data / a new connection"]
```
`select()` is a **destructive** in/out parameter: after it returns, the set only contains
the fds that were ready. That is the entire reason the master set exists.
---
## 2. A real session (what travels on the wire)
```mermaid
sequenceDiagram
participant A as Client 0 (nc)
participant S as mini_serv
participant B as Client 1 (nc)
A->>S: connect
Note over S: assigned id 0
nobody else connected → no announcement
B->>S: connect
S-->>A: server: client 1 just arrived
Note over B: the newcomer gets NOTHING about itself
B->>S: "hello\n"
S-->>A: client 1: hello
B->>S: "par" (no newline yet)
Note over S: held in clients[1].msg — silence on the wire
B->>S: "tial\n"
S-->>A: client 1: partial
B->>S: close (EOF)
S-->>A: server: client 1 just left
```
**Broadcast truth table** (the exact rules the grader diffs):
| Event | The client involved sees | Every OTHER client sees |
|--------------------|--------------------------|-----------------------------------------------|
| client N connects | nothing | `server: client N just arrived\n` |
| client N sends `line\n` | nothing | `client N: line\n` (one per line) |
| client N sends `abc` (no `\n`) | nothing | nothing (held) |
| client N disconnects | (gone) | `server: client N just left\n` — leftover text is dropped, never flushed |
---
## 3. Piece by piece — the friend's variant
### 3.1 The `#include`s — who provides what
| Include | Provides | Used for |
|---|---|---|
| `stdio.h` | `sprintf` | building `"client %d: "` etc. |
| `stdlib.h` | `malloc`, `calloc`, `free`, `exit`, `atoi` | buffers + `exit(1)` + port parsing |
| `string.h` | `strlen`, `strcpy`, `strcat`, `memset` | string work |
| `unistd.h` | `write`, `close` | stderr messages, closing fds |
| `sys/socket.h` | `socket`, `bind`, `listen`, `accept`, `send`, `recv`, `AF_INET`, `SOCK_STREAM` | the actual network |
| `netinet/in.h` | `sockaddr_in`, `htonl`, `htons` | address + byte order |
| `sys/select.h` | `fd_set`, `FD_ZERO/SET/CLR/ISSET`, `select` | the waiting room |
Most of these arrive for free in the exam's `main.c` attachment (your friend marked which
lines came from there).
### 3.2 The client record
```c
typedef struct s_client { int id; char *msg; } t_client;
t_client clients[1024];
```
- The array index **is the fd**. `clients[5]` describes the client whose socket is fd 5.
- `id` — the number that appears in messages: `client 3: ...`, `server: client 3 just left`.
fds and ids are different things: fds get reused by the OS, **ids never are**.
- `msg` — 🚨 badly named: it is **not** the message log. It's the client's *pending partial
line*: bytes that arrived but are not yet a complete line. Think of it as the mailbox
residue. (This is where 80% of exam failures happen.)
- `1024` = `FD_SETSIZE`: `select()` can only watch fds `0..1023`.
### 3.3 The globals
```c
char readbuff[100000], writebuff[100000];
int max_fd = 0, next_id = 0;
fd_set active_fds, read_fds, write_fds;
```
| Global | Job | Exam-relevant note |
|---|---|---|
| `readbuff` | scratch space for one `recv()` | one recv ≠ one message; TCP splits arbitrarily |
| `writebuff` | scratch for small outgoing announcements | `sendMsg` sends this buffer |
| `max_fd` | highest fd in the sets | `select` needs `max_fd + 1`; loops scan `0..max_fd` |
| `next_id` | the ever-increasing client number | must NOT decrease or reuse |
| `active_fds` | master list: server fd + all client fds | never given to `select` |
| `read_fds` / `write_fds` | the per-iteration copies given to `select` | select destroys them → copy again next loop |
### 3.4 `exitError`
```c
void exitError(char *str) { write(2, str, strlen(str)); exit(1); }
```
- Writes to **stderr** (fd 2, not `printf` — `printf` isn't allowed).
- Always `exit(1)`.
- Used with exactly the strings the subject demands: `"Wrong number of arguments\n"`,
`"Fatal error\n"` (newline included in the literal — easy to forget!).
### 3.5 `sendMsg` — the loudspeaker
```c
void sendMsg(int sender_fd) {
for (int fd = 0; fd <= max_fd; fd++)
if (FD_ISSET(fd, &write_fds) && fd != sender_fd)
send(fd, writebuff, strlen(writebuff), 0);
}
```
- Sends the current `writebuff` to everyone **except the sender**.
- Why `write_fds`? It's the post-select copy of the active set (sockets are almost always
writable), used here as "**who exists** right now". A closed fd was `FD_CLR`-ed from
`active_fds`, so it can't appear.
- `sender_fd = -1` would mean "to absolutely everyone".
- This is only for short announcements; the chat relay builds its own heap string because a
single line can be 364 KB — bigger than `writebuff`.
### 3.6 The two given gears — `str_join` and `extract_message`
TCP gives you a **stream of bytes**, not messages. These two functions turn the stream into
lines. They are handed to you in the exam's `main.c` — you do not have to memorize them,
but you must know exactly what they do:
```
kernel delivers clients[fd].msg after str_join
───────────────── ───────────────────────────────
recv → "hel" append → "hel"
recv → "lo\nwor" append → "hello\nwor"
│ extract_message
▼
line = "hello\n" → "client 1: hello\n" → send to others
residue = "wor"
```
- `str_join(buf, add)`: returns a **new** heap string `buf + add`; frees the old `buf`.
(`NULL + add` works too.)
- `extract_message(&buf, &msg)`:
- `1` — found a `\n`: `msg` points at a `\n`-terminated slice (**you must `free(msg)`**),
`buf` is replaced by the remainder;
- `0` — no complete line yet (keep waiting);
- `-1` — allocation failed.
- Both return `NULL`/`-1` on malloc failure → treat as `Fatal error`.
### 3.7 `main`, step by step
1. **`argc != 2` → `Wrong number of arguments\n` + exit 1.** "No port given" is an error.
2. **`socket(AF_INET, SOCK_STREAM, 0)`** — create the listening fd (IPv4 + TCP).
3. **Register it**: `FD_SET(sockfd, &active_fds)`, `max_fd = sockfd`.
4. **Address**:
- `memset(&servaddr, 0, ...)` — zero it or `bind` gets garbage;
- `sin_family = AF_INET` — IPv4;
- `sin_addr.s_addr = htonl(2130706433)` — `2130706433 == 0x7F000001 == 127.0.0.1`
(`htonl` = host → network byte order). The subject demands localhost-only;
- `sin_port = htons(atoi(av[1]))` — `atoi` because argv is text, `htons` for byte order.
5. **`bind`** — claim `127.0.0.1:port` (fails if taken → `Fatal error`).
**`listen(sockfd, 10)`** — start queueing connections (10 = backlog).
6. **The infinite loop** (this is the whole server):
- `read_fds = write_fds = active_fds;` — fresh copies; select will erase what isn't ready;
- `select(max_fd + 1, &read_fds, &write_fds, NULL, NULL)` — sleep until *any* fd is
ready. `max_fd + 1` = "watch fds 0..max_fd";
- scan `fd = 0 .. max_fd`:
- **server fd readable** → `accept()`: new client socket.
Guard negative, raise `max_fd`, `id = next_id++`, `msg = NULL`, `FD_SET` it,
build `"server: client %d just arrived\n"` in `writebuff`, `sendMsg(new_fd)`;
`break` (one event per wakeup).
- **a client fd readable** → `recv(fd, readbuff, ...)`:
- `recv <= 0` → client is gone (0 = EOF, <0 = error): build
`"server: client %d just left\n"`, `sendMsg(fd)`, `FD_CLR`, `close(fd)`,
`free(clients[fd].msg)`; `break`. **No leftover flush.**
- `recv > 0` → `readbuff[n] = 0`, append to the client's buffer with `str_join`,
then `while (extract_message(...) > 0)`: build `"client %d: " + line` in a fresh
heap string and `send` it to every other active fd; `free(str)`, `free(line)`.
### 3.8 The two style tricks (both legitimate)
| Trick | Why it works | Cost |
|---|---|---|
| 3 fd_sets: master + 2 copies | `select` modifies what you pass it; the master preserves the truth | none, it's the classic pattern |
| `break` after every event | one event handled per select wakeup; anything still pending is reported again next call because it's still in the kernel | slightly slower; simpler bookkeeping |
The canonical `reference/mini_serv.c` does the same job the other way: no fd_sets kept
around — it **rebuilds** `read_fds` from the `clients[]` array each loop, and handles
**all** ready fds per wakeup. Same rules, different plumbing. Pick one and drill only that.
### 3.9 Ownership — who allocates, who frees
| Thing | Allocated by | Freed by |
|---|---|---|
| `clients[fd].msg` (pending line) | `str_join` on each append | `free(clients[fd].msg)` on disconnect; old versions freed inside `str_join` |
| `line` from `extract_message` | it slices the old buffer (which becomes `msg`) | **you**: `free(line)` after sending |
| relay `str` (`"client N: " + line`) | `str_join(NULL, ...)` twice per line | **you**: `free(str)` after sending |
| announcements in `writebuff` | nobody (static buffer) | nobody |
| the fd | `accept()` | `close(fd)` on disconnect |
That free-order is exactly why the grader can run "no leaks" checks later: every path has a
matching free.
---
## 4. Exam-morning recall hooks
1. **"Master + copies"** — never hand `active_fds` to `select`.
2. **"Others only"** — arrival, chat lines, departures are all *others only*.
3. **"Append first, extract after"** — `str_join` then loop `extract_message`.
4. **"0 means dead"** — `recv() <= 0` → `left`, close, free; leftover is dropped.
5. **"Ids count up forever"** — fds get recycled, ids never do.
6. **"127.0.0.1 is 2130706433"** — the number is bigger than it looks; it's `0x7F000001`.
7. **"Two strings, exact"** — `Wrong number of arguments\n`, `Fatal error\n`, both with `\n`, both exit 1.