[
  {
    "path": ".gitignore",
    "content": ".vscode\nsmallchat.dSYM\nsmallchat-server\nsmallchat-client\n"
  },
  {
    "path": "Makefile",
    "content": "all: smallchat-server smallchat-client\nCFLAGS=-O2 -Wall -W -std=c99\n\nsmallchat-server: smallchat-server.c chatlib.c\n\t$(CC) smallchat-server.c chatlib.c -o smallchat-server $(CFLAGS)\n\nsmallchat-client: smallchat-client.c chatlib.c\n\t$(CC) smallchat-client.c chatlib.c -o smallchat-client $(CFLAGS)\n\nclean:\n\trm -f smallchat-server\n\trm -f smallchat-client\n"
  },
  {
    "path": "README.md",
    "content": "# Smallchat\n\nTLDR: This is just a programming example for a few friends of mine. It somehow turned into a set of programming videos, continuing one project I started some time ago: Writing System Software videos series.\n\n1. [First episode](https://www.youtube.com/watch?v=eT02gzeLmF0), how the basic server works.\n2. [Second episode](https://youtu.be/yogoUJ2zVYY), writing a simple client with raw terminal handling.\n\nLikely more will follow, stay tuned.\n\n**IMPORTANT: a warning about PRs**: please note that most pull requests adding features will be refused, because the point of this repository is to improve it step by step in the next videos. We will do refactoring during live coding sessions (or explaining how the refactoring was needed in the video), introducing more libraries to improve the program inner working (linenoise, rax, and so forth). So if you want to improve the program as an exercise, go ahead! It's a great idea. But I will not merge new features here since the point of the program is to evolve it step by step during the videos.\n\n## And now, the full story:\n\nYesterday I was talking with a few friends of mine, front-end developers mostly, who are a bit far from system programming. We were remembering the old times of IRC. And inevitably I said: that writing a very simple IRC server is an experience everybody should do (I showed them my implementation written in TCL; I was quite shocked that I wrote it 18 years ago: time passes fast). There are very interesting parts in such a program. A single process doing multiplexing, taking the client state and trying to access such state fast once a client has new data, and so forth.\n\nBut then the discussion evolved and I thought, I'll show you a very minimal example in C. What is the smallest chat server you can write? For starters to be truly minimal we should not require any proper client. Even if not very well, it should work with `telnet` or `nc` (netcat). The server's main operation is just to receive some chat line and send it to all the other clients, in what is sometimes called a fan-out operation. However, this would require a proper `readline()` function, then buffering, and so forth. We want it simpler: let's cheat using the kernel buffers, and pretending we every time receive a full-formed line from the client (an assumption that is in practice often true, so things kinda work).\n\nWell, with these tricks we can implement a chat that even has the ability to let the user set their nick in just 200 lines of code (removing spaces and comments, of course). Since I wrote this little program as an example for my friends, I decided to also push it here on GitHub.\n\n## Future work\n\nIn the next few days, I'll continue to modify this program in order to evolve it. Different evolution steps will be tagged according to the YouTube episode of my series on *Writing System Software* covering such changes. This is my plan (may change, but more or less this is what I want to cover):\n\n* Implementing buffering for reading and writing.\n* Avoiding the linear array, using a dictionary data structure to hold the client state.\n* Writing a proper client: line editing able to handle asynchronous events.\n* Implementing channels.\n* Switching from select(2) to more advanced APIs.\n* Simple symmetric encryption for the chat.\n\nDifferent changes will be covered by one or more YouTube videos. The full commit history will be preserved in this repository.\n"
  },
  {
    "path": "chatlib.c",
    "content": "#define _POSIX_C_SOURCE 200112L\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/tcp.h>\n#include <arpa/inet.h>\n#include <unistd.h>\n#include <fcntl.h>\n#include <netdb.h>\n#include <errno.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n/* ======================== Low level networking stuff ==========================\n * Here you will find basic socket stuff that should be part of\n * a decent standard C library, but you know... there are other\n * crazy goals for the future of C: like to make the whole language an\n * Undefined Behavior.\n * =========================================================================== */\n\n/* Set the specified socket in non-blocking mode, with no delay flag. */\nint socketSetNonBlockNoDelay(int fd) {\n    int flags, yes = 1;\n\n    /* Set the socket nonblocking.\n     * Note that fcntl(2) for F_GETFL and F_SETFL can't be\n     * interrupted by a signal. */\n    if ((flags = fcntl(fd, F_GETFL)) == -1) return -1;\n    if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) return -1;\n\n    /* This is best-effort. No need to check for errors. */\n    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes));\n    return 0;\n}\n\n/* Create a TCP socket listening to 'port' ready to accept connections. */\nint createTCPServer(int port) {\n    int s, yes = 1;\n    struct sockaddr_in sa;\n\n    if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) return -1;\n    setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); // Best effort.\n\n    memset(&sa,0,sizeof(sa));\n    sa.sin_family = AF_INET;\n    sa.sin_port = htons(port);\n    sa.sin_addr.s_addr = htonl(INADDR_ANY);\n\n    if (bind(s,(struct sockaddr*)&sa,sizeof(sa)) == -1 ||\n        listen(s, 511) == -1)\n    {\n        close(s);\n        return -1;\n    }\n    return s;\n}\n\n/* Create a TCP socket and connect it to the specified address.\n * On success the socket descriptor is returned, otherwise -1.\n *\n * If 'nonblock' is non-zero, the socket is put in nonblocking state\n * and the connect() attempt will not block as well, but the socket\n * may not be immediately ready for writing. */\nint TCPConnect(char *addr, int port, int nonblock) {\n    int s, retval = -1;\n    struct addrinfo hints, *servinfo, *p;\n\n    char portstr[6]; /* Max 16 bit number string length. */\n    snprintf(portstr,sizeof(portstr),\"%d\",port);\n    memset(&hints,0,sizeof(hints));\n    hints.ai_family = AF_UNSPEC;\n    hints.ai_socktype = SOCK_STREAM;\n\n    if (getaddrinfo(addr,portstr,&hints,&servinfo) != 0) return -1;\n\n    for (p = servinfo; p != NULL; p = p->ai_next) {\n        /* Try to create the socket and to connect it.\n         * If we fail in the socket() call, or on connect(), we retry with\n         * the next entry in servinfo. */\n        if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1)\n            continue;\n\n        /* Put in non blocking state if needed. */\n        if (nonblock && socketSetNonBlockNoDelay(s) == -1) {\n            close(s);\n            break;\n        }\n\n        /* Try to connect. */\n        if (connect(s,p->ai_addr,p->ai_addrlen) == -1) {\n            /* If the socket is non-blocking, it is ok for connect() to\n             * return an EINPROGRESS error here. */\n            if (errno == EINPROGRESS && nonblock) return s;\n\n            /* Otherwise it's an error. */\n            close(s);\n            break;\n        }\n\n        /* If we ended an iteration of the for loop without errors, we\n         * have a connected socket. Let's return to the caller. */\n        retval = s;\n        break;\n    }\n\n    freeaddrinfo(servinfo);\n    return retval; /* Will be -1 if no connection succeded. */\n}\n\n/* If the listening socket signaled there is a new connection ready to\n * be accepted, we accept(2) it and return -1 on error or the new client\n * socket on success. */\nint acceptClient(int server_socket) {\n    int s;\n\n    while(1) {\n        struct sockaddr_in sa;\n        socklen_t slen = sizeof(sa);\n        s = accept(server_socket,(struct sockaddr*)&sa,&slen);\n        if (s == -1) {\n            if (errno == EINTR)\n                continue; /* Try again. */\n            else\n                return -1;\n        }\n        break;\n    }\n    return s;\n}\n\n/* We also define an allocator that always crashes on out of memory: you\n * will discover that in most programs designed to run for a long time, that\n * are not libraries, trying to recover from out of memory is often futile\n * and at the same time makes the whole program terrible. */\nvoid *chatMalloc(size_t size) {\n    void *ptr = malloc(size);\n    if (ptr == NULL) {\n        perror(\"Out of memory\");\n        exit(1);\n    }\n    return ptr;\n}\n\n/* Also aborting realloc(). */\nvoid *chatRealloc(void *ptr, size_t size) {\n    ptr = realloc(ptr,size);\n    if (ptr == NULL) {\n        perror(\"Out of memory\");\n        exit(1);\n    }\n    return ptr;\n}\n"
  },
  {
    "path": "chatlib.h",
    "content": "#ifndef CHATLIB_H\n#define CHATLIB_H\n\n/* Networking. */\nint createTCPServer(int port);\nint socketSetNonBlockNoDelay(int fd);\nint acceptClient(int server_socket);\nint TCPConnect(char *addr, int port, int nonblock);\n\n/* Allocation. */\nvoid *chatMalloc(size_t size);\nvoid *chatRealloc(void *ptr, size_t size);\n\n#endif // CHATLIB_H\n"
  },
  {
    "path": "smallchat-client.c",
    "content": "/* smallchat-client.c -- Client program for smallchat-server.\n *\n * Copyright (c) 2023, Salvatore Sanfilippo <antirez at gmail dot com>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *   * Redistributions of source code must retain the above copyright notice,\n *     this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *   * Neither the project name of nor the names of its contributors may be used\n *     to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <sys/select.h>\n#include <unistd.h>\n#include <termios.h>\n#include <errno.h>\n\n#include \"chatlib.h\"\n\n/* ============================================================================\n * Low level terminal handling.\n * ========================================================================== */\n\nvoid disableRawModeAtExit(void);\n\n/* Raw mode: 1960 magic shit. */\nint setRawMode(int fd, int enable) {\n    /* We have a bit of global state (but local in scope) here.\n     * This is needed to correctly set/undo raw mode. */\n    static struct termios orig_termios; // Save original terminal status here.\n    static int atexit_registered = 0;   // Avoid registering atexit() many times.\n    static int rawmode_is_set = 0;      // True if raw mode was enabled.\n\n    struct termios raw;\n\n    /* If enable is zero, we just have to disable raw mode if it is\n     * currently set. */\n    if (enable == 0) {\n        /* Don't even check the return value as it's too late. */\n        if (rawmode_is_set && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1)\n            rawmode_is_set = 0;\n        return 0;\n    }\n\n    /* Enable raw mode. */\n    if (!isatty(fd)) goto fatal;\n    if (!atexit_registered) {\n        atexit(disableRawModeAtExit);\n        atexit_registered = 1;\n    }\n    if (tcgetattr(fd,&orig_termios) == -1) goto fatal;\n\n    raw = orig_termios;  /* modify the original mode */\n    /* input modes: no break, no CR to NL, no parity check, no strip char,\n     * no start/stop output control. */\n    raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON);\n    /* output modes - do nothing. We want post processing enabled so that\n     * \\n will be automatically translated to \\r\\n. */\n    // raw.c_oflag &= ...\n    /* control modes - set 8 bit chars */\n    raw.c_cflag |= (CS8);\n    /* local modes - choing off, canonical off, no extended functions,\n     * but take signal chars (^Z,^C) enabled. */\n    raw.c_lflag &= ~(ECHO | ICANON | IEXTEN);\n    /* control chars - set return condition: min number of bytes and timer.\n     * We want read to return every single byte, without timeout. */\n    raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */\n\n    /* put terminal in raw mode after flushing */\n    if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal;\n    rawmode_is_set = 1;\n    return 0;\n\nfatal:\n    errno = ENOTTY;\n    return -1;\n}\n\n/* At exit we'll try to fix the terminal to the initial conditions. */\nvoid disableRawModeAtExit(void) {\n    setRawMode(STDIN_FILENO,0);\n}\n\n/* ============================================================================\n * Mininal line editing.\n * ========================================================================== */\n\nvoid terminalCleanCurrentLine(void) {\n    write(fileno(stdout),\"\\e[2K\",4);\n}\n\nvoid terminalCursorAtLineStart(void) {\n    write(fileno(stdout),\"\\r\",1);\n}\n\n#define IB_MAX 128\nstruct InputBuffer {\n    char buf[IB_MAX];       // Buffer holding the data.\n    int len;                // Current length.\n};\n\n/* inputBuffer*() return values: */\n#define IB_ERR 0        // Sorry, unable to comply.\n#define IB_OK 1         // Ok, got the new char, did the operation, ...\n#define IB_GOTLINE 2    // Hey, now there is a well formed line to read.\n\n/* Append the specified character to the buffer. */\nint inputBufferAppend(struct InputBuffer *ib, int c) {\n    if (ib->len >= IB_MAX) return IB_ERR; // No room.\n\n    ib->buf[ib->len] = c;\n    ib->len++;\n    return IB_OK;\n}\n\nvoid inputBufferHide(struct InputBuffer *ib);\nvoid inputBufferShow(struct InputBuffer *ib);\n\n/* Process every new keystroke arriving from the keyboard. As a side effect\n * the input buffer state is modified in order to reflect the current line\n * the user is typing, so that reading the input buffer 'buf' for 'len'\n * bytes will contain it. */\nint inputBufferFeedChar(struct InputBuffer *ib, int c) {\n    switch(c) {\n    case '\\n':\n        break;          // Ignored. We handle \\r instead.\n    case '\\r':\n        return IB_GOTLINE;\n    case 127:           // Backspace.\n        if (ib->len > 0) {\n            ib->len--;\n            inputBufferHide(ib);\n            inputBufferShow(ib);\n        }\n        break;\n    default:\n        if (inputBufferAppend(ib,c) == IB_OK)\n            write(fileno(stdout),ib->buf+ib->len-1,1);\n        break;\n    }\n    return IB_OK;\n}\n\n/* Hide the line the user is typing. */\nvoid inputBufferHide(struct InputBuffer *ib) {\n    (void)ib; // Not used var, but is conceptually part of the API.\n    terminalCleanCurrentLine();\n    terminalCursorAtLineStart();\n}\n\n/* Show again the current line. Usually called after InputBufferHide(). */\nvoid inputBufferShow(struct InputBuffer *ib) {\n    write(fileno(stdout),ib->buf,ib->len);\n}\n\n/* Reset the buffer to be empty. */\nvoid inputBufferClear(struct InputBuffer *ib) {\n    ib->len = 0;\n    inputBufferHide(ib);\n}\n\n/* =============================================================================\n * Main program logic, finally :)\n * ========================================================================== */\n\nint main(int argc, char **argv) {\n    if (argc != 3) {\n        printf(\"Usage: %s <host> <port>\\n\", argv[0]);\n        exit(1);\n    }\n\n    /* Create a TCP connection with the server. */\n    int s = TCPConnect(argv[1],atoi(argv[2]),0);\n    if (s == -1) {\n        perror(\"Connecting to server\");\n        exit(1);\n    }\n\n    /* Put the terminal in raw mode: this way we will receive every\n     * single key stroke as soon as the user types it. No buffering\n     * nor translation of escape sequences of any kind. */\n    setRawMode(fileno(stdin),1);\n\n    /* Wait for the standard input or the server socket to\n     * have some data. */\n    fd_set readfds;\n    int stdin_fd = fileno(stdin);\n\n    struct InputBuffer ib;\n    inputBufferClear(&ib);\n\n    while(1) {\n        FD_ZERO(&readfds);\n        FD_SET(s, &readfds);\n        FD_SET(stdin_fd, &readfds);\n        int maxfd = s > stdin_fd ? s : stdin_fd;\n\n        int num_events = select(maxfd+1, &readfds, NULL, NULL, NULL);\n        if (num_events == -1) {\n            perror(\"select() error\");\n            exit(1);\n        } else if (num_events) {\n            char buf[128]; /* Generic buffer for both code paths. */\n\n            if (FD_ISSET(s, &readfds)) {\n                /* Data from the server? */\n                ssize_t count = read(s,buf,sizeof(buf));\n                if (count <= 0) {\n                    printf(\"Connection lost\\n\");\n                    exit(1);\n                }\n                inputBufferHide(&ib);\n                write(fileno(stdout),buf,count);\n                inputBufferShow(&ib);\n            } else if (FD_ISSET(stdin_fd, &readfds)) {\n                /* Data from the user typing on the terminal? */\n                ssize_t count = read(stdin_fd,buf,sizeof(buf));\n                for (int j = 0; j < count; j++) {\n                    int res = inputBufferFeedChar(&ib,buf[j]);\n                    switch(res) {\n                    case IB_GOTLINE:\n                        inputBufferAppend(&ib,'\\n');\n                        inputBufferHide(&ib);\n                        write(fileno(stdout),\"you> \", 5);\n                        write(fileno(stdout),ib.buf,ib.len);\n                        write(s,ib.buf,ib.len);\n                        inputBufferClear(&ib);\n                        break;\n                    case IB_OK:\n                        break;\n                    }\n                }\n            }\n        }\n    }\n\n    close(s);\n    return 0;\n}\n"
  },
  {
    "path": "smallchat-server.c",
    "content": "/* smallchat.c -- Read clients input, send to all the other connected clients.\n *\n * Copyright (c) 2023, Salvatore Sanfilippo <antirez at gmail dot com>\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n *   * Redistributions of source code must retain the above copyright notice,\n *     this list of conditions and the following disclaimer.\n *   * Redistributions in binary form must reproduce the above copyright\n *     notice, this list of conditions and the following disclaimer in the\n *     documentation and/or other materials provided with the distribution.\n *   * Neither the project name of nor the names of its contributors may be used\n *     to endorse or promote products derived from this software without\n *     specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n */\n\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n#include <assert.h>\n#include <sys/select.h>\n#include <unistd.h>\n\n#include \"chatlib.h\"\n\n/* ============================ Data structures =================================\n * The minimal stuff we can afford to have. This example must be simple\n * even for people that don't know a lot of C.\n * =========================================================================== */\n\n#define MAX_CLIENTS 1000 // This is actually the higher file descriptor.\n#define SERVER_PORT 7711\n\n/* This structure represents a connected client. There is very little\n * info about it: the socket descriptor and the nick name, if set, otherwise\n * the first byte of the nickname is set to 0 if not set.\n * The client can set its nickname with /nick <nickname> command. */\nstruct client {\n    int fd;     // Client socket.\n    char *nick; // Nickname of the client.\n};\n\n/* This global structure encapsulates the global state of the chat. */\nstruct chatState {\n    int serversock;     // Listening server socket.\n    int numclients;     // Number of connected clients right now.\n    int maxclient;      // The greatest 'clients' slot populated.\n    struct client *clients[MAX_CLIENTS]; // Clients are set in the corresponding\n                                         // slot of their socket descriptor.\n};\n\nstruct chatState *Chat; // Initialized at startup.\n\n/* ====================== Small chat core implementation ========================\n * Here the idea is very simple: we accept new connections, read what clients\n * write us and fan-out (that is, send-to-all) the message to everybody\n * with the exception of the sender. And that is, of course, the most\n * simple chat system ever possible.\n * =========================================================================== */\n\n/* Create a new client bound to 'fd'. This is called when a new client\n * connects. As a side effect updates the global Chat state. */\nstruct client *createClient(int fd) {\n    char nick[32]; // Used to create an initial nick for the user.\n    int nicklen = snprintf(nick,sizeof(nick),\"user:%d\",fd);\n    struct client *c = chatMalloc(sizeof(*c));\n    socketSetNonBlockNoDelay(fd); // Pretend this will not fail.\n    c->fd = fd;\n    c->nick = chatMalloc(nicklen+1);\n    memcpy(c->nick,nick,nicklen);\n    assert(Chat->clients[c->fd] == NULL); // This should be available.\n    Chat->clients[c->fd] = c;\n    /* We need to update the max client set if needed. */\n    if (c->fd > Chat->maxclient) Chat->maxclient = c->fd;\n    Chat->numclients++;\n    return c;\n}\n\n/* Free a client, associated resources, and unbind it from the global\n * state in Chat. */\nvoid freeClient(struct client *c) {\n    free(c->nick);\n    close(c->fd);\n    Chat->clients[c->fd] = NULL;\n    Chat->numclients--;\n    if (Chat->maxclient == c->fd) {\n        /* Ooops, this was the max client set. Let's find what is\n         * the new highest slot used. */\n        int j;\n        for (j = Chat->maxclient-1; j >= 0; j--) {\n            if (Chat->clients[j] != NULL) {\n                Chat->maxclient = j;\n                break;\n            }\n        }\n        if (j == -1) Chat->maxclient = -1; // We no longer have clients.\n    }\n    free(c);\n}\n\n/* Allocate and init the global stuff. */\nvoid initChat(void) {\n    Chat = chatMalloc(sizeof(*Chat));\n    memset(Chat,0,sizeof(*Chat));\n    /* No clients at startup, of course. */\n    Chat->maxclient = -1;\n    Chat->numclients = 0;\n\n    /* Create our listening socket, bound to the given port. This\n     * is where our clients will connect. */\n    Chat->serversock = createTCPServer(SERVER_PORT);\n    if (Chat->serversock == -1) {\n        perror(\"Creating listening socket\");\n        exit(1);\n    }\n}\n\n/* Send the specified string to all connected clients but the one\n * having as socket descriptor 'excluded'. If you want to send something\n * to every client just set excluded to an impossible socket: -1. */\nvoid sendMsgToAllClientsBut(int excluded, char *s, size_t len) {\n    for (int j = 0; j <= Chat->maxclient; j++) {\n        if (Chat->clients[j] == NULL ||\n            Chat->clients[j]->fd == excluded) continue;\n\n        /* Important: we don't do ANY BUFFERING. We just use the kernel\n         * socket buffers. If the content does not fit, we don't care.\n         * This is needed in order to keep this program simple. */\n        write(Chat->clients[j]->fd,s,len);\n    }\n}\n\n/* The main() function implements the main chat logic:\n * 1. Accept new clients connections if any.\n * 2. Check if any client sent us some new message.\n * 3. Send the message to all the other clients. */\nint main(void) {\n    initChat();\n\n    while(1) {\n        fd_set readfds;\n        struct timeval tv;\n        int retval;\n\n        FD_ZERO(&readfds);\n        /* When we want to be notified by select() that there is\n         * activity? If the listening socket has pending clients to accept\n         * or if any other client wrote anything. */\n        FD_SET(Chat->serversock, &readfds);\n\n        for (int j = 0; j <= Chat->maxclient; j++) {\n            if (Chat->clients[j]) FD_SET(j, &readfds);\n        }\n\n        /* Set a timeout for select(), see later why this may be useful\n         * in the future (not now). */\n        tv.tv_sec = 1; // 1 sec timeout\n        tv.tv_usec = 0;\n\n        /* Select wants as first argument the maximum file descriptor\n         * in use plus one. It can be either one of our clients or the\n         * server socket itself. */\n        int maxfd = Chat->maxclient;\n        if (maxfd < Chat->serversock) maxfd = Chat->serversock;\n        retval = select(maxfd+1, &readfds, NULL, NULL, &tv);\n        if (retval == -1) {\n            perror(\"select() error\");\n            exit(1);\n        } else if (retval) {\n\n            /* If the listening socket is \"readable\", it actually means\n             * there are new clients connections pending to accept. */\n            if (FD_ISSET(Chat->serversock, &readfds)) {\n                int fd = acceptClient(Chat->serversock);\n                struct client *c = createClient(fd);\n                /* Send a welcome message. */\n                char *welcome_msg =\n                    \"Welcome to Simple Chat! \"\n                    \"Use /nick <nick> to set your nick.\\n\";\n                write(c->fd,welcome_msg,strlen(welcome_msg));\n                printf(\"Connected client fd=%d\\n\", fd);\n            }\n\n            /* Here for each connected client, check if there are pending\n             * data the client sent us. */\n            char readbuf[256];\n            for (int j = 0; j <= Chat->maxclient; j++) {\n                if (Chat->clients[j] == NULL) continue;\n                if (FD_ISSET(j, &readfds)) {\n                    /* Here we just hope that there is a well formed\n                     * message waiting for us. But it is entirely possible\n                     * that we read just half a message. In a normal program\n                     * that is not designed to be that simple, we should try\n                     * to buffer reads until the end-of-the-line is reached. */\n                    int nread = read(j,readbuf,sizeof(readbuf)-1);\n\n                    if (nread <= 0) {\n                        /* Error or short read means that the socket\n                         * was closed. */\n                        printf(\"Disconnected client fd=%d, nick=%s\\n\",\n                            j, Chat->clients[j]->nick);\n                        freeClient(Chat->clients[j]);\n                    } else {\n                        /* The client sent us a message. We need to\n                         * relay this message to all the other clients\n                         * in the chat. */\n                        struct client *c = Chat->clients[j];\n                        readbuf[nread] = 0;\n\n                        /* If the user message starts with \"/\", we\n                         * process it as a client command. So far\n                         * only the /nick <newnick> command is implemented. */\n                        if (readbuf[0] == '/') {\n                            /* Remove any trailing newline. */\n                            char *p;\n                            p = strchr(readbuf,'\\r'); if (p) *p = 0;\n                            p = strchr(readbuf,'\\n'); if (p) *p = 0;\n                            /* Check for an argument of the command, after\n                             * the space. */\n                            char *arg = strchr(readbuf,' ');\n                            if (arg) {\n                                *arg = 0; /* Terminate command name. */\n                                arg++; /* Argument is 1 byte after the space. */\n                            }\n\n                            if (!strcmp(readbuf,\"/nick\") && arg) {\n                                free(c->nick);\n                                int nicklen = strlen(arg);\n                                c->nick = chatMalloc(nicklen+1);\n                                memcpy(c->nick,arg,nicklen+1);\n                            } else {\n                                /* Unsupported command. Send an error. */\n                                char *errmsg = \"Unsupported command\\n\";\n                                write(c->fd,errmsg,strlen(errmsg));\n                            }\n                        } else {\n                            /* Create a message to send everybody (and show\n                             * on the server console) in the form:\n                             *   nick> some message. */\n                            char msg[256];\n                            int msglen = snprintf(msg, sizeof(msg),\n                                \"%s> %s\", c->nick, readbuf);\n\n                            /* snprintf() return value may be larger than\n                             * sizeof(msg) in case there is no room for the\n                             * whole output. */\n                            if (msglen >= (int)sizeof(msg))\n                                msglen = sizeof(msg)-1;\n                            printf(\"%s\",msg);\n\n                            /* Send it to all the other clients. */\n                            sendMsgToAllClientsBut(j,msg,msglen);\n                        }\n                    }\n                }\n            }\n        } else {\n            /* Timeout occurred. We don't do anything right now, but in\n             * general this section can be used to wakeup periodically\n             * even if there is no clients activity. */\n        }\n    }\n    return 0;\n}\n"
  }
]