# `mini_serv` cheat sheet — the shape to recall on a blank page > Memorize the **structure and the exact strings**, not a specific file. The exam's `main.c` > attachment gives you `str_join` + `extract_message` for free — you only need the ~85 lines > around them. --- ```mermaid flowchart LR M1["1 guard"] --> M2["2 socket"] --> M3["3 bind + listen"] --> M4["4 slots + max_fd"] --> M5["5 select loop"] M5 --> M6["6 accept gives arrived"] --> M7["7 recv, then buffer, then extract, then relay"] --> M8["8 disconnect gives left + cleanup"] M8 --> M5 ``` ## The program in 8 moves 1. **Guard**: `if (argc != 2)` → `write(2, "Wrong number of arguments\n", 26)`, `return 1`. 2. **Server fd**: `socket(AF_INET, SOCK_STREAM, 0)` → error? `fatal()`. 3. **Address**: `sockaddr_in`, `bzero`, `AF_INET`, `s_addr = htonl(2130706433)` (127.0.0.1), `sin_port = htons(atoi(argv[1]))`. → `bind()` → `listen()`. Any failure → `fatal()`. 4. **Slots**: array of clients indexed **by fd**: `{fd = -1, id = -1, buf = NULL}` for all `FD_SETSIZE`. `g_maxfd = server fd`. 5. **Loop** (every iteration, from scratch): - `FD_ZERO`; `FD_SET(server)`; `FD_SET` every live client fd. - `select(g_maxfd + 1, &readfds, NULL, NULL, NULL)`. - server readable → `accept()` → new slot: `id = g_next_id++`, raise `g_maxfd`, broadcast `"server: client %d just arrived\n"` **to others** (skip the newcomer). - each live client readable → `recv()`: - `<= 0` → disconnect. - else append chunk to that client's buffer (`str_join`), then loop `extract_message(&buf, &msg) == 1` → build `"client %d: " + msg` (`sprintf` into a malloc'd buffer) → broadcast **to others** → `free(msg)` → repeat. 6. **Disconnect**: save id → `close(fd)` → clear slot → `free(buf)` → broadcast `"server: client %d just left\n"` → shrink `g_maxfd` while it points at an empty slot (never below the server fd). **Partial line is dropped, not flushed.** 7. **Errors**: `fatal()` = `write(2, "Fatal error\n", 12)` + `exit(1)`. Never `printf`. No `#define` anywhere in the file. 8. **Hygiene**: `free` the extracted message; `free` the client buffer at disconnect. No leaks. Only `recv`/`send` after `select` said the fd is ready. ## Canonical body (this is `reference/mini_serv.c`, annotated) ```c #include #include #include #include #include #include #include typedef struct s_client { int fd; /* -1 = slot free */ int id; /* client number, 0,1,2… */ char *buf; /* pending partial line */ } t_client; static t_client g_c[FD_SETSIZE]; static int g_maxfd; /* highest fd in the sets */ static int g_server; /* listening socket */ static int g_next_id; /* never decreases, never reused */ static void fatal(void) { write(2, "Fatal error\n", 12); exit(1); } /* ---- GIVEN in the exam's main.c attachment (copy verbatim) ---- */ static char *str_join(char *buf, char *add); /* append add to buf, free old buf */ static int extract_message(char **buf, char **msg);/* pull one \n line out of *buf */ /* --------------------------------------------------------------- */ static void to_all_except(int fd, char *s) /* broadcast helper */ { int i = 0; while (i <= g_maxfd) { if (i != fd && g_c[i].fd != -1) send(g_c[i].fd, s, strlen(s), 0); i++; } } static void accept_new(void) { char msg[64]; int fd; fd = accept(g_server, NULL, NULL); if (fd < 0) return ; g_c[fd].fd = fd; g_c[fd].id = g_next_id++; if (fd > g_maxfd) g_maxfd = fd; sprintf(msg, "server: client %d just arrived\n", g_c[fd].id); to_all_except(fd, msg); /* NOT to the newcomer itself */ } static void disconnect(int fd) { char msg[64]; int id = g_c[fd].id; close(fd); g_c[fd].fd = -1; g_c[fd].id = -1; free(g_c[fd].buf); g_c[fd].buf = NULL; sprintf(msg, "server: client %d just left\n", id); to_all_except(-1, msg); while (g_maxfd > g_server && g_c[g_maxfd].fd == -1) g_maxfd--; } static void handle_read(int fd) { char tmp[4096]; char *msg; char *out; int n; n = recv(fd, tmp, sizeof(tmp) - 1, 0); if (n <= 0) return (disconnect(fd)); tmp[n] = 0; g_c[fd].buf = str_join(g_c[fd].buf, tmp); /* append FIRST… */ if (!g_c[fd].buf) fatal(); while (extract_message(&g_c[fd].buf, &msg) == 1) /* …then pull lines */ { out = malloc(strlen(msg) + 64); if (!out) { free(msg); fatal(); } sprintf(out, "client %d: %s", g_c[fd].id, msg); to_all_except(fd, out); free(out); free(msg); } } int main(int argc, char **argv) { struct sockaddr_in addr; fd_set readfds; int i; if (argc != 2) { write(2, "Wrong number of arguments\n", 26); return (1); } g_server = socket(AF_INET, SOCK_STREAM, 0); if (g_server < 0) fatal(); bzero(&addr, sizeof(addr)); addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(2130706433); /* 127.0.0.1 — subject says localhost only */ addr.sin_port = htons(atoi(argv[1])); if (bind(g_server, (struct sockaddr *)&addr, sizeof(addr)) < 0) fatal(); if (listen(g_server, 10) < 0) fatal(); i = 0; while (i < FD_SETSIZE) { g_c[i].fd = -1; g_c[i].id = -1; g_c[i].buf = NULL; i++; } g_maxfd = g_server; while (1) { FD_ZERO(&readfds); /* select destroys the set: rebuild every time */ FD_SET(g_server, &readfds); i = 0; while (i <= g_maxfd) { if (g_c[i].fd != -1) FD_SET(i, &readfds); i++; } if (select(g_maxfd + 1, &readfds, NULL, NULL, NULL) < 0) continue ; if (FD_ISSET(g_server, &readfds)) accept_new(); i = 0; while (i <= g_maxfd) { if (i != g_server && g_c[i].fd != -1 && FD_ISSET(i, &readfds)) handle_read(i); i++; } } return (0); } ``` ## The 15 traps (each one has failed someone's exam) 1. **`select` wrecks the `fd_set`** — rebuild (or copy from a master set) every loop. 2. **`nfds` must be `g_maxfd + 1`** — off-by-one silently ignores your newest fd. 3. **Never `send` to self** — check `i != fd` in the broadcast helper. 4. **Newcomer must NOT receive its own "just arrived"** — the expected trace is built that way. 5. **Don't flush the leftover partial line on disconnect** — the trace shows `arrived`+`left` with no message for that client. 6. **Append first, extract after** — a single `recv` can hold 5 lines, or half a line, or both. 7. **`recv() <= 0` → disconnect.** `0` is EOF, `< 0` is error. Both mean: clean up. 8. **`\x04` is data.** Only the socket closing is EOF. No special bytes. 9. **Free what `extract_message` hands you** (`free(msg)`) and free the leftover buffer on disconnect. Leak checks exist. 10. **`printf` is not in the allowed list.** stderr via `write(2, …)`; build strings with `sprintf`. 11. **No `#define`** in the submitted file (subject rule). 12. **Only bind `127.0.0.1`** — `htonl(2130706433)`. Not `INADDR_ANY`. 13. **Sending back to a client that just died can `SIGPIPE`-kill you** — the official test never does this (clients are serialized), so don't over-engineer; if you finish early and want armor, `signal(SIGPIPE, SIG_IGN)` is the classic line (check your subject's allowed functions first). 14. **`accept` failing is not fatal** — just `return`. 15. **`g_maxfd` can shrink** — keep it ≥ server fd or `select` stops seeing the listener. ## The real test, decoded `tester/grademe/` is the actual exam-style runner: a listener (client **0**) connects, then clients 1…9 connect / send / leave, and the listener's exact bytes are diffed. Reading `normal.output` tells you the ground truth: ``` server: client 1 just arrived client 1: Si vous ne voyez QUE ce message, c'est mauvais signe. ← line relayed server: client 1 just left ← sender closed server: client 2 just arrived client 2: Bienvenue sur le test de votre miniserv server: client 2 just left server: client 3 just arrived client 3: Ceci est un message server: client 3 just left server: client 4 just arrived server: client 4 just left ← sent text with NO \n → nothing relayed, buffer dropped server: client 5 just arrived server: client 5 just left ← same, and note: no leftover ever appears server: client 6 just arrived client 6: Et voici un texte avec plusieurs ← one packet, 5 lines → 5 prefixed lines client 6: retours client 6: a client 6: la client 6: ligne server: client 6 just left server: client 7 just arrived server: client 7 just left ← word-bursts incl. a literal ^D byte, no \n → silence server: client 8 just arrived server: client 8 just left ← 10 320-byte line with no \n → silence server: client 9 just arrived client 9: desu…desu ← 364 KB as ONE line, relayed whole server: client 9 just left ``` Also tested (seen in the runner): no-arg error, `Fatal error` on bind failure, exit status 1. Duration of the real runner is ~20–30 s (it sleeps between clients). Don't "optimize" buffers for it — send as soon as a line is complete. ## Exam-shell reality check - You will write **one file**: `mini_serv.c`, in the `rendu` directory the shell shows you. - Compile: `cc -Wall -Wextra -Werror mini_serv.c -o mini_serv` (the runner compiles for you too). - Test with a second terminal `nc 127.0.0.1 ` before submitting — 3 minutes of `nc` catches 90% of bugs. - Submit with the shell's submit command (`grademe`) — do it early, then again after fixes.