├── .gitignore ├── Makefile ├── README.md ├── chatlib.c ├── chatlib.h ├── smallchat-client.c └── smallchat-server.c /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | smallchat.dSYM 3 | smallchat-server 4 | smallchat-client 5 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | all: smallchat-server smallchat-client 2 | CFLAGS=-O2 -Wall -W -std=c99 3 | 4 | smallchat-server: smallchat-server.c chatlib.c 5 | $(CC) smallchat-server.c chatlib.c -o smallchat-server $(CFLAGS) 6 | 7 | smallchat-client: smallchat-client.c chatlib.c 8 | $(CC) smallchat-client.c chatlib.c -o smallchat-client $(CFLAGS) 9 | 10 | clean: 11 | rm -f smallchat-server 12 | rm -f smallchat-client 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Smallchat 2 | 3 | TLDR: 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. 4 | 5 | 1. [First episode](https://www.youtube.com/watch?v=eT02gzeLmF0), how the basic server works. 6 | 2. [Second episode](https://youtu.be/yogoUJ2zVYY), writing a simple client with raw terminal handling. 7 | 8 | Likely more will follow, stay tuned. 9 | 10 | **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. 11 | 12 | ## And now, the full story: 13 | 14 | Yesterday 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. 15 | 16 | But 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). 17 | 18 | Well, 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. 19 | 20 | ## Future work 21 | 22 | In 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): 23 | 24 | * Implementing buffering for reading and writing. 25 | * Avoiding the linear array, using a dictionary data structure to hold the client state. 26 | * Writing a proper client: line editing able to handle asynchronous events. 27 | * Implementing channels. 28 | * Switching from select(2) to more advanced APIs. 29 | * Simple symmetric encryption for the chat. 30 | 31 | Different changes will be covered by one or more YouTube videos. The full commit history will be preserved in this repository. 32 | -------------------------------------------------------------------------------- /chatlib.c: -------------------------------------------------------------------------------- 1 | #define _POSIX_C_SOURCE 200112L 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | 15 | /* ======================== Low level networking stuff ========================== 16 | * Here you will find basic socket stuff that should be part of 17 | * a decent standard C library, but you know... there are other 18 | * crazy goals for the future of C: like to make the whole language an 19 | * Undefined Behavior. 20 | * =========================================================================== */ 21 | 22 | /* Set the specified socket in non-blocking mode, with no delay flag. */ 23 | int socketSetNonBlockNoDelay(int fd) { 24 | int flags, yes = 1; 25 | 26 | /* Set the socket nonblocking. 27 | * Note that fcntl(2) for F_GETFL and F_SETFL can't be 28 | * interrupted by a signal. */ 29 | if ((flags = fcntl(fd, F_GETFL)) == -1) return -1; 30 | if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) return -1; 31 | 32 | /* This is best-effort. No need to check for errors. */ 33 | setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &yes, sizeof(yes)); 34 | return 0; 35 | } 36 | 37 | /* Create a TCP socket listening to 'port' ready to accept connections. */ 38 | int createTCPServer(int port) { 39 | int s, yes = 1; 40 | struct sockaddr_in sa; 41 | 42 | if ((s = socket(AF_INET, SOCK_STREAM, 0)) == -1) return -1; 43 | setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes)); // Best effort. 44 | 45 | memset(&sa,0,sizeof(sa)); 46 | sa.sin_family = AF_INET; 47 | sa.sin_port = htons(port); 48 | sa.sin_addr.s_addr = htonl(INADDR_ANY); 49 | 50 | if (bind(s,(struct sockaddr*)&sa,sizeof(sa)) == -1 || 51 | listen(s, 511) == -1) 52 | { 53 | close(s); 54 | return -1; 55 | } 56 | return s; 57 | } 58 | 59 | /* Create a TCP socket and connect it to the specified address. 60 | * On success the socket descriptor is returned, otherwise -1. 61 | * 62 | * If 'nonblock' is non-zero, the socket is put in nonblocking state 63 | * and the connect() attempt will not block as well, but the socket 64 | * may not be immediately ready for writing. */ 65 | int TCPConnect(char *addr, int port, int nonblock) { 66 | int s, retval = -1; 67 | struct addrinfo hints, *servinfo, *p; 68 | 69 | char portstr[6]; /* Max 16 bit number string length. */ 70 | snprintf(portstr,sizeof(portstr),"%d",port); 71 | memset(&hints,0,sizeof(hints)); 72 | hints.ai_family = AF_UNSPEC; 73 | hints.ai_socktype = SOCK_STREAM; 74 | 75 | if (getaddrinfo(addr,portstr,&hints,&servinfo) != 0) return -1; 76 | 77 | for (p = servinfo; p != NULL; p = p->ai_next) { 78 | /* Try to create the socket and to connect it. 79 | * If we fail in the socket() call, or on connect(), we retry with 80 | * the next entry in servinfo. */ 81 | if ((s = socket(p->ai_family,p->ai_socktype,p->ai_protocol)) == -1) 82 | continue; 83 | 84 | /* Put in non blocking state if needed. */ 85 | if (nonblock && socketSetNonBlockNoDelay(s) == -1) { 86 | close(s); 87 | break; 88 | } 89 | 90 | /* Try to connect. */ 91 | if (connect(s,p->ai_addr,p->ai_addrlen) == -1) { 92 | /* If the socket is non-blocking, it is ok for connect() to 93 | * return an EINPROGRESS error here. */ 94 | if (errno == EINPROGRESS && nonblock) return s; 95 | 96 | /* Otherwise it's an error. */ 97 | close(s); 98 | break; 99 | } 100 | 101 | /* If we ended an iteration of the for loop without errors, we 102 | * have a connected socket. Let's return to the caller. */ 103 | retval = s; 104 | break; 105 | } 106 | 107 | freeaddrinfo(servinfo); 108 | return retval; /* Will be -1 if no connection succeded. */ 109 | } 110 | 111 | /* If the listening socket signaled there is a new connection ready to 112 | * be accepted, we accept(2) it and return -1 on error or the new client 113 | * socket on success. */ 114 | int acceptClient(int server_socket) { 115 | int s; 116 | 117 | while(1) { 118 | struct sockaddr_in sa; 119 | socklen_t slen = sizeof(sa); 120 | s = accept(server_socket,(struct sockaddr*)&sa,&slen); 121 | if (s == -1) { 122 | if (errno == EINTR) 123 | continue; /* Try again. */ 124 | else 125 | return -1; 126 | } 127 | break; 128 | } 129 | return s; 130 | } 131 | 132 | /* We also define an allocator that always crashes on out of memory: you 133 | * will discover that in most programs designed to run for a long time, that 134 | * are not libraries, trying to recover from out of memory is often futile 135 | * and at the same time makes the whole program terrible. */ 136 | void *chatMalloc(size_t size) { 137 | void *ptr = malloc(size); 138 | if (ptr == NULL) { 139 | perror("Out of memory"); 140 | exit(1); 141 | } 142 | return ptr; 143 | } 144 | 145 | /* Also aborting realloc(). */ 146 | void *chatRealloc(void *ptr, size_t size) { 147 | ptr = realloc(ptr,size); 148 | if (ptr == NULL) { 149 | perror("Out of memory"); 150 | exit(1); 151 | } 152 | return ptr; 153 | } 154 | -------------------------------------------------------------------------------- /chatlib.h: -------------------------------------------------------------------------------- 1 | #ifndef CHATLIB_H 2 | #define CHATLIB_H 3 | 4 | /* Networking. */ 5 | int createTCPServer(int port); 6 | int socketSetNonBlockNoDelay(int fd); 7 | int acceptClient(int server_socket); 8 | int TCPConnect(char *addr, int port, int nonblock); 9 | 10 | /* Allocation. */ 11 | void *chatMalloc(size_t size); 12 | void *chatRealloc(void *ptr, size_t size); 13 | 14 | #endif // CHATLIB_H 15 | -------------------------------------------------------------------------------- /smallchat-client.c: -------------------------------------------------------------------------------- 1 | /* smallchat-client.c -- Client program for smallchat-server. 2 | * 3 | * Copyright (c) 2023, Salvatore Sanfilippo 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the project name of nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | #include 39 | 40 | #include "chatlib.h" 41 | 42 | /* ============================================================================ 43 | * Low level terminal handling. 44 | * ========================================================================== */ 45 | 46 | void disableRawModeAtExit(void); 47 | 48 | /* Raw mode: 1960 magic shit. */ 49 | int setRawMode(int fd, int enable) { 50 | /* We have a bit of global state (but local in scope) here. 51 | * This is needed to correctly set/undo raw mode. */ 52 | static struct termios orig_termios; // Save original terminal status here. 53 | static int atexit_registered = 0; // Avoid registering atexit() many times. 54 | static int rawmode_is_set = 0; // True if raw mode was enabled. 55 | 56 | struct termios raw; 57 | 58 | /* If enable is zero, we just have to disable raw mode if it is 59 | * currently set. */ 60 | if (enable == 0) { 61 | /* Don't even check the return value as it's too late. */ 62 | if (rawmode_is_set && tcsetattr(fd,TCSAFLUSH,&orig_termios) != -1) 63 | rawmode_is_set = 0; 64 | return 0; 65 | } 66 | 67 | /* Enable raw mode. */ 68 | if (!isatty(fd)) goto fatal; 69 | if (!atexit_registered) { 70 | atexit(disableRawModeAtExit); 71 | atexit_registered = 1; 72 | } 73 | if (tcgetattr(fd,&orig_termios) == -1) goto fatal; 74 | 75 | raw = orig_termios; /* modify the original mode */ 76 | /* input modes: no break, no CR to NL, no parity check, no strip char, 77 | * no start/stop output control. */ 78 | raw.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); 79 | /* output modes - do nothing. We want post processing enabled so that 80 | * \n will be automatically translated to \r\n. */ 81 | // raw.c_oflag &= ... 82 | /* control modes - set 8 bit chars */ 83 | raw.c_cflag |= (CS8); 84 | /* local modes - choing off, canonical off, no extended functions, 85 | * but take signal chars (^Z,^C) enabled. */ 86 | raw.c_lflag &= ~(ECHO | ICANON | IEXTEN); 87 | /* control chars - set return condition: min number of bytes and timer. 88 | * We want read to return every single byte, without timeout. */ 89 | raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; /* 1 byte, no timer */ 90 | 91 | /* put terminal in raw mode after flushing */ 92 | if (tcsetattr(fd,TCSAFLUSH,&raw) < 0) goto fatal; 93 | rawmode_is_set = 1; 94 | return 0; 95 | 96 | fatal: 97 | errno = ENOTTY; 98 | return -1; 99 | } 100 | 101 | /* At exit we'll try to fix the terminal to the initial conditions. */ 102 | void disableRawModeAtExit(void) { 103 | setRawMode(STDIN_FILENO,0); 104 | } 105 | 106 | /* ============================================================================ 107 | * Mininal line editing. 108 | * ========================================================================== */ 109 | 110 | void terminalCleanCurrentLine(void) { 111 | write(fileno(stdout),"\e[2K",4); 112 | } 113 | 114 | void terminalCursorAtLineStart(void) { 115 | write(fileno(stdout),"\r",1); 116 | } 117 | 118 | #define IB_MAX 128 119 | struct InputBuffer { 120 | char buf[IB_MAX]; // Buffer holding the data. 121 | int len; // Current length. 122 | }; 123 | 124 | /* inputBuffer*() return values: */ 125 | #define IB_ERR 0 // Sorry, unable to comply. 126 | #define IB_OK 1 // Ok, got the new char, did the operation, ... 127 | #define IB_GOTLINE 2 // Hey, now there is a well formed line to read. 128 | 129 | /* Append the specified character to the buffer. */ 130 | int inputBufferAppend(struct InputBuffer *ib, int c) { 131 | if (ib->len >= IB_MAX) return IB_ERR; // No room. 132 | 133 | ib->buf[ib->len] = c; 134 | ib->len++; 135 | return IB_OK; 136 | } 137 | 138 | void inputBufferHide(struct InputBuffer *ib); 139 | void inputBufferShow(struct InputBuffer *ib); 140 | 141 | /* Process every new keystroke arriving from the keyboard. As a side effect 142 | * the input buffer state is modified in order to reflect the current line 143 | * the user is typing, so that reading the input buffer 'buf' for 'len' 144 | * bytes will contain it. */ 145 | int inputBufferFeedChar(struct InputBuffer *ib, int c) { 146 | switch(c) { 147 | case '\n': 148 | break; // Ignored. We handle \r instead. 149 | case '\r': 150 | return IB_GOTLINE; 151 | case 127: // Backspace. 152 | if (ib->len > 0) { 153 | ib->len--; 154 | inputBufferHide(ib); 155 | inputBufferShow(ib); 156 | } 157 | break; 158 | default: 159 | if (inputBufferAppend(ib,c) == IB_OK) 160 | write(fileno(stdout),ib->buf+ib->len-1,1); 161 | break; 162 | } 163 | return IB_OK; 164 | } 165 | 166 | /* Hide the line the user is typing. */ 167 | void inputBufferHide(struct InputBuffer *ib) { 168 | (void)ib; // Not used var, but is conceptually part of the API. 169 | terminalCleanCurrentLine(); 170 | terminalCursorAtLineStart(); 171 | } 172 | 173 | /* Show again the current line. Usually called after InputBufferHide(). */ 174 | void inputBufferShow(struct InputBuffer *ib) { 175 | write(fileno(stdout),ib->buf,ib->len); 176 | } 177 | 178 | /* Reset the buffer to be empty. */ 179 | void inputBufferClear(struct InputBuffer *ib) { 180 | ib->len = 0; 181 | inputBufferHide(ib); 182 | } 183 | 184 | /* ============================================================================= 185 | * Main program logic, finally :) 186 | * ========================================================================== */ 187 | 188 | int main(int argc, char **argv) { 189 | if (argc != 3) { 190 | printf("Usage: %s \n", argv[0]); 191 | exit(1); 192 | } 193 | 194 | /* Create a TCP connection with the server. */ 195 | int s = TCPConnect(argv[1],atoi(argv[2]),0); 196 | if (s == -1) { 197 | perror("Connecting to server"); 198 | exit(1); 199 | } 200 | 201 | /* Put the terminal in raw mode: this way we will receive every 202 | * single key stroke as soon as the user types it. No buffering 203 | * nor translation of escape sequences of any kind. */ 204 | setRawMode(fileno(stdin),1); 205 | 206 | /* Wait for the standard input or the server socket to 207 | * have some data. */ 208 | fd_set readfds; 209 | int stdin_fd = fileno(stdin); 210 | 211 | struct InputBuffer ib; 212 | inputBufferClear(&ib); 213 | 214 | while(1) { 215 | FD_ZERO(&readfds); 216 | FD_SET(s, &readfds); 217 | FD_SET(stdin_fd, &readfds); 218 | int maxfd = s > stdin_fd ? s : stdin_fd; 219 | 220 | int num_events = select(maxfd+1, &readfds, NULL, NULL, NULL); 221 | if (num_events == -1) { 222 | perror("select() error"); 223 | exit(1); 224 | } else if (num_events) { 225 | char buf[128]; /* Generic buffer for both code paths. */ 226 | 227 | if (FD_ISSET(s, &readfds)) { 228 | /* Data from the server? */ 229 | ssize_t count = read(s,buf,sizeof(buf)); 230 | if (count <= 0) { 231 | printf("Connection lost\n"); 232 | exit(1); 233 | } 234 | inputBufferHide(&ib); 235 | write(fileno(stdout),buf,count); 236 | inputBufferShow(&ib); 237 | } else if (FD_ISSET(stdin_fd, &readfds)) { 238 | /* Data from the user typing on the terminal? */ 239 | ssize_t count = read(stdin_fd,buf,sizeof(buf)); 240 | for (int j = 0; j < count; j++) { 241 | int res = inputBufferFeedChar(&ib,buf[j]); 242 | switch(res) { 243 | case IB_GOTLINE: 244 | inputBufferAppend(&ib,'\n'); 245 | inputBufferHide(&ib); 246 | write(fileno(stdout),"you> ", 5); 247 | write(fileno(stdout),ib.buf,ib.len); 248 | write(s,ib.buf,ib.len); 249 | inputBufferClear(&ib); 250 | break; 251 | case IB_OK: 252 | break; 253 | } 254 | } 255 | } 256 | } 257 | } 258 | 259 | close(s); 260 | return 0; 261 | } 262 | -------------------------------------------------------------------------------- /smallchat-server.c: -------------------------------------------------------------------------------- 1 | /* smallchat.c -- Read clients input, send to all the other connected clients. 2 | * 3 | * Copyright (c) 2023, Salvatore Sanfilippo 4 | * All rights reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * * Redistributions in binary form must reproduce the above copyright 12 | * notice, this list of conditions and the following disclaimer in the 13 | * documentation and/or other materials provided with the distribution. 14 | * * Neither the project name of nor the names of its contributors may be used 15 | * to endorse or promote products derived from this software without 16 | * specific prior written permission. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 22 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 | * POSSIBILITY OF SUCH DAMAGE. 29 | */ 30 | 31 | #include 32 | #include 33 | #include 34 | #include 35 | #include 36 | #include 37 | 38 | #include "chatlib.h" 39 | 40 | /* ============================ Data structures ================================= 41 | * The minimal stuff we can afford to have. This example must be simple 42 | * even for people that don't know a lot of C. 43 | * =========================================================================== */ 44 | 45 | #define MAX_CLIENTS 1000 // This is actually the higher file descriptor. 46 | #define SERVER_PORT 7711 47 | 48 | /* This structure represents a connected client. There is very little 49 | * info about it: the socket descriptor and the nick name, if set, otherwise 50 | * the first byte of the nickname is set to 0 if not set. 51 | * The client can set its nickname with /nick command. */ 52 | struct client { 53 | int fd; // Client socket. 54 | char *nick; // Nickname of the client. 55 | }; 56 | 57 | /* This global structure encapsulates the global state of the chat. */ 58 | struct chatState { 59 | int serversock; // Listening server socket. 60 | int numclients; // Number of connected clients right now. 61 | int maxclient; // The greatest 'clients' slot populated. 62 | struct client *clients[MAX_CLIENTS]; // Clients are set in the corresponding 63 | // slot of their socket descriptor. 64 | }; 65 | 66 | struct chatState *Chat; // Initialized at startup. 67 | 68 | /* ====================== Small chat core implementation ======================== 69 | * Here the idea is very simple: we accept new connections, read what clients 70 | * write us and fan-out (that is, send-to-all) the message to everybody 71 | * with the exception of the sender. And that is, of course, the most 72 | * simple chat system ever possible. 73 | * =========================================================================== */ 74 | 75 | /* Create a new client bound to 'fd'. This is called when a new client 76 | * connects. As a side effect updates the global Chat state. */ 77 | struct client *createClient(int fd) { 78 | char nick[32]; // Used to create an initial nick for the user. 79 | int nicklen = snprintf(nick,sizeof(nick),"user:%d",fd); 80 | struct client *c = chatMalloc(sizeof(*c)); 81 | socketSetNonBlockNoDelay(fd); // Pretend this will not fail. 82 | c->fd = fd; 83 | c->nick = chatMalloc(nicklen+1); 84 | memcpy(c->nick,nick,nicklen); 85 | assert(Chat->clients[c->fd] == NULL); // This should be available. 86 | Chat->clients[c->fd] = c; 87 | /* We need to update the max client set if needed. */ 88 | if (c->fd > Chat->maxclient) Chat->maxclient = c->fd; 89 | Chat->numclients++; 90 | return c; 91 | } 92 | 93 | /* Free a client, associated resources, and unbind it from the global 94 | * state in Chat. */ 95 | void freeClient(struct client *c) { 96 | free(c->nick); 97 | close(c->fd); 98 | Chat->clients[c->fd] = NULL; 99 | Chat->numclients--; 100 | if (Chat->maxclient == c->fd) { 101 | /* Ooops, this was the max client set. Let's find what is 102 | * the new highest slot used. */ 103 | int j; 104 | for (j = Chat->maxclient-1; j >= 0; j--) { 105 | if (Chat->clients[j] != NULL) { 106 | Chat->maxclient = j; 107 | break; 108 | } 109 | } 110 | if (j == -1) Chat->maxclient = -1; // We no longer have clients. 111 | } 112 | free(c); 113 | } 114 | 115 | /* Allocate and init the global stuff. */ 116 | void initChat(void) { 117 | Chat = chatMalloc(sizeof(*Chat)); 118 | memset(Chat,0,sizeof(*Chat)); 119 | /* No clients at startup, of course. */ 120 | Chat->maxclient = -1; 121 | Chat->numclients = 0; 122 | 123 | /* Create our listening socket, bound to the given port. This 124 | * is where our clients will connect. */ 125 | Chat->serversock = createTCPServer(SERVER_PORT); 126 | if (Chat->serversock == -1) { 127 | perror("Creating listening socket"); 128 | exit(1); 129 | } 130 | } 131 | 132 | /* Send the specified string to all connected clients but the one 133 | * having as socket descriptor 'excluded'. If you want to send something 134 | * to every client just set excluded to an impossible socket: -1. */ 135 | void sendMsgToAllClientsBut(int excluded, char *s, size_t len) { 136 | for (int j = 0; j <= Chat->maxclient; j++) { 137 | if (Chat->clients[j] == NULL || 138 | Chat->clients[j]->fd == excluded) continue; 139 | 140 | /* Important: we don't do ANY BUFFERING. We just use the kernel 141 | * socket buffers. If the content does not fit, we don't care. 142 | * This is needed in order to keep this program simple. */ 143 | write(Chat->clients[j]->fd,s,len); 144 | } 145 | } 146 | 147 | /* The main() function implements the main chat logic: 148 | * 1. Accept new clients connections if any. 149 | * 2. Check if any client sent us some new message. 150 | * 3. Send the message to all the other clients. */ 151 | int main(void) { 152 | initChat(); 153 | 154 | while(1) { 155 | fd_set readfds; 156 | struct timeval tv; 157 | int retval; 158 | 159 | FD_ZERO(&readfds); 160 | /* When we want to be notified by select() that there is 161 | * activity? If the listening socket has pending clients to accept 162 | * or if any other client wrote anything. */ 163 | FD_SET(Chat->serversock, &readfds); 164 | 165 | for (int j = 0; j <= Chat->maxclient; j++) { 166 | if (Chat->clients[j]) FD_SET(j, &readfds); 167 | } 168 | 169 | /* Set a timeout for select(), see later why this may be useful 170 | * in the future (not now). */ 171 | tv.tv_sec = 1; // 1 sec timeout 172 | tv.tv_usec = 0; 173 | 174 | /* Select wants as first argument the maximum file descriptor 175 | * in use plus one. It can be either one of our clients or the 176 | * server socket itself. */ 177 | int maxfd = Chat->maxclient; 178 | if (maxfd < Chat->serversock) maxfd = Chat->serversock; 179 | retval = select(maxfd+1, &readfds, NULL, NULL, &tv); 180 | if (retval == -1) { 181 | perror("select() error"); 182 | exit(1); 183 | } else if (retval) { 184 | 185 | /* If the listening socket is "readable", it actually means 186 | * there are new clients connections pending to accept. */ 187 | if (FD_ISSET(Chat->serversock, &readfds)) { 188 | int fd = acceptClient(Chat->serversock); 189 | struct client *c = createClient(fd); 190 | /* Send a welcome message. */ 191 | char *welcome_msg = 192 | "Welcome to Simple Chat! " 193 | "Use /nick to set your nick.\n"; 194 | write(c->fd,welcome_msg,strlen(welcome_msg)); 195 | printf("Connected client fd=%d\n", fd); 196 | } 197 | 198 | /* Here for each connected client, check if there are pending 199 | * data the client sent us. */ 200 | char readbuf[256]; 201 | for (int j = 0; j <= Chat->maxclient; j++) { 202 | if (Chat->clients[j] == NULL) continue; 203 | if (FD_ISSET(j, &readfds)) { 204 | /* Here we just hope that there is a well formed 205 | * message waiting for us. But it is entirely possible 206 | * that we read just half a message. In a normal program 207 | * that is not designed to be that simple, we should try 208 | * to buffer reads until the end-of-the-line is reached. */ 209 | int nread = read(j,readbuf,sizeof(readbuf)-1); 210 | 211 | if (nread <= 0) { 212 | /* Error or short read means that the socket 213 | * was closed. */ 214 | printf("Disconnected client fd=%d, nick=%s\n", 215 | j, Chat->clients[j]->nick); 216 | freeClient(Chat->clients[j]); 217 | } else { 218 | /* The client sent us a message. We need to 219 | * relay this message to all the other clients 220 | * in the chat. */ 221 | struct client *c = Chat->clients[j]; 222 | readbuf[nread] = 0; 223 | 224 | /* If the user message starts with "/", we 225 | * process it as a client command. So far 226 | * only the /nick command is implemented. */ 227 | if (readbuf[0] == '/') { 228 | /* Remove any trailing newline. */ 229 | char *p; 230 | p = strchr(readbuf,'\r'); if (p) *p = 0; 231 | p = strchr(readbuf,'\n'); if (p) *p = 0; 232 | /* Check for an argument of the command, after 233 | * the space. */ 234 | char *arg = strchr(readbuf,' '); 235 | if (arg) { 236 | *arg = 0; /* Terminate command name. */ 237 | arg++; /* Argument is 1 byte after the space. */ 238 | } 239 | 240 | if (!strcmp(readbuf,"/nick") && arg) { 241 | free(c->nick); 242 | int nicklen = strlen(arg); 243 | c->nick = chatMalloc(nicklen+1); 244 | memcpy(c->nick,arg,nicklen+1); 245 | } else { 246 | /* Unsupported command. Send an error. */ 247 | char *errmsg = "Unsupported command\n"; 248 | write(c->fd,errmsg,strlen(errmsg)); 249 | } 250 | } else { 251 | /* Create a message to send everybody (and show 252 | * on the server console) in the form: 253 | * nick> some message. */ 254 | char msg[256]; 255 | int msglen = snprintf(msg, sizeof(msg), 256 | "%s> %s", c->nick, readbuf); 257 | 258 | /* snprintf() return value may be larger than 259 | * sizeof(msg) in case there is no room for the 260 | * whole output. */ 261 | if (msglen >= (int)sizeof(msg)) 262 | msglen = sizeof(msg)-1; 263 | printf("%s",msg); 264 | 265 | /* Send it to all the other clients. */ 266 | sendMsgToAllClientsBut(j,msg,msglen); 267 | } 268 | } 269 | } 270 | } 271 | } else { 272 | /* Timeout occurred. We don't do anything right now, but in 273 | * general this section can be used to wakeup periodically 274 | * even if there is no clients activity. */ 275 | } 276 | } 277 | return 0; 278 | } 279 | --------------------------------------------------------------------------------