Files
42-exam06/exam-pack.md

21 KiB
Raw Permalink Blame History

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.
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):

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

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)

#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'
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)

#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)

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:

./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)

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)

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>&-; }):

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)

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):

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?
  2. nc connects? 4. arrival correct? 5. relay/multiline? 6. split line? 7. disconnect?
  3. 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
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)

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/