core: add all the required files
This commit is contained in:
@@ -0,0 +1,149 @@
|
||||
# Exam Rank 06 — `mini_serv` training gym
|
||||
|
||||
**Goal: walk into Exam Rank 06, get `mini_serv`, submit once, pass. Cold recall — no guessing.**
|
||||
|
||||
---
|
||||
|
||||
## What the exam actually is (confirmed)
|
||||
|
||||
- One file: `mini_serv.c`. A **`select()`-based multi-client chat server** on `127.0.0.1:<port>`.
|
||||
- The exam gives you a `main.c` attachment with socket boilerplate + two helpers
|
||||
(`str_join`, `extract_message`). You are expected to reuse those helpers.
|
||||
- Grading is scripted, automated, **byte-exact**: one listener client is connected, then a
|
||||
series of short-lived clients connect / send / disconnect, and the output the listener
|
||||
received is `diff`-ed against an expected trace. (The real test is in `tester/grademe/`.)
|
||||
- Window: ~2–4 h. No internet. Only the allowed functions from the subject.
|
||||
|
||||
> ⚠️ **Campus caveat.** In the updated exam format some students get **`mini_db`** (C++98
|
||||
> key-value server) instead — sometimes as "level 2" of the same exam. Ask a senior at your
|
||||
> campus exactly what exam 06 serves there. 80% of this training (select loop, line
|
||||
> buffering, broadcast, clean disconnect) transfers to mini_db; if your campus uses it,
|
||||
> tell me and I'll extend this gym.
|
||||
|
||||
## What exactly gets checked (ground truth from the graders)
|
||||
|
||||
1. No argument → stderr `Wrong number of arguments\n`, exit status 1.
|
||||
2. Bind failure → stderr `Fatal error\n`, exit status 1.
|
||||
3. Client N connects → **every other** connected client gets `server: client N just arrived\n`.
|
||||
The newcomer gets **nothing** for itself.
|
||||
4. Client N sends data → every **other** client gets `client N: ` + every complete `\n`-terminated
|
||||
line — one prefix per line, even if one packet contained several lines.
|
||||
5. An incomplete line (no `\n` yet) is held in a per-client buffer… and **dropped if the
|
||||
client disconnects** — never flushed.
|
||||
6. `\x04` (Ctrl-D byte) is plain data, not EOF. Only `recv() <= 0` means disconnect.
|
||||
7. Client disconnects → everyone else gets `server: client N just left\n`.
|
||||
8. Ids increment forever (`0, 1, 2, …`), never reused.
|
||||
9. It must survive a **364 KB single line** and a **10 KB line with no newline** (both are in the test).
|
||||
10. No memory / fd leaks. Non-blocking: only call `recv`/`send` after `select` said "ready".
|
||||
11. Only listen on `127.0.0.1` (`htonl(2130706433)`). No `#define` in the file.
|
||||
|
||||
## Files in this gym
|
||||
|
||||
| Path | What it is |
|
||||
|---|---|
|
||||
| `subject/subject.en.txt` | The exam subject (verbatim, from the official attachment) |
|
||||
| `subject/main.c` | The helper file the exam gives you |
|
||||
| `cheatsheet.md` | **The 8 moves + the 15 traps.** Read once, re-read after every attempt |
|
||||
| `walkthrough.md` | Code block → line-by-line → **real captured behavior** for every station (with probes) |
|
||||
| `exam-pack.md` | **The desert-island file:** exam subject + `main.c` verbatim, full stage plan, debug ladder, checklist, man-page excerpts |
|
||||
| `diagrams.md` | 15 diagrams from scratch: processes, fd table, address, door, state, select loop, accept, pipeline, disconnect, ids, ownership, errors, session |
|
||||
| `exam-answer/mini_serv.c` | The simplest passing implementation (proven 13/13 + Grademe) |
|
||||
| `exam-answer/explained.md` | Every variable, function, expression and ownership rule in that file |
|
||||
| `subject/main.annotated.c` | The exam's `main.c`, annotated: keep the helpers, rewrite `main()` |
|
||||
| `exam-card.md` | One screen for the 5 minutes before you enter |
|
||||
| `fundamentals.md` | What fds, sockets, TCP streams and `select()` really are — with runnable experiments |
|
||||
| `libc-reference.md` | Every syscall/libc call used by `mini_serv`, individually: args, returns, errno, exam pattern, traps |
|
||||
| `man-pages.md` | Curated offline man-page index + reading paths + "power moves" |
|
||||
| `debugging.md` | Debugging toolkit (`gdb`/`valgrind`/`ss`), the symptom→cause table, a 60-second triage checklist |
|
||||
| `explore/` | Four tiny toy programs that make the fundamentals visible |
|
||||
| `drills/drills.md` | D1…D8 training program, scoring, 3-day crash plan |
|
||||
| `templates/mini_serv.skeleton.c` | Fill-in skeleton (compiles, TODOs where the meat is) |
|
||||
| `reference/mini_serv.c` | A known-good solution. **Only for diffing AFTER a timed attempt** |
|
||||
| `reference/variant_friend.c` | Community variant (sets + one-event-per-wakeup style), validated by this gym's graders |
|
||||
| `tester/mini_serv_tester.py` | Fast offline behavioral tester (13 checks, edge cases) |
|
||||
| `tester/grademe/` | The **real** exam-style test suite (exact diff) |
|
||||
| `tester/check.sh` | One command: strict compile + behavioral tester + real grademe diff |
|
||||
| `sandbox/` | Your exam simulation. You write `sandbox/rendu/mini_serv/mini_serv.c` |
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
# check your attempt (compile with -Wall -Wextra -Werror + behavior + real grademe diff):
|
||||
bash tester/check.sh
|
||||
|
||||
# fast behavioral suite only (needs a compiled binary):
|
||||
cc -Wall -Wextra -Werror sandbox/rendu/mini_serv/mini_serv.c -o sandbox/mini_serv
|
||||
python3 tester/mini_serv_tester.py sandbox/mini_serv
|
||||
|
||||
# real grademe runner only:
|
||||
cd sandbox && bash .system/grading/tester.sh
|
||||
# pass -> sandbox/.system/grading/passed exists
|
||||
# fail -> sandbox/traceback contains expected-vs-yours
|
||||
|
||||
# manual testing with netcat (3 terminals):
|
||||
cc -Wall -Wextra -Werror sandbox/rendu/mini_serv/mini_serv.c -o sandbox/mini_serv
|
||||
./sandbox/mini_serv 8081 # terminal 1
|
||||
nc 127.0.0.1 8081 # terminal 2 (listener)
|
||||
nc 127.0.0.1 8081 # terminal 3 (type "hello" + Enter; terminal 2 shows "client 1: hello")
|
||||
# Ctrl-D in terminal 3 → terminal 2 shows "server: client 1 just left"
|
||||
```
|
||||
|
||||
## The plan
|
||||
|
||||
### 7-day plan (default)
|
||||
|
||||
| Day | Work |
|
||||
|---|---|
|
||||
| 1 | Read the subject + `cheatsheet.md`. Drill **D1** (requirement recall), **D2** (boilerplate blast ×3), **D3** (buffer brains ×2) |
|
||||
| 2 | **D4** (join/leave + ids), then **D5**: first full from-blank attempt under timer → `check.sh` → diff vs `reference/` |
|
||||
| 3 | Fix the "what I missed" list. **D5 again**. Target: all green |
|
||||
| 4 | **D6**: full attempt ≤ 90 min, all green. Then **D7** chaos scenarios |
|
||||
| 5 | **D5/D6 again** — two clean runs in a row? |
|
||||
| 6 | **D8**: exam sim — fresh dir, vim, 2 h, no notes, then grade yourself |
|
||||
| 7 | Light repetition (D2/D3 from memory), read cheatsheet traps once, **rest**. |
|
||||
|
||||
### 3-day crash plan (exam in ≤3 days, ~2 h/day)
|
||||
|
||||
| Block | Work |
|
||||
|---|---|
|
||||
| Day 1 · 20 min | Read `subject/subject.en.txt` + cheatsheet "8 moves". Then D1 (write the ground truths from memory) |
|
||||
| Day 1 · 80 min | `drills/typing-script.md` Stage A→F, live `nc` checkpoints. Guided reading allowed this first rep |
|
||||
| Day 1 · 20 min | D2 rep 2 (blank) + Stage D case table from memory |
|
||||
| Day 2 · 15 min | Warm-up: Stage C from blank, < 15 min |
|
||||
| Day 2 · 75 min | D5: full attempt from blank, timer on. Then `check.sh` + diff vs `reference/` + write "what I missed" |
|
||||
| Day 2 · 30 min | Fix the missed bits: re-drill only failing stages ×3 |
|
||||
| Day 3 · 30 min | D5/D6 again from blank, target ≤ 60 min, all green |
|
||||
| Day 3 · 30 min | D7 chaos (`check.sh`, then `tester/mini_serv_tester.py --quick` loops) |
|
||||
| Day 3 · 45 min | D8-lite: fresh dir, only subject + `main.c` open, type the whole file, then grade |
|
||||
| Day 3 · 15 min | Read cheatsheet traps once. Stop. Sleep. |
|
||||
|
||||
> If Day 3's cold run is not green, take the exam only if you must — a failed attempt is
|
||||
> information, not the end. But if you can wait one more day and get one more green, wait.
|
||||
|
||||
### Readiness rule
|
||||
|
||||
> **Two consecutive full attempts written from a blank file, all green, under 2 h = ready.**
|
||||
> Not "I understand it". Not "I did it once". **Twice, in a row, cold.**
|
||||
|
||||
## Rules of the gym
|
||||
|
||||
- During any timed attempt: no internet, no notes, no `reference/`, vim only — same as the exam.
|
||||
- After the attempt: `check.sh` → then **diff your file against `reference/`** line by line and
|
||||
write down every difference you missed (that list is your real study material).
|
||||
- Never copy-paste during practice. Typing the patterns is the point.
|
||||
- `reference/` is for post-attempt study and for keeping the test harness honest. It is not
|
||||
an exam asset. Exam day you write your own code.
|
||||
|
||||
## Exam-day playbook
|
||||
|
||||
1. Read the subject **twice**. Copy the exact strings (`"Wrong number of arguments\n"`,
|
||||
`"Fatal error\n"`, `"server: client %d just arrived\n"`, …) into your file as you go.
|
||||
2. Found the `main.c` attachment? **Open it in a split / second tab.** Copy `str_join` +
|
||||
`extract_message` verbatim — they're free wins.
|
||||
3. Build in this order: args check → socket/bind/listen → fd_set loop → accept + arrivals →
|
||||
recv + buffer + line extract + relay → disconnect + departures. Test with a second
|
||||
terminal **after each layer** (`nc`), don't wait for the end.
|
||||
4. Leave 30 min at the end for `nc` sanity + re-reading the subject + submission.
|
||||
5. Submit early, submit again after fixes if the exam shell allows. A submitted partial
|
||||
program beats a perfect unsent one.
|
||||
6. Panic costs more than bugs. You have drilled this. Type what you drilled.
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
# 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')<br/>exit(1)"]
|
||||
ARG -- yes --> S["socket(AF_INET, SOCK_STREAM, 0)"]
|
||||
S --> SET["fill sockaddr_in:<br/>127.0.0.1 = htonl(2130706433)<br/>port = htons(atoi(argv[1]))"]
|
||||
SET --> BL["bind + listen"]
|
||||
BL -- error --> E2["write(2, 'Fatal error\n')<br/>exit(1)"]
|
||||
BL --> MASTER["active_fds = { listen fd }<br/>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<br/>id = next_id++<br/>FD_SET into active_fds<br/>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'<br/>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<br/>(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)<br/>server + every client<br/>never passed to select"] -->|copy before every select| C["read_fds / write_fds (the copies)<br/>select() modifies them:<br/>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<br/>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.
|
||||
+268
@@ -0,0 +1,268 @@
|
||||
# `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 <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/select.h>
|
||||
|
||||
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 <port>` 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.
|
||||
Executable
BIN
Binary file not shown.
@@ -0,0 +1,237 @@
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <netdb.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
|
||||
#include <sys/select.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
|
||||
/* what client include */
|
||||
typedef struct s_client
|
||||
{
|
||||
int id;
|
||||
int fd;
|
||||
char *buf;
|
||||
} t_client;
|
||||
/* the space for max clients */
|
||||
static t_client g_clients[FD_SETSIZE];
|
||||
/* current max fds */
|
||||
static int g_maxfds;
|
||||
/* current client ids */
|
||||
static int g_nexid;
|
||||
/* the read and write sets */
|
||||
fd_set readfds, writefds;
|
||||
/* global server id */
|
||||
int g_server;
|
||||
|
||||
int extract_message(char **buf, char **msg)
|
||||
{
|
||||
char *newbuf;
|
||||
int i;
|
||||
|
||||
*msg = 0;
|
||||
if (*buf == 0)
|
||||
return (0);
|
||||
i = 0;
|
||||
while ((*buf)[i])
|
||||
{
|
||||
if ((*buf)[i] == '\n')
|
||||
{
|
||||
newbuf = calloc(1, sizeof(*newbuf) * (strlen(*buf + i + 1) + 1));
|
||||
if (newbuf == 0)
|
||||
return (-1);
|
||||
strcpy(newbuf, *buf + i + 1);
|
||||
*msg = *buf;
|
||||
(*msg)[i + 1] = 0;
|
||||
*buf = newbuf;
|
||||
return (1);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return (0);
|
||||
}
|
||||
|
||||
char *str_join(char *buf, char *add)
|
||||
{
|
||||
char *newbuf;
|
||||
int len;
|
||||
|
||||
if (buf == 0)
|
||||
len = 0;
|
||||
else
|
||||
len = strlen(buf);
|
||||
newbuf = malloc(sizeof(*newbuf) * (len + strlen(add) + 1));
|
||||
if (newbuf == 0)
|
||||
return (0);
|
||||
newbuf[0] = 0;
|
||||
if (buf != 0)
|
||||
strcat(newbuf, buf);
|
||||
free(buf);
|
||||
strcat(newbuf, add);
|
||||
return (newbuf);
|
||||
}
|
||||
|
||||
void bc(int id, char *msg)
|
||||
{
|
||||
int i;
|
||||
i = 0;
|
||||
while (i <= g_maxfds)
|
||||
{
|
||||
if(i != id && i != g_server && g_clients[i].fd != -1 && FD_ISSET(i, &writefds))
|
||||
{
|
||||
send(i, msg, strlen(msg), 0);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
void fatal(void)
|
||||
{
|
||||
write(2, "fatal error\n", 12);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
|
||||
void accept_connection(void)
|
||||
{
|
||||
char tmp[64];
|
||||
int fd;
|
||||
|
||||
fd = accept(g_server, NULL, NULL);
|
||||
if(fd < 0)
|
||||
return ;
|
||||
g_clients[fd].fd = fd;
|
||||
g_clients[fd].id = g_nexid++;
|
||||
g_clients[fd].buf = NULL;
|
||||
sprintf(tmp, "server: client %d just arrived\n", g_clients[fd].id);
|
||||
if(fd > g_maxfds)
|
||||
g_maxfds++;
|
||||
bc(fd, tmp);
|
||||
};
|
||||
|
||||
|
||||
void disconnect(int fd)
|
||||
{
|
||||
char tmp[64];
|
||||
int id;
|
||||
|
||||
id = g_clients[fd].id;
|
||||
g_clients[fd].id = -1;
|
||||
g_clients[fd].fd = -1;
|
||||
free(g_clients[fd].buf);
|
||||
g_clients[fd].buf = NULL;
|
||||
sprintf(tmp, "server: client %d just left\n", id);
|
||||
bc(fd, tmp);
|
||||
close(fd);
|
||||
if(g_maxfds > g_server && g_clients[fd].fd == -1)
|
||||
g_maxfds--;
|
||||
}
|
||||
|
||||
|
||||
|
||||
void handle_connection(int fd)
|
||||
{
|
||||
char buff[1046];
|
||||
int size;
|
||||
char *msg;
|
||||
char *out;
|
||||
|
||||
size = recv(fd, buff, sizeof(buff) - 1, 0);
|
||||
if (size <= 0)
|
||||
{
|
||||
disconnect(fd);
|
||||
return ;
|
||||
}
|
||||
buff[size] = 0;
|
||||
g_clients[fd].buf = str_join(g_clients[fd].buf, buff);
|
||||
if(!g_clients[fd].buf)
|
||||
fatal();
|
||||
while(extract_message(&g_clients[fd].buf, &msg))
|
||||
{
|
||||
out = calloc(sizeof(char) ,strlen(msg) + 64);
|
||||
if(!out)
|
||||
{
|
||||
free(msg);
|
||||
fatal();
|
||||
}
|
||||
sprintf(out, "client %d: %s", g_clients[fd].id, msg);
|
||||
bc(fd, out);
|
||||
free(out);
|
||||
free(msg);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
//int sockfd, connfd, len;
|
||||
struct sockaddr_in servaddr;
|
||||
int i; // counter
|
||||
|
||||
|
||||
/* checking process for the arg */
|
||||
if(argc != 2)
|
||||
fatal();
|
||||
// socket create and verification
|
||||
g_server = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (g_server == -1)
|
||||
fatal();
|
||||
bzero(&servaddr, sizeof(servaddr));
|
||||
|
||||
// assign IP, PORT
|
||||
servaddr.sin_family = AF_INET;
|
||||
servaddr.sin_addr.s_addr = htonl(2130706433);
|
||||
servaddr.sin_port = htons(atoi(argv[1]));
|
||||
|
||||
// Binding newly created socket to given IP and verification
|
||||
if ((bind(g_server, (const struct sockaddr *)&servaddr, sizeof(servaddr))) != 0)
|
||||
fatal();
|
||||
if (listen(g_server, 10) != 0)
|
||||
fatal();
|
||||
/* loop and init the t_client to all zeros */
|
||||
i = 0;
|
||||
while (i < FD_SETSIZE)
|
||||
{
|
||||
g_clients[i].id = -1;
|
||||
g_clients[i].fd = -1;
|
||||
g_clients[i].buf = NULL;
|
||||
i++;
|
||||
}
|
||||
g_maxfds = g_server;
|
||||
/* Loop thro all the clients */
|
||||
while(42)
|
||||
{
|
||||
FD_ZERO(&readfds);
|
||||
FD_ZERO(&writefds);
|
||||
FD_SET(g_server, &readfds);
|
||||
FD_SET(g_server, &writefds);
|
||||
i = 0;
|
||||
while(i <= g_maxfds)
|
||||
{
|
||||
if(i != g_server && g_clients[i].fd != -1)
|
||||
{
|
||||
FD_SET(i, &readfds);
|
||||
FD_SET(i, &writefds);
|
||||
}
|
||||
i++;
|
||||
};
|
||||
if(select(g_maxfds + 1, &readfds, &writefds, NULL, NULL) < 0)
|
||||
continue;
|
||||
if(FD_ISSET(g_server, &readfds))
|
||||
accept_connection();
|
||||
i = 0;
|
||||
while(i <= g_maxfds)
|
||||
{
|
||||
if(i != g_server && g_clients[i].id != -1 && FD_ISSET(i, &readfds))
|
||||
{
|
||||
handle_connection(i);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return (0);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <netdb.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/select.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
|
||||
|
||||
typedef struct s_client
|
||||
{
|
||||
int id;
|
||||
int fd;
|
||||
char *buf;
|
||||
} t_client;
|
||||
|
||||
static t_client g_clients[FD_SETSIZE];
|
||||
static int g_server;
|
||||
static int g_maxfds;
|
||||
static int g_nextid;
|
||||
fd_set readfds, writefds;
|
||||
|
||||
|
||||
int extract_message(char **buf, char **msg)
|
||||
{
|
||||
char *newbuf;
|
||||
int i;
|
||||
|
||||
*msg = 0;
|
||||
if (*buf == 0)
|
||||
return (0);
|
||||
i = 0;
|
||||
while ((*buf)[i])
|
||||
{
|
||||
if ((*buf)[i] == '\n')
|
||||
{
|
||||
newbuf = calloc(1, sizeof(*newbuf) * (strlen(*buf + i + 1) + 1));
|
||||
if (newbuf == 0)
|
||||
return (-1);
|
||||
strcpy(newbuf, *buf + i + 1);
|
||||
*msg = *buf;
|
||||
(*msg)[i + 1] = 0;
|
||||
*buf = newbuf;
|
||||
return (1);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return (0);
|
||||
}
|
||||
|
||||
char *str_join(char *buf, char *add)
|
||||
{
|
||||
char *newbuf;
|
||||
int len;
|
||||
|
||||
if (buf == 0)
|
||||
len = 0;
|
||||
else
|
||||
len = strlen(buf);
|
||||
newbuf = malloc(sizeof(*newbuf) * (len + strlen(add) + 1));
|
||||
if (newbuf == 0)
|
||||
return (0);
|
||||
newbuf[0] = 0;
|
||||
if (buf != 0)
|
||||
strcat(newbuf, buf);
|
||||
free(buf);
|
||||
strcat(newbuf, add);
|
||||
return (newbuf);
|
||||
}
|
||||
|
||||
|
||||
void fatal(void)
|
||||
{
|
||||
write(2, "fatal error\n", 12);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
|
||||
void bc(int fd, char *msg)
|
||||
{
|
||||
int i;
|
||||
|
||||
i = 0;
|
||||
while(i <= g_maxfds)
|
||||
{
|
||||
if(i != fd && i != g_server && g_clients[i].fd != -1 && FD_ISSET(i, &writefds))
|
||||
{
|
||||
send(i, msg, strlen(msg), 0);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
void accept_conn()
|
||||
{
|
||||
char msg[64];
|
||||
int fd;
|
||||
|
||||
fd = accept(g_server, NULL, NULL);
|
||||
if(fd < 0)
|
||||
fatal();
|
||||
g_clients[fd].id = g_nextid++;
|
||||
g_clients[fd].fd = fd;
|
||||
g_clients[fd].buf = NULL;
|
||||
if(fd > g_maxfds)
|
||||
g_maxfds = fd;
|
||||
sprintf(msg, "client %d just arrive\n", g_clients[fd].id);
|
||||
bc(fd, msg);
|
||||
|
||||
}
|
||||
|
||||
|
||||
void dis(int fd)
|
||||
{
|
||||
char msg[64];
|
||||
int id;
|
||||
|
||||
id = g_clients[fd].id;
|
||||
g_clients[fd].id = -1;
|
||||
g_clients[fd].fd = -1;
|
||||
if(g_clients[fd].buf)
|
||||
free(g_clients[fd].buf);
|
||||
sprintf(msg, "server: client %d just left\n", id);
|
||||
bc(fd, msg);
|
||||
close(fd);
|
||||
if(fd > g_maxfds && g_clients[g_maxfds].fd == -1)
|
||||
g_maxfds--;
|
||||
}
|
||||
|
||||
|
||||
void handler(int fd)
|
||||
{
|
||||
char buffer[1024];
|
||||
char *msg;
|
||||
char *out;
|
||||
int size;
|
||||
|
||||
size = recv(fd, buffer, sizeof(buffer) -1, 0);
|
||||
if (size <= 0)
|
||||
{
|
||||
dis(fd);
|
||||
return;
|
||||
}
|
||||
|
||||
buffer[size] = 0;
|
||||
g_clients[fd].buf = str_join(g_clients[fd].buf, buffer);
|
||||
if(!g_clients[fd].buf)
|
||||
fatal();
|
||||
|
||||
while(extract_message(&g_clients[fd].buf, &msg))
|
||||
{
|
||||
out = calloc(sizeof(char), strlen(msg) + 64);
|
||||
if(!out)
|
||||
{
|
||||
free(msg);
|
||||
fatal();
|
||||
}
|
||||
sprintf(out, "client %d: %s", g_clients[fd].id, msg);
|
||||
bc(fd, out);
|
||||
free(out);
|
||||
free(msg);
|
||||
out = NULL;
|
||||
msg = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
struct sockaddr_in servaddr;
|
||||
int i;
|
||||
|
||||
if(argc != 2)
|
||||
{
|
||||
write(1, "Wrong number of arguments\n", 26);
|
||||
return 1;
|
||||
}
|
||||
// socket create and verification
|
||||
g_server = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (g_server < 0)
|
||||
fatal();
|
||||
bzero(&servaddr, sizeof(servaddr));
|
||||
|
||||
// assign IP, PORT
|
||||
servaddr.sin_family = AF_INET;
|
||||
servaddr.sin_addr.s_addr = htonl(2130706433); //127.0.0.1
|
||||
servaddr.sin_port = htons(atoi(argv[1]));
|
||||
|
||||
// Binding newly created socket to given IP and verification
|
||||
if ((bind(g_server, (const struct sockaddr *)&servaddr, sizeof(servaddr))) < 0)
|
||||
fatal();
|
||||
if (listen(g_server, 10) < 0)
|
||||
fatal();
|
||||
g_maxfds = g_server;
|
||||
i = 0;
|
||||
while (i < FD_SETSIZE)
|
||||
{
|
||||
g_clients[i].id = -1;
|
||||
g_clients[i].fd = -1;
|
||||
g_clients[i].buf = NULL;
|
||||
i++;
|
||||
}
|
||||
while(42)
|
||||
{
|
||||
FD_ZERO(&readfds);
|
||||
FD_ZERO(&writefds);
|
||||
FD_SET(g_server, &readfds);
|
||||
FD_SET(g_server, &writefds);
|
||||
|
||||
i = 0;
|
||||
while (i <= g_maxfds)
|
||||
{
|
||||
if (g_clients[i].fd != -1)
|
||||
{
|
||||
FD_SET(g_clients[i].fd, &readfds);
|
||||
FD_SET(g_clients[i].fd, &writefds);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
if(select(g_maxfds + 1, &readfds, &writefds, NULL, NULL) < 0)
|
||||
continue ;
|
||||
|
||||
if(FD_ISSET(g_server, &readfds))
|
||||
{
|
||||
accept_conn();
|
||||
}
|
||||
int i = 0;
|
||||
while(i <= g_maxfds)
|
||||
{
|
||||
if(i != g_server && g_clients[i].fd != -1 && FD_ISSET(i, &readfds))
|
||||
{
|
||||
handler(i);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+202
@@ -0,0 +1,202 @@
|
||||
# Debugging — how to find out why `mini_serv` misbehaves
|
||||
|
||||
Debugging is **bisecting your assumptions**: test one layer at a time, make each layer prove
|
||||
itself with your own eyes. This file gives you the toolkit, the symptom table, and a triage
|
||||
checklist. On this machine: `nc`, `ss`, `gdb`, `valgrind`, `lsof` are available (`strace`
|
||||
isn't; everything still works without it).
|
||||
|
||||
---
|
||||
|
||||
## 1. The golden rules
|
||||
|
||||
1. **Compile strict, always**: `cc -Wall -Wextra -Werror -g mini_serv.c -o mini_serv`.
|
||||
`-g` = debug symbols for gdb/valgrind. The exam runner compiles for you, but your own
|
||||
compile is your fast feedback loop.
|
||||
2. **Keep a last-known-good copy** before every edit: `cp mini_serv.c mini_serv.ok.c`.
|
||||
If things get weird: `cp mini_serv.ok.c mini_serv.c`.
|
||||
3. **Build in layers and test each layer** (that's exactly what your checkpoints in
|
||||
`drills/typing-script.md` are). Never write 150 lines and *then* run it for the first time.
|
||||
4. **One change at a time.** Two changes at once = you learn nothing from the result.
|
||||
5. **Write down what you expect before you test.** If expectation ≠ observation, you have a
|
||||
clue, not a mystery. The `sandbox/traceback` file from the grader is exactly this: their
|
||||
expectation vs your output.
|
||||
|
||||
## 2. Your three terminals
|
||||
|
||||
- **T1**: the server. Watch its stderr.
|
||||
- **T2**: `nc 127.0.0.1 PORT` — client A (the "listener", like the grader's).
|
||||
- **T3**: scripted sender (repeatable, race-free):
|
||||
|
||||
```bash
|
||||
send() { exec 3<>/dev/tcp/127.0.0.1/"$1"; cat >&3; exec 3>&-; }
|
||||
printf 'hello\n' | send 8081 # connects, sends, disconnects
|
||||
{ printf 'par'; sleep 1; printf 'tial\n'; } | send 8081 # split line
|
||||
printf 'abc' | send 8081 # no newline, then EOF
|
||||
```
|
||||
|
||||
T3 is how you reproduce anything deterministically. T2 is how you *observe*.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
T1["T1: the server<br/>./mini_serv PORT — watch stderr"]
|
||||
T2["T2: the observer<br/>nc 127.0.0.1 PORT (like the grader)"]
|
||||
T3["T3: the scripted sender<br/>send() helper — repeatable"]
|
||||
T2 <-->|"chat traffic"| T1
|
||||
T3 -->|"connect / send / disappear"| T1
|
||||
```
|
||||
|
||||
## 3. Trace prints (poor man's debugger)
|
||||
|
||||
Add temporary prints in the server. Two flavors:
|
||||
|
||||
```c
|
||||
write(2, "accepted\n", 9); /* exam-safe */
|
||||
fprintf(stderr, "recv fd=%d id=%d n=%zd buf=%s\n",
|
||||
fd, clients[fd].id, n, clients[fd].msg); /* local-only */
|
||||
```
|
||||
|
||||
Rules:
|
||||
- print to **stderr** (fd 2) so it interleaves with the client traffic in T1 without messing
|
||||
with anything else;
|
||||
- useful things to print: which fd `select` reported ready, `max_fd`, the `recv` return
|
||||
value, the buffer after appending, the string you're about to relay;
|
||||
- **before submitting, delete every trace line** (`grep -n 'fprintf\|printf' mini_serv.c`) —
|
||||
`printf` is not in the allowed-function list.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["select() returned"] --> B{"listen fd ready?"}
|
||||
B -->|"yes"| C["accept() — print: new fd + client id"]
|
||||
B -->|"no"| D["recv() — print: return value n"]
|
||||
D --> E{"n <= 0 ?"}
|
||||
E -->|"yes"| F["print: disconnecting fd + id"]
|
||||
E -->|"no"| G["after str_join — print the whole buffer"]
|
||||
G --> H["inside the extract loop — print each line before send"]
|
||||
```
|
||||
|
||||
## 4. Fast signals from the outside
|
||||
|
||||
| Observation | What it already tells you |
|
||||
|---|---|
|
||||
| `./mini_serv; echo $?` → `1` + stderr text | your argc guard + `exit` path work, or the strings are wrong |
|
||||
| `nc` prints **Connection refused** | nothing is listening on that port: server not running / died / wrong port |
|
||||
| `nc` connects but nothing ever arrives | listen works, but accept/broadcast never happens (or `select` misses the fd) |
|
||||
| `nc` can't connect until server starts, then works | bind+listen fine |
|
||||
| `top` shows 100% CPU with no clients | `select` returns instantly forever: set not rebuilt / readiness not consumed |
|
||||
| server silently dies after a client disconnects | `echo $?` → `141` = killed by SIGPIPE; `139` = segfault (see §6) |
|
||||
| everything works for 1 client, breaks at 2 | `max_fd` not updated on accept, or set rebuilt from a stale copy |
|
||||
| message appears only when the sender sends MORE bytes | you flush on `recv` instead of extracting full lines |
|
||||
|
||||
## 5. Symptom → cause table (the one to tape to your monitor)
|
||||
|
||||
| Symptom | Most likely cause | Confirm with | Fix |
|
||||
|---|---|---|---|
|
||||
| `Wrong number of arguments` even with a port | `argc` test wrong (`< 2`, `<= 2`…) | `./mini_serv 8081; echo $?` | `if (argc != 2)` |
|
||||
| immediate `Fatal error`, port free | bind hit a stale/TIME_WAIT port; or bad addr | `ss -tan \| grep PORT` | try another port; check `htonl(2130706433)` |
|
||||
| nc connects, nothing happens | accept branch never runs: fd not in set, `max_fd` wrong, or you check readiness against the wrong set (`active_fds` instead of the copy) | print every fd `select` reports; print `max_fd` | rebuild/copy sets each loop; `FD_SET` new fds into the *master*; pass `max_fd + 1` |
|
||||
| 100% CPU, no clients | `select` never blocks — e.g. `FD_SET(0,…)`/junk bits, or you `continue`d past a ready fd | `top`, trace prints | `FD_ZERO` + set only real fds; always consume readiness |
|
||||
| 1 client fine, 2nd client ignored | `max_fd` not raised on accept | trace `max_fd` after accept | `if (fd > max_fd) max_fd = fd;` |
|
||||
| extra answer: newcomer gets its own arrival line | broadcast includes the new fd | two nc | exclude the new fd (or broadcast before `FD_SET`-ing it — the pre-accept set copy naturally excludes it) |
|
||||
| recipient gets text only after ANOTHER packet arrives | you only extract one line per `recv`, or you wait for `\n` to appear before treating the chunk | send `a\nb\n` in one shot | `while (extract_message(...) == 1)` after every append |
|
||||
| prefix missing / duplicated | prefix built once per `recv` instead of per line | same test | build `"client N: " + line` *inside* the extract loop |
|
||||
| sender sees its own message | broadcast doesn't exclude `fd` | 2 nc, one sends | skip the sender |
|
||||
| ids restart or equal fds | `id` derived from fd/count | connect → leave → connect | dedicated `id = next_id++` |
|
||||
| no `just left` on Ctrl-D | `recv <= 0` branch missing, or you `exit()` there | Ctrl-C an nc | broadcast left, `FD_CLR`, `close`, `free` |
|
||||
| leftover partial text is flushed on disconnect | you broadcast the buffer at EOF | `printf 'abc' \| send PORT` | drop it: free, don't send |
|
||||
| segfault after churn | fd used after close, index out of bounds, `strlen(NULL)` | `gdb`, `valgrind` (§6) | see §6 output |
|
||||
| `select: Bad file descriptor` | closed fd still in the set, or `max_fd` smaller than a watched fd | trace prints | `FD_CLR` **before** `close(fd)`; keep `max_fd` honest |
|
||||
| killed when a client leaves (exit 141) | SIGPIPE: you `send` to a socket that got a reset | `echo $?` = 141 | official test doesn't hit this; if you want armor: `signal(SIGPIPE, SIG_IGN)` (check your subject's allowed list) |
|
||||
| valgrind `definitely lost` | forgot `free(msg)` after relay; forgot `free(clients[fd].msg)` on disconnect; leaked remainder buffers | valgrind recipe §6 | free every `char *` the two helpers hand you |
|
||||
| works, but the 364 KB test never delivers | fixed-size buffers + no append, or single-line extract only | `bash tester/check.sh`, read `sandbox/traceback` | heap-append the chunk; extract when `\n` shows up |
|
||||
|
||||
## 6. The tools in practice
|
||||
|
||||
### gdb — freeze it and look inside
|
||||
|
||||
```bash
|
||||
gdb --args ./mini_serv 8081
|
||||
(gdb) run
|
||||
# ... reproduce the misbehaviour in T2/T3 ...
|
||||
# if it hangs: press Ctrl-C in gdb
|
||||
(gdb) bt # where is it stuck?
|
||||
(gdb) info locals # variables at that frame
|
||||
(gdb) p fd
|
||||
(gdb) p clients[fd].id
|
||||
```
|
||||
Segfault case: run, reproduce, then `bt`, `frame <n>`, `info locals`, `p *buf`.
|
||||
The frame where the crash happened plus the variables is usually the whole story.
|
||||
(When `bt` shows `recv` or `select` waiting — that's not a crash, that's *blocking*:
|
||||
go up a frame or two to find whose loop forgot to check readiness.)
|
||||
|
||||
### valgrind — memory and fd audit
|
||||
|
||||
```bash
|
||||
cc -Wall -Wextra -Werror -g mini_serv.c -o mini_serv
|
||||
valgrind --leak-check=full --track-fds=yes ./mini_serv 8099
|
||||
# in another terminal: reproduce a full session (connect, chat, Ctrl-C, replay)
|
||||
# then Ctrl-C the server and read the summary
|
||||
```
|
||||
What to look for:
|
||||
- `definitely lost: N bytes` → a `malloc` nobody freed (see table above);
|
||||
- `FILE DESCRIPTORS: N open at exit` → an fd never `close`d;
|
||||
- `Invalid read/write` → out-of-bounds (classic: `clients[fd]` indexing, `buf[n]` off-by-one).
|
||||
|
||||
### ss / lsof — see what the kernel sees
|
||||
|
||||
```bash
|
||||
ss -tlnp | grep 8081 # is anything LISTENing?
|
||||
ss -tnp | grep 8081 # who is CONNECTED (and how many are queued)
|
||||
lsof -p $(pgrep mini_serv) # the process's open files/fds
|
||||
ls -l /proc/$(pgrep mini_serv)/fd # same, without lsof
|
||||
```
|
||||
|
||||
### The gym's graders
|
||||
|
||||
```bash
|
||||
bash tester/check.sh # the full mill
|
||||
python3 tester/mini_serv_tester.py sandbox/mini_serv --quick # fast loop
|
||||
sed -n '1,60p' sandbox/traceback # grader's expected-vs-you diff
|
||||
```
|
||||
`traceback` is not an error message — it's a **difference report**. Read the first
|
||||
difference and work backwards; don't read the whole thing.
|
||||
|
||||
## 7. 60-second triage checklist
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
P["server misbehaves"] --> C{"compiles?"}
|
||||
C -->|"no"| C1["fix the FIRST error only, recompile"]
|
||||
C -->|"yes"| R{"process alive? check echo $?"}
|
||||
R -->|"141 = SIGPIPE, 139 = segv, 1 = exit(1)"| R1["read stderr; gdb / valgrind; see §5 table"]
|
||||
R -->|"alive"| L{"ss -tlnp shows LISTEN on the port?"}
|
||||
L -->|"no"| L1["bind failed, wrong port, or Fatal error already printed"]
|
||||
L -->|"yes"| N{"nc connects?"}
|
||||
N -->|"refused"| L1
|
||||
N -->|"connected but silent"| T["trace prints: is accept() reached? is the fd in the set?"]
|
||||
N -->|"chat flows"| M{"messages exactly right?"}
|
||||
M -->|"flushed early / lines missing"| M1["buffer + extract logic — cheatsheet trap 6"]
|
||||
M -->|"only the first client works"| M2["max_fd and the set rebuild — traps 1 and 2"]
|
||||
M -->|"yes"| G["bash tester/check.sh — let the grader speak"]
|
||||
```
|
||||
|
||||
1. `cc -Wall -Wextra -Werror -g` — does it even compile?
|
||||
2. `./mini_serv 8081; echo $?` — argument path sane?
|
||||
3. `ss -tlnp | grep 8081` — is it listening?
|
||||
4. `nc` connect works; arrival message correct on the *other* client?
|
||||
5. One scripted line `printf 'a\nb\n' | send PORT` — both lines relayed, prefix per line?
|
||||
6. Split line test — one message, no early flush?
|
||||
7. EOF test — `left` broadcast, no partial flush?
|
||||
8. `bash tester/check.sh` — the whole thing.
|
||||
|
||||
Fix the **first** red step, not the last one. Everything downstream is usually a
|
||||
consequence.
|
||||
|
||||
## 8. Exam-day debugging budget
|
||||
|
||||
Plan for ~30 minutes of debugging even on a good run. Order of attack:
|
||||
1. `nc` two windows — behavior first, code second.
|
||||
2. Trace prints at: `select` result → accept → recv return value → buffer after append →
|
||||
what you relay. That's 5 prints that locate almost every bug.
|
||||
3. If it dies: `echo $?` (141 SIGPIPE / 139 segv), then `bt` in gdb if installed.
|
||||
4. Last resort, not first: simplify — comment out the relay, make it echo to the sender
|
||||
only, confirm the pipeline, then re-enable.
|
||||
+287
@@ -0,0 +1,287 @@
|
||||
# Diagrams — mini_serv from scratch, one picture at a time
|
||||
|
||||
> Read in order. Each diagram is a layer: processes → fd table → address → door → state →
|
||||
> the loop → accept → data → disconnect → ids → memory → errors → one full session.
|
||||
> Final code: `exam-answer/mini_serv.c`.
|
||||
|
||||
---
|
||||
|
||||
## 1. The whole system
|
||||
|
||||
Three processes, three fd tables, two TCP connections. A socket fd is only meaningful **inside
|
||||
the process that owns it** — the same TCP connection appears as a different fd in each process.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["client A process<br/>own fd table<br/>fd 3 = its socket"] -- "TCP connection" --> K["kernel<br/>socket objects +<br/>send/recv buffers"]
|
||||
B["client B process<br/>own fd table<br/>fd 3 = its socket"] -- "TCP connection" --> K
|
||||
K -- "same connections,<br/>seen from the server side" --> S["mini_serv process<br/>fd 3 = listening socket<br/>fd 4 = A's socket<br/>fd 5 = B's socket"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. One process's fd table
|
||||
|
||||
The kernel assigns the **lowest free number**. 0/1/2 are always taken by stdio, so the first
|
||||
socket is usually 3. The listening socket and each client socket are separate entries.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
T["fd table of mini_serv"] --> F0["0 — stdin"]
|
||||
T --> F1["1 — stdout"]
|
||||
T --> F2["2 — stderr"]
|
||||
T --> F3["3 — listening socket<br/>127.0.0.1:8081"]
|
||||
T --> F4["4 — client A socket"]
|
||||
T --> F5["5 — client B socket"]
|
||||
T --> FN["... up to 1023<br/>(FD_SETSIZE)"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. The address you bind
|
||||
|
||||
`bind` reads the whole struct, so it must be zeroed first. The IP is the number
|
||||
`2130706433` = `0x7F000001` = `127.0.0.1`, in network byte order.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["struct sockaddr_in addr"] --> B["sin_family = AF_INET"]
|
||||
A --> C["sin_port = htons(atoi(argv[1]))"]
|
||||
A --> D["sin_addr.s_addr = htonl(2130706433)"]
|
||||
D --> E["2130706433 = 0x7F000001<br/>= 127.0.0.1"]
|
||||
C --> F["network byte order"]
|
||||
E --> G["bind() claims 127.0.0.1:port"]
|
||||
F --> G
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. The door: socket → bind → listen → accept
|
||||
|
||||
`listen` does not accept anything; it asks the kernel to **queue completed handshakes**. Each
|
||||
`accept` pops one and returns a **new fd**. The listening fd keeps listening forever.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
S["socket()<br/>one new fd"] --> B["bind()<br/>claim 127.0.0.1:port"]
|
||||
B --> L["listen(10)<br/>mark as accepting"]
|
||||
L --> Q["kernel accept queue<br/>up to 10 completed handshakes"]
|
||||
Q -- "accept() pops ONE" --> C["new fd for that conversation"]
|
||||
L -.->|keeps listening forever| L
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. The state arrays, indexed by fd
|
||||
|
||||
There is no client struct. The fd is the slot number, and two arrays hold everything the
|
||||
server must remember about that slot.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
FD4["fd 4"] --> ID4["g_id[4] = 0"]
|
||||
FD4 --> B4["g_buf[4] = NULL"]
|
||||
FD5["fd 5"] --> ID5["g_id[5] = 1"]
|
||||
FD5 --> B5["g_buf[5] = a partial line, e.g. 'wor'"]
|
||||
ID4 --> FREE["g_id[fd] = -1 means: slot is free"]
|
||||
B5 --> FREE2["g_buf[fd] is freed when the client leaves"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. One client slot's life
|
||||
|
||||
The same slot moves through four states. Note that `recv 0 or -1` can arrive in **either**
|
||||
connected state, and a partial line is dropped in both.
|
||||
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> Free
|
||||
Free --> Connected: accept / id = g_nextid++, g_buf = NULL
|
||||
Connected --> Buffering: recv data without a newline
|
||||
Buffering --> Connected: newline found / relay the line, keep remainder
|
||||
Connected --> Free: recv returns 0 or -1 / announce left, close, free
|
||||
Buffering --> Free: recv returns 0 or -1 / drop buffer, announce left, close
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. The heartbeat: rebuild → select → dispatch
|
||||
|
||||
Every iteration starts from an empty bitmap because `select` destroys the one you give it.
|
||||
`select` returns when at least one watched fd is ready.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["iteration start"] --> B["FD_ZERO: empty bitmap"]
|
||||
B --> C["FD_SET(g_server)"]
|
||||
C --> D["for fd 0..g_maxfd:<br/>if the slot is live, FD_SET(fd)"]
|
||||
D --> E["select(g_maxfd + 1, &readfds, NULL, NULL, NULL)"]
|
||||
E --> F{"select < 0 ?"}
|
||||
F -- yes --> A
|
||||
F -- no --> G["readfds now contains ONLY ready fds"]
|
||||
G --> H{"FD_ISSET(g_server) ?"}
|
||||
H -- yes --> I["on_accept()"]
|
||||
H -- no --> J{"FD_ISSET(a client) ?"}
|
||||
I --> A
|
||||
J -- yes --> K["on_read(fd)"]
|
||||
J -- no --> A
|
||||
K --> A
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Why the bitmap must be rebuilt: `select` rewrites it
|
||||
|
||||
Before the call, the bitmap means "watch these". After the call, it means "these were ready".
|
||||
The next iteration needs the first meaning again, so it is rebuilt from `g_id[]`.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["before select<br/>bits 3, 4, 5 set"] --> B["select()"]
|
||||
B --> C["after select<br/>only READY bits remain<br/>e.g. bit 4"]
|
||||
C --> D["those bits are your to-do list"]
|
||||
D --> E["handle fd 4"]
|
||||
E --> F["next iteration:<br/>rebuild from g_id[]"]
|
||||
F --> A
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 9. Accept: a new client, step by step
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["g_server readable"] --> B["fd = accept(g_server, NULL, NULL)"]
|
||||
B --> C{"fd < 0 ?"}
|
||||
C -- yes --> D["return — keep serving"]
|
||||
C -- no --> E{"fd >= FD_SETSIZE ?"}
|
||||
E -- yes --> F["close(fd) — select cannot watch it"]
|
||||
E -- no --> G["g_id[fd] = g_nextid++"]
|
||||
G --> H["g_buf[fd] = NULL"]
|
||||
H --> I["g_maxfd = max(g_maxfd, fd)"]
|
||||
I --> J["sprintf: server: client N just arrived"]
|
||||
J --> K["send_all(fd, msg)<br/>everyone EXCEPT the newcomer"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. The data pipeline: bytes in → lines out
|
||||
|
||||
This is the part the exam is really testing. Append first (a chunk can end mid-line), then cut
|
||||
complete lines in a loop, build one prefixed string per line, send to the others.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["recv chunk 1: 'hel'"] --> B["g_buf[fd] = 'hel'"]
|
||||
B --> C{"contains a newline ?"}
|
||||
C -- no --> D["send nothing — wait"]
|
||||
D --> E["recv chunk 2: 'lo' newline 'world' newline"]
|
||||
E --> F["append → 'hello' newline 'world' newline"]
|
||||
F --> G["extract_message loop"]
|
||||
G --> H["line: 'hello' newline"]
|
||||
H --> I["out = 'client 1: hello' newline"]
|
||||
I --> J["send_all(sender, out) — others only"]
|
||||
G --> K["line: 'world' newline"]
|
||||
K --> L["out = 'client 1: world' newline"]
|
||||
L --> J
|
||||
G --> M["remainder (empty here) stays in g_buf"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 11. Disconnect: order matters
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["recv returns 0 (EOF)<br/>or -1 (error)"] --> B["on_leave(fd)"]
|
||||
B --> C["id = g_id[fd] — save it FIRST"]
|
||||
C --> D["close(fd)"]
|
||||
D --> E["g_id[fd] = -1"]
|
||||
E --> F["free(g_buf[fd])<br/>DROP the partial line, never flush it"]
|
||||
F --> G["sprintf: server: client N just left"]
|
||||
G --> H["send_all(-1, msg) — everyone left"]
|
||||
H --> I["shrink g_maxfd while the last slot is empty<br/>and g_maxfd > g_server"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 12. fds are recycled; ids are not
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
L["listener: id 0"] --> A["Alice: fd 4, id 1"]
|
||||
A --> X["Alice leaves"]
|
||||
X --> R["kernel may reuse fd 4"]
|
||||
X --> N["g_nextid stays 2"]
|
||||
R --> B["Bob gets fd 4 again"]
|
||||
N --> B2["Bob gets id 2"]
|
||||
B --> Z["fd: recycled by the kernel"]
|
||||
B2 --> Y["id: never reused by you"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 13. Memory ownership: who frees what
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["str_join"] -->|"returns a new buffer,<br/>frees the old one"| B["g_buf[fd]"]
|
||||
C["extract_message"] -->|"returns one line,<br/>a slice of the old buffer"| D["line — free after send"]
|
||||
C -->|"returns the remainder"| B
|
||||
E["malloc(strlen(line) + 64)"] --> F["out — free after send"]
|
||||
G["accept()"] --> H["fd — close in on_leave"]
|
||||
I["free(g_buf[fd])"] --> B
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 14. Every error path in the program
|
||||
|
||||
The rule from the subject: failures **before accepting** are fatal (`Fatal error` + exit 1);
|
||||
failures **after** accepting must keep the server alive.
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["program start"] --> B{"argc == 2 ?"}
|
||||
B -- no --> B1["stderr: Wrong number of arguments<br/>exit 1"]
|
||||
B -- yes --> C{"socket / bind / listen ok ?"}
|
||||
C -- no --> C1["stderr: Fatal error<br/>exit 1"]
|
||||
C -- yes --> D["enter the select loop"]
|
||||
D --> E{"accept fails ?"}
|
||||
E -- yes --> E1["return — keep serving"]
|
||||
D --> F{"recv returns 0 or -1 ?"}
|
||||
F -- yes --> F1["disconnect — keep serving"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 15. One full session, in order
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant L as Listener id 0
|
||||
participant S as mini_serv
|
||||
participant A as Alice id 1
|
||||
participant B as Bob id 2
|
||||
A->>S: connect
|
||||
S-->>L: server: client 1 just arrived
|
||||
A->>S: hello + newline
|
||||
S-->>L: client 1: hello
|
||||
A->>S: par (no newline)
|
||||
Note over S: g_buf[Alice] = "par" — nothing sent
|
||||
A->>S: tial + newline
|
||||
S-->>L: client 1: partial
|
||||
A->>S: close (EOF)
|
||||
S-->>L: server: client 1 just left
|
||||
B->>S: connect (reuses Alice's fd 4)
|
||||
S-->>L: server: client 2 just arrived
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## The whole thing on one line
|
||||
|
||||
**fd table → bind/listen door → rebuild bitmap → `select` → accept or recv → append → cut
|
||||
lines → send to others → on EOF close/free/announce.** Every diagram above is one arrow of
|
||||
that sentence, and every condition in the code is a fork in one of them.
|
||||
@@ -0,0 +1,123 @@
|
||||
# Drills — the actual training
|
||||
|
||||
Every drill is written **from a blank file, by hand, no copy-paste**. Timer on. Report card
|
||||
at the bottom. `R = red` (failed / looked) · `Y = yellow` (done but slow) · `G = green` (clean, on time).
|
||||
|
||||
---
|
||||
|
||||
## D1 — Requirement recall · 20 min · day 1
|
||||
|
||||
Close everything (including this file). Write the 11 ground-truth behaviors of the exam from
|
||||
memory (start from the README list mentally; do NOT open it). Then compare with README
|
||||
"ground truth". Every line you missed → mark it on the traps list in `cheatsheet.md`.
|
||||
|
||||
**Green = all 11, in order, no peeking.**
|
||||
|
||||
## D1.5 — Fundamentals sprint · 45 min · day 1 (optional, very recommended)
|
||||
|
||||
Read `fundamentals.md` §1–§8 while running the four experiments in `explore/` (they make
|
||||
fds, backlog, chunking and `select` visible). Then read §10 — the "how to test each part of
|
||||
your code" table — and keep `debugging.md` §5 (symptom table) open from now on.
|
||||
Timebox: 45 minutes. If you're behind schedule, do **§4, §5, §7 + experiments 02, 03** only.
|
||||
|
||||
## D2 — Boilerplate blast · 15 min ×3 · day 1
|
||||
|
||||
Blank file. Type, without notes:
|
||||
|
||||
- includes, `t_client` struct, globals (`g_c`, `g_maxfd`, `g_server`, `g_next_id`), `fatal()`
|
||||
- `main`: argc guard with the exact string, socket/bind/listen with `htonl(2130706433)`
|
||||
- init all slots, then the loop: rebuild `fd_set` → `select` → `accept`-only handling
|
||||
|
||||
Compile clean: `cc -Wall -Wextra -Werror file.c -o test`. It doesn't have to *work* yet — just be
|
||||
typed from memory. Repeat 3 times; target the last one **under 8 minutes**.
|
||||
|
||||
**Green = third run < 8 min, compiles clean, zero peeks.**
|
||||
|
||||
## D3 — Buffer brains · 10 min ×2 · day 1
|
||||
|
||||
Blank file. Type `str_join` + `extract_message` from `subject/main.c` (they're given in the exam —
|
||||
this is fluency training). Then, from memory, type `handle_read()` that uses them:
|
||||
`recv` → append → extract loop → `sprintf("client %d: %s")` → free.
|
||||
|
||||
Then a paper check on these cases — what is buffered, what is relayed?
|
||||
|
||||
| input chunks (in order) | relayed lines |
|
||||
|------------------------------|----------------|
|
||||
| `"ab\ncd\n"` | ? |
|
||||
| `"ab"` then `"cd\n"` | ? |
|
||||
| `"a\nb"` then `"c\n"` | ? |
|
||||
| `"lonely"` then disconnect | ? |
|
||||
|
||||
**Green = code compiles + all four cases answered correctly.**
|
||||
|
||||
## D4 — Arrivals & departures · 25 min · day 2
|
||||
|
||||
Take D2's file and complete it: `accept_new` (ids, maxfd, "just arrived" to others only),
|
||||
`disconnect` (left message, slot cleanup, maxfd shrink), `to_all_except`.
|
||||
Test with two `nc` windows: connect/leave order, ids 0,1,2…, newcomer receives nothing on connect.
|
||||
|
||||
**Green = all of the above verified with `nc`.**
|
||||
|
||||
## D5 — Full attempt #1 · 60–90 min · day 2+
|
||||
|
||||
Blank file. Timer. No internet, no notes, vim only. Write the whole program. Then:
|
||||
|
||||
```bash
|
||||
bash tester/check.sh
|
||||
```
|
||||
|
||||
Then diff against `reference/mini_serv.c` and write your **"what I missed"** list (function by
|
||||
function, be honest). That list is your study plan for the next session.
|
||||
|
||||
**Green = check.sh fully green.**
|
||||
|
||||
## D6 — Full attempt #2, faster · ≤90 min · day 3+
|
||||
|
||||
Same as D5 but the target is **≤ 90 min, all green**. If you red anything, do the smallest
|
||||
targeted drill for the weak part and run D6 again the same day.
|
||||
|
||||
**Green = ≤90 min, all green.**
|
||||
|
||||
## D7 — Chaos hour · 30 min · day 4
|
||||
|
||||
Make the tester try to break you:
|
||||
|
||||
```bash
|
||||
python3 tester/mini_serv_tester.py sandbox/mini_serv # everything
|
||||
python3 tester/mini_serv_tester.py sandbox/mini_serv --quick # quick loop
|
||||
```
|
||||
|
||||
Add your own abuse: two servers on one port (→ `Fatal error`), a client that sends 300 KB and
|
||||
disconnects mid-line, 20 clients at once, `printf`-free stderr. Read every failure message
|
||||
slowly — those messages are written the way the real grader thinks.
|
||||
|
||||
**Green = all 13 tests pass and you can explain any red to yourself.**
|
||||
|
||||
## D8 — Exam simulation · 2 h · day 5+
|
||||
|
||||
Fresh empty directory (`mkdir /tmp/opencode/examsim && cd /tmp/opencode/examsim`). Simulate
|
||||
everything: only the subject (`subject/subject.en.txt`) + `subject/main.c` open in another tab
|
||||
(like the exam attachment), vim, 2 hours, no other references. When done, copy your file to
|
||||
`sandbox/rendu/mini_serv/mini_serv.c` and run `bash tester/check.sh`.
|
||||
|
||||
**Green = all green within the 2 h.** Two consecutive D8 greens = **you're ready**.
|
||||
|
||||
---
|
||||
|
||||
## Report card
|
||||
|
||||
| Drill | Run 1 | Run 2 | Run 3 | Notes |
|
||||
|---|---|---|---|---|
|
||||
| D1 | | | | |
|
||||
| D2 | | | | |
|
||||
| D3 | | | | |
|
||||
| D4 | | | | |
|
||||
| D5 | | | | |
|
||||
| D6 | | | | |
|
||||
| D7 | | | | |
|
||||
| D8 | | | | |
|
||||
|
||||
## Readiness rule (repeat until true)
|
||||
|
||||
> Two consecutive full attempts **from a blank file, under 2 h, all green** = ready.
|
||||
> Then stop drilling the full thing; do D2/D3 once a day to stay warm until exam day.
|
||||
@@ -0,0 +1,133 @@
|
||||
# Typing script — reconstruct `mini_serv` cold, stage by stage
|
||||
|
||||
Your situation: exam in ~3 days, never wrote a socket server, 1–2 h/day.
|
||||
So the strategy is **not** "invent it" and **not** "understand every syscall".
|
||||
It is: **replay this exact typing order** until your hands know it. After every stage
|
||||
there is a checkpoint. If a checkpoint fails, fix that stage before moving on.
|
||||
|
||||
> Time budget per stage is for your *third* rep. First rep: double it. Don't rush the first one.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["A: top of file<br/>checkpoint: compiles clean"] --> B["B: guard + socket/bind/listen<br/>checkpoint: args error + LISTEN in ss"]
|
||||
B --> C["C: loop + accept + broadcast<br/>checkpoint: two nc windows see 'just arrived'"]
|
||||
C --> D["D: recv + buffer + relay<br/>checkpoint: hello relays; split line stays silent"]
|
||||
D --> E["E: disconnect<br/>checkpoint: Ctrl-D gives 'just left'; partial dropped"]
|
||||
E --> F["F: bash tester/check.sh<br/>checkpoint: 13/13 + GRADEME PASSED"]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Stage 0 — setup (1 min)
|
||||
|
||||
- In the exam: you write in the `rendu` directory the shell shows you (ask the shell).
|
||||
- Here: create `sandbox/rendu/mini_serv/mini_serv.c`.
|
||||
- Open `subject/subject.en.txt` and `subject/main.c` in another tab — **in the exam you have both**, use them.
|
||||
|
||||
## Stage A — top of file (10 min)
|
||||
|
||||
Type, in this order:
|
||||
|
||||
1. the 7 includes (`stdlib, string, unistd, stdio, sys/socket, netinet/in, sys/select`)
|
||||
2. the struct:
|
||||
```c
|
||||
typedef struct s_client { int fd; int id; char *buf; } t_client;
|
||||
```
|
||||
3. the 4 globals: `g_c[FD_SETSIZE]`, `g_maxfd`, `g_server`, `g_next_id`
|
||||
4. `fatal()`:
|
||||
```c
|
||||
write(2, "Fatal error\n", 12); exit(1);
|
||||
```
|
||||
|
||||
**Checkpoint A:** `cc -Wall -Wextra -Werror mini_serv.c -o mini_serv` → no output, no errors.
|
||||
(If the compiler lists an unused something: that's Stage A material, not exam material — fix it now.)
|
||||
|
||||
## Stage B — main(), part 1: guard + socket (15 min)
|
||||
|
||||
1. `if (argc != 2)` → `write(2, "Wrong number of arguments\n", 26);` → `return (1);`
|
||||
2. `g_server = socket(AF_INET, SOCK_STREAM, 0);` + `if (< 0) fatal();`
|
||||
3. `struct sockaddr_in addr;` → `bzero(&addr, sizeof(addr));`
|
||||
4. `addr.sin_family = AF_INET;`
|
||||
5. `addr.sin_addr.s_addr = htonl(2130706433);` ← **the 127.0.0.1 magic number. Never forget it.**
|
||||
6. `addr.sin_port = htons(atoi(argv[1]));`
|
||||
7. `if (bind(...) < 0) fatal();`
|
||||
8. `if (listen(g_server, 10) < 0) fatal();`
|
||||
|
||||
**Checkpoint B:** compiles. `./mini_serv` → prints `Wrong number of arguments` on stderr, exit 1.
|
||||
`echo $?` shows 1.
|
||||
|
||||
## Stage C — main(), part 2: slots + loop + accept (25 min)
|
||||
|
||||
1. init loop: all `g_c[i].fd = -1; id = -1; buf = NULL;` then `g_maxfd = g_server;`
|
||||
2. `while (1) {` and inside, **in this exact order**:
|
||||
- `FD_ZERO(&readfds);`
|
||||
- `FD_SET(g_server, &readfds);`
|
||||
- loop `i = 0..g_maxfd`: if slot live → `FD_SET(i, &readfds);`
|
||||
- `if (select(g_maxfd + 1, &readfds, NULL, NULL, NULL) < 0) continue ;`
|
||||
- `if (FD_ISSET(g_server, &readfds)) accept_new();`
|
||||
- loop `i = 0..g_maxfd`: if `i != g_server && slot live && FD_ISSET(i, &readfds)` → `handle_read(i);`
|
||||
3. `accept_new()` (write it now, above main):
|
||||
```c
|
||||
fd = accept(g_server, NULL, NULL); if (fd < 0) return ;
|
||||
g_c[fd].fd = fd; g_c[fd].id = g_next_id++; g_c[fd].buf = NULL;
|
||||
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 */
|
||||
```
|
||||
4. `to_all_except(fd, s)`: loop `i = 0..g_maxfd`, `if (i != fd && g_c[i].fd != -1) send(g_c[i].fd, s, strlen(s), 0);`
|
||||
|
||||
**Checkpoint C:** compiles. Then live test: `./mini_serv 8081` in terminal 1,
|
||||
`nc 127.0.0.1 8081` in terminal 2 (nothing appears), open terminal 3 with `nc 127.0.0.1 8081`
|
||||
→ **terminal 2 must show `server: client 1 just arrived`.**
|
||||
(Client ids: viewer is 0, newcomer is 1 — and the newcomer sees nothing for itself. That's correct!)
|
||||
|
||||
## Stage D — the read path (30 min, the exam lives here)
|
||||
|
||||
1. `handle_read(fd)`:
|
||||
```c
|
||||
n = recv(fd, tmp, sizeof(tmp) - 1, 0);
|
||||
if (n <= 0) { disconnect(fd); return ; }
|
||||
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); /* NOT to self */
|
||||
free(out); free(msg);
|
||||
}
|
||||
```
|
||||
2. `str_join` + `extract_message`: **copy verbatim from `subject/main.c`.** You are allowed to.
|
||||
Type them once by hand tonight (D3), then you'll never think about them again.
|
||||
|
||||
**Checkpoint D:** terminal 3 types `hello` + Enter → **terminal 2 shows `client 1: hello`.**
|
||||
Terminal 3 itself shows nothing. Partial-line test: type `par` Enter? No — type `par` and
|
||||
*don't* press Enter yet; terminal 2 must stay silent until you press Enter.
|
||||
|
||||
## Stage E — disconnect (10 min)
|
||||
|
||||
`disconnect(fd)`: save `id` → `close(fd)` → slot `fd = -1; id = -1` → `free(buf); buf = NULL;`
|
||||
→ `sprintf(msg, "server: client %d just left\n", id);` → `to_all_except(-1, msg);`
|
||||
→ shrink: `while (g_maxfd > g_server && g_c[g_maxfd].fd == -1) g_maxfd--;`
|
||||
|
||||
**Checkpoint E:** Ctrl-D in terminal 3 → terminal 2 shows `server: client 1 just left`.
|
||||
Retype an incomplete line and Ctrl-D → **no message** with it, only `left` (buffer dropped).
|
||||
|
||||
## Stage F — grade yourself (5 min)
|
||||
|
||||
From the repo root: `bash tester/check.sh` → 13/13 + `GRADEME: PASSED`.
|
||||
|
||||
---
|
||||
|
||||
## Pace targets
|
||||
|
||||
| Rep | Goal | Time |
|
||||
|---|---|---|
|
||||
| 1st (today, guided allowed) | compiles, checkpoints C–E work with `nc` | 60–90 min |
|
||||
| 2nd (blank, cheatsheet only on failure) | `bash tester/check.sh` all green | ≤ 60 min |
|
||||
| 3rd (blank, exam conditions) | all green, no references at all | ≤ 45 min |
|
||||
|
||||
**When any stage fails, re-drill *only that stage* 3× before the next full rep.**
|
||||
Partial-line handling (Stage D) is where 80% of candidates fail — over-drill it.
|
||||
@@ -0,0 +1,268 @@
|
||||
# The exam answer — simplest version, every variable explained
|
||||
|
||||
File: `exam-answer/mini_serv.c` (this is literally what you submit; the two helpers are the
|
||||
ones the exam gives you in `main.c`).
|
||||
|
||||
**Proof it passes (run in this gym):**
|
||||
|
||||
```
|
||||
cc -Wall -Wextra -Werror : clean
|
||||
behavioral tester : 13/13 PASS (args, bind, arrival, relay, split, no-flush, ids,
|
||||
^D, 400 KB line, 10 KB drop, 25 clients, lazy, fds)
|
||||
real Grademe diff : PASSED
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 0. The whole idea in four lines
|
||||
|
||||
```
|
||||
fd = the slot number inside the process (kernel gives it)
|
||||
id = the name announced to clients (yours, 0,1,2,…)
|
||||
g_id[fd] = -1 if nobody is there, else that client's id
|
||||
g_buf[fd] = bytes of a line that has not ended with '\n' yet
|
||||
```
|
||||
|
||||
That's the entire state. Everything else is: wait on fds with `select`, accept one, read
|
||||
bytes, cut complete lines, send them to the others, clean up.
|
||||
|
||||
---
|
||||
|
||||
## 1. The data model
|
||||
|
||||
```
|
||||
index = fd
|
||||
┌────┬────┬────┬────┬────┬─────┬──────┐
|
||||
g_id │ -1 │ -1 │ -1 │ 0 │ 1 │ ... │ 1023 │ -1 = free, else client id
|
||||
├────┼────┼────┼────┼────┼─────┼──────┤
|
||||
g_buf │NULL│NULL│NULL│"hel│NULL│ ... │ NULL │ pending partial line per fd
|
||||
└────┴────┴────┴────┴────┴─────┴──────┘
|
||||
fd: 0 1 2 3 4 ... 1023
|
||||
▲ ▲
|
||||
listener client A (id 0), waiting for "\n"
|
||||
```
|
||||
|
||||
`FD_SETSIZE` = 1024 = how many bits a `select()` fd_set has → fds 0..1023 only.
|
||||
|
||||
---
|
||||
|
||||
## 2. Globals — every variable
|
||||
|
||||
| Variable | Type | Meaning | Who changes it | Why it must exist |
|
||||
|---|---|---|---|---|
|
||||
| `g_id[FD_SETSIZE]` | `int[]` | slot table: **index = fd**, value = client id, `-1` = free | `main` (init), `on_accept`, `on_leave` | the server's memory of "who is connected" |
|
||||
| `g_buf[FD_SETSIZE]` | `char *[]` | per-client pending text (no `\n` yet) | `on_read`, `on_leave` | TCP is a stream: a line can arrive in pieces |
|
||||
| `g_server` | `int` | the **listening** fd | `main` | `select` must always watch it; `g_maxfd` must never fall below it |
|
||||
| `g_maxfd` | `int` | highest fd currently in use | `on_accept` (raise), `on_leave` (shrink), `main` (init) | `select(max+1, …)` only watches fds `0..max` |
|
||||
| `g_nextid` | `int` | next id to hand out | `on_accept` (`g_nextid++`) | ids must increment forever, never reuse fds |
|
||||
|
||||
Static/global → zero-initialized, but `g_id` needs `-1`, so `main` fills it before the loop.
|
||||
|
||||
---
|
||||
|
||||
## 3. Functions — every one
|
||||
|
||||
### `fatal()`
|
||||
Writes `Fatal error\n` to **stderr** (fd 2) and exits with status **1**. Used for socket,
|
||||
bind, listen, and allocation failures. Exact bytes: `"Fatal error\n"` = 12 chars.
|
||||
|
||||
### `str_join(buf, add)` — given in the exam
|
||||
Returns a **new heap string** `buf + add`, **frees the old `buf`**, `NULL` on OOM. This is how
|
||||
`g_buf[fd]` grows across `recv()` calls. Because it frees the old buffer, you must never keep
|
||||
the old pointer.
|
||||
|
||||
### `extract_message(&buf, &msg)` — given in the exam
|
||||
Scans `buf` for `'\n'`:
|
||||
|
||||
- returns **1**: `msg` points at the complete line **including `\n`** (you own it → `free`),
|
||||
and `buf` is replaced by the remainder (heap, zero-terminated);
|
||||
- returns **0**: no newline yet — keep waiting;
|
||||
- returns **-1**: allocation failure → `fatal()`.
|
||||
|
||||
Call it in a **`while (… == 1)` loop** after every append: one `recv` can hold several lines.
|
||||
|
||||
### `send_all(skip_fd, s)`
|
||||
Loops `fd = 0..g_maxfd`; if `fd != skip_fd` **and** `g_id[fd] != -1`, `send(fd, s, strlen(s), 0)`.
|
||||
|
||||
- `skip_fd = <client>` → "to everybody except this one" (arrival and chat relay);
|
||||
- `skip_fd = -1` → "to everyone still connected" (departure).
|
||||
|
||||
This one helper enforces the "others only" rules that the grader diffs.
|
||||
|
||||
### `on_leave(fd)`
|
||||
Called when `recv` returns `0` (EOF) or `-1` (error).
|
||||
|
||||
1. `id = g_id[fd]` — save the **public id before** clearing the slot;
|
||||
2. `close(fd)` — release the kernel socket;
|
||||
3. `g_id[fd] = -1` — mark the slot free (broadcast will skip it);
|
||||
4. `free(g_buf[fd]); g_buf[fd] = NULL` — drop the unfinished line (**never flush it**);
|
||||
5. build `server: client %d just left\n`, `send_all(-1, …)`;
|
||||
6. shrink `g_maxfd` while the last slot is free, but never below `g_server`.
|
||||
|
||||
### `on_read(fd)`
|
||||
Called when `select` says `fd` is readable.
|
||||
|
||||
1. `n = recv(fd, chunk, sizeof(chunk) - 1, 0)` — read up to 4095 bytes;
|
||||
2. `n <= 0` → `on_leave(fd)` and return (0 = EOF, -1 = error);
|
||||
3. `chunk[n] = 0` — make it a C string (that's why size−1);
|
||||
4. `g_buf[fd] = str_join(g_buf[fd], chunk)` — **append first**;
|
||||
5. `while (extract_message(...) == 1)` — for each complete line:
|
||||
- `out = malloc(strlen(line) + 64)` — room for `"client N: "` + line + `\0`;
|
||||
- `sprintf(out, "client %d: %s", g_id[fd], line)`;
|
||||
- `send_all(fd, out)` — to others only;
|
||||
- `free(out); free(line);` — both are heap (line came from the helper).
|
||||
|
||||
### `on_accept()`
|
||||
1. `fd = accept(g_server, NULL, NULL)` — a **new** fd for the conversation;
|
||||
2. `fd < 0` → ignore (never die on accept);
|
||||
3. `fd >= FD_SETSIZE` → `close(fd)` (select cannot watch it);
|
||||
4. `g_id[fd] = g_nextid++` — assign the public id;
|
||||
5. `g_buf[fd] = NULL` — fresh, empty pending line;
|
||||
6. raise `g_maxfd`;
|
||||
7. build `server: client %d just arrived\n` and `send_all(fd, …)` → others only.
|
||||
|
||||
### `main(argc, argv)`
|
||||
1. `argc != 2` → stderr `Wrong number of arguments\n`, return 1;
|
||||
2. `socket(AF_INET, SOCK_STREAM, 0)`;
|
||||
3. `sockaddr_in`: zero it, `AF_INET`, `htonl(2130706433)` (127.0.0.1), `htons(atoi(argv[1]))`;
|
||||
4. `bind`, `listen(…, 10)` — any failure → `fatal()`;
|
||||
5. init `g_id[0..1023] = -1`, `g_maxfd = g_server`;
|
||||
6. forever:
|
||||
- rebuild `readfds`: `FD_ZERO`, `FD_SET(g_server)`, `FD_SET(i)` for every live `g_id[i]`;
|
||||
- `select(g_maxfd + 1, &readfds, NULL, NULL, NULL)` — sleep until something is ready;
|
||||
- `FD_ISSET(g_server)` → `on_accept()`;
|
||||
- for each live client (skipping `g_server`) with `FD_ISSET(i)` → `on_read(i)`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Locals — every variable
|
||||
|
||||
| Variable | Where | Type | Meaning |
|
||||
|---|---|---|---|
|
||||
| `argc`, `argv` | `main` | int, char ** | `argv[1]` is the port as text |
|
||||
| `addr` | `main` | `struct sockaddr_in` | the address to bind: family/port/IP |
|
||||
| `readfds` | `main` | `fd_set` | the bitmap handed to `select` (rebuilt every loop) |
|
||||
| `i` | `main` | int | loop index over fds |
|
||||
| `chunk[4096]` | `on_read` | char[] | scratch landing zone for one `recv` |
|
||||
| `n` | `on_read` | `ssize_t` | bytes received, or 0/negative → gone |
|
||||
| `line` | `on_read` | char * | one complete line handed back by `extract_message` (free it) |
|
||||
| `out` | `on_read` | char * | the relay string `"client N: " + line` (malloc/free) |
|
||||
| `msg[64]` | `on_accept`, `on_leave` | char[] | small stack buffer for the announcement |
|
||||
| `fd` | `on_accept` | int | the accepted conversation fd |
|
||||
| `id` | `on_leave` | int | saved public id, before the slot is cleared |
|
||||
|
||||
---
|
||||
|
||||
## 4.5 The attachment's variables vs yours
|
||||
|
||||
The demo's `main` and your file declare the same *kinds* of things under different names. Names don't
|
||||
matter; **scope and lifetime** do.
|
||||
|
||||
| Attachment | Type | What it is | Your file | Why the difference |
|
||||
|---|---|---|---|---|
|
||||
| `sockfd` | `int` | the listening socket | `g_server` (file scope) | your `select` loop and `on_accept` need it outside `main` |
|
||||
| `connfd` | `int` | the one accepted client fd | `int fd` inside `on_accept` | one per event; after that, the fd number *is* the table index (`g_id[fd]`) |
|
||||
| `len` | `int` (should be `socklen_t`) | address length for `accept` | *(none)* | you pass `NULL, NULL` to `accept`; no address storage, no length needed |
|
||||
| `servaddr` | `struct sockaddr_in` | server address for `bind` | `addr` | identical role, shorter name |
|
||||
| `cli` | `struct sockaddr_in` | peer address written by `accept` | *(none)* | you never need the client's address |
|
||||
| `argc`, `argv` | `int`, `char **` | command line (demo ignores it) | same | `argv[1]` is the port |
|
||||
|
||||
The demo's `int len` is also a **type bug**: `accept` expects `socklen_t *`, not `int *`. Passing
|
||||
`NULL` for the address arguments removes the question entirely.
|
||||
|
||||
**Why these are global in your file:** the listening fd, the slot tables, `g_maxfd` and `g_nextid`
|
||||
must survive between loop iterations and be visible to the handlers. **Why the rest are local:**
|
||||
they exist for exactly one event — the recv chunk, the byte count, the extracted line, the relay
|
||||
string, the id saved while leaving.
|
||||
|
||||
---
|
||||
|
||||
## 5. Expressions decoded
|
||||
|
||||
| Expression | Meaning |
|
||||
|---|---|
|
||||
| `htonl(2130706433)` | `2130706433 == 0x7F000001 == 127.0.0.1`, converted to network byte order |
|
||||
| `htons(atoi(argv[1]))` | port text → int → network byte order (16-bit) |
|
||||
| `sizeof(chunk) - 1` | reserve one byte for the `'\0'` you add at `chunk[n]` |
|
||||
| `chunk[n] = 0` | terminate the received bytes so `strlen/strcat/strcpy` work |
|
||||
| `recv(...) <= 0` | `0` = peer closed (EOF), `-1` = error; both mean "client is gone" |
|
||||
| `g_buf[fd] = str_join(g_buf[fd], chunk)` | grow the pending buffer (old buffer freed inside) |
|
||||
| `extract_message(...) == 1` | exactly one complete `\n`-line was produced |
|
||||
| `strlen(line) + 64` | worst-case space for `"client " + id + ": " + line + "\0"` |
|
||||
| `send_all(fd, out)` | everyone **except** the sender |
|
||||
| `send_all(-1, msg)` | everyone still connected |
|
||||
| `g_id[fd] = -1` | free the slot; broadcast loops skip it |
|
||||
| `g_maxfd > g_server && …` | shrink the scan window, but never lose the listener |
|
||||
| `select(g_maxfd + 1, …)` | watch fds `0..g_maxfd` (nfds = highest + 1) |
|
||||
| `i != g_server` | the listener is not a chat client; it only `accept`s |
|
||||
|
||||
---
|
||||
|
||||
## 6. Ownership and fd lifecycle (the leak rules)
|
||||
|
||||
| Thing | Allocated by | Freed by |
|
||||
|---|---|---|
|
||||
| `g_buf[fd]` | `str_join` (old one freed inside) | `free(g_buf[fd])` in `on_leave`; also `free(g_buf[fd])` if a new accept reuses the fd |
|
||||
| `line` | `extract_message` (slice of old buffer) | **you**, right after `send` |
|
||||
| `out` | `malloc(strlen(line) + 64)` | **you**, right after `send` |
|
||||
| `msg[64]` | stack | nobody (automatic) |
|
||||
| the fd | `accept()` | `close(fd)` in `on_leave` |
|
||||
|
||||
ids vs fds: after a client leaves, the kernel may hand the **same fd** to a new client, but
|
||||
`g_nextid++` guarantees the new client's **id** is new (0, 1, 2, … forever). The grader checks
|
||||
the id, not the fd.
|
||||
|
||||
---
|
||||
|
||||
## 7. Why this is the simplest shape
|
||||
|
||||
| Decision | Simpler because | Cost |
|
||||
|---|---|---|
|
||||
| Two arrays indexed by fd, no struct | one concept: slot = fd; no `.fd` field to keep in sync | arrays must both be updated |
|
||||
| Rebuild `fd_set` from `g_id[]` each loop | no master `fd_set`, no 3-set juggling | one O(max_fd) scan per iteration |
|
||||
| One `send_all(skip_fd, …)` helper | arrival, relay and departure all share it | none |
|
||||
| Copy the given helpers verbatim | zero thinking about chunk assembly | ~50 lines you must include |
|
||||
| One `while` extraction loop | handles 1 line, N lines, or half a line identically | none |
|
||||
| `g_maxfd` shrink loop | keeps `select` scanning small | one line |
|
||||
|
||||
---
|
||||
|
||||
## 8. Typing order in the exam (and what to test after each step)
|
||||
|
||||
| Step | Type | Checkpoint |
|
||||
|---|---|---|
|
||||
| 1 | includes, globals, `fatal` | `cc -Wall -Wextra -Werror -c` clean |
|
||||
| 2 | copy `str_join` + `extract_message` from `main.c` | compiles |
|
||||
| 3 | `main`: args, socket, addr, bind, listen | `./mini_serv` → args error; `ss -tlnp` shows LISTEN |
|
||||
| 4 | slots init + `select` loop skeleton | idle CPU ~0%, no crash |
|
||||
| 5 | `on_accept` + `send_all` | 2 `nc`: older sees `just arrived`, newcomer silent |
|
||||
| 6 | `on_read` (+ extraction/relay) | `hello`, `a\nb\n`, split `par`/`tial` correct |
|
||||
| 7 | `on_leave` + maxfd shrink | Ctrl-C → `just left`; partial buffer dropped |
|
||||
| 8 | full smoke | 5 probes + submit |
|
||||
|
||||
---
|
||||
|
||||
## 9. Edge cases this version handles (and why)
|
||||
|
||||
| Case | Handled by |
|
||||
|---|---|
|
||||
| one packet with 5 lines | `while (extract_message == 1)` |
|
||||
| one line split across packets | `str_join` + no send until `\n` |
|
||||
| message with no trailing `\n`, then disconnect | buffer freed, never flushed |
|
||||
| `^D` byte inside data | treated as a normal byte (`recv` only ends on 0) |
|
||||
| 364 KB single line | heap buffer + `malloc(strlen(line) + 64)`; no fixed 1 KB relay buffer |
|
||||
| sender must not see its own message | `send_all(fd, …)` |
|
||||
| newcomer must not see its own arrival | `send_all(fd, …)` called with the new fd as skip |
|
||||
| sibling clients connect/leave repeatedly | ids via `g_nextid++`; slots freed |
|
||||
| idle server | blocks inside `select` (0% CPU) |
|
||||
| lazy client that never reads | server never calls `recv` before readiness, and `send` keeps going (official test never forces a block) |
|
||||
|
||||
---
|
||||
|
||||
## 10. If your campus subject differs
|
||||
|
||||
Read the real subject twice. This implementation matches the standard `mini_serv` (the one in
|
||||
`subject/subject.en.txt`). If your version adds a stdout banner or changes a string, change
|
||||
**only the string/banner** — the structure (select loop, buffers, others-only broadcast) is
|
||||
the same. If your campus serves **mini_db** (C++98), this file does not apply; tell me and
|
||||
we'll build that variant.
|
||||
@@ -0,0 +1,226 @@
|
||||
/* ============================================================================
|
||||
* mini_serv.c — the simplest version that passes the exam
|
||||
*
|
||||
* Build: cc -Wall -Wextra -Werror mini_serv.c -o mini_serv
|
||||
* Run: ./mini_serv <port>
|
||||
*
|
||||
* Shape: two arrays indexed by fd:
|
||||
* g_id[fd] -1 if the slot is free, otherwise that client's public id
|
||||
* g_buf[fd] pending bytes for a line that is not finished yet
|
||||
* The fd_set is rebuilt from g_id[] before every select(). That's it.
|
||||
*
|
||||
* The two helpers (str_join, extract_message) are GIVEN in the exam's main.c.
|
||||
* ==========================================================================*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/select.h>
|
||||
|
||||
/* ---- the whole server state (all indexed by fd) ------------------------- */
|
||||
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: 0, 1, 2, ... */
|
||||
|
||||
static void fatal(void)
|
||||
{
|
||||
write(2, "Fatal error\n", 12);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
/* ---- GIVEN in the exam's main.c: copy these two verbatim ---------------- */
|
||||
|
||||
static char *str_join(char *buf, char *add)
|
||||
{
|
||||
char *newbuf;
|
||||
int len;
|
||||
|
||||
if (buf == 0)
|
||||
len = 0;
|
||||
else
|
||||
len = strlen(buf);
|
||||
newbuf = malloc(sizeof(*newbuf) * (len + strlen(add) + 1));
|
||||
if (newbuf == 0)
|
||||
return (0);
|
||||
newbuf[0] = 0;
|
||||
if (buf != 0)
|
||||
strcat(newbuf, buf);
|
||||
free(buf);
|
||||
strcat(newbuf, add);
|
||||
return (newbuf);
|
||||
}
|
||||
|
||||
static int extract_message(char **buf, char **msg)
|
||||
{
|
||||
char *newbuf;
|
||||
int i;
|
||||
|
||||
*msg = 0;
|
||||
if (*buf == 0)
|
||||
return (0);
|
||||
i = 0;
|
||||
while ((*buf)[i])
|
||||
{
|
||||
if ((*buf)[i] == '\n')
|
||||
{
|
||||
newbuf = calloc(1, sizeof(*newbuf) * (strlen(*buf + i + 1) + 1));
|
||||
if (newbuf == 0)
|
||||
return (-1);
|
||||
strcpy(newbuf, *buf + i + 1);
|
||||
*msg = *buf;
|
||||
(*msg)[i + 1] = 0;
|
||||
*buf = newbuf;
|
||||
return (1);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return (0);
|
||||
}
|
||||
|
||||
/* ---- server helpers ----------------------------------------------------- */
|
||||
|
||||
/* Send s to every connected client except skip_fd (skip_fd = -1: everyone). */
|
||||
static void send_all(int skip_fd, const char *s)
|
||||
{
|
||||
int fd;
|
||||
|
||||
fd = 0;
|
||||
while (fd <= g_maxfd)
|
||||
{
|
||||
if (fd != skip_fd && g_id[fd] != -1)
|
||||
send(fd, s, strlen(s), 0);
|
||||
fd++;
|
||||
}
|
||||
}
|
||||
|
||||
/* EOF/error on fd: announce, close, drop the slot and its buffer. */
|
||||
static void on_leave(int fd)
|
||||
{
|
||||
char msg[64];
|
||||
int id;
|
||||
|
||||
id = g_id[fd];
|
||||
close(fd);
|
||||
g_id[fd] = -1;
|
||||
free(g_buf[fd]);
|
||||
g_buf[fd] = NULL;
|
||||
sprintf(msg, "server: client %d just left\n", id);
|
||||
send_all(-1, msg);
|
||||
while (g_maxfd > g_server && g_id[g_maxfd] == -1)
|
||||
g_maxfd--;
|
||||
}
|
||||
|
||||
/* Data on fd: append it, then relay every COMPLETE line to the others. */
|
||||
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 ;
|
||||
}
|
||||
chunk[n] = 0;
|
||||
g_buf[fd] = str_join(g_buf[fd], chunk);
|
||||
if (!g_buf[fd])
|
||||
fatal();
|
||||
while (extract_message(&g_buf[fd], &line) == 1)
|
||||
{
|
||||
out = malloc(strlen(line) + 64);
|
||||
if (!out)
|
||||
{
|
||||
free(line);
|
||||
fatal();
|
||||
}
|
||||
sprintf(out, "client %d: %s", g_id[fd], line);
|
||||
send_all(fd, out);
|
||||
free(out);
|
||||
free(line);
|
||||
}
|
||||
}
|
||||
|
||||
/* New connection: give it an id, a slot, and announce it to the others. */
|
||||
static void on_accept(void)
|
||||
{
|
||||
char msg[64];
|
||||
int fd;
|
||||
|
||||
fd = accept(g_server, NULL, NULL);
|
||||
if (fd < 0)
|
||||
return ;
|
||||
if (fd >= FD_SETSIZE)
|
||||
{
|
||||
close(fd);
|
||||
return ;
|
||||
}
|
||||
g_id[fd] = g_nextid++;
|
||||
g_buf[fd] = NULL;
|
||||
if (fd > g_maxfd)
|
||||
g_maxfd = fd;
|
||||
sprintf(msg, "server: client %d just arrived\n", g_id[fd]);
|
||||
send_all(fd, 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();
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(2130706433); /* 127.0.0.1 */
|
||||
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_id[i] = -1;
|
||||
i++;
|
||||
}
|
||||
g_maxfd = g_server;
|
||||
while (1)
|
||||
{
|
||||
FD_ZERO(&readfds);
|
||||
FD_SET(g_server, &readfds);
|
||||
i = 0;
|
||||
while (i <= g_maxfd)
|
||||
{
|
||||
if (g_id[i] != -1)
|
||||
FD_SET(i, &readfds);
|
||||
i++;
|
||||
}
|
||||
if (select(g_maxfd + 1, &readfds, NULL, NULL, NULL) < 0)
|
||||
continue ;
|
||||
if (FD_ISSET(g_server, &readfds))
|
||||
on_accept();
|
||||
i = 0;
|
||||
while (i <= g_maxfd)
|
||||
{
|
||||
if (i != g_server && g_id[i] != -1 && FD_ISSET(i, &readfds))
|
||||
on_read(i);
|
||||
i++;
|
||||
}
|
||||
}
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,497 @@
|
||||
# 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.**
|
||||
@@ -0,0 +1,53 @@
|
||||
# EXAM CARD — mini_serv (one screen, read right before you start)
|
||||
|
||||
## Exact strings (bytes matter, `\n` included)
|
||||
|
||||
```c
|
||||
write(2, "Wrong number of arguments\n", 26); return 1; /* argc != 2 */
|
||||
write(2, "Fatal error\n", 12); exit(1); /* syscall/alloc failed */
|
||||
sprintf(m, "server: client %d just arrived\n", id); /* to OTHERS */
|
||||
sprintf(o, "client %d: %s", id, line); /* per line, OTHERS */
|
||||
sprintf(m, "server: client %d just left\n", id); /* to everyone left */
|
||||
```
|
||||
|
||||
127.0.0.1 ⇔ `htonl(2130706433)` · only localhost · no `#define` · no `printf` in the file.
|
||||
|
||||
## The 8 moves
|
||||
|
||||
1. `argc != 2` → args error · 2. `socket(AF_INET, SOCK_STREAM, 0)` → `fatal()` ·
|
||||
3. `sockaddr_in`: bzero, `AF_INET`, `htonl(2130706433)`, `htons(atoi(argv[1]))` → `bind` → `listen` ·
|
||||
4. slots init `fd/id/buf = -1,-1,NULL`, `g_maxfd = g_server` ·
|
||||
5. every loop: `FD_ZERO` + `FD_SET(g_server)` + `FD_SET` live fds → `select(g_maxfd + 1, NULL, NULL, NULL)` ·
|
||||
6. listener ready → `accept` → `id = g_next_id++` → raise `g_maxfd` → "arrived" **to others** ·
|
||||
7. client ready → `recv` → `n<=0` disconnect / else append `str_join`, `while extract_message` →
|
||||
`sprintf("client %d: %s")` → send **to others** → `free(msg)` ·
|
||||
8. disconnect → keep id, `close`, clear slot, `free(buf)`, "left" to everyone, shrink `g_maxfd` (≥ server fd).
|
||||
|
||||
## The 5 traps that fail exams
|
||||
|
||||
1. Not rebuilding/copying the fd_set every loop (or wrong `nfds`) → newest client invisible / 100% CPU.
|
||||
2. Sending arrival or messages to the sender/newcomer → extra lines → diff fails.
|
||||
3. Flushing the partial buffer at disconnect → phantom message → diff fails.
|
||||
4. One line per `recv` instead of a `while` extraction loop → lines lost/delayed.
|
||||
5. Closing an fd still in the set → `select` fails `EBADF`; always `FD_CLR`/remove logically before `close`.
|
||||
|
||||
## My commands
|
||||
|
||||
```bash
|
||||
bash tester/check.sh # compile + 13 behavioral + real grademe diff
|
||||
python3 tester/mini_serv_tester.py sandbox/mini_serv --quick # fast loop
|
||||
cd sandbox && bash .system/grading/tester.sh ; ls .system/grading/passed || sed -n '1,40p' traceback
|
||||
```
|
||||
|
||||
## Exam-day order (first 10 minutes)
|
||||
|
||||
1. Read subject twice; copy the exact strings from it, not from memory.
|
||||
2. Open the `main.c` attachment; plan to copy `str_join` + `extract_message` verbatim.
|
||||
3. Type Stage A→E from `drills/typing-script.md`; test with `nc` after C and after D.
|
||||
4. `nc` sanity: 2 windows — arrival, relay, split line, Ctrl-C → left.
|
||||
5. Re-read the subject; submit; fix; resubmit if allowed. Never sit on a working copy.
|
||||
|
||||
## If stuck (first three checks)
|
||||
|
||||
1. `ss -tlnp` → LISTEN? 2. `nc` connects? 3. trace prints: which fd got ready, `recv` n, buffer contents.
|
||||
Symptom table: `debugging.md` §5. Exit codes: 141 = SIGPIPE, 139 = segv, 1 = your `exit(1)`.
|
||||
+519
@@ -0,0 +1,519 @@
|
||||
# THE EXAM PACK — the exam kit + the full plan in one file
|
||||
|
||||
> **Study-only.** This is the desert-island document: what you receive in the exam, what to
|
||||
> type, how to test each stage, how to debug, what to check before submitting, and the man
|
||||
> pages to consult at each step. If you only keep one file, keep this one — and practise
|
||||
> until you don't need it.
|
||||
|
||||
---
|
||||
|
||||
## 0. The exam in 60 seconds
|
||||
|
||||
- One file: `mini_serv.c`. A `select()` chat server on **127.0.0.1:<argv[1]>**.
|
||||
- You also receive **`main.c`**: socket boilerplate + two helpers (`str_join`, `extract_message`). Keep the helpers, throw away its `main()`.
|
||||
- Grading: one listener client + short-lived senders, **byte-exact diff** of what the listener saw.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["stage A<br/>struct + globals + fatal"] --> B["stage B<br/>args + socket/bind/listen"]
|
||||
B --> C["stage C<br/>slots + select + accept + arrival"]
|
||||
C --> D["stage D<br/>recv + buffer + extract + relay"]
|
||||
D --> E["stage E<br/>disconnect + cleanup"]
|
||||
E --> F["stage F<br/>nc checks + submit"]
|
||||
```
|
||||
|
||||
**The 8 moves:** guard → socket → bind/listen → slots → select loop → accept+arrival →
|
||||
recv+buffer+relay → disconnect+cleanup.
|
||||
|
||||
**The 6 exact strings** (bytes matter, `\n` included):
|
||||
|
||||
```c
|
||||
write(2, "Wrong number of arguments\n", 26); return 1;
|
||||
write(2, "Fatal error\n", 12); exit(1);
|
||||
sprintf(m, "server: client %d just arrived\n", id); /* to OTHERS */
|
||||
sprintf(o, "client %d: %s", id, line); /* per line, to OTHERS */
|
||||
sprintf(m, "server: client %d just left\n", id); /* to everyone left */
|
||||
/* 127.0.0.1 == htonl(2130706433) */
|
||||
```
|
||||
|
||||
**The 5 traps:** ① not rebuilding/copying the fd_set every loop (or wrong `nfds`);
|
||||
② sending arrival/relay to the sender/newcomer; ③ flushing the partial buffer at disconnect;
|
||||
④ one line per `recv` instead of a `while` extraction loop; ⑤ closing an fd still in the set.
|
||||
|
||||
---
|
||||
|
||||
## 1. What you receive — verbatim
|
||||
|
||||
### 1.1 `subject.en.txt`
|
||||
|
||||
```text
|
||||
Assignment name : mini_serv
|
||||
Expected files : mini_serv.c
|
||||
Allowed functions: write, close, select, socket, accept, listen, send, recv, bind, strstr, malloc, realloc, free, calloc, bzero, atoi, sprintf, strlen, exit, strcpy, strcat, memset
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Write a program that will listen for client to connect on a certain port on 127.0.0.1 and will let clients to speak with each other
|
||||
|
||||
This program will take as first argument the port to bind to
|
||||
If no argument is given, it should write in stderr "Wrong number of arguments" followed by a \n and exit with status 1
|
||||
If a System Calls returns an error before the program start accepting connection, it should write in stderr "Fatal error" followed by a \n and exit with status 1
|
||||
If you cant allocate memory it should write in stderr "Fatal error" followed by a \n and exit with status 1
|
||||
|
||||
Your program must be non-blocking but client can be lazy and if they don't read your message you must NOT disconnect them...
|
||||
|
||||
Your program must not contains #define preproc
|
||||
Your program must only listen to 127.0.0.1
|
||||
The fd that you will receive will already be set to make 'recv' or 'send' to block if select hasn't be called before calling them, but will not block otherwise.
|
||||
|
||||
When a client connect to the server:
|
||||
- the client will be given an id. the first client will receive the id 0 and each new client will received the last client id + 1
|
||||
- %d will be replace by this number
|
||||
- a message is sent to all the client that was connected to the server: "server: client %d just arrived\n"
|
||||
|
||||
clients must be able to send messages to your program.
|
||||
- message will only be printable characters, no need to check
|
||||
- a single message can contains multiple \n
|
||||
- when the server receive a message, it must resend it to all the other client with "client %d: " before every line!
|
||||
|
||||
When a client disconnect from the server:
|
||||
- a message is sent to all the client that was connected to the server: "server: client %d just left\n"
|
||||
|
||||
Memory or fd leaks are forbidden
|
||||
|
||||
To help you, you will find the file main.c with the beginning of a server and maybe some useful functions. (Beware this file use forbidden functions or write things that must not be there in your final program)
|
||||
|
||||
Warning our tester is expecting that you send the messages as fast as you can. Don't do un-necessary buffer.
|
||||
|
||||
Evaluation can be a bit longer than usual...
|
||||
|
||||
Hint: you can use nc to test your program
|
||||
Hint: you should use nc to test your program
|
||||
Hint: To test you can use fcntl(fd, F_SETFL, O_NONBLOCK) but use select and NEVER check EAGAIN (man 2 send)
|
||||
```
|
||||
|
||||
### 1.2 `main.c` (the attachment)
|
||||
|
||||
```c
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <netdb.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
|
||||
int extract_message(char **buf, char **msg)
|
||||
{
|
||||
char *newbuf;
|
||||
int i;
|
||||
|
||||
*msg = 0;
|
||||
if (*buf == 0)
|
||||
return (0);
|
||||
i = 0;
|
||||
while ((*buf)[i])
|
||||
{
|
||||
if ((*buf)[i] == '\n')
|
||||
{
|
||||
newbuf = calloc(1, sizeof(*newbuf) * (strlen(*buf + i + 1) + 1));
|
||||
if (newbuf == 0)
|
||||
return (-1);
|
||||
strcpy(newbuf, *buf + i + 1);
|
||||
*msg = *buf;
|
||||
(*msg)[i + 1] = 0;
|
||||
*buf = newbuf;
|
||||
return (1);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return (0);
|
||||
}
|
||||
|
||||
char *str_join(char *buf, char *add)
|
||||
{
|
||||
char *newbuf;
|
||||
int len;
|
||||
|
||||
if (buf == 0)
|
||||
len = 0;
|
||||
else
|
||||
len = strlen(buf);
|
||||
newbuf = malloc(sizeof(*newbuf) * (len + strlen(add) + 1));
|
||||
if (newbuf == 0)
|
||||
return (0);
|
||||
newbuf[0] = 0;
|
||||
if (buf != 0)
|
||||
strcat(newbuf, buf);
|
||||
free(buf);
|
||||
strcat(newbuf, add);
|
||||
return (newbuf);
|
||||
}
|
||||
|
||||
|
||||
int main() {
|
||||
int sockfd, connfd, len;
|
||||
struct sockaddr_in servaddr, cli;
|
||||
|
||||
// socket create and verification
|
||||
sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sockfd == -1) {
|
||||
printf("socket creation failed...\n");
|
||||
exit(0);
|
||||
}
|
||||
else
|
||||
printf("Socket successfully created..\n");
|
||||
bzero(&servaddr, sizeof(servaddr));
|
||||
|
||||
// assign IP, PORT
|
||||
servaddr.sin_family = AF_INET;
|
||||
servaddr.sin_addr.s_addr = htonl(2130706433); //127.0.0.1
|
||||
servaddr.sin_port = htons(8081);
|
||||
|
||||
// Binding newly created socket to given IP and verification
|
||||
if ((bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr))) != 0) {
|
||||
printf("socket bind failed...\n");
|
||||
exit(0);
|
||||
}
|
||||
else
|
||||
printf("Socket successfully binded..\n");
|
||||
if (listen(sockfd, 10) != 0) {
|
||||
printf("cannot listen\n");
|
||||
exit(0);
|
||||
}
|
||||
len = sizeof(cli);
|
||||
connfd = accept(sockfd, (struct sockaddr *)&cli, &len);
|
||||
if (connfd < 0) {
|
||||
printf("server acccept failed...\n");
|
||||
exit(0);
|
||||
}
|
||||
else
|
||||
printf("server acccept the client...\n");
|
||||
}
|
||||
```
|
||||
|
||||
### 1.3 Inventory: what to keep, what to rewrite
|
||||
|
||||
| Part | Verdict |
|
||||
|---|---|
|
||||
| `extract_message()` | **KEEP verbatim.** Returns `1` = one line in `*msg` (free it), `0` = no newline yet, `-1` = alloc fail → fatal |
|
||||
| `str_join()` | **KEEP verbatim.** Append + free old buffer; `NULL` on OOM. Frees the old buffer itself |
|
||||
| `main()` | **REWRITE.** It's a one-client demo: hardcoded 8081, `printf` (forbidden), `exit(0)` (wrong), no `argc` check, no loop |
|
||||
| socket setup lines | Reuse them **inside** your `main`, but with `argv[1]` and `fatal()` |
|
||||
| includes | Incomplete: add `<stdlib.h>` (malloc/calloc/free/exit/atoi), `<stdio.h>` (sprintf), `<sys/select.h>` |
|
||||
|
||||
Verified: the attachment does **not** compile as-is on a modern gcc (missing `<stdlib.h>`/`<stdio.h>`, and `int len` passed where `socklen_t *` is expected). It is a starting kit, not a solution. Annotated copy: `subject/main.annotated.c`.
|
||||
|
||||
---
|
||||
|
||||
## 2. The 2-hour plan (minute by minute)
|
||||
|
||||
| Time | Stage | You are done when… |
|
||||
|---|---|---|
|
||||
| 0:00–0:08 | read subject ×2, write the 6 strings + 5 traps on a scratch comment | you can state the arrival/relay/left rules without looking |
|
||||
| 0:08–0:22 | **A + B**: struct/globals/`fatal` + args + socket/bind/listen | `./mini_serv` → args error, exit 1; `ss -tlnp` shows LISTEN |
|
||||
| 0:22–0:42 | **C**: slots, select loop, `accept_new`, arrival broadcast | 2 `nc` windows: older one sees `server: client 1 just arrived`, newcomer silent |
|
||||
| 0:42–1:15 | **D**: `recv` + `str_join` + extract loop + relay + frees | `hello`, `a\nb\n`, split `par`/`tial` all behave |
|
||||
| 1:15–1:32 | **E**: disconnect + `left` broadcast + close/free + maxfd shrink | Ctrl-C → `just left`; `printf 'abc' | send PORT` → nothing + left |
|
||||
| 1:32–1:48 | **F**: 5-probe smoke + (if available) `check.sh` | all probes pass |
|
||||
| 1:48–1:56 | pre-submit checklist + **submit** | submitted |
|
||||
| 1:56–2:00 | re-read subject, fix, resubmit if allowed | nothing red |
|
||||
|
||||
> **If you get 4 hours:** still submit at ~2 h. Use the rest for valgrind, a 25-client stress,
|
||||
> a 400 KB single line, and a second cold pass over the checklist. Never sit on a working copy.
|
||||
|
||||
### Stage A — skeleton (5 min)
|
||||
|
||||
```c
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/select.h>
|
||||
|
||||
typedef struct s_client { int fd; int id; char *buf; } t_client;
|
||||
static t_client g_c[FD_SETSIZE];
|
||||
static int g_maxfd, g_server, g_next_id;
|
||||
|
||||
static void fatal(void) { write(2, "Fatal error\n", 12); exit(1); }
|
||||
```
|
||||
|
||||
**Prove it:** `cc -Wall -Wextra -Werror -c mini_serv.c -o /tmp/x.o` → silence.
|
||||
|
||||
📖 **man:** `man 2 socket` (RETURN VALUE) · `man 3 malloc`/`man 3 free` (NULL rules) · `man 3 errno`.
|
||||
|
||||
### Stage B — guard + socket/bind/listen (15 min)
|
||||
|
||||
```c
|
||||
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 */
|
||||
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();
|
||||
```
|
||||
|
||||
**Prove it:**
|
||||
|
||||
```bash
|
||||
./mini_serv; echo $? # Wrong number of arguments / 1
|
||||
./mini_serv 1; echo $? # Fatal error / 1 (privileged port)
|
||||
./mini_serv 8081 & ss -tlnp | grep 8081 # LISTEN ... 127.0.0.1:8081
|
||||
```
|
||||
|
||||
**If red:** port already in use → another run is alive (`ss -tlnp`); wrong bytes → count the
|
||||
string lengths (26 / 12) and keep `\n` inside the literal.
|
||||
|
||||
📖 **man:** `man 7 socket` (AF_INET/SOCK_STREAM) · `man 2 bind` · `man 2 listen` (backlog) ·
|
||||
`man 7 ip` (`sockaddr_in`) · `man 3 htons` → **byteorder(3)** · `man 2 accept`.
|
||||
|
||||
### Stage C — slots + select loop + accept + arrival (20 min)
|
||||
|
||||
```c
|
||||
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);
|
||||
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++;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`accept_new`: `fd = accept(g_server, NULL, NULL); if (fd < 0) return; g_c[fd].fd = fd;
|
||||
g_c[fd].id = g_next_id++; g_c[fd].buf = NULL; if (fd > g_maxfd) g_maxfd = fd;
|
||||
sprintf(msg, "server: client %d just arrived\n", g_c[fd].id); to_all_except(fd, msg);`
|
||||
|
||||
**Prove it:** two `nc 127.0.0.1 8081` windows → older sees the arrival line, newcomer sees
|
||||
nothing. Idle CPU must be ~0% (`ps -o %cpu= -p $PID`) — 100% means the set rebuild is broken.
|
||||
|
||||
**If red:** no arrival → is the fd in the set? is `g_maxfd` raised? did you use `FD_ISSET` on
|
||||
the copy? newcomer hears itself → you didn't skip the new fd.
|
||||
|
||||
📖 **man:** **`man 2 select_tut`** (worked example!) · `man 2 select` (nfds + sets destroyed) ·
|
||||
`man 2 accept` (new fd) · `man 2 listen` (backlog) · `man 8 ss` · `man 1 nc`.
|
||||
|
||||
### Stage D — recv + buffer + extract + relay (30–35 min)
|
||||
|
||||
```c
|
||||
n = recv(fd, tmp, sizeof(tmp) - 1, 0);
|
||||
if (n <= 0) { disconnect(fd); return ; }
|
||||
tmp[n] = 0;
|
||||
g_c[fd].buf = str_join(g_c[fd].buf, tmp);
|
||||
if (!g_c[fd].buf) fatal();
|
||||
while (extract_message(&g_c[fd].buf, &msg) == 1) {
|
||||
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);
|
||||
}
|
||||
```
|
||||
|
||||
**Prove it** (helper: `send() { exec 3<>/dev/tcp/127.0.0.1/"$1"; cat >&3; exec 3>&-; }`):
|
||||
|
||||
```bash
|
||||
printf 'hello\n' | send 8081 # other nc: client 1: hello
|
||||
printf 'a\nb\n' | send 8081 # two prefixed lines
|
||||
{ printf 'par'; sleep 1; printf 'tial\n'; } | send 8081 # ONE client 1: partial, nothing before
|
||||
printf 'a\x04b\n' | send 8081 # 0x04 is plain data, relayed
|
||||
```
|
||||
|
||||
**If red:** text only after more data → you flush per recv instead of extracting lines;
|
||||
partial line echoed early → same; sender sees own message → exclusion missing.
|
||||
|
||||
📖 **man:** `man 2 recv` (0 = EOF!) · `man 2 send` (partial sends, EPIPE) · `man 3 sprintf` ·
|
||||
`man 3 strlen` · `man 7 tcp` · `man 2 select`.
|
||||
|
||||
### Stage E — disconnect + cleanup (15 min)
|
||||
|
||||
```c
|
||||
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--;
|
||||
```
|
||||
|
||||
**Prove it:** Ctrl-C in a client → other windows show `just left`. `printf 'abc' | send 8081`
|
||||
→ **no** message, just `left`. `/proc/$PID/fd` returns to just the listener after everyone
|
||||
leaves. Connect/leave/connect → the new client is id 2 (never reused).
|
||||
|
||||
**If red:** no `left` → `recv <= 0` branch; leftover text appears → you flushed the buffer;
|
||||
`EBADF` from select → you closed without removing from the set.
|
||||
|
||||
📖 **man:** `man 2 recv` (EOF) · `man 2 close` · `man 2 shutdown` (context) · `man 5 proc`
|
||||
(fd table) · `man 7 signal` (SIGPIPE!) · `man 1 valgrind`.
|
||||
|
||||
### Stage F — final checks + submit (15 min)
|
||||
|
||||
Run the 5 probes (arrival, relay, multiline, split, disconnect), then submit. If the gym is
|
||||
available: `bash tester/check.sh` must be all green (13/13 + `GRADEME: PASSED`).
|
||||
|
||||
📖 **man:** `man 8 ss` · `man 1 nc` · `man 1 valgrind` · `man 1 gdb`.
|
||||
|
||||
---
|
||||
|
||||
## 3. In-exam debug ladder
|
||||
|
||||
**Add five trace prints** (delete before submit — `printf` is forbidden):
|
||||
|
||||
```c
|
||||
fprintf(stderr, "select: maxfd=%d\n", g_maxfd); /* once per loop, only while debugging */
|
||||
fprintf(stderr, "accept: fd=%d id=%d\n", fd, g_c[fd].id);
|
||||
fprintf(stderr, "recv: fd=%d n=%zd\n", fd, n);
|
||||
fprintf(stderr, "buf: fd=%d [%s]\n", fd, g_c[fd].buf);
|
||||
fprintf(stderr, "relay: fd=%d [%s]\n", fd, out);
|
||||
```
|
||||
|
||||
**Triage order (stop at the first red step):**
|
||||
|
||||
1. `cc -Wall -Wextra -Werror -g` compiles? 2. `ss -tlnp | grep PORT` LISTEN?
|
||||
3. `nc` connects? 4. arrival correct? 5. relay/multiline? 6. split line? 7. disconnect?
|
||||
8. `echo $?` after a crash.
|
||||
|
||||
| Symptom | Likely cause | Fix |
|
||||
|---|---|---|
|
||||
| args error with a port given | `argc` test wrong | `if (argc != 2)` |
|
||||
| immediate `Fatal error` | bind failed: port busy / wrong addr | `ss -tan | grep PORT`; check `htonl(2130706433)` |
|
||||
| nc “Connection refused” | not listening / died / wrong port | `ps`, read stderr |
|
||||
| connects, silence | accept/select never reached; `max_fd` stale; wrong set checked | trace prints; rebuild set each loop |
|
||||
| 100% CPU idle | set not rebuilt, or readiness not consumed | `FD_ZERO` + handle every ready fd |
|
||||
| only first client works | `max_fd` not raised | `if (fd > g_maxfd) g_maxfd = fd;` |
|
||||
| newcomer sees own arrival | broadcast includes new fd | exclude it (`to_all_except(fd, …)`) |
|
||||
| lines lost/delayed | one line per `recv` | `while (extract_message(...) == 1)` |
|
||||
| prefix missing/duplicated | built once per recv | build inside the extract loop |
|
||||
| no `just left` | `recv <= 0` branch missing | save id, broadcast, close, free |
|
||||
| dies silently | `141` SIGPIPE / `139` segv | `gdb` → `bt`; `MSG_NOSIGNAL` if time |
|
||||
| `EBADF` loop | closed fd still in set | remove before `close` |
|
||||
|
||||
📖 **man:** `man 3 errno` · `man 3 perror` · `man 3 strerror` (dev-only prints) · `man 8 ss` ·
|
||||
`man 5 proc` · `man 1 nc` · `man 1 gdb` · `man 1 valgrind` · `man 7 signal`.
|
||||
|
||||
---
|
||||
|
||||
## 4. Pre-submit checklist (2 minutes)
|
||||
|
||||
```bash
|
||||
cc -Wall -Wextra -Werror mini_serv.c -o mini_serv # 1. compiles clean
|
||||
grep -n 'printf\|#define' mini_serv.c # 2. only sprintf; no #define
|
||||
grep -n 'Wrong number of arguments\|Fatal error\|just arrived\|just left' mini_serv.c
|
||||
./mini_serv; echo $? # 3. exact stderr + exit 1
|
||||
./mini_serv 8081 & ss -tlnp | grep 8081 # 4. LISTEN
|
||||
# 5. five probes: arrival (2 nc) · relay · a\nb\n · split par/tial · Ctrl-C → left
|
||||
# 6. ids: connect/leave/connect → next id (not reused)
|
||||
# 7. if time: valgrind --leak-check=full --track-fds=yes ./mini_serv 8099
|
||||
```
|
||||
|
||||
Then **submit**. Re-read the subject once after submitting; if something is off, fix and
|
||||
resubmit before the window closes.
|
||||
|
||||
---
|
||||
|
||||
## 5. Preparation plan (before the exam)
|
||||
|
||||
| When | Do |
|
||||
|---|---|
|
||||
| T-2 days | `drills/typing-script.md` stages A–E; first cold attempt; `bash tester/check.sh`; write the "what I missed" diff vs `reference/mini_serv.c` |
|
||||
| T-1 day | two more cold attempts (target ≤ 90 min, all green); `drills/drills.md` D7 chaos; read `walkthrough.md` stations 9–11 one last time |
|
||||
| Exam morning | **no new material.** Read `exam-card.md`; do 5 man-page lookups (below); one 10-minute warm-up typing pass of stages A+B |
|
||||
| In the room | read subject twice; write the 6 strings; then stage A→F |
|
||||
|
||||
**Readiness rule:** two consecutive cold runs from a blank file, all green, under 90 minutes.
|
||||
|
||||
**Man-page drill (5 lookups, 10 min):**
|
||||
1. `man 2 recv` → what do `>0`, `0`, `-1` mean?
|
||||
2. `man 2 select` → why must the set be reinitialised each loop?
|
||||
3. `man 7 signal` → SIGPIPE default action?
|
||||
4. `man 8 ss` → which flag shows the owning process?
|
||||
5. `man 5 proc` → where is the fd table of a pid?
|
||||
|
||||
---
|
||||
|
||||
## 6. Salvage playbook (when it goes wrong)
|
||||
|
||||
| Situation | Action |
|
||||
|---|---|
|
||||
| Can’t connect at all | `ss -tlnp`: if no LISTEN → bind failed (Fatal error path is *correct*); retry on a free port |
|
||||
| Works for one client only | 2-minute fix: raise `g_maxfd` on accept, rebuild the set every loop |
|
||||
| Arrival works, relay dead | check `recv` branch: append → `while extract` → `sprintf` → `to_all_except(fd, …)` |
|
||||
| Big line never arrives | ensure heap append (`str_join`) + one `send` of the built string; never a fixed 1 KB buffer |
|
||||
| Server dies on disconnect | `echo $?` → 141 = SIGPIPE; add `MSG_NOSIGNAL` to `send` if the window allows |
|
||||
| 10 minutes left | stop coding. Run the 5 probes, fix only showstoppers, **submit**, then iterate if resubmission is allowed |
|
||||
|
||||
---
|
||||
|
||||
## 7. Man-page appendix (what to read, and the exact lines that matter)
|
||||
|
||||
**Sections:** 1 commands · 2 syscalls · 3 libc · 5 formats · 7 concepts · 8 admin tools.
|
||||
Read **RETURN VALUE → ERRORS → NOTES → EXAMPLES**. `man -k keyword` finds pages.
|
||||
|
||||
**Core ten:** `select_tut(2)`, `select(2)`, `socket(7)`, `socket(2)`, `bind(2)`, `listen(2)`,
|
||||
`accept(2)`, `recv(2)`, `send(2)`, `close(2)`, `signal(7)`, `errno(3)`, `ss(8)`, `nc(1)`,
|
||||
`proc(5)`. (`errno` is section **3**; `htons/htonl` live in **byteorder(3)**. `strace(1)` and
|
||||
`netstat(1)` are not installed here — use `ss` + gdb/valgrind.)
|
||||
|
||||
**Verified excerpts:**
|
||||
|
||||
`recv(2)`:
|
||||
> These calls return the number of bytes received, or -1 if an error occurred. […] When a
|
||||
> stream socket peer has performed an orderly shutdown, the **return value will be 0** (the
|
||||
> traditional “end-of-file” return).
|
||||
|
||||
`select(2)`:
|
||||
> On success, select() […] return the number of file descriptors contained in the three
|
||||
> returned descriptor sets […] The return value may be zero if the timeout expired.
|
||||
>
|
||||
> **Note well: Upon return, each of the file descriptor sets is modified in place** to
|
||||
> indicate which file descriptors are currently “ready”. Thus, if using select() within a
|
||||
> loop, **the sets must be reinitialized before each call.**
|
||||
|
||||
`accept(2)`:
|
||||
> On success, these system calls return a **file descriptor for the accepted socket** (a
|
||||
> nonnegative integer). On error, -1 is returned, errno is set […]
|
||||
>
|
||||
> NOTE: a readiness event does not guarantee a connection is still waiting (it may have been
|
||||
> removed by a network error first).
|
||||
|
||||
`listen(2)`:
|
||||
> The backlog argument defines the maximum length to which the **queue of pending
|
||||
> connections** for sockfd may grow.
|
||||
|
||||
`send(2)`:
|
||||
> **MSG_NOSIGNAL** — Don’t generate a SIGPIPE signal if the peer on a stream-oriented socket
|
||||
> has closed the connection. The EPIPE error is still returned.
|
||||
|
||||
`signal(7)`:
|
||||
> SIGPIPE — Broken pipe: write to pipe with no readers — default action **Term**.
|
||||
|
||||
`socket(2)` / `bind(2)` / `listen(2)` return values: new fd / `0` / `0` on success, `-1` +
|
||||
`errno` on error.
|
||||
|
||||
`select_tut(2)` is a **tutorial with a complete select-server example** — the single most
|
||||
useful page for this exam.
|
||||
|
||||
---
|
||||
|
||||
## 8. Where the rest of the gym fits
|
||||
|
||||
| If you need… | Open |
|
||||
|---|---|
|
||||
| The code↔behavior lab (real captured output per block) | `walkthrough.md` |
|
||||
| The full 14-drill training program | `drills/drills.md` + `drills/typing-script.md` |
|
||||
| Per-call reference (args, returns, errno) | `libc-reference.md` |
|
||||
| The illustrated fundamentals (fd, socket, select) | `fundamentals.md` + `explore/` |
|
||||
| Symptom → cause debugging table | `debugging.md` §5 |
|
||||
| The 5-minute pre-exam card | `exam-card.md` |
|
||||
| Man-page index + reading paths | `man-pages.md` |
|
||||
| The exact real grader + testers | `tester/check.sh`, `tester/mini_serv_tester.py`, `tester/grademe/` |
|
||||
@@ -0,0 +1,37 @@
|
||||
/* Experiment 01 — file descriptors are small integers, and they get reused.
|
||||
*
|
||||
* Build: cc -Wall -Wextra -Werror 01_fds.c -o 01_fds
|
||||
* Run: ./01_fds
|
||||
*
|
||||
* Observe: stdin/stdout/stderr are 0/1/2 (they exist before your program runs).
|
||||
* A file and a socket both get the next free numbers — 3, 4 — because the
|
||||
* kernel reuses the smallest free slot. Close them and open again: the numbers
|
||||
* come back. That's the whole "fd" concept.
|
||||
*/
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#include <netinet/in.h>
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int file_fd; // normal file
|
||||
int sock_fd; // network file
|
||||
|
||||
printf("always there: stdin=%d stdout=%d stderr=%d\n", 0, 1, 2);
|
||||
|
||||
file_fd = open("/etc/hostname", O_RDONLY); // open the hostname file
|
||||
sock_fd = socket(AF_INET, SOCK_STREAM, 0);// creat ea socket on the internet
|
||||
printf("first round: file=%d socket=%d\n", file_fd, sock_fd);
|
||||
close(file_fd);
|
||||
close(sock_fd);
|
||||
|
||||
file_fd = open("/etc/hostname", O_RDONLY);
|
||||
sock_fd = socket(AF_INET, SOCK_STREAM, 0);// socket(ipv4, tcp connection, 0)
|
||||
printf("after close: file=%d socket=%d <- reused the smallest free slots\n",
|
||||
file_fd, sock_fd);
|
||||
close(file_fd);
|
||||
close(sock_fd);
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/* Experiment 02 — bind + listen without accept: the kernel queues connections
|
||||
* for you. This shows what "backlog" and "someone connected" really mean.
|
||||
*
|
||||
* Build: cc -Wall -Wextra -Werror 02_bind_listen.c -o 02_bind_listen
|
||||
* Run: ./02_bind_listen 8081 (Ctrl-C to stop)
|
||||
*
|
||||
* In other terminals:
|
||||
* ss -tlnp | grep 8081 -> your LISTEN socket, with backlog info
|
||||
* nc -v 127.0.0.1 8081 -> nc says "succeeded"! even though this
|
||||
* program never calls accept()
|
||||
* ss -tnp | grep 8081 -> the connection sits ESTABLISHED in the
|
||||
* accept queue, waiting for accept()
|
||||
*
|
||||
* Lesson: TCP handshakes are completed by the KERNEL. accept() only dequeues
|
||||
* an already-established connection. "nc connects" != "my code accepted it".
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
struct sockaddr_in addr; // socket information
|
||||
int sfd; // socket file discriptor
|
||||
|
||||
if (argc != 2) // check the arg cound
|
||||
{
|
||||
fprintf(stderr, "usage: %s PORT\n", argv[0]);
|
||||
return (1);
|
||||
}
|
||||
setvbuf(stdout, NULL, _IOLBF, 0); //empty the stdout buffer
|
||||
sfd = socket(AF_INET, SOCK_STREAM, 0); // create a socket
|
||||
if (sfd < 0)
|
||||
{
|
||||
perror("socket");
|
||||
return (1);
|
||||
}
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(2130706433); /* 127.0.0.1 */
|
||||
addr.sin_port = htons(atoi(argv[1]));
|
||||
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
|
||||
{
|
||||
perror("bind");
|
||||
return (1);
|
||||
}
|
||||
if (listen(sfd, 10) < 0)
|
||||
{
|
||||
perror("listen");
|
||||
return (1);
|
||||
}
|
||||
printf("listening on 127.0.0.1:%s (fd %d) — and I will NEVER accept.\n",
|
||||
argv[1], sfd);
|
||||
printf("try: nc -v 127.0.0.1 %s && ss -tnp | grep %s\n", argv[1], argv[1]);
|
||||
printf("Ctrl-C to stop.\n");
|
||||
pause();
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/* Experiment 03 — accept() and the truth about TCP chunking + EOF.
|
||||
*
|
||||
* Build: cc -Wall -Wextra -Werror 03_accept_recv.c -o 03_accept_recv
|
||||
* Run: ./03_accept_recv 8081
|
||||
*
|
||||
* In another terminal:
|
||||
* nc 127.0.0.1 8081 -> type "hello" + Enter, then more text, watch this
|
||||
* program print one line per recv() with its size
|
||||
* Ctrl-D / Ctrl-C -> watch the final recv() return 0 (EOF)
|
||||
*
|
||||
* Scripted split-line test (same connection, "par" then later "tial\n"):
|
||||
* send() { exec 3<>/dev/tcp/127.0.0.1/"$1"; cat >&3; exec 3>&-; }
|
||||
* { printf 'par'; sleep 1; printf 'tial\n'; } | send 8081
|
||||
*
|
||||
* Lesson: recv() returns whatever bytes are available, not "one message".
|
||||
* A logical line can arrive in pieces; the final 0 is EOF.
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
struct sockaddr_in addr; // for the host configration
|
||||
unsigned char buf[64]; // message size
|
||||
ssize_t n;
|
||||
ssize_t i;
|
||||
int sfd; // socket fd
|
||||
int cfd; //
|
||||
|
||||
if (argc != 2)
|
||||
{
|
||||
fprintf(stderr, "usage: %s PORT\n", argv[0]);
|
||||
return (1);
|
||||
}
|
||||
sfd = socket(AF_INET, SOCK_STREAM, 0); // init the socket fd
|
||||
if (sfd < 0)
|
||||
{
|
||||
perror("socket");
|
||||
return (1);
|
||||
}
|
||||
memset(&addr, 0, sizeof(addr)); // remove the struct data
|
||||
addr.sin_family = AF_INET; // add the configrations
|
||||
addr.sin_addr.s_addr = htonl(2130706433); // add the configrations
|
||||
addr.sin_port = htons(atoi(argv[1])); // add the configrations
|
||||
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) // use the socket alocate the port
|
||||
{
|
||||
perror("bind");
|
||||
return (1);
|
||||
}
|
||||
if (listen(sfd, 10) < 0) // listn to the network
|
||||
{
|
||||
perror("listen");
|
||||
return (1);
|
||||
}
|
||||
printf("waiting: nc 127.0.0.1 %s\n", argv[1]);
|
||||
cfd = accept(sfd, NULL, NULL); // connection fd when accetp the connection
|
||||
if (cfd < 0)
|
||||
{
|
||||
perror("accept");
|
||||
return (1);
|
||||
}
|
||||
printf("accepted! listening fd = %d, conversation fd = %d (a NEW one)\n",
|
||||
sfd, cfd);
|
||||
while ((n = recv(cfd, buf, sizeof(buf), 0)) > 0) //byte get revived form the connection
|
||||
{
|
||||
printf("recv -> %zd bytes: [", n);
|
||||
i = 0;
|
||||
while (i < n)
|
||||
{
|
||||
if (isprint(buf[i]))
|
||||
printf("%c", buf[i]);
|
||||
else
|
||||
printf(".");
|
||||
i++;
|
||||
}
|
||||
printf("]\n");
|
||||
fflush(stdout);
|
||||
}
|
||||
printf("recv returned %zd <- EOF (peer closed) or error. Bye.\n", n);
|
||||
close(cfd);
|
||||
close(sfd);
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/* Experiment 04 — select() with TWO sources: your keyboard (stdin) and a
|
||||
* listening socket. You are watching the waiting room in action.
|
||||
*
|
||||
* Build: cc -Wall -Wextra -Werror 04_select_two.c -o 04_select_two
|
||||
* Run: ./04_select_two 8081
|
||||
*
|
||||
* Then, in order:
|
||||
* - type something + Enter here -> "stdin ready"
|
||||
* - nc 127.0.0.1 8081 -> "listener ready", it accepts,
|
||||
* reads one line, closes that client
|
||||
* - Ctrl-D in this terminal -> stdin EOF, program exits
|
||||
*
|
||||
* Lesson: select() blocks until ANY watched fd is ready, then tells you which
|
||||
* one(s) via FD_ISSET. This is the exact heartbeat of mini_serv.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/select.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
struct sockaddr_in addr; // socket
|
||||
fd_set rfds; // a set of fds to read
|
||||
char buf[128]; // the buffer
|
||||
ssize_t n;
|
||||
int sfd; // socket fd
|
||||
int cfd; // connection fd
|
||||
int maxfd; // max number of fds
|
||||
|
||||
if (argc != 2)
|
||||
{
|
||||
fprintf(stderr, "usage: %s PORT\n", argv[0]);
|
||||
return (1);
|
||||
}
|
||||
setvbuf(stdout, NULL, _IOLBF, 0);
|
||||
sfd = socket(AF_INET, SOCK_STREAM, 0); //create a stream socket
|
||||
if (sfd < 0)
|
||||
{
|
||||
perror("socket");
|
||||
return (1);
|
||||
}
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sin_family = AF_INET; // add the configrations
|
||||
addr.sin_addr.s_addr = htonl(2130706433);
|
||||
addr.sin_port = htons(atoi(argv[1]));
|
||||
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
|
||||
{
|
||||
perror("bind");
|
||||
return (1);
|
||||
}
|
||||
if (listen(sfd, 10) < 0)
|
||||
{
|
||||
perror("listen");
|
||||
return (1);
|
||||
}
|
||||
maxfd = sfd; /* stdin is fd 0, so the highest is the socket */
|
||||
printf("watching stdin(0) and the listener(fd %d). Type here, or nc 127.0.0.1 %s\n",
|
||||
sfd, argv[1]);
|
||||
while (1)
|
||||
{
|
||||
FD_ZERO(&rfds); /* select destroys the set: rebuild every loop */
|
||||
FD_SET(0, &rfds);
|
||||
FD_SET(sfd, &rfds);
|
||||
if (select(maxfd + 1, &rfds, NULL, NULL, NULL) < 0)
|
||||
continue ;
|
||||
if (FD_ISSET(0, &rfds))
|
||||
{
|
||||
n = read(0, buf, sizeof(buf) - 1);
|
||||
if (n <= 0)
|
||||
{
|
||||
printf("stdin EOF — bye.\n");
|
||||
break ;
|
||||
}
|
||||
buf[n] = 0;
|
||||
printf("stdin ready: [%s]", buf);
|
||||
}
|
||||
if (FD_ISSET(sfd, &rfds))
|
||||
{
|
||||
cfd = accept(sfd, NULL, NULL);
|
||||
if (cfd < 0)
|
||||
continue ;
|
||||
printf("listener ready: accepted fd %d — reading one line...\n", cfd);
|
||||
n = recv(cfd, buf, sizeof(buf) - 1, 0);
|
||||
if (n > 0)
|
||||
{
|
||||
buf[n] = 0;
|
||||
printf(" got: [%s]", buf);
|
||||
}
|
||||
else
|
||||
printf(" recv returned %zd (EOF/error)\n", n);
|
||||
close(cfd);
|
||||
}
|
||||
}
|
||||
close(sfd);
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/* Experiment 05 — fd_set is a bitmap. See the bits, then watch select() rewrite them.
|
||||
*
|
||||
* Build: cc -Wall -Wextra -Werror 05_fdset.c -o 05_fdset
|
||||
* Run: ./05_fdset
|
||||
*
|
||||
* Part 1 (pure macros): the set is just bits. FD_ZERO/SET/CLR/ISSET only flip
|
||||
* and read bits — no fd is created, closed, or checked.
|
||||
*
|
||||
* Part 2 (real syscall): two pipes — one with a byte waiting (readable), one
|
||||
* empty (not readable). Both bits go into the set; select() returns with ONLY
|
||||
* the readable one still marked. That is the destructive rewrite that makes
|
||||
* "rebuild or copy the set every loop" mandatory in mini_serv.
|
||||
*
|
||||
* Note: FD_SET(5) in part 1 does not create fd 5. If you pass select() a bit
|
||||
* whose fd is not actually open, select fails with -1 / EBADF. Bits are not fds.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/select.h>
|
||||
#include <sys/time.h>
|
||||
|
||||
static void print16(const char *label, const fd_set *set)
|
||||
{
|
||||
int i;
|
||||
|
||||
printf("%s\n ", label);
|
||||
i = 15;
|
||||
while (i >= 0)
|
||||
{
|
||||
printf("%d", FD_ISSET(i, set) ? 1 : 0);
|
||||
if (i % 8 == 0)
|
||||
printf(" ");
|
||||
i--;
|
||||
}
|
||||
printf(" (bits 15..0)\n");
|
||||
}
|
||||
|
||||
static int max_of(int a, int b)
|
||||
{
|
||||
if (a > b)
|
||||
return (a);
|
||||
return (b);
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
fd_set set;
|
||||
struct timeval tv;
|
||||
int ready[2];
|
||||
int empty[2];
|
||||
int r;
|
||||
|
||||
printf("FD_SETSIZE = %d | sizeof(fd_set) = %zu bytes (%zu bits)\n",
|
||||
FD_SETSIZE, sizeof(fd_set), sizeof(fd_set) * 8);
|
||||
|
||||
/* ---- part 1: the macros are only bit operations ------------------- */
|
||||
FD_ZERO(&set);
|
||||
print16("FD_ZERO(&set):", &set);
|
||||
FD_SET(3, &set);
|
||||
FD_SET(5, &set);
|
||||
print16("after FD_SET(3) + FD_SET(5):", &set);
|
||||
printf("FD_ISSET(3)=%d FD_ISSET(4)=%d FD_ISSET(5)=%d\n",
|
||||
FD_ISSET(3, &set) != 0, FD_ISSET(4, &set) != 0,
|
||||
FD_ISSET(5, &set) != 0);
|
||||
FD_CLR(3, &set);
|
||||
print16("after FD_CLR(3):", &set);
|
||||
|
||||
/* ---- part 2: select() with real file descriptors ------------------ */
|
||||
if (pipe(ready) < 0 || pipe(empty) < 0)
|
||||
{
|
||||
perror("pipe");
|
||||
return (1);
|
||||
}
|
||||
if (write(ready[1], "x", 1) != 1)
|
||||
{
|
||||
perror("write");
|
||||
return (1);
|
||||
}
|
||||
printf("\nreal fds: readable pipe fd=%d (1 byte waiting), silent pipe fd=%d (empty)\n",
|
||||
ready[0], empty[0]);
|
||||
FD_ZERO(&set);
|
||||
FD_SET(ready[0], &set);
|
||||
FD_SET(empty[0], &set);
|
||||
printf("before select: FD_ISSET(readable)=%d FD_ISSET(silent)=%d\n",
|
||||
FD_ISSET(ready[0], &set) != 0, FD_ISSET(empty[0], &set) != 0);
|
||||
tv.tv_sec = 0;
|
||||
tv.tv_usec = 0;
|
||||
r = select(max_of(ready[0], empty[0]) + 1, &set, NULL, NULL, &tv);
|
||||
printf("select returned %d (number of ready fds)\n", r);
|
||||
printf("after select: FD_ISSET(readable)=%d FD_ISSET(silent)=%d <- non-ready bit GONE\n",
|
||||
FD_ISSET(ready[0], &set) != 0, FD_ISSET(empty[0], &set) != 0);
|
||||
|
||||
printf("\nConclusion: select() is an in/out parameter that keeps only ready bits.\n"
|
||||
"mini_serv therefore rebuilds or copies its set before every call.\n");
|
||||
close(ready[0]);
|
||||
close(ready[1]);
|
||||
close(empty[0]);
|
||||
close(empty[1]);
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
# Explore — four tiny programs to make the fundamentals visible
|
||||
|
||||
These are **learning toys**, not exam material. Run them once, understand what you saw,
|
||||
then forget the code (the exam is `mini_serv` only).
|
||||
|
||||
```bash
|
||||
cd explore
|
||||
for n in 01_fds 02_bind_listen 03_accept_recv 04_select_two; do
|
||||
cc -Wall -Wextra -Werror $n.c -o $n && echo "$n built"
|
||||
done
|
||||
```
|
||||
|
||||
Open two or three terminals for the experiments that need `nc`.
|
||||
|
||||
---
|
||||
|
||||
## 01 — fds are small integers, reused
|
||||
|
||||
```bash
|
||||
./01_fds
|
||||
```
|
||||
|
||||
**Look for:** `stdin=0 stdout=1 stderr=2`, then a file and a socket taking `3` and `4`, then
|
||||
the same numbers coming back after `close()`. This is the *whole* idea behind "the array
|
||||
index is the fd".
|
||||
|
||||
## 02 — listen without accept: connections queue in the kernel
|
||||
|
||||
```bash
|
||||
./02_bind_listen 8081 # terminal 1
|
||||
|
||||
# terminal 2:
|
||||
ss -tlnp | grep 8081 # LISTEN, with backlog
|
||||
nc -v 127.0.0.1 8081 # says "succeeded"!
|
||||
ss -tnp | grep 8081 # ESTABLISHED — sitting in the accept queue
|
||||
```
|
||||
|
||||
**Look for:** `nc` succeeding even though the program never called `accept()`. Then `Ctrl-C`
|
||||
the server and run `nc -v` again → **Connection refused** (nobody listening). That pair of
|
||||
observations covers 90% of "why does nc say X" questions.
|
||||
|
||||
## 03 — accept returns a NEW fd; recv gives chunks, not messages
|
||||
|
||||
```bash
|
||||
./03_accept_recv 8081 # terminal 1
|
||||
|
||||
# terminal 2 (interactive):
|
||||
nc 127.0.0.1 8081 # type slowly, then fast; press Enter; watch chunks
|
||||
|
||||
# terminal 2 (scripted split line, same connection):
|
||||
send() { exec 3<>/dev/tcp/127.0.0.1/"$1"; cat >&3; exec 3>&-; }
|
||||
{ printf 'par'; sleep 1; printf 'tial\n'; } | send 8081
|
||||
```
|
||||
|
||||
**Look for:** `listening fd = 3, conversation fd = 4`; the same line arriving in 1, 2 or 3
|
||||
`recv` events; and finally `recv returned 0` when the client goes away (EOF).
|
||||
|
||||
## 04 — select() = "wait for any of these fds"
|
||||
|
||||
```bash
|
||||
./04_select_two 8081 # terminal 1
|
||||
|
||||
# type in terminal 1 -> stdin ready
|
||||
# nc 127.0.0.1 8081 -> listener ready, accepted, one line read
|
||||
# Ctrl-D in terminal 1 -> stdin EOF, exits
|
||||
```
|
||||
|
||||
**Look for:** one `select()` call being woken by *two completely different sources*. That's
|
||||
exactly how the exam server juggles the listening socket and every client at once.
|
||||
|
||||
---
|
||||
|
||||
## 05 — `fd_set` is a bitmap, and `select` rewrites it
|
||||
|
||||
```bash
|
||||
cc -Wall -Wextra -Werror 05_fdset.c -o 05_fdset
|
||||
./05_fdset
|
||||
```
|
||||
|
||||
**Look for:** `FD_SETSIZE = 1024`; the 16-bit picture changing as you `FD_SET`/`FD_CLR`;
|
||||
then two real pipes (one with a byte, one empty) going into a set — after `select`, **only
|
||||
the readable pipe's bit survives**. That last line is the reason mini_serv rebuilds or copies
|
||||
its sets every loop. (Bonus: marking a bit for an fd that isn't open makes `select` fail with
|
||||
`EBADF` — bits are not fds.)
|
||||
|
||||
---
|
||||
|
||||
## After each experiment, write one sentence
|
||||
|
||||
What did I *see* that I didn't believe before? (e.g. "the connection exists before accept",
|
||||
"one line can arrive in pieces", "fds get reused"). Those sentences are worth more than the
|
||||
code. Then go back to `fundamentals.md` §4–§8 and read the matching section — it will feel
|
||||
obvious now.
|
||||
Executable
BIN
Binary file not shown.
+281
@@ -0,0 +1,281 @@
|
||||
# Fundamentals — the 9 ideas behind `mini_serv`
|
||||
|
||||
You said it: it's time to *understand*, not just replay. This file explains the 9 ideas the
|
||||
exam is built out of. Each idea ends with a tiny experiment (in `explore/`) that lets you
|
||||
**see** it. Do them in order — total ~45 minutes with the experiments.
|
||||
|
||||
Everything here assumes Linux (like the 42 exam sessions).
|
||||
|
||||
---
|
||||
|
||||
## 1. Everything is a file number (fd)
|
||||
|
||||
The kernel gives every process a table of open resources. **The fd (file descriptor) is the
|
||||
index into that table** — just a small integer. It doesn't matter if the "file" is a real
|
||||
file, a pipe, the terminal, or a socket: same namespace, same `read`/`write`/`close`.
|
||||
|
||||
| fd | Normally |
|
||||
|---|---|
|
||||
| 0 | stdin (your terminal input) |
|
||||
| 1 | stdout (terminal output) |
|
||||
| 2 | stderr (always write error messages here: `write(2, ...)`) |
|
||||
| 3+ | everything the program opens: files, sockets, … |
|
||||
|
||||
Two consequences the exam cares about:
|
||||
|
||||
- the kernel always reuses the **smallest free number**, so fds get recycled after `close()`;
|
||||
- `close(fd)` and then using that fd anyway = undefined behavior (usually "Bad file descriptor").
|
||||
|
||||
**Experiment 01** (`explore/01_fds.c`): prints fd numbers of a file and a socket, then closes
|
||||
them and opens again — watch the numbers get *reused*.
|
||||
|
||||
## 2. A socket is an fd that talks to the network
|
||||
|
||||
`int fd = socket(AF_INET, SOCK_STREAM, 0);` asks the kernel for a network endpoint:
|
||||
|
||||
- `AF_INET` — IPv4 (the exam uses only IPv4 and only `127.0.0.1`);
|
||||
- `SOCK_STREAM` — TCP: connection-oriented, reliable, ordered **byte stream**;
|
||||
- returns an fd, or `-1` on failure.
|
||||
|
||||
A socket is one **end** of a connection. TCP connections have two ends living in two
|
||||
processes (maybe on different machines). Yours talks to the kernel on this side and the
|
||||
kernel talks to the peer's kernel. You never see packets — you see bytes in, bytes out.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
A["your process (mini_serv)<br/>fd 3 = listening socket<br/>fd 4, 5 = client sockets"] -->|"syscalls on fd numbers"| K["kernel<br/>socket objects with send/recv buffers"]
|
||||
K <-->|"TCP byte stream (loopback here)"| B["the other process (nc, or the grader)<br/>its own fd table, its own socket"]
|
||||
```
|
||||
|
||||
## 3. Addresses, ports and byte order
|
||||
|
||||
To be reachable, a TCP endpoint needs an address: `IP : port`.
|
||||
|
||||
```c
|
||||
struct sockaddr_in addr;
|
||||
memset(&addr, 0, sizeof(addr)); /* zero first — garbage fields break bind */
|
||||
addr.sin_family = AF_INET; /* IPv4 */
|
||||
addr.sin_addr.s_addr = htonl(2130706433);/* 127.0.0.1, in network byte order */
|
||||
addr.sin_port = htons(atoi(argv[1])); /* port from argv, network byte order */
|
||||
```
|
||||
|
||||
- **Ports** are 16-bit; your program gets one as text (`"8081"`) → `atoi` turns it into a number.
|
||||
- **Byte order**: x86 stores numbers little-endian; the network protocol is big-endian.
|
||||
`htons` = host-to-network-short (16 bit, ports), `htonl` = host-to-network-long (32 bit, IPs).
|
||||
Forget them and you bind to a bizarre address.
|
||||
- `2130706433` = `0x7F000001` = the four bytes `127.0.0.1`. The subject demands you listen
|
||||
**only** on localhost, so this magic number is your friend. (`INADDR_ANY` would listen on
|
||||
every interface — wrong for this exam.)
|
||||
|
||||
## 4. Server lifecycle: socket → bind → listen → accept
|
||||
|
||||
| Call | Meaning | Analogy |
|
||||
|---|---|---|
|
||||
| `socket()` | create an endpoint | buy a phone |
|
||||
| `bind()` | attach address+port to it | get a phone number |
|
||||
| `listen()` | mark it as "accepting connections", with a backlog | open the shop, queue callers |
|
||||
| `accept()` | take **one** pending connection out of the queue; **returns a NEW fd** | answer one call |
|
||||
|
||||
The critical insight: the **listening fd keeps listening forever**; `accept()` returns a
|
||||
*different* fd — the fd of that one conversation. The exam server has: 1 listening fd +
|
||||
1 fd per connected client.
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
C1["client connect()"] --> Q
|
||||
C2["client connect()"] --> Q
|
||||
Q["accept queue (backlog 10)<br/>the kernel finishes each TCP handshake<br/>and parks the connection here"]
|
||||
L["listening fd"] --> Q
|
||||
Q -- "accept() pops ONE connection" --> S["your program gets a NEW fd for it<br/>(the listening fd keeps listening)"]
|
||||
```
|
||||
|
||||
**Experiment 02** (`explore/02_bind_listen.c`): binds and `listen`s but deliberately *never*
|
||||
calls `accept()`. Run it, then:
|
||||
|
||||
```bash
|
||||
ss -tlnp | grep PORT # your LISTEN socket, backlog visible
|
||||
nc -v 127.0.0.1 PORT # the TCP handshake COMPLETES anyway!
|
||||
ss -tnp | grep PORT # the connection sits ESTABLISHED in the accept queue
|
||||
```
|
||||
|
||||
This shows why "nc connects" ≠ "my program accepted it", and what "backlog" means: the
|
||||
kernel accepts handshakes for you and queues them until your program calls `accept()`.
|
||||
|
||||
## 5. TCP is a byte stream, not messages
|
||||
|
||||
This one is *the* exam. There are no message boundaries on a TCP connection. If the peer
|
||||
writes `"hello\nworld\n"`, then in your process:
|
||||
|
||||
- the first `recv()` may return `"hello\nworld\n"` (both lines),
|
||||
- or `"hel"`, then `"lo\nworld\n"`,
|
||||
- or `"hello\nw"`, then `"orld\n"`,
|
||||
- anything — the split is decided by the kernel, network timing, buffering… not by you.
|
||||
|
||||
Also: your `recv()` returns *up to* what you asked (`sizeof buf`) and waits if there's
|
||||
nothing available (unless the fd is non-blocking). The exam's rule is: only call `recv`
|
||||
after `select` said that fd is readable, and never assume a full line arrived.
|
||||
|
||||
Real servers therefore keep **a buffer per client** (`clients[fd].msg` in your friend's
|
||||
code) and split complete lines out of it: that's exactly `str_join` + `extract_message`.
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant W as sender writes
|
||||
participant K as kernel buffers
|
||||
participant R as your recv calls
|
||||
W->>K: "hello\nworld\n" (one write)
|
||||
K-->>R: recv gives "hel"
|
||||
R->>R: buffer = "hel"
|
||||
K-->>R: recv gives "lo\nwor"
|
||||
R->>R: buffer = "hello\nwor" then extract "hello\n"
|
||||
K-->>R: recv gives "ld\n"
|
||||
R->>R: buffer = "wor" + "ld\n" then extract "world\n"
|
||||
Note over R: one write, three chunks, lines rebuilt — never assume the split
|
||||
```
|
||||
|
||||
**Experiment 03** (`explore/03_accept_recv.c`): accepts one client and prints each `recv()`
|
||||
with its exact size. Then in another terminal:
|
||||
|
||||
```bash
|
||||
nc 127.0.0.1 PORT # type "hello" + Enter slowly, then fast, and watch the chunking
|
||||
```
|
||||
|
||||
and try the scripted split (sends "par", waits 1s, sends "tial\n" on the same connection):
|
||||
|
||||
```bash
|
||||
send() { exec 3<>/dev/tcp/127.0.0.1/"$1"; cat >&3; exec 3>&-; }
|
||||
{ printf 'par'; sleep 1; printf 'tial\n'; } | send PORT
|
||||
```
|
||||
|
||||
You'll see two `recv` events for one logical line — THAT is why the buffer exists.
|
||||
|
||||
## 6. EOF: `recv()` returns 0
|
||||
|
||||
How do you learn the peer is gone? `recv()` tells you by returning:
|
||||
|
||||
| return | meaning |
|
||||
|---|---|
|
||||
| `> 0` | that many bytes arrived |
|
||||
| `0` | **EOF** — the peer closed/shutdown its writing side (orderly close) |
|
||||
| `-1` | error (connection reset, bad fd, …) |
|
||||
|
||||
In the exam: `recv() <= 0` → broadcast `"server: client N just left\n"`, `close(fd)`, free
|
||||
the buffer. Nothing else. The leftover partial line is **not** flushed.
|
||||
|
||||
On a live `nc`, press **Ctrl-C** (process dies → kernel sends FIN → your `recv` returns 0),
|
||||
or use `nc -N` which closes the socket when its stdin hits EOF.
|
||||
|
||||
## 7. `select()` — the waiting room
|
||||
|
||||
Without select you'd need one thread per client (allowed? complicated) or blocking reads in
|
||||
a loop (you'd stall on the first idle client). `select` solves "wait for *any* of N fds":
|
||||
|
||||
```c
|
||||
fd_set readfds;
|
||||
FD_ZERO(&readfds); /* empty the set (bitmap of fds) */
|
||||
FD_SET(3, &readfds); /* add fd 3 */
|
||||
FD_SET(listen_fd, &readfds); /* add the listener */
|
||||
select(max_fd + 1, &readfds, NULL, NULL, NULL);
|
||||
/* returns when >= 1 fd in the set is readable */
|
||||
if (FD_ISSET(3, &readfds)) { /* fd 3 has data (or EOF) */ }
|
||||
```
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["FD_ZERO + FD_SET: rebuild the watch list"] --> B["select: sleep until at least one fd is ready"]
|
||||
B --> C["FD_ISSET(fd): which one(s)?"]
|
||||
C --> D["handle it, then loop back and rebuild"]
|
||||
D --> A
|
||||
```
|
||||
|
||||
| Macro / rule | Meaning |
|
||||
|---|---|
|
||||
| `FD_ZERO` | clear all bits |
|
||||
| `FD_SET(fd, &set)` | mark one fd |
|
||||
| `FD_CLR(fd, &set)` | unmark (do this when a client leaves!) |
|
||||
| `FD_ISSET(fd, &set)` | was that fd ready? |
|
||||
| `nfds = max_fd + 1` | "watch fds 0..max_fd" |
|
||||
| timeout `NULL` | block forever until something is ready |
|
||||
|
||||
Two traps that decide the exam:
|
||||
|
||||
1. **`select` is destructive.** It rewrites the sets to contain only the ready fds.
|
||||
Next iteration you must start from a fresh/master set (that's what `active_fds` is for in
|
||||
your friend's code, or the rebuild-from-array approach in `reference/mini_serv.c`).
|
||||
2. **`max_fd` must be correct.** If the newest client is fd 7 but you pass 6+1, that client
|
||||
can pile up data unnoticed.
|
||||
|
||||
Why `select` instead of `poll`? The subject's allowed list has `select`. That's the reason.
|
||||
|
||||
**Experiment 04** (`explore/04_select_two.c`): `select`s on **stdin and a listening socket**
|
||||
at once: type in the terminal → "stdin ready"; run `nc` → "listener ready". You are literally
|
||||
watching the waiting room.
|
||||
|
||||
## 8. What "readable" means per socket type
|
||||
|
||||
| Socket | "readable" means | your reaction |
|
||||
|---|---|---|
|
||||
| listening fd | a new connection is waiting in the accept queue | `accept()` |
|
||||
| client fd | bytes arrived **or EOF** is pending | `recv()`; if it returns `<= 0` → disconnect |
|
||||
|
||||
`select` also can report **writable** — and a connected TCP socket is almost always writable
|
||||
(the kernel's send buffer has room). That's why the friend's code can use `write_fds` as a
|
||||
cheap "who's still connected" list, and why *waiting for writability* is not useful here.
|
||||
|
||||
## 9. The little world your server keeps
|
||||
|
||||
```
|
||||
listening fd ── select() says readable ──► accept() ──► new client fd
|
||||
│
|
||||
for each client fd: ▼
|
||||
clients[fd].id the announced number (0,1,2,… forever, never reused)
|
||||
clients[fd].msg pending partial line (append with str_join, mine lines with
|
||||
extract_message, free it on disconnect)
|
||||
|
||||
ids ≠ fds: fd = kernel's slot number (recycled), id = your counter (monotonic).
|
||||
```
|
||||
|
||||
Ownership in one line: **whoever sees a `malloc` (or receives a `char *`) frees it.**
|
||||
`str_join` frees the old buffer; the message `extract_message` gives you is yours to free;
|
||||
the leftover buffer dies with the client; the relay string you build dies right after `send`.
|
||||
|
||||
---
|
||||
|
||||
## 10. How to test each part of YOUR `mini_serv`
|
||||
|
||||
Paste this helper in a terminal once (it's the same trick the grader uses):
|
||||
|
||||
```bash
|
||||
send() { exec 3<>/dev/tcp/127.0.0.1/"$1"; cat >&3; exec 3>&-; }
|
||||
```
|
||||
|
||||
Then, from the repo root (`./sandbox/mini_serv 8081` running in another terminal):
|
||||
|
||||
| Part of your code | Test | Expected observation |
|
||||
|---|---|---|
|
||||
| argc guard | `./mini_serv; echo $?` | `Wrong number of arguments` on stderr, exit 1 |
|
||||
| bind/listen | `ss -tlnp \| grep 8081` | a `LISTEN` line, plus the process name |
|
||||
| select loop idle sanity | `top -p $(pgrep mini_serv)` | ~0% CPU when nobody is connected (100% = set rebuild bug) |
|
||||
| accept/join | `nc 127.0.0.1 8081` (A), then again (B) | A shows `server: client 1 just arrived`, B shows nothing about itself |
|
||||
| recv flush-per-chunk bug | `{ printf 'par'; sleep 1; printf 'tial\n'; } \| send 8081` | other clients get exactly one `client N: partial` — nothing before |
|
||||
| multi-line packet | `printf 'a\nb\n' \| send 8081` | two lines: `client N: a`, `client N: b` |
|
||||
| EOF / disconnect | `printf 'abc' \| send 8081` then watch A | no text, then `server: client N just left` (partial dropped) |
|
||||
| ids never reused | connect, disconnect, connect | the new one is `client 2`, not `client 1` again |
|
||||
| relay exclusion | two `nc` windows, A types `hi` + Enter | B sees it, A doesn't |
|
||||
| leak check | `valgrind --leak-check=full --track-fds=yes ./mini_serv 8099` + one client session + Ctrl-C | no `definitely lost`, fd count stable |
|
||||
| the whole program | `bash tester/check.sh` | 13/13 + `GRADEME: PASSED` |
|
||||
|
||||
If a row misbehaves, jump to `debugging.md` §5 (symptom table).
|
||||
|
||||
---
|
||||
|
||||
## 11. Suggested 45-minute path (day 1, optional but recommended)
|
||||
|
||||
1. Read §1–§5 (20 min) with experiments 01, 02, 03 running.
|
||||
2. Read §6–§8 (15 min) with experiment 04.
|
||||
3. Read §9–§10 (10 min), then close this file and go do `drills/typing-script.md`
|
||||
Stage A + B.
|
||||
|
||||
You don't have to become a network engineer. You have to know what each fd, each call and
|
||||
each message means — that's what makes the replay code *make sense*, and what lets you
|
||||
debug it at the exam instead of panicking.
|
||||
@@ -0,0 +1,392 @@
|
||||
# libc & syscall reference — every call `mini_serv` uses, one by one
|
||||
|
||||
A lookup table, not a reading book. When a call returns `-1`, or you can't remember what
|
||||
`accept` returns, or what `nfds` means — find the entry here.
|
||||
|
||||
Context: man pages exist on 42 machines. `man 2 <syscall>` (kernel, e.g. `man 2 recv`) vs
|
||||
`man 3 <function>` (libc, e.g. `man 3 printf`). `man 7 socket`, `man 7 tcp` are gold.
|
||||
**Read the RETURN VALUE section first in any man page — it's where the bugs live.**
|
||||
|
||||
**The whole program in one picture** (every call in this file appears here):
|
||||
|
||||
```mermaid
|
||||
flowchart TD
|
||||
A["socket()"] -->|"-1"| F1["write(2, 'Fatal error\n') + exit(1)"]
|
||||
A -->|"fd >= 0"| B["bind()"]
|
||||
B -->|"!= 0"| F1
|
||||
B --> C["listen()"]
|
||||
C -->|"!= 0"| F1
|
||||
C --> L["LOOP: select() — sleep until any fd is ready"]
|
||||
L -->|"listen fd ready"| AC["accept() gives a NEW fd<br/>broadcast 'just arrived' to the others"]
|
||||
L -->|"client fd ready"| RC["recv()"]
|
||||
RC -->|"0 = EOF, or -1"| LV["broadcast 'just left'<br/>FD_CLR + close + free"]
|
||||
RC -->|"n > 0"| BUF["append to that client's buffer<br/>extract complete lines"]
|
||||
BUF --> SD["send() 'client N: line'<br/>to the other clients"]
|
||||
AC --> L
|
||||
LV --> L
|
||||
SD --> L
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 0. The four families (they behave differently)
|
||||
|
||||
| Family | Examples | Failure style |
|
||||
|---|---|---|
|
||||
| **Syscalls** (kernel) | `socket bind listen accept recv send select write close` | return `-1` and set `errno` |
|
||||
| **Macros / inline** | `FD_ZERO FD_SET FD_CLR FD_ISSET htons htonl` | can't fail, pure bit math |
|
||||
| **libc helpers** | `malloc calloc realloc free strlen strcpy strcat memset bzero sprintf atoi` | return `NULL` / garbage / nothing |
|
||||
| **Types & constants** | `fd_set sockaddr sockaddr_in socklen_t AF_INET SOCK_STREAM FD_SETSIZE` | not callable, just vocabulary |
|
||||
|
||||
---
|
||||
|
||||
## 1. Networking syscalls
|
||||
|
||||
### `socket` — create a network endpoint
|
||||
```c
|
||||
int socket(int domain, int type, int protocol);
|
||||
```
|
||||
- `domain`: `AF_INET` = IPv4 (the exam allows nothing else)
|
||||
- `type`: `SOCK_STREAM` = TCP (reliable, ordered byte stream)
|
||||
- `protocol`: `0` (default for that pair)
|
||||
- **Returns:** a new fd `>= 0`, or `-1` + errno (e.g. `EMFILE` = too many fds)
|
||||
- **Exam pattern:** `g_server = socket(AF_INET, SOCK_STREAM, 0); if (g_server < 0) fatal();`
|
||||
- **Remember:** this fd is the *listener* — it never carries chat data.
|
||||
|
||||
### `bind` — attach an address+port to a socket
|
||||
```c
|
||||
int bind(int fd, const struct sockaddr *addr, socklen_t len);
|
||||
```
|
||||
- `fd`: the socket from above
|
||||
- `addr`: your filled `sockaddr_in`, **cast** to `struct sockaddr *` (that's what the API wants)
|
||||
- `len`: `sizeof(struct sockaddr_in)` (or `sizeof(addr)` for the variable)
|
||||
- **Returns:** `0` ok, `-1` + errno
|
||||
- **Errors you'll actually see:** `EADDRINUSE` (port busy — the grader may pick another port),
|
||||
`EACCES` (privileged port, don't use <1024), `EINVAL` (already bound)
|
||||
- **Exam pattern:** fill + `if (bind(...) < 0) fatal();`
|
||||
- **Trap:** forgetting `memset`/`bzero` on the struct → garbage address fields.
|
||||
|
||||
### `listen` — mark the socket as accepting connections
|
||||
```c
|
||||
int listen(int fd, int backlog);
|
||||
```
|
||||
- `backlog`: how many *not-yet-accepted* connections the kernel may queue (exam code uses `10`)
|
||||
- **Returns:** `0` / `-1`
|
||||
- **Exam pattern:** `if (listen(g_server, 10) < 0) fatal();`
|
||||
- **Remember:** after `listen`, clients can already connect (the kernel completes the TCP
|
||||
handshake); `accept` just dequeues them. See `explore/02_bind_listen.c`.
|
||||
|
||||
### `accept` — dequeue one pending connection
|
||||
```c
|
||||
int accept(int listen_fd, struct sockaddr *addr, socklen_t *len);
|
||||
```
|
||||
- `listen_fd`: the **listening** fd (not a client)
|
||||
- `addr` / `len`: where to write the peer's address — the exam passes `NULL, NULL`
|
||||
- **Returns:** a **NEW fd** for that one conversation, or `-1` + errno
|
||||
- **Exam pattern:**
|
||||
```c
|
||||
fd = accept(g_server, NULL, NULL);
|
||||
if (fd < 0) return ; /* not fatal! */
|
||||
```
|
||||
- **Traps:**
|
||||
- it returns a *different* fd than the one you passed — the client count grows by 1 fd;
|
||||
- a fresh fd is created for **every** connection, even from the same machine;
|
||||
- far more than `backlog` clients connecting without accept → connections queue/time out.
|
||||
|
||||
### `recv` — read bytes from a connected socket
|
||||
```c
|
||||
ssize_t recv(int fd, void *buf, size_t len, int flags);
|
||||
```
|
||||
- `fd`: a **connected client** fd (never the listener)
|
||||
- `buf`, `len`: your buffer and its capacity (`sizeof buf - 1` if you null-terminate yourself)
|
||||
- `flags`: `0` here
|
||||
- **Returns:** `> 0` bytes received; `0` = **EOF** (peer closed/shutdown its writing side);
|
||||
`-1` = error + errno (`ECONNRESET`, `EBADF`, `EAGAIN` if non-blocking…)
|
||||
- **Exam pattern:** call only when `select` said the fd is readable; then
|
||||
`if (n <= 0) disconnect(fd); else { buf[n] = 0; append to client's buffer; extract lines; }`
|
||||
- **Traps:**
|
||||
- **no message boundaries** — a "line" can arrive in pieces or several lines at once;
|
||||
- `0` is not an error, it's a goodbye;
|
||||
- `-1` with `EINTR` can be retried; the official test never provokes it.
|
||||
|
||||
### `send` — write bytes to a connected socket
|
||||
```c
|
||||
ssize_t send(int fd, const void *buf, size_t len, int flags);
|
||||
```
|
||||
- **Returns:** bytes queued to the kernel (may be **less than `len`**), or `-1`
|
||||
- **Errors:** `EPIPE` (= peer gone; *also raises `SIGPIPE`*, see §6), `ECONNRESET`, `EAGAIN`
|
||||
- **Exam pattern:** `send(fd, s, strlen(s), 0);` — one call per complete message, no retry
|
||||
loops. All passing solutions do exactly this (the official test drains, so partial sends
|
||||
don't bite).
|
||||
- **Trap:** `strlen(s)` is what you send — forget it and you send garbage if `s` isn't
|
||||
terminated.
|
||||
|
||||
### `close` — release an fd
|
||||
```c
|
||||
int close(int fd);
|
||||
```
|
||||
- **Returns:** `0` / `-1`
|
||||
- **Exam pattern:** on disconnect: `FD_CLR` the client (from your master set), `close(fd)`,
|
||||
`free` its buffer.
|
||||
- **Traps:** closing an fd that's still in an `fd_set` → next `select` fails with `EBADF`;
|
||||
double `close` = UB (may close a *new* innocent fd!).
|
||||
|
||||
### `fcntl` — the subject hints at it (you don't need it)
|
||||
```c
|
||||
fcntl(fd, F_SETFL, O_NONBLOCK);
|
||||
```
|
||||
The subject says: *"you should use fcntl(fd, F_SETFL, O_NONBLOCK) but use select and NEVER
|
||||
check EAGAIN"*. Translation: in this exam, do **not** make sockets non-blocking manually and
|
||||
never loop on `EAGAIN`. Just don't call `recv`/`send` before `select` said the fd is ready.
|
||||
Passing solutions don't call `fcntl` at all.
|
||||
|
||||
---
|
||||
|
||||
## 2. Waiting: `select` and the FD_* macros
|
||||
|
||||
### The whole family is one idea: a bitmap
|
||||
|
||||
`fd_set` is **not a list of fds** — it is a fixed-size **bitmap** with one bit per fd
|
||||
number. Bit `n` = "fd `n` is in this set". There are `FD_SETSIZE` bits (1024 on Linux), so
|
||||
fd numbers `0..1023` are all you can watch.
|
||||
|
||||
```
|
||||
FD_ZERO(&set) 0000 0000 0000 0000 nobody watched
|
||||
FD_SET(3, &set) 0000 0000 0000 1000 bit 3 on
|
||||
FD_SET(5, &set) 0000 0000 0010 1000 bits 5 and 3
|
||||
FD_CLR(3, &set) 0000 0000 0010 0000 bit 3 off
|
||||
FD_ISSET(5, s) non-zero (true) is bit 5 on?
|
||||
```
|
||||
|
||||
| Member | Kind | Meaning | Exam use |
|
||||
|---|---|---|---|
|
||||
| `fd_set` | type | the bitmap itself | one `readfds` per loop + a master or rebuild |
|
||||
| `FD_SETSIZE` | constant | number of bits = 1024 = highest fd you can watch + 1 | array sizes; reject fds >= it |
|
||||
| `FD_ZERO(&s)` | macro | clear all bits | first line of every loop iteration |
|
||||
| `FD_SET(fd, &s)` | macro | turn bit `fd` on | add the listener + every live client |
|
||||
| `FD_CLR(fd, &s)` | macro | turn bit `fd` off | when a client leaves (before/at `close`) |
|
||||
| `FD_ISSET(fd, &s)` | macro | test bit `fd` | after `select`: was this fd ready? |
|
||||
| `select(nfds, &r, &w, &e, timeout)` | syscall | sleep until a watched fd is ready, then keep only the ready bits | the heartbeat |
|
||||
|
||||
Two contracts that cause almost every bug:
|
||||
|
||||
1. **`nfds` = highest fd in the set + 1.** The kernel only looks at bits `0..nfds-1`; a
|
||||
client with a higher fd is invisible. `FD_SETSIZE` is *not* the right value — `max + 1` is.
|
||||
2. **`select` rewrites the set in place** (it is an in/out parameter). On return, only the
|
||||
ready fds still have their bits. Hence: rebuild from your slot array every iteration
|
||||
(`reference/mini_serv.c`), or keep a master and copy it before each call (your friend's
|
||||
variant with `active_fds`).
|
||||
|
||||
**What "ready" means:** listening fd readable = a connection is waiting; client fd readable =
|
||||
bytes arrived **or EOF is pending** (so `FD_ISSET` does not distinguish data from goodbye —
|
||||
`recv` does).
|
||||
|
||||
**Pitfalls:** no `FD_ZERO` (garbage bits → `EBADF`/spurious readiness); checking `FD_ISSET`
|
||||
against the master instead of the copy; clearing a bit after `close` instead of before;
|
||||
**`FD_SET` only marks a bit — it does not open an fd, and selecting a bit for a closed fd
|
||||
fails with `EBADF`**; `fd >= FD_SETSIZE` (undefined/overflow); using `poll`-style thinking
|
||||
(`select`'s return is a count, not a list).
|
||||
|
||||
### `select` — sleep until any watched fd is ready
|
||||
```c
|
||||
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout);
|
||||
```
|
||||
- `nfds`: **highest fd in your sets + 1**. Wrong value = newest clients invisible.
|
||||
- `readfds`: fds you want to know "has data / new connection / EOF"
|
||||
- `writefds`: fds that can accept writes "now" (a healthy TCP socket almost always can)
|
||||
- `exceptfds`: out-of-band data — `NULL` for this exam
|
||||
- `timeout`: `NULL` = block forever (what mini_serv wants)
|
||||
- **Returns:** number of ready fds; `0` = timeout (won't happen with `NULL`); `-1` + errno
|
||||
(`EBADF` = fd in set closed/not valid; `EINVAL` = `nfds` bogus; `EINTR` = signal, retry)
|
||||
- **THE trap:** `select` **overwrites** the sets with only the ready ones. Start every
|
||||
iteration from a fresh/master set.
|
||||
- **Exam pattern:**
|
||||
```c
|
||||
FD_ZERO(&readfds);
|
||||
FD_SET(g_server, &readfds);
|
||||
for (i = 0; i <= g_maxfd; i++)
|
||||
if (g_c[i].fd != -1)
|
||||
FD_SET(i, &readfds);
|
||||
if (select(g_maxfd + 1, &readfds, NULL, NULL, NULL) < 0)
|
||||
continue ;
|
||||
```
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
M["your source of truth: master set / slots array<br/>server fd + every live client"] -->|"rebuild or copy BEFORE every select"| SE["read_fds that you pass to select()"]
|
||||
SE -->|"select returns: only the READY bits remain"| CH["FD_ISSET checks decide who to serve"]
|
||||
CH --> M
|
||||
```
|
||||
|
||||
### `FD_ZERO` / `FD_SET` / `FD_CLR` / `FD_ISSET`
|
||||
```c
|
||||
void FD_ZERO(fd_set *set);
|
||||
void FD_SET(int fd, fd_set *set);
|
||||
void FD_CLR(int fd, fd_set *set);
|
||||
int FD_ISSET(int fd, fd_set *set);
|
||||
```
|
||||
- A `fd_set` is a bitmap of fd numbers. `FD_ISSET` after `select` = "this fd is ready".
|
||||
- `FD_CLR` when a client leaves (before/at `close`) — otherwise `select` sees a dead fd.
|
||||
- **`FD_SETSIZE`** is **1024**: only fds `0..1023` can be watched at all. That's why client
|
||||
tables are `[1024]`. Fd numbers can't exceed it on Linux for this purpose.
|
||||
|
||||
---
|
||||
|
||||
## 3. I/O and formatting
|
||||
|
||||
### `write` — raw output, no formatting
|
||||
```c
|
||||
ssize_t write(int fd, const void *buf, size_t count);
|
||||
```
|
||||
- **Exam pattern (errors):** `write(2, "Fatal error\n", 12);` — fd 2 = stderr, length counted
|
||||
by *you* (12, not `strlen`).
|
||||
- Works for any fd, including sockets (`send` is just the socket-flavored variant).
|
||||
|
||||
### `read` — raw input
|
||||
Only used in toys here; in the exam server you use `recv` on sockets. Same semantics: returns
|
||||
bytes, `0` EOF, `-1` error.
|
||||
|
||||
### `sprintf` — build a string in a buffer
|
||||
```c
|
||||
int sprintf(char *dst, const char *fmt, ...);
|
||||
```
|
||||
- **Returns:** number of chars written (excluding `\0`) — junk if the buffer was too small
|
||||
(buffer overflow, no protection!).
|
||||
- **Exam patterns:** `sprintf(buf, "server: client %d just arrived\n", id);`
|
||||
and, for relay, first `malloc(strlen(line) + 64)` then `sprintf(out, "client %d: %s", id, line);`
|
||||
- **Trap:** no size argument — always size the destination for the worst case.
|
||||
|
||||
---
|
||||
|
||||
## 4. Strings
|
||||
|
||||
| Call | Purpose | Returns / traps |
|
||||
|---|---|---|
|
||||
| `size_t strlen(const char *s)` | length without `\0` | UB if `s` is not terminated / `NULL` |
|
||||
| `char *strcpy(char *dst, const char *src)` | copy incl. `\0` | no bounds check |
|
||||
| `char *strcat(char *dst, const char *src)` | append at the end of `dst` | `dst` must be big enough |
|
||||
| `int strcmp(const char *a, const char *b)` | compare | `0` = equal |
|
||||
| `char *strstr(const char *hay, const char *needle)` | find substring | `NULL` if absent — allowed in the exam but the given helpers make it unnecessary |
|
||||
| `void *memset(void *s, int c, size_t n)` | fill bytes | the standard zeroing: `memset(&addr, 0, sizeof(addr))` |
|
||||
| `void bzero(void *s, size_t n)` | zero (legacy) | same as `memset(s, 0, n)`; the exam's `main.c` uses it |
|
||||
|
||||
`str_join` and `extract_message` (given in the exam's `main.c`) are built from these — see
|
||||
`architecture.md` §3.6 for their contract; **you don't memorize them, you copy them.**
|
||||
|
||||
---
|
||||
|
||||
## 5. Memory
|
||||
|
||||
| Call | Purpose | Returns / rules |
|
||||
|---|---|---|
|
||||
| `void *malloc(size_t n)` | n uninitialized bytes | `NULL` on failure — check it |
|
||||
| `void *calloc(size_t n, size_t size)` | `n*size` bytes, zeroed | used by `extract_message` |
|
||||
| `void *realloc(void *p, size_t n)` | resize | allowed, but the helpers avoid it |
|
||||
| `void free(void *p)` | release | `free(NULL)` is OK; double free = UB |
|
||||
|
||||
**Ownership rule** (from `architecture.md` §3.9): every `char *` handed to you by a helper is
|
||||
yours to `free()`; every client's leftover buffer is freed when the client disconnects. The
|
||||
leak check exists — the final reminder "Memory or fd leaks are forbidden".
|
||||
|
||||
---
|
||||
|
||||
## 6. SIGPIPE — the silent killer (know about it, don't fear it)
|
||||
|
||||
`send` on a socket whose peer reset the connection fails with `EPIPE` **and raises SIGPIPE**.
|
||||
Default action of SIGPIPE: **kill your process**. So a server can die with *no message* —
|
||||
exit code `141` (128 + 13).
|
||||
|
||||
- The official test never kills a peer while messages are in flight (clients leave one by
|
||||
one), so passing solutions don't handle it.
|
||||
- Optional armor if you finish early:
|
||||
- `send(fd, buf, len, MSG_NOSIGNAL);` (Linux: suppresses SIGPIPE per call — only `send` is
|
||||
involved, which is allowed), or
|
||||
- `signal(SIGPIPE, SIG_IGN);` — but `signal` is **not** in the subject's allowed list, so
|
||||
only if your campus's grader tolerates it.
|
||||
- Diagnosing: server "mysteriously dies" → `echo $?` → `141`.
|
||||
|
||||
---
|
||||
|
||||
## 7. Types, structs, constants
|
||||
|
||||
### `struct sockaddr_in` — "an IPv4 address + port"
|
||||
```c
|
||||
struct sockaddr_in {
|
||||
sa_family_t sin_family; /* AF_INET */
|
||||
in_port_t sin_port; /* htons(port) */
|
||||
struct in_addr sin_addr; /* .s_addr = htonl(ip) */
|
||||
char sin_zero[8]; /* padding: memset it all */
|
||||
};
|
||||
struct in_addr { uint32_t s_addr; };
|
||||
```
|
||||
|
||||
### `struct sockaddr` — the generic type in the API
|
||||
`bind`/`accept` are declared with `struct sockaddr *` (because C has no generics). You fill
|
||||
`sockaddr_in` and **cast**: `(struct sockaddr *)&addr`. The kernel checks `sin_family` to
|
||||
know which concrete struct you meant.
|
||||
|
||||
### `socklen_t` — address length
|
||||
Just an integer type for "size of that address struct" (in/out param of `accept`). With
|
||||
`NULL` peer you never meet it in the exam.
|
||||
|
||||
### `fd_set`, `FD_SETSIZE`
|
||||
Opaque bitmap of fds; `FD_SETSIZE` = 1024 = the hard ceiling for fds watched by `select`.
|
||||
|
||||
### `size_t` vs `ssize_t`
|
||||
`size_t`: unsigned count (lengths). `ssize_t`: signed — because results need a `-1`.
|
||||
If you print them: `%zu` / `%zd`.
|
||||
|
||||
### Constants
|
||||
| Constant | Meaning |
|
||||
|---|---|
|
||||
| `AF_INET` | IPv4 |
|
||||
| `SOCK_STREAM` | TCP |
|
||||
| `INADDR_ANY` | "bind on all interfaces" — **wrong for this subject** (localhost only) |
|
||||
| `2130706433` | `0x7F000001` = 127.0.0.1, used with `htonl` |
|
||||
| `FD_SETSIZE` | 1024 |
|
||||
| `SOMAXCONN` | some solutions use it as backlog (`180`ish); `10` is fine |
|
||||
|
||||
### Byte order: `htons` / `htonl` / `ntohs` / `ntohl`
|
||||
Host ↔ network byte order. Ports are 16-bit (`htons`), IPv4 addresses 32-bit (`htonl`).
|
||||
They are **not literally in the subject's allowed list**, but the exam's own `main.c` uses
|
||||
them — so they're de facto required and accepted. No `ntoh*` needed in this exam.
|
||||
|
||||
---
|
||||
|
||||
## 8. `errno` — why did it return `-1`?
|
||||
|
||||
Failing syscalls set the global `int errno` (`#include <errno.h>`). During development:
|
||||
|
||||
```c
|
||||
perror("bind"); /* prints: bind: Address already in use */
|
||||
fprintf(stderr, "recv: %d (%s)\n", errno, strerror(errno));
|
||||
```
|
||||
|
||||
`perror` and `strerror` are **dev-only** here (not in the exam's allowed list) — delete them
|
||||
before submission. The errno values you'll actually meet:
|
||||
|
||||
| errno | Means | Usual appearance |
|
||||
|---|---|---|
|
||||
| `EADDRINUSE` | address already bound | `bind` fails — another server on the port |
|
||||
| `EBADF` | bad fd number | closed fd still in an `fd_set`; `select` fails |
|
||||
| `EINTR` | interrupted by a signal | `select` — safe to retry (`continue`) |
|
||||
| `EAGAIN`/`EWOULDBLOCK` | would block | you called recv/send on a non-blocking fd with no readiness — in this exam: a bug in your select usage |
|
||||
| `ECONNRESET` | peer vanished abruptly | `recv`/`send` — treat like "client left" |
|
||||
| `EPIPE` | peer gone | `send` — see §6 |
|
||||
| `EINVAL` | invalid argument | `nfds` > `FD_SETSIZE` or nonsense; also `listen` on a bound-but-not-socket |
|
||||
|
||||
---
|
||||
|
||||
## 9. Who calls whom — the exam program map
|
||||
|
||||
| Stage (`typing-script.md`) | Calls used |
|
||||
|---|---|
|
||||
| A — structs/globals/fatal | `write`, `exit`, `free` |
|
||||
| B — socket setup | `socket`, `memset`/`bzero`, `htons`, `htonl`, `atoi`, `bind`, `listen` |
|
||||
| C — loop + accept | `FD_ZERO`, `FD_SET`, `select`, `accept`, `sprintf`, `send` |
|
||||
| D — read path | `recv`, `strlen`, `str_join`, `extract_message`, `malloc`, `sprintf`, `send`, `free` |
|
||||
| E — disconnect | `sprintf`, `send`, `FD_CLR`, `close`, `free` |
|
||||
| F — grading | the testers (`tester/check.sh`) |
|
||||
|
||||
And the two helpers you get for free (`subject/main.c`): `str_join`, `extract_message` — plus
|
||||
that file's socket boilerplate whose calls are all in this reference.
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
# Man pages — the offline documentation you'll actually use
|
||||
|
||||
> In the exam there is no internet. Man pages are local, instant, and exam-legal — they are
|
||||
> the only "documentation site" you get. Most students never open them. You will.
|
||||
|
||||
Check availability per page with `man -w 2 recv`; read with `man 2 recv`.
|
||||
|
||||
---
|
||||
|
||||
## 0. Man-page literacy (2 minutes, pays off forever)
|
||||
|
||||
| Section | Content | Example here |
|
||||
|---|---|---|
|
||||
| 1 | user commands | `nc`, `valgrind`, `gdb`, `bash` |
|
||||
| 2 | **system calls** | `socket`, `select`, `recv` |
|
||||
| 3 | **library functions** | `malloc`, `strlen`, `errno`, `htonl` |
|
||||
| 5 | file formats | `proc` (`/proc/PID/fd`) |
|
||||
| 7 | concepts/overviews | `socket`, `tcp`, `signal` |
|
||||
| 8 | admin tools | `ss` |
|
||||
|
||||
- `man -k select` (apropos) — search by keyword when you don't know the page name.
|
||||
- `man 2 select` — force a section when names collide (`printf(1)` shell vs `printf(3)` C).
|
||||
- Inside the pager: `/RETURN VALUE` search, `n` next hit, `G` bottom, `q` quit.
|
||||
- **Read the bottom half first.** RETURN VALUE, ERRORS, NOTES, EXAMPLES, SEE ALSO are where
|
||||
the answers are. Skip HISTORY/BUGS/COLOPHON.
|
||||
- Plain output you can grep:
|
||||
```bash
|
||||
man -P cat 2 select | col -b | less
|
||||
man -P cat 2 select | col -b | sed -n '/RETURN VALUE/,/^ERRORS/p'
|
||||
```
|
||||
- Save a page offline for your notes: `man -P cat 2 recv | col -b > recv.txt`.
|
||||
|
||||
---
|
||||
|
||||
## 1. The core 10 (if you read nothing else)
|
||||
|
||||
| # | Page | Why it matters for mini_serv |
|
||||
|---|---|---|
|
||||
| 1 | `man 2 select_tut` | **A full tutorial with a working select-server example.** The closest thing to a solved mini_serv in the docs |
|
||||
| 2 | `man 2 select` | The exact contract: `nfds`, the three sets, destructive overwrite, return values |
|
||||
| 3 | `man 7 socket` | What AF_INET / SOCK_STREAM are; socket options (`SO_REUSEADDR`) |
|
||||
| 4 | `man 2 socket` · `man 2 bind` · `man 2 listen` · `man 2 accept` | The server lifecycle; backlog; accept queue; why accept returns a new fd |
|
||||
| 5 | `man 2 recv` · `man 2 send` | Return values (`0` = EOF!), flags, partial sends |
|
||||
| 6 | `man 2 close` | Cleanup; NOTES explains close vs shutdown |
|
||||
| 7 | `man 7 signal` | The SIGPIPE default action (exam exit code 141) |
|
||||
| 8 | `man 3 errno` · `man 3 perror` · `man 3 strerror` | Decoding every `-1`: EADDRINUSE, EBADF, EINTR, EPIPE… |
|
||||
| 9 | `man 8 ss` · `man 1 nc` | Seeing LISTEN/ESTABLISHED and talking to your server |
|
||||
| 10 | `man 5 proc` | `/proc/PID/fd` — your fd-leak microscope |
|
||||
|
||||
---
|
||||
|
||||
## 2. Full curated index (grouped)
|
||||
|
||||
### A. Sockets — the server's body
|
||||
|
||||
| Page | What you learn | Gym link |
|
||||
|---|---|---|
|
||||
| `man 2 socket` | domain/type/protocol; fd returned | Station 3 |
|
||||
| `man 2 bind` | tying address+port; `EADDRINUSE`, `EACCES` | Station 4 |
|
||||
| `man 2 listen` | backlog = queue of completed-but-unaccepted connections | Station 4, `explore/02` |
|
||||
| `man 2 accept` | dequeue one connection; **returns a new fd**; when it can fail | Station 7 |
|
||||
| `man 2 connect` | the client side (what `nc` does) | context only |
|
||||
| `man 2 send` | partial sends, `EPIPE`, `MSG_NOSIGNAL` | Station 10, libc-ref §6 |
|
||||
| `man 2 recv` | `0` = EOF, `-1` = error, no message boundaries | Station 9 |
|
||||
| `man 2 close` | releasing fds; close-vs-shutdown notes | Station 11 |
|
||||
| `man 2 shutdown` | half-close semantics (not needed, but explains what peers do) | optional |
|
||||
| `man 2 setsockopt` | `SO_REUSEADDR` — why a restart sometimes says "Address already in use" | debugging |
|
||||
| `man 2 getsockname` · `man 2 getpeername` | identifying endpoints (useful trace prints) | debugging |
|
||||
| `man 7 ip` | `sockaddr_in`, `sin_addr`, `sin_port` layout | Station 3 |
|
||||
| `man 3 inet_addr` · `man 3 inet_ntoa` · `man 3 inet_pton` | address ↔ text (`127.0.0.1` ↔ bytes) — not required, great for debug prints | optional |
|
||||
| `man 3 htons` → **byteorder(3)** | htons/htonl/ntohs/ntohl in one page | Station 3 |
|
||||
| `man 7 tcp` | TCP behavior, socket options, state names | fundamentals §5 |
|
||||
|
||||
### B. Waiting room — select and friends
|
||||
|
||||
| Page | What you learn | Gym link |
|
||||
|---|---|---|
|
||||
| `man 2 select` | sets, `nfds = max+1`, destructive overwrite, EINTR/EBADF | Station 6 |
|
||||
| `man 2 select_tut` | **worked example server** — read this one with coffee | Station 6 |
|
||||
| `man 2 poll` | the fd-array alternative (not allowed; helps you understand why select is clunky) | optional |
|
||||
| `man 7 epoll` | how real servers scale (not exam material) | optional |
|
||||
|
||||
### C. Errors and signals
|
||||
|
||||
| Page | What you learn | Gym link |
|
||||
|---|---|---|
|
||||
| `man 3 errno` | the errno mechanism + full name list | debugging §8 |
|
||||
| `man 3 perror` · `man 3 strerror` | printable error strings (dev-only here) | debugging §8 |
|
||||
| `man 7 signal` | every signal + default action; SIGPIPE kills by default | libc-ref §6 |
|
||||
| `man 7 signal-safety` | why async-signal-safety matters (signal() isn't in this exam) | optional |
|
||||
| `man 3 exit` | exit status conventions, flushing | Station 2 |
|
||||
|
||||
### D. Bytes, strings, memory, formatting (section 3)
|
||||
|
||||
| Page | Use in mini_serv |
|
||||
|---|---|
|
||||
| `man 3 strlen` | lengths; UB if unterminated |
|
||||
| `man 3 strcpy` · `man 3 strcat` | copies/appends used by the given helpers |
|
||||
| `man 3 strcmp` · `man 3 strstr` | allowed; rarely needed |
|
||||
| `man 3 memset` · `man 3 bzero` | zeroing `sockaddr_in`; the exam `main.c` uses bzero |
|
||||
| `man 3 malloc` · `man 3 calloc` · `man 3 realloc` · `man 3 free` | per-client buffers; `free(NULL)` is fine |
|
||||
| `man 3 sprintf` | building `"client %d: %s"` (size it: `strlen + 64`) |
|
||||
| `man 3 snprintf` | the safe variant (learning; not in the allowed list) |
|
||||
| `man 3 atoi` | port parsing; no error detection |
|
||||
|
||||
### E. Debugging & observation (the other half of the skill)
|
||||
|
||||
| Page | What it gives you |
|
||||
|---|---|
|
||||
| `man 8 ss` | `-t -l -n -p` flags; listening/established states; filters |
|
||||
| `man 1 nc` | `-N` (close after stdin EOF), `-v`, `-l`; what "connected" means |
|
||||
| `man 5 proc` | `/proc/PID/fd` (fd tables), `status`, `maps` — search for "fd" |
|
||||
| `man 1 valgrind` | leak-check and fd-tracking flags |
|
||||
| `man 1 gdb` | `-ex run -ex bt`, attaching, batch mode |
|
||||
| `man 1 top` · `man 1 ps` | CPU% and process state (the 100%-CPU signature) |
|
||||
| `man 1 bash` | the grader's `/dev/tcp/host/port` trick is documented here (REDIRECTIONS) |
|
||||
| `man lsof` | open files/fds per process (alternative to /proc) |
|
||||
| `man 7 man-pages` | conventions + which section to look in |
|
||||
| `man 2 intro` · `man 2 syscalls` | what syscalls exist at all (check the allowed list) |
|
||||
|
||||
**Missing on this machine (checked):** `strace(1)` and `netstat(1)` pages — strace isn't
|
||||
installed either; use `ss(8)` and gdb/valgrind instead. Note `errno` is **section 3**, and
|
||||
`htons/htonl` live in **byteorder(3)**, not section 7.
|
||||
|
||||
---
|
||||
|
||||
## 3. Suggested reading paths
|
||||
|
||||
**Path A — sockets literacy (45 min, day 1)**
|
||||
`7 socket` → `2 socket` → `2 bind` → `2 listen` → `2 accept` → `2 connect` (skim) →
|
||||
`2 recv` → `2 send` → `2 close` → `2 select_tut` (read fully) → `7 signal` (SIGPIPE row).
|
||||
|
||||
**Path B — debugging kit (20 min, day 2)**
|
||||
`8 ss` → `1 nc` → `5 proc` (fd part) → `3 errno` → `3 perror` → `1 valgrind` → `1 gdb`.
|
||||
|
||||
**Path C — exam-eve refresher (10 min, day 3)**
|
||||
`2 listen` (backlog) → `2 accept` (new fd) → `2 recv` (0 = EOF) → `2 select` (nfds,
|
||||
overwrite) → `7 signal` (SIGPIPE) → `3 exit` (status codes).
|
||||
|
||||
---
|
||||
|
||||
## 4. Power moves
|
||||
|
||||
```bash
|
||||
man -k "file descriptor" # when you don't know the page name
|
||||
man -P cat 2 accept | col -b | sed -n '/RETURN VALUE/,/^ERRORS/p'
|
||||
man -P cat 7 signal | col -b | grep -A2 SIGPIPE # default action, one line
|
||||
man -P cat 2 listen | col -b | grep -B2 -A8 backlog # the queue explanation
|
||||
man 2 socket # then follow SEE ALSO → socket(7) → tcp(7)
|
||||
```
|
||||
|
||||
`SEE ALSO` at the bottom of every page is a curated reading list. Following
|
||||
`socket(2) → socket(7) → tcp(7) → ip(7)` teaches you the whole network stack in four hops,
|
||||
in the order the docs intend.
|
||||
|
||||
---
|
||||
|
||||
## 5. How to practise man pages (yes, practise)
|
||||
|
||||
1. Open `man 2 recv`, cover the screen, and answer: what are the three return cases?
|
||||
2. `man 2 select` — find `nfds` and explain the destructive-overwrite warning out loud.
|
||||
3. `man 7 signal` — find SIGPIPE's default action and connect it to exit code 141.
|
||||
4. `man 8 ss` — find the flag that shows the owning process (`-p`), use it on your server.
|
||||
5. `man 5 proc` — find the fd directory and use it in a leak test.
|
||||
|
||||
If you can do those five without scrolling in panic, you're ready for any error the exam
|
||||
throws at you.
|
||||
Executable
BIN
Binary file not shown.
@@ -0,0 +1,295 @@
|
||||
/* ============================================================================
|
||||
* THE EXAM'S main.c — ANNOTATED STUDY COPY
|
||||
*
|
||||
* Code below is verbatim from the exam attachment (subject/main.c), comments
|
||||
* added. This is what you receive in the exam, and what you must triage in the
|
||||
* first 2 minutes.
|
||||
*
|
||||
* It does NOT compile as-is on a modern gcc (verified): calloc, malloc, free,
|
||||
* exit, printf, bzero are used without <stdlib.h>/<stdio.h>/<strings.h>, and
|
||||
* `int len` is passed where accept() wants socklen_t *. It is not supposed to
|
||||
* be compiled — the subject warns it "uses forbidden functions or writes
|
||||
* things that must not be there in your final program".
|
||||
*
|
||||
* HOW TO USE IT IN THE EXAM:
|
||||
* 1. KEEP extract_message() and str_join() — copy them verbatim into your file.
|
||||
* 2. THROW AWAY main() — it is a one-client demo with a hardcoded port.
|
||||
* 3. Reuse the socket setup LINES (socket/sockaddr/bind/listen) from main().
|
||||
* 4. Never ship printf/exit(0): errors are "Wrong number of arguments\n" /
|
||||
* "Fatal error\n" on stderr + exit status 1.
|
||||
*
|
||||
* Stage map:
|
||||
* B <- the socket setup lines in main()
|
||||
* C <- you add: slots, the select loop, accept, arrival broadcast
|
||||
* D <- you add: recv + str_join + extract_message + relay
|
||||
* E <- you add: recv<=0 -> "just left", close, free
|
||||
* ==========================================================================*/
|
||||
|
||||
#include <errno.h> /* unused here; not needed in your file */
|
||||
#include <string.h> /* strlen, strcpy, strcat, bzero */
|
||||
#include <unistd.h> /* write, close */
|
||||
#include <netdb.h> /* unused here; not needed in your file */
|
||||
#include <sys/socket.h> /* socket, bind, listen, accept, send, recv */
|
||||
#include <netinet/in.h> /* sockaddr_in, htonl, htons */
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h> // sprintf
|
||||
#include <sys/select.h> // fd_set + FDs
|
||||
#include <unistd.h>
|
||||
/* MISSING (you add in your file): <stdlib.h> for malloc/calloc/free/exit/atoi,
|
||||
* <stdio.h> for sprintf, <sys/select.h> for select + FD_* macros. */
|
||||
|
||||
typedef struct s_client
|
||||
{
|
||||
int id;
|
||||
int fd;
|
||||
char *buf;
|
||||
} t_client;
|
||||
|
||||
static t_client g_client[FD_SETSIZE];
|
||||
static int g_server;
|
||||
static int g_maxfds;
|
||||
static int g_next_id;
|
||||
|
||||
void fatal(void)
|
||||
{
|
||||
write(2, "fatal error\n", 12);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------------- *
|
||||
* extract_message — pull ONE complete \n-terminated line out of *buf.
|
||||
*
|
||||
* CONTRACT (memorize the three return values, not the body):
|
||||
* 1 -> a line was found: *msg points at it (you must free(*msg)),
|
||||
* *buf now holds the remainder
|
||||
* 0 -> no '\n' yet: keep waiting, nothing to send
|
||||
* -1 -> allocation failure: treat as "Fatal error\n" + exit 1
|
||||
*
|
||||
* This is THE function that makes TCP's arbitrary chunking irrelevant.
|
||||
* Call it in a loop after every append — a single recv may contain several
|
||||
* lines, and a line may span several recv calls.
|
||||
* ------------------------------------------------------------------------- */
|
||||
int extract_message(char **buf, char **msg)
|
||||
{
|
||||
char *newbuf;
|
||||
int i;
|
||||
|
||||
*msg = 0;
|
||||
if (*buf == 0)
|
||||
return (0);
|
||||
i = 0;
|
||||
while ((*buf)[i])
|
||||
{
|
||||
if ((*buf)[i] == '\n')
|
||||
{
|
||||
newbuf = calloc(1, sizeof(*newbuf) * (strlen(*buf + i + 1) + 1));
|
||||
if (newbuf == 0)
|
||||
return (-1);
|
||||
strcpy(newbuf, *buf + i + 1);
|
||||
*msg = *buf;
|
||||
(*msg)[i + 1] = 0;
|
||||
*buf = newbuf;
|
||||
return (1);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return (0);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------- *
|
||||
* str_join — append `add` to `buf`, return a NEW heap string, free old `buf`.
|
||||
* Returns NULL on allocation failure. Handles buf == NULL (new buffer).
|
||||
*
|
||||
* This is how a per-client pending buffer grows across recv calls. The exam
|
||||
* gives it to you; copy it verbatim. Leak rule: the function frees the old
|
||||
* buffer itself; you free the final buffer when the client disconnects.
|
||||
* ------------------------------------------------------------------------- */
|
||||
char *str_join(char *buf, char *add)
|
||||
{
|
||||
char *newbuf;
|
||||
int len;
|
||||
|
||||
if (buf == 0)
|
||||
len = 0;
|
||||
else
|
||||
len = strlen(buf);
|
||||
newbuf = malloc(sizeof(*newbuf) * (len + strlen(add) + 1));
|
||||
if (newbuf == 0)
|
||||
return (0);
|
||||
newbuf[0] = 0;
|
||||
if (buf != 0)
|
||||
strcat(newbuf, buf);
|
||||
free(buf);
|
||||
strcat(newbuf, add);
|
||||
return (newbuf);
|
||||
}
|
||||
|
||||
|
||||
|
||||
void to_all_except(int fd, char *msg)
|
||||
{
|
||||
int i;
|
||||
|
||||
i = 0;
|
||||
while (i <= g_maxfds)
|
||||
{
|
||||
if (i != fd && g_client[i].fd != -1)
|
||||
{
|
||||
send(g_client[i].fd, msg, strlen(msg), 0);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void accept_new(void)
|
||||
{
|
||||
char tmp[64];
|
||||
int fd;
|
||||
|
||||
fd = accept(g_server, NULL, NULL);
|
||||
if (fd < 0)
|
||||
return ;
|
||||
g_client[fd].id = g_next_id++;
|
||||
g_client[fd].fd = fd;
|
||||
g_client[fd].buf = NULL;
|
||||
if(fd > g_maxfds)
|
||||
g_maxfds = fd;
|
||||
sprintf(tmp, "server: client %d just arrived\n", g_client[fd].id);
|
||||
to_all_except(fd, tmp);
|
||||
}
|
||||
|
||||
|
||||
void disconnect(int fd)
|
||||
{
|
||||
int id;
|
||||
char tmp[64];
|
||||
|
||||
id = g_client[fd].id;
|
||||
g_client[fd].id = -1;
|
||||
g_client[fd].fd = -1;
|
||||
if(g_client[fd].buf)
|
||||
free(g_client[fd].buf);
|
||||
if(g_maxfds > g_server && g_client[g_maxfds].fd == -1)
|
||||
g_maxfds--;
|
||||
sprintf(tmp, "client: %d just left\n", id);
|
||||
to_all_except(-1, tmp);
|
||||
close(fd);
|
||||
}
|
||||
|
||||
|
||||
void handle_read(int fd)
|
||||
{
|
||||
char buff[1046];
|
||||
char *msg;
|
||||
char *out;
|
||||
int n;
|
||||
|
||||
n = recv(fd,buff, sizeof(buff) - 1, 0);
|
||||
if (n <= 0)
|
||||
{
|
||||
disconnect(fd);
|
||||
return ;
|
||||
}
|
||||
buff[n] = 0;
|
||||
g_client[fd].buf = str_join(g_client[fd].buf, buff);
|
||||
if(!g_client[fd].buf)
|
||||
fatal();
|
||||
while(extract_message(&g_client[fd].buf, &msg))
|
||||
{
|
||||
out = malloc(strlen(msg)+ 64);
|
||||
if(!out)
|
||||
{
|
||||
free(msg);
|
||||
fatal();
|
||||
}
|
||||
sprintf(out, "client %d: %s", g_client[fd].id, msg);
|
||||
to_all_except(fd, out);
|
||||
free(out);
|
||||
out = NULL;
|
||||
free(msg);
|
||||
msg = NULL;
|
||||
}
|
||||
}
|
||||
/* ------------------------------------------------------------------------- *
|
||||
* main — A DEMO, NOT A SOLUTION. Replace it entirely.
|
||||
*
|
||||
* What is wrong with it (why you rewrite main):
|
||||
* - no argc check, no "Wrong number of arguments\n";
|
||||
* - hardcoded port 8081 instead of atoi(argv[1]);
|
||||
* - printf() everywhere (forbidden) and exit(0) on errors (must be exit 1
|
||||
* with "Fatal error\n" on stderr);
|
||||
* - accepts ONE client and then does nothing with it: no select loop, no
|
||||
* ids, no broadcast, no disconnect handling;
|
||||
* - `int len` is passed to accept() which wants socklen_t *.
|
||||
*
|
||||
* What is worth keeping: the exact socket/sockaddr/bind/listen lines.
|
||||
* ------------------------------------------------------------------------- */
|
||||
int main(int argc, char **argv) {
|
||||
fd_set readfds, writefds;
|
||||
struct sockaddr_in serveraddr;
|
||||
int i;
|
||||
|
||||
if (argc != 2)
|
||||
fatal();
|
||||
// socket create and verification
|
||||
g_server = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (g_server < 0)
|
||||
fatal();
|
||||
bzero(&serveraddr, sizeof(serveraddr)); /* KEEP: must zero the struct */
|
||||
|
||||
// assign IP, PORT
|
||||
serveraddr.sin_family = AF_INET; /* KEEP: IPv4 */
|
||||
serveraddr.sin_addr.s_addr = htonl(2130706433); //127.0.0.1 /* KEEP: localhost only */
|
||||
serveraddr.sin_port = htons(atoi(argv[1])); /* in your file: htons(atoi(argv[1])) */
|
||||
|
||||
// Binding newly created socket to given IP and verification
|
||||
if ((bind(g_server, (const struct sockaddr *)&serveraddr, sizeof(serveraddr))) < 0)
|
||||
fatal();
|
||||
if (listen(g_server, 10) < 0)
|
||||
fatal();
|
||||
i = 0;
|
||||
while (i < FD_SETSIZE)
|
||||
{
|
||||
g_client[i].id = -1;
|
||||
g_client[i].fd = -1;
|
||||
g_client[i].buf = NULL;
|
||||
i++;
|
||||
}
|
||||
g_maxfds = g_server;
|
||||
|
||||
while(1)
|
||||
{
|
||||
// init the server fds inside the set for read / write
|
||||
FD_ZERO(&readfds);
|
||||
FD_ZERO(&writefds);
|
||||
FD_SET(g_server, &readfds);
|
||||
FD_SET(g_server, &writefds);
|
||||
// init the client fds in the set for read / write
|
||||
i = 0;
|
||||
while (i < FD_SETSIZE)
|
||||
{
|
||||
if (g_client[i].id != -1)
|
||||
{
|
||||
FD_SET(g_client[i].fd, &readfds);
|
||||
FD_SET(g_client[i].fd, &writefds);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
if(select(g_maxfds + 1, &readfds, &writefds, NULL, NULL) < 0)
|
||||
continue;
|
||||
if (FD_ISSET(g_server, &readfds))
|
||||
accept_new();
|
||||
i = 0;
|
||||
while(i <= g_maxfds)
|
||||
{
|
||||
if (i != g_server && g_client[i].fd != -1 && FD_ISSET(i, &readfds))
|
||||
handle_read(i);
|
||||
i++;
|
||||
}
|
||||
|
||||
}
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
/* ============================================================================
|
||||
* THE EXAM'S main.c — ANNOTATED STUDY COPY
|
||||
*
|
||||
* Code below is verbatim from the exam attachment (subject/main.c), comments
|
||||
* added. This is what you receive in the exam, and what you must triage in the
|
||||
* first 2 minutes.
|
||||
*
|
||||
* It does NOT compile as-is on a modern gcc (verified): calloc, malloc, free,
|
||||
* exit, printf, bzero are used without <stdlib.h>/<stdio.h>/<strings.h>, and
|
||||
* `int len` is passed where accept() wants socklen_t *. It is not supposed to
|
||||
* be compiled — the subject warns it "uses forbidden functions or writes
|
||||
* things that must not be there in your final program".
|
||||
*
|
||||
* HOW TO USE IT IN THE EXAM:
|
||||
* 1. KEEP extract_message() and str_join() — copy them verbatim into your file.
|
||||
* 2. THROW AWAY main() — it is a one-client demo with a hardcoded port.
|
||||
* 3. Reuse the socket setup LINES (socket/sockaddr/bind/listen) from main().
|
||||
* 4. Never ship printf/exit(0): errors are "Wrong number of arguments\n" /
|
||||
* "Fatal error\n" on stderr + exit status 1.
|
||||
*
|
||||
* Stage map:
|
||||
* B <- the socket setup lines in main()
|
||||
* C <- you add: slots, the select loop, accept, arrival broadcast
|
||||
* D <- you add: recv + str_join + extract_message + relay
|
||||
* E <- you add: recv<=0 -> "just left", close, fr#include <sys/select.h>ee
|
||||
* ==========================================================================*/
|
||||
|
||||
#include <errno.h> /* unused here; not needed in your file */
|
||||
#include <string.h> /* strlen, strcpy, strcat, bzero */
|
||||
#include <unistd.h> /* write, close */
|
||||
#include <netdb.h> /* unused here; not needed in your file */
|
||||
#include <sys/socket.h> /* socket, bind, listen, accept, send, recv */
|
||||
#include <netinet/in.h> /* sockaddr_in, htonl, htons */
|
||||
#include <sys/select.h>
|
||||
#include <sys/socket.h>
|
||||
/* MISSING (you add in your file): <stdlib.h> for malloc/calloc/free/exit/atoi,
|
||||
* <stdio.h> for sprintf, <sys/select.h> for select + FD_* macros. */
|
||||
|
||||
|
||||
|
||||
|
||||
static int g_id[FD_SETSIZE];
|
||||
static char *g_buffer[FD_SETSIZE];
|
||||
static int g_server, g_maxfd, g_nextid;
|
||||
|
||||
static void fatal(void)
|
||||
{
|
||||
write(2, "Fatal error\n", 12);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------- *
|
||||
* extract_message — pull ONE complete \n-terminated line out of *buf.
|
||||
*
|
||||
* CONTRACT (memorize the three return values, not the body):
|
||||
* 1 -> a line was found: *msg points at it (you must free(*msg)),
|
||||
* *buf now holds the remainder
|
||||
* 0 -> no '\n' yet: keep waiting, nothing to send
|
||||
* -1 -> allocation failure: treat as "Fatal error\n" + exit 1
|
||||
*
|
||||
* This is THE function that makes TCP's arbitrary chunking irrelevant.
|
||||
* Call it in a loop after every append — a single recv may contain several
|
||||
* lines, and a line may span several recv calls.
|
||||
* ------------------------------------------------------------------------- */
|
||||
int extract_message(char **buf, char **msg)
|
||||
{
|
||||
char *newbuf;
|
||||
int i;
|
||||
|
||||
*msg = 0;
|
||||
if (*buf == 0)
|
||||
return (0);
|
||||
i = 0;
|
||||
while ((*buf)[i])
|
||||
{
|
||||
if ((*buf)[i] == '\n')
|
||||
{
|
||||
newbuf = calloc(1, sizeof(*newbuf) * (strlen(*buf + i + 1) + 1));
|
||||
if (newbuf == 0)
|
||||
return (-1);
|
||||
strcpy(newbuf, *buf + i + 1);
|
||||
*msg = *buf;
|
||||
(*msg)[i + 1] = 0;
|
||||
*buf = newbuf;
|
||||
return (1);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return (0);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------- *
|
||||
* str_join — append `add` to `buf`, return a NEW heap string, free old `buf`.
|
||||
* Returns NULL on allocation failure. Handles buf == NULL (new buffer).
|
||||
*
|
||||
* This is how a per-client pending buffer grows across recv calls. The exam
|
||||
* gives it to you; copy it verbatim. Leak rule: the function frees the old
|
||||
* buffer itself; you free the final buffer when the client disconnects.
|
||||
* ------------------------------------------------------------------------- */
|
||||
char *str_join(char *buf, char *add)
|
||||
{
|
||||
char *newbuf;
|
||||
int len;
|
||||
|
||||
if (buf == 0)
|
||||
len = 0;
|
||||
else
|
||||
len = strlen(buf);
|
||||
newbuf = malloc(sizeof(*newbuf) * (len + strlen(add) + 1));
|
||||
if (newbuf == 0)
|
||||
return (0);
|
||||
newbuf[0] = 0;
|
||||
if (buf != 0)
|
||||
strcat(newbuf, buf);
|
||||
free(buf);
|
||||
strcat(newbuf, add);
|
||||
return (newbuf);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------- *
|
||||
* main — A DEMO, NOT A SOLUTION. Replace it entirely.
|
||||
*
|
||||
* What is wrong with it (why you rewrite main):
|
||||
* - no argc check, no "Wrong number of arguments\n";
|
||||
* - hardcoded port 8081 instead of atoi(argv[1]);
|
||||
* - printf() everywhere (forbidden) and exit(0) on errors (must be exit 1
|
||||
* with "Fatal error\n" on stderr);
|
||||
* - accepts ONE client and then does nothing with it: no select loop, no
|
||||
* ids, no broadcast, no disconnect handling;
|
||||
* - `int len` is passed to accept() which wants socklen_t *.
|
||||
*
|
||||
* What is worth keeping: the exact socket/sockaddr/bind/listen lines.
|
||||
* ------------------------------------------------------------------------- */
|
||||
int main(int argc, char **argv) {
|
||||
if (argc != 2)
|
||||
{
|
||||
write(2, "Wrong number of arguments\n", 26);
|
||||
return (1);
|
||||
}
|
||||
|
||||
int sockfd, connfd, len;
|
||||
struct sockaddr_in servaddr, cli;
|
||||
|
||||
// socket create and verification
|
||||
sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sockfd == -1) { /* in your file: fatal() */
|
||||
printf("socket creation failed...\n"); /* forbidden */
|
||||
exit(0); /* wrong status, wrong text */
|
||||
}
|
||||
else
|
||||
printf("Socket successfully created..\n"); /* forbidden; grader ignores stdout */
|
||||
bzero(&servaddr, sizeof(servaddr)); /* KEEP: must zero the struct */
|
||||
|
||||
// assign IP, PORT
|
||||
servaddr.sin_family = AF_INET; /* KEEP: IPv4 */
|
||||
servaddr.sin_addr.s_addr = htonl(2130706433); //127.0.0.1 /* KEEP: localhost only */
|
||||
servaddr.sin_port = htons(8081); /* in your file: htons(atoi(argv[1])) */
|
||||
|
||||
// Binding newly created socket to given IP and verification
|
||||
if ((bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr))) != 0) {
|
||||
printf("socket bind failed...\n"); /* replace with fatal() */
|
||||
exit(0);
|
||||
}
|
||||
else
|
||||
printf("Socket successfully binded..\n");
|
||||
if (listen(sockfd, 10) != 0) { /* KEEP: backlog 10 */
|
||||
printf("cannot listen\n"); /* replace with fatal() */
|
||||
exit(0);
|
||||
}
|
||||
len = sizeof(cli); /* should be socklen_t len */
|
||||
connfd = accept(sockfd, (struct sockaddr *)&cli, &len);
|
||||
if (connfd < 0) { /* in your loop: do NOT exit */
|
||||
printf("server acccept failed...\n"); /* forbidden */
|
||||
exit(0);
|
||||
}
|
||||
else
|
||||
printf("server acccept the client...\n");
|
||||
/* ... and then the demo ends. Your program now needs:
|
||||
* - slots init, g_maxfd = g_server;
|
||||
* - while (1): rebuild fd_set, select, accept / recv, broadcast,
|
||||
* disconnect, cleanup.
|
||||
* Follow drills/typing-script.md stages C-E. */
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
/* ============================================================================
|
||||
* mini_serv — reference solution (known good).
|
||||
*
|
||||
* NOT an exam asset. Use it only to:
|
||||
* 1) validate the test harness (tester/check.sh must be green on it), and
|
||||
* 2) diff YOUR attempt against it afterwards to build your "what I missed" list.
|
||||
*
|
||||
* Written for: subject/subject.en.txt
|
||||
* Compile: cc -Wall -Wextra -Werror mini_serv.c -o mini_serv
|
||||
* ==========================================================================*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/select.h>
|
||||
|
||||
typedef struct s_client
|
||||
{
|
||||
int fd;
|
||||
int id;
|
||||
char *buf;
|
||||
} t_client;
|
||||
|
||||
static t_client g_c[FD_SETSIZE];
|
||||
static int g_maxfd;
|
||||
static int g_server;
|
||||
static int g_next_id;
|
||||
|
||||
static void fatal(void)
|
||||
{
|
||||
write(2, "Fatal error\n", 12);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
/* ---- helpers as given in the exam's main.c attachment ---- */
|
||||
|
||||
static char *str_join(char *buf, char *add)
|
||||
{
|
||||
char *newbuf;
|
||||
int len;
|
||||
|
||||
if (buf == 0)
|
||||
len = 0;
|
||||
else
|
||||
len = strlen(buf);
|
||||
newbuf = malloc(sizeof(*newbuf) * (len + strlen(add) + 1));
|
||||
if (newbuf == 0)
|
||||
return (0);
|
||||
newbuf[0] = 0;
|
||||
if (buf != 0)
|
||||
strcat(newbuf, buf);
|
||||
free(buf);
|
||||
strcat(newbuf, add);
|
||||
return (newbuf);
|
||||
}
|
||||
|
||||
static int extract_message(char **buf, char **msg)
|
||||
{
|
||||
char *newbuf;
|
||||
int i;
|
||||
|
||||
*msg = 0;
|
||||
if (*buf == 0)
|
||||
return (0);
|
||||
i = 0;
|
||||
while ((*buf)[i])
|
||||
{
|
||||
if ((*buf)[i] == '\n')
|
||||
{
|
||||
newbuf = calloc(1, sizeof(*newbuf) * (strlen(*buf + i + 1) + 1));
|
||||
if (newbuf == 0)
|
||||
return (-1);
|
||||
strcpy(newbuf, *buf + i + 1);
|
||||
*msg = *buf;
|
||||
(*msg)[i + 1] = 0;
|
||||
*buf = newbuf;
|
||||
return (1);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return (0);
|
||||
}
|
||||
|
||||
/* ---- server logic ---- */
|
||||
|
||||
static void to_all_except(int fd, char *s)
|
||||
{
|
||||
int i;
|
||||
|
||||
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++;
|
||||
g_c[fd].buf = NULL;
|
||||
if (fd > g_maxfd)
|
||||
g_maxfd = fd;
|
||||
sprintf(msg, "server: client %d just arrived\n", g_c[fd].id);
|
||||
to_all_except(fd, msg);
|
||||
}
|
||||
|
||||
static void disconnect(int fd)
|
||||
{
|
||||
char msg[64];
|
||||
int id;
|
||||
|
||||
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)
|
||||
{
|
||||
disconnect(fd);
|
||||
return ;
|
||||
}
|
||||
tmp[n] = 0;
|
||||
g_c[fd].buf = str_join(g_c[fd].buf, tmp);
|
||||
if (!g_c[fd].buf)
|
||||
fatal();
|
||||
while (extract_message(&g_c[fd].buf, &msg) == 1)
|
||||
{
|
||||
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);
|
||||
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);
|
||||
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);
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
/* ============================================================================
|
||||
* mini_serv — community variant ("the sets + one-event-per-wakeup style").
|
||||
*
|
||||
* Source: the version the user's friend passed exam 06 with.
|
||||
* Validated in this gym with:
|
||||
* - cc -Wall -Wextra -Werror
|
||||
* - tester/mini_serv_tester.py (13/13)
|
||||
* - the real exam-style Grademe diff (PASSED)
|
||||
*
|
||||
* Style differences vs reference/mini_serv.c:
|
||||
* - keeps a master fd_set (active_fds) and copies it into read_fds/write_fds
|
||||
* before select, instead of rebuilding from a slot array;
|
||||
* - processes ONE event per select() wakeup and `break`s (slower, but simpler);
|
||||
* - sends arrival/departure messages via a shared writebuff.
|
||||
*
|
||||
* Known cosmetic wart: guards `cl_sock >= 10240` while `clients[1024]` — with
|
||||
* select(2) fds are always < 1024, so the array cannot be overrun in practice.
|
||||
* ==========================================================================*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/select.h>
|
||||
|
||||
typedef struct s_client {
|
||||
int id;
|
||||
char *msg;
|
||||
} t_client;
|
||||
|
||||
static t_client clients[1024];
|
||||
static char readbuff[100000], writebuff[100000];
|
||||
static int max_fd = 0, next_id = 0;
|
||||
static fd_set active_fds, read_fds, write_fds;
|
||||
|
||||
void exitError(char *str) {
|
||||
write(2, str, strlen(str));
|
||||
exit(1);
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
/* str_join and extract_message are given in the exam's main.c */
|
||||
char *str_join(char *buf, char *add)
|
||||
{
|
||||
char *newbuf;
|
||||
int len;
|
||||
|
||||
if (buf == 0)
|
||||
len = 0;
|
||||
else
|
||||
len = strlen(buf);
|
||||
newbuf = malloc(sizeof(*newbuf) * (len + strlen(add) + 1));
|
||||
if (newbuf == 0)
|
||||
return (0);
|
||||
newbuf[0] = 0;
|
||||
if (buf != 0)
|
||||
strcat(newbuf, buf);
|
||||
free(buf);
|
||||
strcat(newbuf, add);
|
||||
return (newbuf);
|
||||
}
|
||||
|
||||
int extract_message(char **buf, char **msg)
|
||||
{
|
||||
char *newbuf;
|
||||
int i;
|
||||
|
||||
*msg = 0;
|
||||
if (*buf == 0)
|
||||
return (0);
|
||||
i = 0;
|
||||
while ((*buf)[i])
|
||||
{
|
||||
if ((*buf)[i] == '\n')
|
||||
{
|
||||
newbuf = calloc(1, sizeof(*newbuf) * (strlen(*buf + i + 1) + 1));
|
||||
if (newbuf == 0)
|
||||
return (-1);
|
||||
strcpy(newbuf, *buf + i + 1);
|
||||
*msg = *buf;
|
||||
(*msg)[i + 1] = 0;
|
||||
*buf = newbuf;
|
||||
return (1);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return (0);
|
||||
}
|
||||
|
||||
int main(int ac, char **av) {
|
||||
if (ac != 2)
|
||||
exitError("Wrong number of arguments\n");
|
||||
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sockfd == -1)
|
||||
exitError("Fatal error\n");
|
||||
max_fd = sockfd;
|
||||
FD_ZERO(&active_fds);
|
||||
FD_SET(sockfd, &active_fds);
|
||||
struct sockaddr_in servaddr;
|
||||
memset(&servaddr, 0, sizeof(servaddr));
|
||||
servaddr.sin_family = AF_INET;
|
||||
servaddr.sin_addr.s_addr = htonl(2130706433);
|
||||
servaddr.sin_port = htons(atoi(av[1]));
|
||||
if (bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr)) != 0)
|
||||
exitError("Fatal error\n");
|
||||
if (listen(sockfd, 10) != 0)
|
||||
exitError("Fatal error\n");
|
||||
while (1) {
|
||||
read_fds = write_fds = active_fds;
|
||||
if (select(max_fd + 1, &read_fds, &write_fds, NULL, NULL) < 0)
|
||||
continue;
|
||||
for (int fd = 0; fd <= max_fd; fd++) {
|
||||
if (FD_ISSET(fd, &read_fds) && fd == sockfd) {
|
||||
int cl_sock = accept(sockfd, NULL, NULL);
|
||||
if (cl_sock < 0)
|
||||
continue;
|
||||
if (cl_sock >= 10240) {
|
||||
close(cl_sock);
|
||||
continue;
|
||||
}
|
||||
if (cl_sock > max_fd)
|
||||
max_fd = cl_sock;
|
||||
clients[cl_sock].id = next_id++;
|
||||
clients[cl_sock].msg = NULL;
|
||||
FD_SET(cl_sock, &active_fds);
|
||||
sprintf(writebuff, "server: client %d just arrived\n", clients[cl_sock].id);
|
||||
sendMsg(cl_sock);
|
||||
break;
|
||||
}
|
||||
else if (FD_ISSET(fd, &read_fds)) {
|
||||
int read_bytes = recv(fd, readbuff, sizeof(readbuff) - 1, 0);
|
||||
if (read_bytes <= 0) {
|
||||
sprintf(writebuff, "server: client %d just left\n", clients[fd].id);
|
||||
sendMsg(fd);
|
||||
FD_CLR(fd, &active_fds);
|
||||
close(fd);
|
||||
free(clients[fd].msg);
|
||||
break;
|
||||
} else {
|
||||
readbuff[read_bytes] = '\0';
|
||||
clients[fd].msg = str_join(clients[fd].msg, readbuff);
|
||||
char *line = NULL;
|
||||
int res;
|
||||
while ((res = extract_message(&clients[fd].msg, &line)) > 0)
|
||||
{
|
||||
sprintf(writebuff, "client %d: ", clients[fd].id);
|
||||
char *str = str_join(NULL, writebuff);
|
||||
str = str_join(str, line);
|
||||
for (int cli_fd = 0; cli_fd <= max_fd; cli_fd++)
|
||||
if (FD_ISSET(cli_fd, &write_fds) && fd != cli_fd)
|
||||
send(cli_fd, str, strlen(str), 0);
|
||||
free(str);
|
||||
free(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
|
||||
# close fd before init
|
||||
exec 6<&-
|
||||
exec 6</dev/tcp/127.0.0.1/"$1"
|
||||
|
||||
while read -r <&6
|
||||
do
|
||||
echo "$REPLY"
|
||||
done
|
||||
@@ -0,0 +1,5 @@
|
||||
Ceci est un test de Ctrl+D dans ton programme ici:\04Si tu ne passes pas ce test, tu devrais verifier le fonctionnement du ctrl+d.
|
||||
voici
|
||||
un
|
||||
nouveau
|
||||
test
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/bin/bash
|
||||
# Print the first free TCP port in [first_port, last_port]
|
||||
# (default: a random start in 8888-9887, so back-to-back runs use other ports).
|
||||
# Works with ss (Linux), lsof (macOS/Linux) or netstat, whichever is installed.
|
||||
|
||||
first_port=${1:-$((8888 + RANDOM % 1000))}
|
||||
last_port=${2:-$((first_port + 1000))}
|
||||
|
||||
port_in_use()
|
||||
{
|
||||
if command -v ss >/dev/null 2>&1; then
|
||||
ss -tuln 2>/dev/null | grep -q "[.:]$1 "
|
||||
elif command -v lsof >/dev/null 2>&1; then
|
||||
lsof -nP -iTCP:"$1" -sTCP:LISTEN >/dev/null 2>&1
|
||||
elif command -v netstat >/dev/null 2>&1; then
|
||||
netstat -an 2>/dev/null | grep -E "[.:]$1 " | grep -q LISTEN
|
||||
else
|
||||
# last resort: something accepts connections on this port
|
||||
(exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null
|
||||
fi
|
||||
}
|
||||
|
||||
for ((port = first_port; port <= last_port; port++)); do
|
||||
if ! port_in_use "$port"; then
|
||||
echo "$port"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
echo 0
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
# usage: bash test_eof.sh <port>
|
||||
# Sends eof_test one word at a time (with a literal ^D inside) on one connection.
|
||||
|
||||
PORT=$1
|
||||
|
||||
send_msg()
|
||||
{
|
||||
exec 3<>"/dev/tcp/127.0.0.1/$PORT" || return 1
|
||||
cat >&3
|
||||
exec 3>&-
|
||||
}
|
||||
|
||||
for x in $(cat eof_test); do
|
||||
printf "$x"
|
||||
sleep 0.1
|
||||
done | send_msg
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/bin/bash
|
||||
# usage: bash test_miniserv.sh <port> (run from .system/grading)
|
||||
# Starts the student's server, connects a listener (catchmsg.sh) and several
|
||||
# short-lived clients, then stores everything the listener received in `bim`.
|
||||
# Only uses bash's /dev/tcp, so it does not depend on the installed nc flavor.
|
||||
|
||||
PORT=$1
|
||||
rm -f bim trace final
|
||||
|
||||
fail()
|
||||
{
|
||||
{
|
||||
echo "----------------8<-------------[ START TEST "
|
||||
printf "%b" "$1"
|
||||
echo "----------------8<------------- END TEST ]"
|
||||
} >> traceback
|
||||
}
|
||||
|
||||
send_msg()
|
||||
{
|
||||
exec 3<>"/dev/tcp/127.0.0.1/$PORT" || return 1
|
||||
cat >&3
|
||||
exec 3>&-
|
||||
}
|
||||
|
||||
# 0 = listening, 1 = not listening, 2 = no tool available to check
|
||||
port_listening()
|
||||
{
|
||||
if command -v ss >/dev/null 2>&1; then
|
||||
ss -tln 2>/dev/null | grep -q "[.:]$PORT "
|
||||
elif command -v lsof >/dev/null 2>&1; then
|
||||
lsof -nP -iTCP:"$PORT" -sTCP:LISTEN >/dev/null 2>&1
|
||||
elif command -v netstat >/dev/null 2>&1; then
|
||||
netstat -an 2>/dev/null | grep -E "[.:]$PORT " | grep -q LISTEN
|
||||
else
|
||||
return 2
|
||||
fi
|
||||
}
|
||||
|
||||
CC=$(command -v clang || command -v cc || command -v gcc)
|
||||
if ! "$CC" -o final ../../rendu/mini_serv/mini_serv.c > trace 2>&1 || [ ! -e final ]; then
|
||||
fail " 🔎 YOUR OUTPUT:\n$(cat trace)\n ❌ COMPILATION ERROR\n"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SERVER=""
|
||||
CATCH=""
|
||||
|
||||
cleanup()
|
||||
{
|
||||
# stop the server first: the listener then reads EOF and flushes `bim`
|
||||
[ -n "$SERVER" ] && kill "$SERVER" 2>/dev/null
|
||||
[ -n "$SERVER" ] && wait "$SERVER" 2>/dev/null
|
||||
if [ -n "$CATCH" ]; then
|
||||
for _ in $(seq 1 20); do
|
||||
kill -0 "$CATCH" 2>/dev/null || break
|
||||
sleep 0.1
|
||||
done
|
||||
kill "$CATCH" 2>/dev/null
|
||||
wait "$CATCH" 2>/dev/null
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
# start the server and wait (max 3s) until it listens
|
||||
# 0 = listening, 1 = never listened, 2 = the process exited (e.g. bind failed)
|
||||
start_server()
|
||||
{
|
||||
./final "$PORT" > /dev/null 2>&1 &
|
||||
SERVER=$!
|
||||
for _ in $(seq 1 30); do
|
||||
port_listening
|
||||
case $? in
|
||||
0) return 0 ;;
|
||||
2) sleep 1; kill -0 "$SERVER" 2>/dev/null && return 0 || return 2 ;;
|
||||
esac
|
||||
kill -0 "$SERVER" 2>/dev/null || return 2
|
||||
sleep 0.1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# A port can still be busy (TIME_WAIT) right after a previous run, which
|
||||
# makes bind() fail: if the server exits at startup, retry on other ports.
|
||||
attempt=1
|
||||
while true; do
|
||||
start_server
|
||||
status=$?
|
||||
[ $status -eq 0 ] && break
|
||||
kill "$SERVER" 2>/dev/null
|
||||
wait "$SERVER" 2>/dev/null
|
||||
SERVER=""
|
||||
if [ $status -eq 1 ] || [ $attempt -ge 5 ]; then
|
||||
fail " ❌ PORT IS NOT OPEN \n 💻 TEST\n./a.out $PORT\n Connecting after the server is started\n Cannot connect to port $PORT\n"
|
||||
exit 1
|
||||
fi
|
||||
attempt=$((attempt + 1))
|
||||
PORT=$(bash findport.sh $((PORT + 1)))
|
||||
done
|
||||
|
||||
bash catchmsg.sh "$PORT" >> bim &
|
||||
CATCH=$!
|
||||
sleep 1
|
||||
|
||||
echo "Si vous ne voyez QUE ce message, c'est mauvais signe." | send_msg
|
||||
sleep 0.2
|
||||
echo "Bienvenue sur le test de votre miniserv" | send_msg
|
||||
sleep 0.2
|
||||
echo "Ceci est un message" | send_msg
|
||||
sleep 0.2
|
||||
printf "Voici un texte sans retour a la ligne" | send_msg
|
||||
sleep 0.2
|
||||
echo -n "This is a text without backline at the end" | send_msg
|
||||
sleep 0.4
|
||||
printf "Et voici un texte avec plusieurs\nretours\na\nla\nligne\n" | send_msg
|
||||
sleep 0.2
|
||||
|
||||
bash test_eof.sh "$PORT"
|
||||
sleep 1
|
||||
|
||||
send_msg < very_long_msg.txt
|
||||
sleep 1
|
||||
|
||||
send_msg < other_long_msg.txt
|
||||
sleep 2
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/bin/bash
|
||||
cd .system/grading/
|
||||
# if there is a traceback file then remove it
|
||||
if [ -e traceback ]; then
|
||||
rm traceback
|
||||
fi
|
||||
|
||||
echo "Test may be long, please wait..."
|
||||
|
||||
# for port in $(seq 4444 65000); do echo -ne "\035" | telnet 127.0.0.1 $port > /dev/null 2>&1; [ $? -eq 1 ] && break; done
|
||||
|
||||
PORT=$(bash findport.sh)
|
||||
|
||||
bash test_miniserv.sh $PORT &> /dev/null 2>&1
|
||||
|
||||
# if there is a final file and there is not a traceback file then the diff is check
|
||||
if [ -e final ] && [ ! -e traceback ]; then
|
||||
|
||||
DIFF=$(diff bim normal.output)
|
||||
if [ "$DIFF" != "" ]
|
||||
then
|
||||
|
||||
echo "----------------8<-------------[ START TEST " >> traceback
|
||||
printf " 💻 TEST\n./a.out $PORT\n" >> traceback
|
||||
printf " Then there is 3 connexion to the server\n" >> traceback
|
||||
printf " 🔎 YOUR OUTPUT:\n" >> traceback
|
||||
cat bim >> traceback
|
||||
printf " 🗝 EXPECTED OUTPUT:\n" >> traceback
|
||||
cat normal.output >> traceback
|
||||
echo "----------------8<------------- END TEST ]" >> traceback
|
||||
mv traceback ../../traceback
|
||||
cd ../../
|
||||
exit 1
|
||||
fi
|
||||
|
||||
touch passed
|
||||
else
|
||||
mv traceback ../../traceback
|
||||
fi
|
||||
cd ../../
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,8 @@
|
||||
Write your mini_serv.c HERE (exact filename: mini_serv.c).
|
||||
|
||||
Then from the repo root run:
|
||||
|
||||
bash tester/check.sh
|
||||
|
||||
That compiles this file strictly, runs the behavioral tester, and then runs
|
||||
the real exam-style Grademe diff on it.
|
||||
@@ -0,0 +1,162 @@
|
||||
/* ============================================================================
|
||||
* THE EXAM'S main.c — ANNOTATED STUDY COPY
|
||||
*
|
||||
* Code below is verbatim from the exam attachment (subject/main.c), comments
|
||||
* added. This is what you receive in the exam, and what you must triage in the
|
||||
* first 2 minutes.
|
||||
*
|
||||
* It does NOT compile as-is on a modern gcc (verified): calloc, malloc, free,
|
||||
* exit, printf, bzero are used without <stdlib.h>/<stdio.h>/<strings.h>, and
|
||||
* `int len` is passed where accept() wants socklen_t *. It is not supposed to
|
||||
* be compiled — the subject warns it "uses forbidden functions or writes
|
||||
* things that must not be there in your final program".
|
||||
*
|
||||
* HOW TO USE IT IN THE EXAM:
|
||||
* 1. KEEP extract_message() and str_join() — copy them verbatim into your file.
|
||||
* 2. THROW AWAY main() — it is a one-client demo with a hardcoded port.
|
||||
* 3. Reuse the socket setup LINES (socket/sockaddr/bind/listen) from main().
|
||||
* 4. Never ship printf/exit(0): errors are "Wrong number of arguments\n" /
|
||||
* "Fatal error\n" on stderr + exit status 1.
|
||||
*
|
||||
* Stage map:
|
||||
* B <- the socket setup lines in main()
|
||||
* C <- you add: slots, the select loop, accept, arrival broadcast
|
||||
* D <- you add: recv + str_join + extract_message + relay
|
||||
* E <- you add: recv<=0 -> "just left", close, free
|
||||
* ==========================================================================*/
|
||||
|
||||
#include <errno.h> /* unused here; not needed in your file */
|
||||
#include <string.h> /* strlen, strcpy, strcat, bzero */
|
||||
#include <unistd.h> /* write, close */
|
||||
#include <netdb.h> /* unused here; not needed in your file */
|
||||
#include <sys/socket.h> /* socket, bind, listen, accept, send, recv */
|
||||
#include <netinet/in.h> /* sockaddr_in, htonl, htons */
|
||||
/* MISSING (you add in your file): <stdlib.h> for malloc/calloc/free/exit/atoi,
|
||||
* <stdio.h> for sprintf, <sys/select.h> for select + FD_* macros. */
|
||||
|
||||
/* ------------------------------------------------------------------------- *
|
||||
* extract_message — pull ONE complete \n-terminated line out of *buf.
|
||||
*
|
||||
* CONTRACT (memorize the three return values, not the body):
|
||||
* 1 -> a line was found: *msg points at it (you must free(*msg)),
|
||||
* *buf now holds the remainder
|
||||
* 0 -> no '\n' yet: keep waiting, nothing to send
|
||||
* -1 -> allocation failure: treat as "Fatal error\n" + exit 1
|
||||
*
|
||||
* This is THE function that makes TCP's arbitrary chunking irrelevant.
|
||||
* Call it in a loop after every append — a single recv may contain several
|
||||
* lines, and a line may span several recv calls.
|
||||
* ------------------------------------------------------------------------- */
|
||||
int extract_message(char **buf, char **msg)
|
||||
{
|
||||
char *newbuf;
|
||||
int i;
|
||||
|
||||
*msg = 0;
|
||||
if (*buf == 0)
|
||||
return (0);
|
||||
i = 0;
|
||||
while ((*buf)[i])
|
||||
{
|
||||
if ((*buf)[i] == '\n')
|
||||
{
|
||||
newbuf = calloc(1, sizeof(*newbuf) * (strlen(*buf + i + 1) + 1));
|
||||
if (newbuf == 0)
|
||||
return (-1);
|
||||
strcpy(newbuf, *buf + i + 1);
|
||||
*msg = *buf;
|
||||
(*msg)[i + 1] = 0;
|
||||
*buf = newbuf;
|
||||
return (1);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return (0);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------- *
|
||||
* str_join — append `add` to `buf`, return a NEW heap string, free old `buf`.
|
||||
* Returns NULL on allocation failure. Handles buf == NULL (new buffer).
|
||||
*
|
||||
* This is how a per-client pending buffer grows across recv calls. The exam
|
||||
* gives it to you; copy it verbatim. Leak rule: the function frees the old
|
||||
* buffer itself; you free the final buffer when the client disconnects.
|
||||
* ------------------------------------------------------------------------- */
|
||||
char *str_join(char *buf, char *add)
|
||||
{
|
||||
char *newbuf;
|
||||
int len;
|
||||
|
||||
if (buf == 0)
|
||||
len = 0;
|
||||
else
|
||||
len = strlen(buf);
|
||||
newbuf = malloc(sizeof(*newbuf) * (len + strlen(add) + 1));
|
||||
if (newbuf == 0)
|
||||
return (0);
|
||||
newbuf[0] = 0;
|
||||
if (buf != 0)
|
||||
strcat(newbuf, buf);
|
||||
free(buf);
|
||||
strcat(newbuf, add);
|
||||
return (newbuf);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------- *
|
||||
* main — A DEMO, NOT A SOLUTION. Replace it entirely.
|
||||
*
|
||||
* What is wrong with it (why you rewrite main):
|
||||
* - no argc check, no "Wrong number of arguments\n";
|
||||
* - hardcoded port 8081 instead of atoi(argv[1]);
|
||||
* - printf() everywhere (forbidden) and exit(0) on errors (must be exit 1
|
||||
* with "Fatal error\n" on stderr);
|
||||
* - accepts ONE client and then does nothing with it: no select loop, no
|
||||
* ids, no broadcast, no disconnect handling;
|
||||
* - `int len` is passed to accept() which wants socklen_t *.
|
||||
*
|
||||
* What is worth keeping: the exact socket/sockaddr/bind/listen lines.
|
||||
* ------------------------------------------------------------------------- */
|
||||
int main() {
|
||||
int sockfd, connfd, len;
|
||||
struct sockaddr_in servaddr, cli;
|
||||
|
||||
// socket create and verification
|
||||
sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sockfd == -1) { /* in your file: fatal() */
|
||||
printf("socket creation failed...\n"); /* forbidden */
|
||||
exit(0); /* wrong status, wrong text */
|
||||
}
|
||||
else
|
||||
printf("Socket successfully created..\n"); /* forbidden; grader ignores stdout */
|
||||
bzero(&servaddr, sizeof(servaddr)); /* KEEP: must zero the struct */
|
||||
|
||||
// assign IP, PORT
|
||||
servaddr.sin_family = AF_INET; /* KEEP: IPv4 */
|
||||
servaddr.sin_addr.s_addr = htonl(2130706433); //127.0.0.1 /* KEEP: localhost only */
|
||||
servaddr.sin_port = htons(8081); /* in your file: htons(atoi(argv[1])) */
|
||||
|
||||
// Binding newly created socket to given IP and verification
|
||||
if ((bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr))) != 0) {
|
||||
printf("socket bind failed...\n"); /* replace with fatal() */
|
||||
exit(0);
|
||||
}
|
||||
else
|
||||
printf("Socket successfully binded..\n");
|
||||
if (listen(sockfd, 10) != 0) { /* KEEP: backlog 10 */
|
||||
printf("cannot listen\n"); /* replace with fatal() */
|
||||
exit(0);
|
||||
}
|
||||
len = sizeof(cli); /* should be socklen_t len */
|
||||
connfd = accept(sockfd, (struct sockaddr *)&cli, &len);
|
||||
if (connfd < 0) { /* in your loop: do NOT exit */
|
||||
printf("server acccept failed...\n"); /* forbidden */
|
||||
exit(0);
|
||||
}
|
||||
else
|
||||
printf("server acccept the client...\n");
|
||||
/* ... and then the demo ends. Your program now needs:
|
||||
* - slots init, g_maxfd = g_server;
|
||||
* - while (1): rebuild fd_set, select, accept / recv, broadcast,
|
||||
* disconnect, cleanup.
|
||||
* Follow drills/typing-script.md stages C-E. */
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
#include <errno.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <netdb.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
|
||||
int extract_message(char **buf, char **msg)
|
||||
{
|
||||
char *newbuf;
|
||||
int i;
|
||||
|
||||
*msg = 0;
|
||||
if (*buf == 0)
|
||||
return (0);
|
||||
i = 0;
|
||||
while ((*buf)[i])
|
||||
{
|
||||
if ((*buf)[i] == '\n')
|
||||
{
|
||||
newbuf = calloc(1, sizeof(*newbuf) * (strlen(*buf + i + 1) + 1));
|
||||
if (newbuf == 0)
|
||||
return (-1);
|
||||
strcpy(newbuf, *buf + i + 1);
|
||||
*msg = *buf;
|
||||
(*msg)[i + 1] = 0;
|
||||
*buf = newbuf;
|
||||
return (1);
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return (0);
|
||||
}
|
||||
|
||||
char *str_join(char *buf, char *add)
|
||||
{
|
||||
char *newbuf;
|
||||
int len;
|
||||
|
||||
if (buf == 0)
|
||||
len = 0;
|
||||
else
|
||||
len = strlen(buf);
|
||||
newbuf = malloc(sizeof(*newbuf) * (len + strlen(add) + 1));
|
||||
if (newbuf == 0)
|
||||
return (0);
|
||||
newbuf[0] = 0;
|
||||
if (buf != 0)
|
||||
strcat(newbuf, buf);
|
||||
free(buf);
|
||||
strcat(newbuf, add);
|
||||
return (newbuf);
|
||||
}
|
||||
|
||||
|
||||
int main() {
|
||||
int sockfd, connfd, len;
|
||||
struct sockaddr_in servaddr, cli;
|
||||
|
||||
// socket create and verification
|
||||
sockfd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
if (sockfd == -1) {
|
||||
printf("socket creation failed...\n");
|
||||
exit(0);
|
||||
}
|
||||
else
|
||||
printf("Socket successfully created..\n");
|
||||
bzero(&servaddr, sizeof(servaddr));
|
||||
|
||||
// assign IP, PORT
|
||||
servaddr.sin_family = AF_INET;
|
||||
servaddr.sin_addr.s_addr = htonl(2130706433); //127.0.0.1
|
||||
servaddr.sin_port = htons(8081);
|
||||
|
||||
// Binding newly created socket to given IP and verification
|
||||
if ((bind(sockfd, (const struct sockaddr *)&servaddr, sizeof(servaddr))) != 0) {
|
||||
printf("socket bind failed...\n");
|
||||
exit(0);
|
||||
}
|
||||
else
|
||||
printf("Socket successfully binded..\n");
|
||||
if (listen(sockfd, 10) != 0) {
|
||||
printf("cannot listen\n");
|
||||
exit(0);
|
||||
}
|
||||
len = sizeof(cli);
|
||||
connfd = accept(sockfd, (struct sockaddr *)&cli, &len);
|
||||
if (connfd < 0) {
|
||||
printf("server acccept failed...\n");
|
||||
exit(0);
|
||||
}
|
||||
else
|
||||
printf("server acccept the client...\n");
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
Assignment name : mini_serv
|
||||
Expected files : mini_serv.c
|
||||
Allowed functions: write, close, select, socket, accept, listen, send, recv, bind, strstr, malloc, realloc, free, calloc, bzero, atoi, sprintf, strlen, exit, strcpy, strcat, memset
|
||||
--------------------------------------------------------------------------------
|
||||
|
||||
Write a program that will listen for client to connect on a certain port on 127.0.0.1 and will let clients to speak with each other
|
||||
|
||||
This program will take as first argument the port to bind to
|
||||
If no argument is given, it should write in stderr "Wrong number of arguments" followed by a \n and exit with status 1
|
||||
If a System Calls returns an error before the program start accepting connection, it should write in stderr "Fatal error" followed by a \n and exit with status 1
|
||||
If you cant allocate memory it should write in stderr "Fatal error" followed by a \n and exit with status 1
|
||||
|
||||
Your program must be non-blocking but client can be lazy and if they don't read your message you must NOT disconnect them...
|
||||
|
||||
Your program must not contains #define preproc
|
||||
Your program must only listen to 127.0.0.1
|
||||
The fd that you will receive will already be set to make 'recv' or 'send' to block if select hasn't be called before calling them, but will not block otherwise.
|
||||
|
||||
When a client connect to the server:
|
||||
- the client will be given an id. the first client will receive the id 0 and each new client will received the last client id + 1
|
||||
- %d will be replace by this number
|
||||
- a message is sent to all the client that was connected to the server: "server: client %d just arrived\n"
|
||||
|
||||
clients must be able to send messages to your program.
|
||||
- message will only be printable characters, no need to check
|
||||
- a single message can contains multiple \n
|
||||
- when the server receive a message, it must resend it to all the other client with "client %d: " before every line!
|
||||
|
||||
When a client disconnect from the server:
|
||||
- a message is sent to all the client that was connected to the server: "server: client %d just left\n"
|
||||
|
||||
Memory or fd leaks are forbidden
|
||||
|
||||
To help you, you will find the file main.c with the beginning of a server and maybe some useful functions. (Beware this file use forbidden functions or write things that must not be there in your final program)
|
||||
|
||||
Warning our tester is expecting that you send the messages as fast as you can. Don't do un-necessary buffer.
|
||||
|
||||
Evaluation can be a bit longer than usual...
|
||||
|
||||
Hint: you can use nc to test your program
|
||||
Hint: you should use nc to test your program
|
||||
Hint: To test you can use fcntl(fd, F_SETFL, O_NONBLOCK) but use select and NEVER check EAGAIN (man 2 send)
|
||||
@@ -0,0 +1,173 @@
|
||||
/* ============================================================================
|
||||
* mini_serv — fill-in skeleton.
|
||||
*
|
||||
* Compiles clean with: cc -Wall -Wextra -Werror mini_serv.skeleton.c -o test
|
||||
* It does NOT work until you fill every TODO. That's the point.
|
||||
*
|
||||
* The main() loop and the socket setup are already typed for you (memorize
|
||||
* them anyway). The four functions below are where the exam is won or lost.
|
||||
*
|
||||
* Do not look at reference/mini_serv.c until you have done a full timed
|
||||
* attempt. Hints are in cheatsheet.md (read it once, then close it).
|
||||
* ==========================================================================*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <sys/select.h>
|
||||
|
||||
typedef struct s_client
|
||||
{
|
||||
int fd; /* -1 = free slot */
|
||||
int id;
|
||||
char *buf; /* pending partial line */
|
||||
} t_client;
|
||||
|
||||
t_client g_c[FD_SETSIZE];
|
||||
int g_maxfd;
|
||||
int g_server;
|
||||
int g_next_id;
|
||||
|
||||
void fatal(void)
|
||||
{
|
||||
write(2, "Fatal error\n", 12);
|
||||
exit(1);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* The exam GIVES YOU these two functions in main.c — copy them verbatim from
|
||||
* subject/main.c (both of them). Type them once by hand in drill D3, then
|
||||
* you'll never think about them again.
|
||||
*
|
||||
* str_join(buf, add) -> new buffer = buf + add (old buf freed)
|
||||
* extract_message(&buf, &msg) -> 1: one \n-terminated line pulled into msg
|
||||
* 0: no complete line yet
|
||||
* -1: allocation failure
|
||||
* ------------------------------------------------------------------------- */
|
||||
|
||||
char *str_join(char *buf, char *add)
|
||||
{
|
||||
/* TODO: copy verbatim from subject/main.c */
|
||||
(void)buf;
|
||||
(void)add;
|
||||
return (0);
|
||||
}
|
||||
|
||||
int extract_message(char **buf, char **msg)
|
||||
{
|
||||
/* TODO: copy verbatim from subject/main.c */
|
||||
(void)buf;
|
||||
(void)msg;
|
||||
return (0);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* Broadcast s to every connected client except fd (fd = -1 means "everyone").
|
||||
* Remember: slots are indexed by fd, empty slots have fd == -1.
|
||||
* ------------------------------------------------------------------------- */
|
||||
void to_all_except(int fd, char *s)
|
||||
{
|
||||
/* TODO */
|
||||
(void)fd;
|
||||
(void)s;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* accept() the pending connection, fill its slot (fd, id = g_next_id++, buf),
|
||||
* raise g_maxfd if needed, then broadcast
|
||||
* "server: client %d just arrived\n"
|
||||
* to the OTHER clients (NOT to the newcomer).
|
||||
* If accept fails: just return.
|
||||
* ------------------------------------------------------------------------- */
|
||||
void accept_new(void)
|
||||
{
|
||||
/* TODO */
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* The client on fd is gone (recv() <= 0):
|
||||
* remember its id, close(fd), mark the slot free (-1), free its buffer,
|
||||
* broadcast "server: client %d just left\n" to everyone else,
|
||||
* then shrink g_maxfd while the last slot is empty (never below g_server).
|
||||
* The leftover partial line in the buffer is DROPPED, never flushed.
|
||||
* ------------------------------------------------------------------------- */
|
||||
void disconnect(int fd)
|
||||
{
|
||||
/* TODO */
|
||||
(void)fd;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------------------
|
||||
* recv() -> if <= 0: disconnect(fd).
|
||||
* Otherwise: append the chunk to this client's buffer (str_join), then in a
|
||||
* loop pull every complete line (extract_message) and broadcast
|
||||
* "client %d: <line>"
|
||||
* to the OTHER clients. Free the message extract_message gave you.
|
||||
* A chunk can contain several lines, a partial line, or both.
|
||||
* ------------------------------------------------------------------------- */
|
||||
void handle_read(int fd)
|
||||
{
|
||||
/* TODO */
|
||||
(void)fd;
|
||||
}
|
||||
|
||||
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 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)
|
||||
{
|
||||
/* STEP: rebuild the set from scratch — select() destroys it. */
|
||||
FD_ZERO(&readfds);
|
||||
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);
|
||||
}
|
||||
Executable
+60
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
# One-shot check for mini_serv:
|
||||
# [1/3] strict compile (-Wall -Wextra -Werror)
|
||||
# [2/3] behavioral tester (13 checks, offline)
|
||||
# [3/3] the real exam-style Grademe diff
|
||||
#
|
||||
# Usage: bash tester/check.sh [path/to/mini_serv.c]
|
||||
# Default source: sandbox/rendu/mini_serv/mini_serv.c
|
||||
#
|
||||
# Env: SKIP_GRADEME=1 -> stop after the behavioral tester
|
||||
set -u
|
||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
SRC="${1:-$ROOT/sandbox/rendu/mini_serv/mini_serv.c}"
|
||||
BIN="$ROOT/sandbox/mini_serv"
|
||||
|
||||
if [ ! -f "$SRC" ]; then
|
||||
echo "No source file at: $SRC"
|
||||
echo "Write your mini_serv.c there (exact filename matters), or pass a path."
|
||||
exit 2
|
||||
fi
|
||||
|
||||
echo "== [1/3] strict compile: cc -Wall -Wextra -Werror =="
|
||||
mkdir -p "$ROOT/sandbox"
|
||||
if ! cc -Wall -Wextra -Werror -g "$SRC" -o "$BIN"; then
|
||||
echo "COMPILE FAILED."
|
||||
exit 1
|
||||
fi
|
||||
echo "OK -> $BIN"
|
||||
|
||||
echo
|
||||
echo "== [2/3] behavioral tester =="
|
||||
if ! python3 "$ROOT/tester/mini_serv_tester.py" "$BIN"; then
|
||||
echo
|
||||
echo "Behavioral tests FAILED — fix and run again."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "${SKIP_GRADEME:-0}" = "1" ]; then
|
||||
echo
|
||||
echo "SKIP_GRADEME=1 -> stopping here. All green so far."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo
|
||||
echo "== [3/3] grademe final boss (exact exam-style diff, ~25s) =="
|
||||
cd "$ROOT/sandbox" || exit 1
|
||||
rm -f traceback .system/grading/passed
|
||||
bash .system/grading/tester.sh
|
||||
if [ -f .system/grading/passed ]; then
|
||||
echo "GRADEME: PASSED"
|
||||
echo
|
||||
echo "ALL GREEN. Now: close this, start from a blank file, and do it again."
|
||||
else
|
||||
echo "GRADEME: FAILED"
|
||||
echo "See sandbox/traceback (expected vs your output). First lines:"
|
||||
if [ -f traceback ]; then
|
||||
sed -n '1,40p' traceback
|
||||
fi
|
||||
exit 1
|
||||
fi
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
|
||||
# close fd before init
|
||||
exec 6<&-
|
||||
exec 6</dev/tcp/127.0.0.1/"$1"
|
||||
|
||||
while read -r <&6
|
||||
do
|
||||
echo "$REPLY"
|
||||
done
|
||||
@@ -0,0 +1,5 @@
|
||||
Ceci est un test de Ctrl+D dans ton programme ici:\04Si tu ne passes pas ce test, tu devrais verifier le fonctionnement du ctrl+d.
|
||||
voici
|
||||
un
|
||||
nouveau
|
||||
test
|
||||
@@ -0,0 +1,29 @@
|
||||
#!/bin/bash
|
||||
# Print the first free TCP port in [first_port, last_port]
|
||||
# (default: a random start in 8888-9887, so back-to-back runs use other ports).
|
||||
# Works with ss (Linux), lsof (macOS/Linux) or netstat, whichever is installed.
|
||||
|
||||
first_port=${1:-$((8888 + RANDOM % 1000))}
|
||||
last_port=${2:-$((first_port + 1000))}
|
||||
|
||||
port_in_use()
|
||||
{
|
||||
if command -v ss >/dev/null 2>&1; then
|
||||
ss -tuln 2>/dev/null | grep -q "[.:]$1 "
|
||||
elif command -v lsof >/dev/null 2>&1; then
|
||||
lsof -nP -iTCP:"$1" -sTCP:LISTEN >/dev/null 2>&1
|
||||
elif command -v netstat >/dev/null 2>&1; then
|
||||
netstat -an 2>/dev/null | grep -E "[.:]$1 " | grep -q LISTEN
|
||||
else
|
||||
# last resort: something accepts connections on this port
|
||||
(exec 3<>"/dev/tcp/127.0.0.1/$1") 2>/dev/null
|
||||
fi
|
||||
}
|
||||
|
||||
for ((port = first_port; port <= last_port; port++)); do
|
||||
if ! port_in_use "$port"; then
|
||||
echo "$port"
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
echo 0
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
# usage: bash test_eof.sh <port>
|
||||
# Sends eof_test one word at a time (with a literal ^D inside) on one connection.
|
||||
|
||||
PORT=$1
|
||||
|
||||
send_msg()
|
||||
{
|
||||
exec 3<>"/dev/tcp/127.0.0.1/$PORT" || return 1
|
||||
cat >&3
|
||||
exec 3>&-
|
||||
}
|
||||
|
||||
for x in $(cat eof_test); do
|
||||
printf "$x"
|
||||
sleep 0.1
|
||||
done | send_msg
|
||||
@@ -0,0 +1,125 @@
|
||||
#!/bin/bash
|
||||
# usage: bash test_miniserv.sh <port> (run from .system/grading)
|
||||
# Starts the student's server, connects a listener (catchmsg.sh) and several
|
||||
# short-lived clients, then stores everything the listener received in `bim`.
|
||||
# Only uses bash's /dev/tcp, so it does not depend on the installed nc flavor.
|
||||
|
||||
PORT=$1
|
||||
rm -f bim trace final
|
||||
|
||||
fail()
|
||||
{
|
||||
{
|
||||
echo "----------------8<-------------[ START TEST "
|
||||
printf "%b" "$1"
|
||||
echo "----------------8<------------- END TEST ]"
|
||||
} >> traceback
|
||||
}
|
||||
|
||||
send_msg()
|
||||
{
|
||||
exec 3<>"/dev/tcp/127.0.0.1/$PORT" || return 1
|
||||
cat >&3
|
||||
exec 3>&-
|
||||
}
|
||||
|
||||
# 0 = listening, 1 = not listening, 2 = no tool available to check
|
||||
port_listening()
|
||||
{
|
||||
if command -v ss >/dev/null 2>&1; then
|
||||
ss -tln 2>/dev/null | grep -q "[.:]$PORT "
|
||||
elif command -v lsof >/dev/null 2>&1; then
|
||||
lsof -nP -iTCP:"$PORT" -sTCP:LISTEN >/dev/null 2>&1
|
||||
elif command -v netstat >/dev/null 2>&1; then
|
||||
netstat -an 2>/dev/null | grep -E "[.:]$PORT " | grep -q LISTEN
|
||||
else
|
||||
return 2
|
||||
fi
|
||||
}
|
||||
|
||||
CC=$(command -v clang || command -v cc || command -v gcc)
|
||||
if ! "$CC" -o final ../../rendu/mini_serv/mini_serv.c > trace 2>&1 || [ ! -e final ]; then
|
||||
fail " 🔎 YOUR OUTPUT:\n$(cat trace)\n ❌ COMPILATION ERROR\n"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
SERVER=""
|
||||
CATCH=""
|
||||
|
||||
cleanup()
|
||||
{
|
||||
# stop the server first: the listener then reads EOF and flushes `bim`
|
||||
[ -n "$SERVER" ] && kill "$SERVER" 2>/dev/null
|
||||
[ -n "$SERVER" ] && wait "$SERVER" 2>/dev/null
|
||||
if [ -n "$CATCH" ]; then
|
||||
for _ in $(seq 1 20); do
|
||||
kill -0 "$CATCH" 2>/dev/null || break
|
||||
sleep 0.1
|
||||
done
|
||||
kill "$CATCH" 2>/dev/null
|
||||
wait "$CATCH" 2>/dev/null
|
||||
fi
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
# start the server and wait (max 3s) until it listens
|
||||
# 0 = listening, 1 = never listened, 2 = the process exited (e.g. bind failed)
|
||||
start_server()
|
||||
{
|
||||
./final "$PORT" > /dev/null 2>&1 &
|
||||
SERVER=$!
|
||||
for _ in $(seq 1 30); do
|
||||
port_listening
|
||||
case $? in
|
||||
0) return 0 ;;
|
||||
2) sleep 1; kill -0 "$SERVER" 2>/dev/null && return 0 || return 2 ;;
|
||||
esac
|
||||
kill -0 "$SERVER" 2>/dev/null || return 2
|
||||
sleep 0.1
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
# A port can still be busy (TIME_WAIT) right after a previous run, which
|
||||
# makes bind() fail: if the server exits at startup, retry on other ports.
|
||||
attempt=1
|
||||
while true; do
|
||||
start_server
|
||||
status=$?
|
||||
[ $status -eq 0 ] && break
|
||||
kill "$SERVER" 2>/dev/null
|
||||
wait "$SERVER" 2>/dev/null
|
||||
SERVER=""
|
||||
if [ $status -eq 1 ] || [ $attempt -ge 5 ]; then
|
||||
fail " ❌ PORT IS NOT OPEN \n 💻 TEST\n./a.out $PORT\n Connecting after the server is started\n Cannot connect to port $PORT\n"
|
||||
exit 1
|
||||
fi
|
||||
attempt=$((attempt + 1))
|
||||
PORT=$(bash findport.sh $((PORT + 1)))
|
||||
done
|
||||
|
||||
bash catchmsg.sh "$PORT" >> bim &
|
||||
CATCH=$!
|
||||
sleep 1
|
||||
|
||||
echo "Si vous ne voyez QUE ce message, c'est mauvais signe." | send_msg
|
||||
sleep 0.2
|
||||
echo "Bienvenue sur le test de votre miniserv" | send_msg
|
||||
sleep 0.2
|
||||
echo "Ceci est un message" | send_msg
|
||||
sleep 0.2
|
||||
printf "Voici un texte sans retour a la ligne" | send_msg
|
||||
sleep 0.2
|
||||
echo -n "This is a text without backline at the end" | send_msg
|
||||
sleep 0.4
|
||||
printf "Et voici un texte avec plusieurs\nretours\na\nla\nligne\n" | send_msg
|
||||
sleep 0.2
|
||||
|
||||
bash test_eof.sh "$PORT"
|
||||
sleep 1
|
||||
|
||||
send_msg < very_long_msg.txt
|
||||
sleep 1
|
||||
|
||||
send_msg < other_long_msg.txt
|
||||
sleep 2
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/bin/bash
|
||||
cd .system/grading/
|
||||
# if there is a traceback file then remove it
|
||||
if [ -e traceback ]; then
|
||||
rm traceback
|
||||
fi
|
||||
|
||||
echo "Test may be long, please wait..."
|
||||
|
||||
# for port in $(seq 4444 65000); do echo -ne "\035" | telnet 127.0.0.1 $port > /dev/null 2>&1; [ $? -eq 1 ] && break; done
|
||||
|
||||
PORT=$(bash findport.sh)
|
||||
|
||||
bash test_miniserv.sh $PORT &> /dev/null 2>&1
|
||||
|
||||
# if there is a final file and there is not a traceback file then the diff is check
|
||||
if [ -e final ] && [ ! -e traceback ]; then
|
||||
|
||||
DIFF=$(diff bim normal.output)
|
||||
if [ "$DIFF" != "" ]
|
||||
then
|
||||
|
||||
echo "----------------8<-------------[ START TEST " >> traceback
|
||||
printf " 💻 TEST\n./a.out $PORT\n" >> traceback
|
||||
printf " Then there is 3 connexion to the server\n" >> traceback
|
||||
printf " 🔎 YOUR OUTPUT:\n" >> traceback
|
||||
cat bim >> traceback
|
||||
printf " 🗝 EXPECTED OUTPUT:\n" >> traceback
|
||||
cat normal.output >> traceback
|
||||
echo "----------------8<------------- END TEST ]" >> traceback
|
||||
mv traceback ../../traceback
|
||||
cd ../../
|
||||
exit 1
|
||||
fi
|
||||
|
||||
touch passed
|
||||
else
|
||||
mv traceback ../../traceback
|
||||
fi
|
||||
cd ../../
|
||||
File diff suppressed because one or more lines are too long
Executable
+512
@@ -0,0 +1,512 @@
|
||||
#!/usr/bin/env python3
|
||||
"""mini_serv behavioral tester.
|
||||
|
||||
Usage:
|
||||
python3 mini_serv_tester.py <compiled-mini_serv> [--quick]
|
||||
|
||||
Mirrors what the exam-style grading script checks, plus edge cases:
|
||||
bad args, bind failure, arrival broadcast rules, per-line relay, split lines,
|
||||
no-flush-on-disconnect, id monotonicity, 0x04-as-data, a 400 KB single line,
|
||||
a no-newline payload, 25 clients, a lazy client that never reads, fd leaks.
|
||||
|
||||
Exit code 0 = all tests passed.
|
||||
|
||||
NOTE: client disconnects are serialized (small sleeps) on purpose — the real
|
||||
test does the same. RST/SIGPIPE storms are not part of the exam, so we don't
|
||||
weaponize them here.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
HOST = "127.0.0.1"
|
||||
PASS = "\033[32mPASS\033[0m"
|
||||
FAIL = "\033[31mFAIL\033[0m"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- helpers ---
|
||||
|
||||
def free_port():
|
||||
s = socket.socket()
|
||||
s.bind((HOST, 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close()
|
||||
return port
|
||||
|
||||
|
||||
def port_taken(port):
|
||||
"""Passive check: can we bind it? (No connection is made.)"""
|
||||
s = socket.socket()
|
||||
try:
|
||||
s.bind((HOST, port))
|
||||
return False
|
||||
except OSError:
|
||||
return True
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
class Server:
|
||||
def __init__(self, binary):
|
||||
self.binary = binary
|
||||
self.proc = None
|
||||
self.port = 0
|
||||
|
||||
def start(self):
|
||||
for _ in range(10):
|
||||
port = free_port()
|
||||
proc = subprocess.Popen(
|
||||
[self.binary, str(port)],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
for _ in range(60):
|
||||
if port_taken(port):
|
||||
self.proc, self.port = proc, port
|
||||
return port
|
||||
if proc.poll() is not None:
|
||||
break
|
||||
time.sleep(0.05)
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
raise RuntimeError("server never became reachable")
|
||||
|
||||
def stop(self):
|
||||
if self.proc and self.proc.poll() is None:
|
||||
self.proc.terminate()
|
||||
try:
|
||||
self.proc.wait(timeout=2)
|
||||
except subprocess.TimeoutExpired:
|
||||
self.proc.kill()
|
||||
self.proc.wait()
|
||||
|
||||
|
||||
def connect(port):
|
||||
s = socket.create_connection((HOST, port), timeout=5.0)
|
||||
s.settimeout(0.2)
|
||||
return s
|
||||
|
||||
|
||||
def drain(s, wait=0.4):
|
||||
data = b""
|
||||
deadline = time.time() + wait
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
chunk = s.recv(1 << 20)
|
||||
if not chunk:
|
||||
break
|
||||
data += chunk
|
||||
deadline = time.time() + 0.15
|
||||
except socket.timeout:
|
||||
continue
|
||||
except OSError:
|
||||
break
|
||||
return data
|
||||
|
||||
|
||||
def close_all(*socks):
|
||||
for s in socks:
|
||||
if s is None:
|
||||
continue
|
||||
try:
|
||||
s.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
|
||||
class Collector(threading.Thread):
|
||||
"""Background reader for scenarios where the client must drain while
|
||||
another client is still sending (otherwise kernel buffers can deadlock
|
||||
the test, not the server)."""
|
||||
|
||||
def __init__(self, sock):
|
||||
super().__init__(daemon=True)
|
||||
self.sock = sock
|
||||
self.data = b""
|
||||
self._stop = False
|
||||
|
||||
def run(self):
|
||||
self.sock.settimeout(0.2)
|
||||
while not self._stop:
|
||||
try:
|
||||
chunk = self.sock.recv(1 << 20)
|
||||
if not chunk:
|
||||
break
|
||||
self.data += chunk
|
||||
except socket.timeout:
|
||||
continue
|
||||
except OSError:
|
||||
break
|
||||
|
||||
def stop(self):
|
||||
self._stop = True
|
||||
self.join(timeout=2)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ tests ---
|
||||
|
||||
def t_bad_args(binary):
|
||||
r = subprocess.run([binary], capture_output=True, timeout=10)
|
||||
if r.returncode != 1:
|
||||
return False, f"exit code {r.returncode}, want 1"
|
||||
if r.stderr != b"Wrong number of arguments\n":
|
||||
return False, f"stderr {r.stderr!r}, want b'Wrong number of arguments\\n'"
|
||||
return True, "exit 1 + exact stderr"
|
||||
|
||||
|
||||
def t_bind_failure(binary):
|
||||
port = free_port()
|
||||
blocker = socket.socket()
|
||||
blocker.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
blocker.bind((HOST, port))
|
||||
blocker.listen(1)
|
||||
try:
|
||||
r = subprocess.run([binary, str(port)], capture_output=True, timeout=10)
|
||||
finally:
|
||||
blocker.close()
|
||||
if r.returncode != 1:
|
||||
return False, f"exit code {r.returncode}, want 1"
|
||||
if r.stderr != b"Fatal error\n":
|
||||
return False, f"stderr {r.stderr!r}, want b'Fatal error\\n'"
|
||||
return True, "exit 1 + exact stderr"
|
||||
|
||||
|
||||
def t_arrivals(binary):
|
||||
srv = Server(binary)
|
||||
port = srv.start()
|
||||
c0 = c1 = None
|
||||
try:
|
||||
c0 = connect(port)
|
||||
got = drain(c0, 0.5)
|
||||
if got:
|
||||
return False, f"client 0 received {got!r} on its own connect, want silence"
|
||||
c1 = connect(port)
|
||||
got0, got1 = drain(c0), drain(c1, 0.3)
|
||||
want = b"server: client 1 just arrived\n"
|
||||
if got0 != want:
|
||||
return False, f"client 0 got {got0!r}, want {want!r}"
|
||||
if got1:
|
||||
return False, f"newcomer got {got1!r}, want silence (arrival is for OTHERS only)"
|
||||
return True, "arrival broadcast to others only; first id is 0"
|
||||
finally:
|
||||
close_all(c0, c1)
|
||||
srv.stop()
|
||||
|
||||
|
||||
def t_chat(binary):
|
||||
srv = Server(binary)
|
||||
port = srv.start()
|
||||
c0 = c1 = c2 = None
|
||||
try:
|
||||
c0, c1, c2 = connect(port), connect(port), connect(port)
|
||||
drain(c0, 0.5)
|
||||
drain(c1, 0.3)
|
||||
c1.sendall(b"hello\n")
|
||||
g0, g2, g1 = drain(c0), drain(c2), drain(c1, 0.3)
|
||||
want = b"client 1: hello\n"
|
||||
if g0 != want or g2 != want:
|
||||
return False, f"c0={g0!r} c2={g2!r}, want {want!r} each"
|
||||
if g1:
|
||||
return False, f"sender received its own message: {g1!r}"
|
||||
c0.sendall(b"a\nb\n")
|
||||
want2 = b"client 0: a\nclient 0: b\n"
|
||||
g1, g2 = drain(c1), drain(c2)
|
||||
if g1 != want2 or g2 != want2:
|
||||
return False, f"multi-line c1={g1!r} c2={g2!r}, want {want2!r}"
|
||||
return True, "relay to others; one 'client N: ' prefix per line"
|
||||
finally:
|
||||
close_all(c0, c1, c2)
|
||||
srv.stop()
|
||||
|
||||
|
||||
def t_split_line(binary):
|
||||
srv = Server(binary)
|
||||
port = srv.start()
|
||||
c0 = c1 = None
|
||||
try:
|
||||
c0, c1 = connect(port), connect(port)
|
||||
drain(c0, 0.5)
|
||||
c1.sendall(b"par")
|
||||
if drain(c0, 0.35):
|
||||
return False, "server emitted something for an incomplete line"
|
||||
c1.sendall(b"tial\n")
|
||||
got = drain(c0)
|
||||
want = b"client 1: partial\n"
|
||||
if got != want:
|
||||
return False, f"got {got!r}, want {want!r}"
|
||||
return True, "partial line held, completed by the next packet"
|
||||
finally:
|
||||
close_all(c0, c1)
|
||||
srv.stop()
|
||||
|
||||
|
||||
def t_no_flush_on_eof(binary):
|
||||
srv = Server(binary)
|
||||
port = srv.start()
|
||||
c0 = c1 = None
|
||||
try:
|
||||
c0, c1 = connect(port), connect(port)
|
||||
drain(c0, 0.5)
|
||||
c1.sendall(b"never terminated")
|
||||
time.sleep(0.3)
|
||||
c1.close()
|
||||
c1 = None
|
||||
got = drain(c0, 1.0)
|
||||
want = b"server: client 1 just left\n"
|
||||
if got != want:
|
||||
return False, f"got {got!r}, want {want!r} (leftover partial must be dropped)"
|
||||
return True, "partial line dropped on disconnect; 'left' broadcast sent"
|
||||
finally:
|
||||
close_all(c0, c1)
|
||||
srv.stop()
|
||||
|
||||
|
||||
def t_ids_increment(binary):
|
||||
srv = Server(binary)
|
||||
port = srv.start()
|
||||
c0 = c1 = c2 = None
|
||||
try:
|
||||
c0 = connect(port)
|
||||
c1 = connect(port)
|
||||
drain(c0, 0.5)
|
||||
c1.close()
|
||||
c1 = None
|
||||
drain(c0, 0.4)
|
||||
c2 = connect(port)
|
||||
got = drain(c0)
|
||||
want = b"server: client 2 just arrived\n"
|
||||
if got != want:
|
||||
return False, f"got {got!r}, want {want!r} (id must not be reused)"
|
||||
return True, "ids increment forever, never reused"
|
||||
finally:
|
||||
close_all(c0, c1, c2)
|
||||
srv.stop()
|
||||
|
||||
|
||||
def t_ctrl_d_is_data(binary):
|
||||
srv = Server(binary)
|
||||
port = srv.start()
|
||||
c0 = c1 = None
|
||||
try:
|
||||
c0, c1 = connect(port), connect(port)
|
||||
drain(c0, 0.5)
|
||||
c1.sendall(b"a\x04b\n")
|
||||
got = drain(c0)
|
||||
want = b"client 1: a\x04b\n"
|
||||
if got != want:
|
||||
return False, f"got {got!r}, want {want!r}"
|
||||
return True, "0x04 relayed as plain data"
|
||||
finally:
|
||||
close_all(c0, c1)
|
||||
srv.stop()
|
||||
|
||||
|
||||
def t_big_line(binary):
|
||||
srv = Server(binary)
|
||||
port = srv.start()
|
||||
c0 = c1 = None
|
||||
col = None
|
||||
try:
|
||||
c0, c1 = connect(port), connect(port)
|
||||
drain(c0, 0.5)
|
||||
payload = b"y" * 400000 + b"\n"
|
||||
want = b"client 1: " + payload
|
||||
col = Collector(c0)
|
||||
col.start()
|
||||
c1.sendall(payload)
|
||||
deadline = time.time() + 10
|
||||
while time.time() < deadline and col.data != want:
|
||||
time.sleep(0.05)
|
||||
col.stop()
|
||||
if col.data != want:
|
||||
return False, f"got {len(col.data)} bytes, want {len(want)}"
|
||||
return True, "400 KB single line relayed intact"
|
||||
finally:
|
||||
if col:
|
||||
col.stop()
|
||||
close_all(c0, c1)
|
||||
srv.stop()
|
||||
|
||||
|
||||
def t_no_newline_dropped(binary):
|
||||
srv = Server(binary)
|
||||
port = srv.start()
|
||||
c0 = c1 = None
|
||||
try:
|
||||
c0, c1 = connect(port), connect(port)
|
||||
drain(c0, 0.5)
|
||||
c1.sendall(b"z" * 10000)
|
||||
time.sleep(0.4)
|
||||
c1.close()
|
||||
c1 = None
|
||||
got = drain(c0, 1.0)
|
||||
want = b"server: client 1 just left\n"
|
||||
if got != want:
|
||||
return False, f"got {got[:120]!r}..., want {want!r}"
|
||||
return True, "10 KB no-newline payload buffered then dropped"
|
||||
finally:
|
||||
close_all(c0, c1)
|
||||
srv.stop()
|
||||
|
||||
|
||||
def t_many_clients(binary):
|
||||
srv = Server(binary)
|
||||
port = srv.start()
|
||||
clients = []
|
||||
try:
|
||||
clients.append(connect(port))
|
||||
for _ in range(24):
|
||||
clients.append(connect(port))
|
||||
time.sleep(0.02)
|
||||
want_arr = b"".join(b"server: client %d just arrived\n" % i
|
||||
for i in range(1, 25))
|
||||
got = drain(clients[0], 1.5)
|
||||
if got != want_arr:
|
||||
return False, f"arrivals mismatch: {len(got)} bytes vs {len(want_arr)} expected"
|
||||
for c in clients[1:]:
|
||||
c.close()
|
||||
time.sleep(0.12)
|
||||
want_left = b"".join(b"server: client %d just left\n" % i
|
||||
for i in range(1, 25))
|
||||
got = drain(clients[0], 2.0)
|
||||
if got != want_left:
|
||||
return False, f"departures mismatch: {len(got)} bytes vs {len(want_left)} expected"
|
||||
return True, "25 clients: arrivals and departures in order"
|
||||
finally:
|
||||
close_all(*clients)
|
||||
srv.stop()
|
||||
|
||||
|
||||
def t_lazy_client(binary):
|
||||
"""c0 never reads while others chat. The server must not drop c0, must not
|
||||
lose data for it, and must stay responsive."""
|
||||
srv = Server(binary)
|
||||
port = srv.start()
|
||||
c0 = c1 = c2 = None
|
||||
try:
|
||||
n = 500
|
||||
chunk1 = (b"client 1: " + b"a" * 40 + b"\n") * n
|
||||
chunk2 = (b"client 2: " + b"b" * 40 + b"\n") * n
|
||||
c0 = connect(port) # lazy: never reads until the end
|
||||
c1 = connect(port)
|
||||
time.sleep(0.25) # server sends arrival to c0
|
||||
c1.sendall((b"a" * 40 + b"\n") * n)
|
||||
time.sleep(0.4)
|
||||
c2 = connect(port)
|
||||
time.sleep(0.25)
|
||||
c2.sendall((b"b" * 40 + b"\n") * n + b"final\n")
|
||||
time.sleep(0.4)
|
||||
c0.sendall(b"ping\n")
|
||||
time.sleep(0.25)
|
||||
exp_c0 = (b"server: client 1 just arrived\n"
|
||||
+ chunk1
|
||||
+ b"server: client 2 just arrived\n"
|
||||
+ chunk2
|
||||
+ b"client 2: final\n")
|
||||
exp_c1 = (b"server: client 2 just arrived\n"
|
||||
+ chunk2
|
||||
+ b"client 2: final\n"
|
||||
+ b"client 0: ping\n")
|
||||
exp_c2 = b"client 0: ping\n"
|
||||
got0, got1, got2 = drain(c0, 3.0), drain(c1, 1.0), drain(c2, 0.5)
|
||||
if got0 != exp_c0:
|
||||
return False, f"lazy client c0: {len(got0)} bytes, want {len(exp_c0)}"
|
||||
if got1 != exp_c1:
|
||||
return False, f"c1: {len(got1)} bytes, want {len(exp_c1)}"
|
||||
if got2 != exp_c2:
|
||||
return False, f"c2: {got2!r}, want {exp_c2!r}"
|
||||
if srv.proc.poll() is not None:
|
||||
return False, "server died during the scenario"
|
||||
return True, "lazy client kept, no data lost, server alive"
|
||||
finally:
|
||||
close_all(c0, c1, c2)
|
||||
srv.stop()
|
||||
|
||||
|
||||
def t_fd_leaks(binary):
|
||||
srv = Server(binary)
|
||||
port = srv.start()
|
||||
socks = []
|
||||
try:
|
||||
fd_dir = f"/proc/{srv.proc.pid}/fd"
|
||||
base = len(os.listdir(fd_dir))
|
||||
for _ in range(10):
|
||||
socks.append(connect(port))
|
||||
time.sleep(0.05)
|
||||
time.sleep(0.3)
|
||||
for s in socks:
|
||||
s.close()
|
||||
time.sleep(0.25)
|
||||
socks = []
|
||||
time.sleep(0.5)
|
||||
now = len(os.listdir(fd_dir))
|
||||
if now > base + 2:
|
||||
return False, f"fds before={base}, after={now} — looks like a leak"
|
||||
return True, f"fds stable ({base} -> {now})"
|
||||
finally:
|
||||
close_all(*socks)
|
||||
srv.stop()
|
||||
|
||||
|
||||
TESTS = [
|
||||
("args: no argument -> exit 1 + 'Wrong number of arguments\\n'", t_bad_args),
|
||||
("bind failure -> exit 1 + 'Fatal error\\n'", t_bind_failure),
|
||||
("connect: arrival broadcast goes to others only", t_arrivals),
|
||||
("chat: relay to others, one prefix per line", t_chat),
|
||||
("chat: line split across packets is reassembled", t_split_line),
|
||||
("disconnect: partial line is dropped, not flushed", t_no_flush_on_eof),
|
||||
("ids increment, never reused", t_ids_increment),
|
||||
("0x04 byte is data, not EOF", t_ctrl_d_is_data),
|
||||
("400 KB single line relayed intact", t_big_line),
|
||||
("10 KB line without newline: dropped on disconnect", t_no_newline_dropped),
|
||||
("25 clients: arrivals and departures in order", t_many_clients),
|
||||
("lazy client: kept connected, no data loss", t_lazy_client),
|
||||
("fd leak check after connect/disconnect churn", t_fd_leaks),
|
||||
]
|
||||
|
||||
QUICK_SKIP = {"400 KB single line relayed intact",
|
||||
"25 clients: arrivals and departures in order",
|
||||
"lazy client: kept connected, no data loss"}
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description="mini_serv behavioral tester")
|
||||
ap.add_argument("binary", help="compiled mini_serv executable")
|
||||
ap.add_argument("--quick", action="store_true",
|
||||
help="skip the heavy 400 KB / 25-client / lazy-client tests")
|
||||
args = ap.parse_args()
|
||||
|
||||
if not os.path.exists(args.binary):
|
||||
print(f"binary not found: {args.binary}")
|
||||
return 2
|
||||
|
||||
failures = 0
|
||||
for name, fn in TESTS:
|
||||
if args.quick and name in QUICK_SKIP:
|
||||
print(f"[SKIP] {name}")
|
||||
continue
|
||||
t0 = time.time()
|
||||
try:
|
||||
ok, msg = fn(args.binary)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
ok, msg = False, f"tester exception: {exc!r}"
|
||||
dt = time.time() - t0
|
||||
print(f"[{PASS if ok else FAIL}] {name} ({dt:.1f}s)")
|
||||
print(f" {msg}")
|
||||
if not ok:
|
||||
failures += 1
|
||||
|
||||
print()
|
||||
if failures:
|
||||
print(f"{failures} test(s) failed.")
|
||||
else:
|
||||
print("all tests passed.")
|
||||
return 1 if failures else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
+479
@@ -0,0 +1,479 @@
|
||||
# Walkthrough — every block of code, then the behavior it produces
|
||||
|
||||
> **How to use this file.** Keep `reference/mini_serv.c` open next to it. Go station by
|
||||
> station: read the code, *predict* what the behaviour probe will show, then run it.
|
||||
> Every block marked **See it** contains real output captured from this machine — if yours
|
||||
> differs, you just found your bug.
|
||||
>
|
||||
> Helper used in the probes (same trick the grader uses):
|
||||
> ```bash
|
||||
> send() { exec 3<>/dev/tcp/127.0.0.1/"$1"; cat >&3; exec 3>&-; }
|
||||
> ```
|
||||
|
||||
**Station map:**
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
S1["1-4 · stages A-B<br/>file top, fatal, socket, bind+listen"] --> S2["5-6 · stage C<br/>slots + select loop"]
|
||||
S2 --> S3["7-8 · stage C<br/>accept + broadcast"]
|
||||
S3 --> S4["9-10 · stage D<br/>recv, buffer, extract, relay"]
|
||||
S4 --> S5["11 · stage E<br/>disconnect + cleanup"]
|
||||
S5 --> S6["12 · stage F<br/>the graders"]
|
||||
S6 --> S7["13-14 · audit + self-quiz"]
|
||||
```
|
||||
|
||||
Stations carry their `typing-script.md` stage tag so you can work in parallel with drilling.
|
||||
|
||||
---
|
||||
|
||||
## Station 1 · Top of the file: includes, struct, globals `[stage A]`
|
||||
|
||||
```c
|
||||
typedef struct s_client { int fd; int id; char *buf; } t_client;
|
||||
static t_client g_c[FD_SETSIZE];
|
||||
static int g_maxfd, g_server, g_next_id;
|
||||
```
|
||||
|
||||
- `fd` — slot marker: `-1` means "not a client". That's why the array can be indexed by fd.
|
||||
- `id` — the number announced in messages; **not** the fd (fds get recycled, ids never do).
|
||||
- `buf` — the pending partial line (append with `str_join`, mine lines with `extract_message`).
|
||||
- `g_c[FD_SETSIZE]` — one slot per possible fd; `FD_SETSIZE` is 1024, the ceiling of `select`.
|
||||
- `g_maxfd` — highest fd in use; `select` and every scan loop depend on it.
|
||||
- `g_server` — the listening fd, kept separately so `max_fd` shrinking never drops it.
|
||||
- `g_next_id` — the counter behind `id`; only ever increments.
|
||||
|
||||
**See it** — nothing runs, but it must compile clean:
|
||||
|
||||
```console
|
||||
$ cc -Wall -Wextra -Werror -c reference/mini_serv.c -o /tmp/x.o
|
||||
$ echo $?
|
||||
0
|
||||
```
|
||||
|
||||
If this fails, you're not writing mini_serv yet, you're writing C. Fix that first.
|
||||
|
||||
---
|
||||
|
||||
## Station 2 · `fatal()` and the argument guard `[stage B]`
|
||||
|
||||
```c
|
||||
static void fatal(void) { write(2, "Fatal error\n", 12); exit(1); }
|
||||
|
||||
if (argc != 2)
|
||||
{
|
||||
write(2, "Wrong number of arguments\n", 26);
|
||||
return (1);
|
||||
}
|
||||
```
|
||||
|
||||
- `write(2, ...)` — fd 2 is stderr (never stdout, never `printf`).
|
||||
- The `\n` is inside the string, and the length counts it: `"Fatal error\n"` = 12, `"Wrong number of arguments\n"` = 26. The grader diffs these bytes.
|
||||
- Both paths exit status **1**.
|
||||
|
||||
**See it:**
|
||||
|
||||
```console
|
||||
$ ./mini_serv
|
||||
Wrong number of arguments
|
||||
$ echo $?
|
||||
1
|
||||
|
||||
$ ./mini_serv 1 # port 1 needs root → bind fails → fatal()
|
||||
Fatal error
|
||||
$ echo $?
|
||||
1
|
||||
```
|
||||
|
||||
The port-1 trick is a free way to test the `Fatal error` path on purpose.
|
||||
**Grader link:** behavioral tests 1 (bad args) and 2 (bind failure).
|
||||
|
||||
---
|
||||
|
||||
## Station 3 · `socket()` and the address struct `[stage B]`
|
||||
|
||||
```c
|
||||
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 */
|
||||
addr.sin_port = htons(atoi(argv[1]));
|
||||
```
|
||||
|
||||
- `AF_INET` + `SOCK_STREAM` = IPv4 + TCP.
|
||||
- `bzero` — zero the struct first, or `bind` reads garbage.
|
||||
- `2130706433` = `0x7F000001` = the four bytes `127.0.0.1`. `htonl` converts to network byte order.
|
||||
- `atoi(argv[1])` — argv is text; `htons` again for byte order.
|
||||
|
||||
**See it** — the kernel gives your new socket the lowest free fd, and `/proc` shows it:
|
||||
|
||||
```console
|
||||
$ ls -l /proc/$PID/fd
|
||||
0 -> /dev/null
|
||||
1 -> /dev/null
|
||||
2 -> /dev/null
|
||||
3 -> socket:[870369] <- the listening socket
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Station 4 · `bind` + `listen` — becoming reachable `[stage B]`
|
||||
|
||||
```c
|
||||
if (bind(g_server, (struct sockaddr *)&addr, sizeof(addr)) < 0) fatal();
|
||||
if (listen(g_server, 10) < 0) fatal();
|
||||
```
|
||||
|
||||
- `bind` claims `127.0.0.1:port`; captured errors go to `fatal()`.
|
||||
- The cast to `struct sockaddr *` is just C's way of passing a concrete struct to a generic API.
|
||||
- `listen(fd, 10)` turns on accepting; `10` is the kernel backlog (queue of connected-but-unaccepted clients).
|
||||
|
||||
**See it:**
|
||||
|
||||
```console
|
||||
$ ss -tlnp | grep 8091
|
||||
LISTEN 0 10 127.0.0.1:8091 0.0.0.0:* users:(("ref_mini_serv",pid=127850,fd=3))
|
||||
```
|
||||
|
||||
Read that line: state `LISTEN`, backlog `10`, address `127.0.0.1:8091`, and the program's
|
||||
listening `fd=3`. A second instance on the same port gets `Fatal error` (bind → `EADDRINUSE`).
|
||||
The full "connections queue before accept" demo is `explore/02_bind_listen.c`.
|
||||
|
||||
---
|
||||
|
||||
## Station 5 · Slot initialisation and `g_maxfd` `[stage C]`
|
||||
|
||||
```c
|
||||
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;
|
||||
```
|
||||
|
||||
**Behavior:** the invariant everything else assumes: "every loop scans `0..g_maxfd`, and any
|
||||
slot with `fd != -1` is a live client".
|
||||
|
||||
**How it breaks (and where you'll see it):** forget to raise `g_maxfd` in `accept_new` and the
|
||||
second client is invisible — you'll see it immediately in the 25-client behavioral test
|
||||
("only the first one works").
|
||||
|
||||
---
|
||||
|
||||
## Station 6 · Loop head: rebuild the set, then sleep `[stage C]`
|
||||
|
||||
```c
|
||||
while (1)
|
||||
{
|
||||
FD_ZERO(&readfds);
|
||||
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 ;
|
||||
```
|
||||
|
||||
- `FD_ZERO` — fresh bitmap every iteration, because `select` **destroys** the one you give it.
|
||||
- `FD_SET(g_server)` — the listener is the source of "new connection" events.
|
||||
- `FD_SET(i)` for each live client — the sources of data/EOF events.
|
||||
- `select(max + 1, ...)` — `nfds` = "watch fds 0..max". Sleep until any watched fd is ready.
|
||||
- `< 0` (e.g. `EINTR`) — just retry; do **not** exit the server for a signal poke.
|
||||
|
||||
**See it** — an idle server must be *asleep*, not spinning:
|
||||
|
||||
```console
|
||||
$ ps -o %cpu= -p $PID
|
||||
0.0
|
||||
```
|
||||
|
||||
If you see ~100% with no clients, you broke the rebuild (or never consumed readiness) —
|
||||
that is the single most common exam bug. See `debugging.md` §5.
|
||||
|
||||
---
|
||||
|
||||
## Station 7 · `accept_new()` — a client is born `[stage C]`
|
||||
|
||||
```c
|
||||
fd = accept(g_server, NULL, NULL);
|
||||
if (fd < 0) return ;
|
||||
g_c[fd].fd = fd;
|
||||
g_c[fd].id = g_next_id++;
|
||||
g_c[fd].buf = NULL;
|
||||
if (fd > g_maxfd) g_maxfd = fd;
|
||||
sprintf(msg, "server: client %d just arrived\n", g_c[fd].id);
|
||||
to_all_except(fd, msg);
|
||||
```
|
||||
|
||||
- `accept` returns a **new fd** per connection (the listener keeps listening).
|
||||
- `id = g_next_id++` — 0, 1, 2, … forever. Independent of fd.
|
||||
- `buf = NULL` — fresh client, empty pending line.
|
||||
- `g_maxfd` rises so the next `select` watches the newcomer.
|
||||
- `to_all_except(fd, ...)` — **not** to the newcomer.
|
||||
|
||||
**See it** — two terminals connect; only the older one hears about it:
|
||||
|
||||
```console
|
||||
# terminal A: nc 127.0.0.1 8091 (connects, sees nothing yet)
|
||||
# terminal B: nc 127.0.0.1 8091 (connects)
|
||||
# terminal A now shows:
|
||||
server: client 1 just arrived
|
||||
# terminal B shows nothing — and that is CORRECT (arrival is "others only")
|
||||
```
|
||||
|
||||
And the fd table grows while they're connected:
|
||||
|
||||
```console
|
||||
$ ls -l /proc/$PID/fd
|
||||
3 -> socket:[870369] <- listener
|
||||
4 -> socket:[872305] <- client A
|
||||
5 -> socket:[872306] <- client B
|
||||
|
||||
$ ss -tn | grep 8095
|
||||
ESTAB 30 0 127.0.0.1:57962 127.0.0.1:8095
|
||||
ESTAB 0 0 127.0.0.1:57974 127.0.0.1:8095
|
||||
```
|
||||
|
||||
ids vs fds: right now A has fd 4 / id 0, B has fd 5 / id 1. Disconnect A, connect C — C gets
|
||||
fd 4 again (kernel recycles) but id 2 (your counter never recycles). The grader checks the id.
|
||||
|
||||
---
|
||||
|
||||
## Station 8 · `to_all_except()` — the loudspeaker `[stage C/D]`
|
||||
|
||||
```c
|
||||
i = 0;
|
||||
while (i <= g_maxfd)
|
||||
{
|
||||
if (i != fd && g_c[i].fd != -1)
|
||||
send(g_c[i].fd, s, strlen(s), 0);
|
||||
i++;
|
||||
}
|
||||
```
|
||||
|
||||
- Skip the source (`i != fd`), skip dead slots (`fd != -1`), send the whole message in one call.
|
||||
- `fd = -1` means "everyone" (used for departures).
|
||||
|
||||
**See it:** in terminal A press keys + Enter → terminal B shows `client 0: hihi`. Terminal A
|
||||
shows nothing of itself. If the sender *does* see its own message, you removed this check —
|
||||
that's behavioral test 4 failing.
|
||||
|
||||
---
|
||||
|
||||
## Station 9 · `handle_read()` part 1 — recv and append `[stage D]`
|
||||
|
||||
```c
|
||||
n = recv(fd, tmp, sizeof(tmp) - 1, 0);
|
||||
if (n <= 0) { disconnect(fd); return ; }
|
||||
tmp[n] = 0;
|
||||
g_c[fd].buf = str_join(g_c[fd].buf, tmp);
|
||||
if (!g_c[fd].buf) fatal();
|
||||
```
|
||||
|
||||
- `sizeof(tmp) - 1` — room for your own `\0` at `tmp[n]`.
|
||||
- `n <= 0` — `0` is EOF, `< 0` is error; **both** mean "client is gone".
|
||||
- Append **before** extracting: a packet may hold 5 lines, half a line, or both.
|
||||
- `str_join` returns a new heap string and frees the old one; `NULL` means OOM → fatal.
|
||||
|
||||
**See it** — this is a real captured session. Add three temporary prints (recipe below),
|
||||
connect one listener + one sender, send `hel` then `lo`+`world`:
|
||||
|
||||
```console
|
||||
[recv] fd=5 n=3
|
||||
[buf ] fd=5 buf="hel"
|
||||
[recv] fd=5 n=9
|
||||
[buf ] fd=5 buf="hello
|
||||
world
|
||||
"
|
||||
```
|
||||
|
||||
Read it carefully: 3 bytes arrive, the buffer holds `hel` — **nothing is sent** (no `\n`).
|
||||
Then 9 more bytes arrive; the buffer now holds `hello\nworld\n`. The temp prints:
|
||||
|
||||
```c
|
||||
fprintf(stderr, "[recv] fd=%d n=%d\n", fd, n); /* after tmp[n] = 0 */
|
||||
fprintf(stderr, "[buf ] fd=%d buf=\"%s\"\n", fd, g_c[fd].buf); /* before the while */
|
||||
```
|
||||
|
||||
**Behavior drills** (with the `send()` helper, other client watching):
|
||||
| input | other side sees | why |
|
||||
|---|---|---|
|
||||
| `printf 'hello\n' \| send 8091` | `client 1: hello` | complete line |
|
||||
| `{ printf 'par'; sleep 1; printf 'tial\n'; } \| send 8091` | one `client 1: partial` only after the second chunk | buffer holds, no early flush |
|
||||
| `printf 'a\nb\n' \| send 8091` | `client 1: a` then `client 1: b` | per-line relay |
|
||||
| `printf 'abc' \| send 8091` (then close) | **nothing** + `just left` | leftover dropped |
|
||||
|
||||
---
|
||||
|
||||
## Station 10 · `handle_read()` part 2 — extract, build, send, free `[stage D]`
|
||||
|
||||
```c
|
||||
while (extract_message(&g_c[fd].buf, &msg) == 1)
|
||||
{
|
||||
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);
|
||||
}
|
||||
```
|
||||
|
||||
- `while (... == 1)` — one iteration per complete line in the buffer.
|
||||
- `malloc(strlen(msg) + 64)` — room for `"client N: "` + line + `\0`; a line can be 364 KB,
|
||||
so you must size it, never use a fixed buffer.
|
||||
- `sprintf` builds the exact wire format; `send` delivers it to others only.
|
||||
- `free(out)` and `free(msg)` — `extract_message` handed you ownership of that slice.
|
||||
|
||||
**See it** (same captured session, right after Station 9's output):
|
||||
|
||||
```console
|
||||
[send] fd=5 to_others="client 1: hello
|
||||
"
|
||||
[send] fd=5 to_others="client 1: world
|
||||
"
|
||||
```
|
||||
|
||||
Two sends from one `recv` of 9 bytes — the buffer produced two complete lines.
|
||||
**Grader link:** tests 4–6 (relay, split, multiline) and the 400 KB test.
|
||||
|
||||
---
|
||||
|
||||
## Station 11 · `disconnect()` — goodbye, cleanly `[stage E]`
|
||||
|
||||
```c
|
||||
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--;
|
||||
```
|
||||
|
||||
- Save `id` first — after clearing the slot you can't build the message.
|
||||
- `close` + mark dead + `free` the pending line (which is **dropped**, never flushed).
|
||||
- Broadcast to everyone; then let `g_maxfd` fall back over empty trailing slots
|
||||
(but never below `g_server`, or `select` stops watching the listener).
|
||||
|
||||
**See it:**
|
||||
|
||||
```console
|
||||
# terminal A watching; in B press Ctrl-C (or let the scripted sender end)
|
||||
# terminal A shows:
|
||||
server: client 1 just left
|
||||
|
||||
$ ls -l /proc/$PID/fd # after everyone left
|
||||
3 -> socket:[870369] # back to the listener only — no fd leak
|
||||
```
|
||||
|
||||
Partial-drop proof: `printf 'abc' | send 8091` then A shows *only* `just left` — no `abc`.
|
||||
**Grader link:** test 6 (no-flush) and test 13 (fd stability).
|
||||
|
||||
---
|
||||
|
||||
## Station 12 · The whole program, graded `[stage F]`
|
||||
|
||||
```console
|
||||
$ bash tester/check.sh
|
||||
== [1/3] strict compile: cc -Wall -Wextra -Werror ==
|
||||
OK -> .../sandbox/mini_serv
|
||||
== [2/3] behavioral tester ==
|
||||
... 13 × PASS ...
|
||||
all tests passed.
|
||||
== [3/3] grademe final boss (exact exam-style diff, ~25s) ==
|
||||
GRADEME: PASSED
|
||||
```
|
||||
|
||||
On failure, `sandbox/traceback` shows expected-vs-yours, first difference first.
|
||||
Map of ground truth → implementation:
|
||||
|
||||
| Grader expectation | Implemented in |
|
||||
|---|---|
|
||||
| exact arg/bind errors + exit 1 | Station 2 |
|
||||
| arrival to others only | Station 7 + 8 |
|
||||
| per-line prefix relay | Station 10 |
|
||||
| split lines reassembled | Station 9 |
|
||||
| partial dropped on disconnect | Station 11 |
|
||||
| ids monotonic | Station 7 |
|
||||
| 364 KB line | Station 10 (`malloc(strlen+64)`) |
|
||||
| fd/memory cleanliness | Stations 11 + 13 |
|
||||
|
||||
---
|
||||
|
||||
## Station 13 · Audit day: valgrind tells the truth (and one honest finding)
|
||||
|
||||
```console
|
||||
$ valgrind --leak-check=full --track-fds=yes ./mini_serv 8093
|
||||
# ... run a small session: two clients chat, one leaves mid-line, then Ctrl-C the server ...
|
||||
==129228== HEAP SUMMARY:
|
||||
==129228== in use at exit: 0 bytes in 0 blocks
|
||||
==129228== All heap blocks were freed -- no leaks are possible
|
||||
```
|
||||
|
||||
That's the line you want. Now the honest finding from the same session — this happened:
|
||||
|
||||
```console
|
||||
==129228== Process terminating with default action of signal 13 (SIGPIPE)
|
||||
==129228== at ... send
|
||||
==129228== by ... to_all_except
|
||||
==129228== by ... disconnect
|
||||
==129228== by ... handle_read
|
||||
```
|
||||
|
||||
The server was **killed by SIGPIPE** because my test client closed a socket while it had
|
||||
unread messages waiting (that makes the kernel answer with RST; the next `send` to it raises
|
||||
`EPIPE` + SIGPIPE, default action: die). The official grader never does that — its clients
|
||||
read everything or close cleanly one at a time — which is why plain `send` passes. Options if
|
||||
you want armor anyway: `send(fd, s, len, MSG_NOSIGNAL)` (Linux; `send` is allowed), or
|
||||
`signal(SIGPIPE, SIG_IGN)` (not in the allowed list — only with care). Exit code when it
|
||||
happens to you: `141` (128+13).
|
||||
|
||||
Same report, the other line:
|
||||
|
||||
```console
|
||||
==129228== FILE DESCRIPTORS: 5 open (3 inherited) at exit.
|
||||
```
|
||||
|
||||
"3 inherited" = stdin/out/err; the others are sockets that existed when the signal killed the
|
||||
process mid-loop — not a leak. The leak check that matters is behavioral: connect and
|
||||
disconnect clients, watch `/proc/$PID/fd` return to listener-only (Station 11) — that's
|
||||
exactly what behavioral test 13 automates.
|
||||
|
||||
---
|
||||
|
||||
## Station 14 · Self-quiz (answers at the bottom)
|
||||
|
||||
1. Which fd is the listener in this program, and what changes it?
|
||||
2. B connects; why does B receive *nothing* about itself — and what would break if it did?
|
||||
3. A sends `x\ny` (no trailing newline). What do others see right now? What stays in A's buffer?
|
||||
4. Why is A's leftover buffer dropped rather than sent at disconnect?
|
||||
5. Two clients come and go. Who decides the ids, and what happens to ids vs fds on reuse?
|
||||
6. `select(4, ...)` — which fds are being watched? What breaks if the real max fd is 7?
|
||||
7. After `recv` returns, which two conditions must `handle_read` distinguish?
|
||||
8. Why is `free(msg)` required after the relay `send`, and who frees `out`?
|
||||
9. Idle server at 100% CPU — name two causes.
|
||||
10. Server dies with no message, exit code 141 — cause, and the exam-relevant stance?
|
||||
|
||||
<details>
|
||||
<summary>Answers</summary>
|
||||
|
||||
1. fd 3 — the first fd after stdio; if you open files before `socket()`, it shifts. Always
|
||||
track it in `g_server`; never hardcode it.
|
||||
2. Arrival is broadcast to *others only* (subject + trace). If B heard its own arrival, the
|
||||
grader's expected output (listener's byte stream) would gain an extra line → diff fails.
|
||||
3. Others see nothing yet — no `\n` was received. The buffer holds `"x\ny"`. When the next
|
||||
chunk arrives, the first complete line (`x`) is relayed and the remainder stays.
|
||||
4. The subject says leftovers are not messages; the expected trace shows `arrived`+`left`
|
||||
with nothing between. Flushing it would inject a phantom `client N: ...` line.
|
||||
5. `g_next_id++` at accept — monotonic forever. fds are recycled by the kernel;
|
||||
ids are never reused.
|
||||
6. fds 0..3. With real max 7, fds 4–7 are watched by nobody → clients 4–7 pile up data
|
||||
silently; always `select(g_maxfd + 1, ...)` and raise `g_maxfd` on accept.
|
||||
7. `n > 0` → append + extract + relay; `n <= 0` (EOF or error) → disconnect. Same branch for
|
||||
both, different meaning from `n > 0`.
|
||||
8. `extract_message` hands you a slice of the old buffer (`*msg = *buf`); it's yours to free
|
||||
after use. `out` is malloc'd right there — freed right after `send`.
|
||||
9. (a) the fd_set isn't rebuilt/copied before `select`; (b) a ready fd isn't consumed
|
||||
(e.g. accept never called), so `select` returns immediately forever.
|
||||
10. SIGPIPE from `send` after the peer reset (rude close with unread data). Official test
|
||||
never triggers it; keep plain `send` and know the signature, or add `MSG_NOSIGNAL`.
|
||||
</details>
|
||||
Reference in New Issue
Block a user