core: add all the required files

This commit is contained in:
mkurkar
2026-11-04 16:42:12 +03:00 Unverified
commit 29324ac2ea
57 changed files with 57688 additions and 0 deletions
+295
View File
@@ -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);
}