Files
42-exam06/playground/my_code.c
T

184 lines
6.8 KiB
C

/* ============================================================================
* 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. */
}