core: add all the required files
This commit is contained in:
@@ -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.
|
||||
Reference in New Issue
Block a user