aboutsummaryrefslogtreecommitdiff
path: root/src/chat-server-with-allocated-clients.c
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-10 09:34:34 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-10 09:34:34 +0000
commit3b539f06811a181249d6a154a5fce54d95ce9693 (patch)
tree2117ff0f1c65ebfa94c27df288f3604762e65a73 /src/chat-server-with-allocated-clients.c
downloadlab-05-master.tar.gz
publishHEADmaster
Diffstat (limited to 'src/chat-server-with-allocated-clients.c')
-rw-r--r--src/chat-server-with-allocated-clients.c487
1 files changed, 487 insertions, 0 deletions
diff --git a/src/chat-server-with-allocated-clients.c b/src/chat-server-with-allocated-clients.c
new file mode 100644
index 0000000..ab98c3d
--- /dev/null
+++ b/src/chat-server-with-allocated-clients.c
@@ -0,0 +1,487 @@
1#include <stdio.h>
2#include <stdlib.h>
3#include <stdarg.h>
4#include <string.h>
5#include <ctype.h>
6#include <errno.h>
7#include <unistd.h>
8#include <fcntl.h>
9#include <sys/select.h>
10#include <sys/socket.h>
11#include <netinet/in.h>
12#include "utils.h"
13
14#define ASSERT assert
15// #define ASSERT
16
17#define LISTEN_QUEUE 2
18// #define MAX_CLIENT_COUNT (FD_SETSIZE - 5) // stdin, stdout, stderr, listener, reserved
19#define MAX_CLIENT_COUNT 4
20#define MAX_NICK_LENGTH 9
21#define MAX_MESSAGE_SIZE 512
22#define BUFFER_SIZE (1 + MAX_NICK_LENGTH + 2 + MAX_MESSAGE_SIZE) // "<nick> msg"
23#define NICK_INDEX_SIZE FD_SETSIZE
24#define HASH djb2
25#define HASHN djb2n
26#define HASHV djb2v
27#define INITIAL_CLIENT_CAPACITY 1
28
29typedef uint16_t client_id;
30typedef uint16_t buffer_index;
31
32// arena with free list, socket luts and nick indexing
33struct clients {
34 struct client {
35 char nick[MAX_NICK_LENGTH + 1];
36 client_id prev; // prev in hash map bucket
37 client_id next; // next in hash map bucket / free list
38 client_id socket_index;
39 buffer_index buffer_message_beg;
40 buffer_index buffer_message_end;
41 char buffer[BUFFER_SIZE]; // only for reading from socket
42 } *items;
43 client_id count;
44 client_id capacity;
45 client_id free_list_head;
46
47 int socket_count;
48 int socket_index_to_socket[MAX_CLIENT_COUNT];
49 client_id socket_to_id [FD_SETSIZE ];
50
51 client_id nick_index[NICK_INDEX_SIZE]; // hash map bucket heads
52} clients = {0};
53
54int max_fd = 0;
55fd_set active_fds;
56int listener = -1;
57
58client_id
59djb2 (const char *str)
60{
61 client_id hash = 5381;
62
63 while (*str)
64 hash = ((hash << 5) + hash) + *str++;
65
66 return hash;
67}
68
69client_id
70djb2n (const char *str, int n)
71{
72 client_id hash = 5381;
73
74 while (n && *str) {
75 hash = ((hash << 5) + hash) + *str++;
76 n -= 1;
77 }
78
79 return hash;
80}
81
82client_id
83djb2v (const char *str, const char *end)
84{
85 client_id hash = 5381;
86
87 while (str < end && *str)
88 hash = ((hash << 5) + hash) + *str++;
89
90 return hash;
91}
92
93bool
94clients__server_vprintf (int sock, const char *template, va_list ap)
95{
96 static char buffer[513];
97 int len = 0;
98 len += snprintf (buffer + len, 513 - len, "<server> ");
99 len += vsnprintf (buffer + len, 513 - len, template, ap);
100 len += snprintf (buffer + len, 513 - len, "\n");
101
102 if (write (sock, buffer, len) == -1) {
103 ERROR ("write: %s", strerror (errno));
104 return false;
105 }
106
107 return true;
108}
109
110bool
111clients__server_printf_to (int sock, const char *template, ...)
112{
113 va_list ap;
114 va_start (ap, template);
115 bool ret = clients__server_vprintf (sock, template, ap);
116 va_end (ap);
117 return ret;
118}
119
120bool
121clients__server_printf_except (int except, const char *template, ...)
122{
123 va_list ap;
124 bool ret = true;
125 for (client_id i = 0; i < clients.socket_count; ++i) {
126 int sock = clients.socket_index_to_socket[i];
127 if (sock == except) continue;
128 va_start (ap, template);
129 if (!clients__server_vprintf (sock, template, ap))
130 ret = false;
131 va_end (ap);
132 }
133 return ret;
134}
135
136bool
137clients__server_printf_all (const char *template, ...)
138{
139 va_list ap;
140 bool ret = true;
141 for (client_id i = 0; i < clients.socket_count; ++i) {
142 int sock = clients.socket_index_to_socket[i];
143 va_start (ap, template);
144 if (!clients__server_vprintf (sock, template, ap))
145 ret = false;
146 va_end (ap);
147 }
148 return ret;
149}
150
151bool
152clients__add_client (int sock)
153{
154 ASSERT (sock < FD_SETSIZE);
155 ASSERT (!FD_ISSET (sock, &active_fds));
156
157 FD_SET (sock, &active_fds);
158 if (sock > max_fd)
159 max_fd = sock;
160
161 client_id id;
162 if (clients.free_list_head) {
163 id = clients.free_list_head - 1;
164 clients.free_list_head = clients.items[id].next;
165 } else {
166 id = clients.count++;
167 if (clients.count > clients.capacity) {
168 if (clients.count == MAX_CLIENT_COUNT) {
169 // TODO(cmmm): disconnect with error
170 }
171
172 clients.capacity *= 2;
173 if (clients.capacity > MAX_CLIENT_COUNT)
174 clients.capacity = MAX_CLIENT_COUNT;
175 clients.items = realloc (clients.items, clients.capacity*sizeof (*clients.items));
176 }
177 }
178 struct client *client = &clients.items[id];
179 snprintf (client->nick, sizeof (client->nick), "guest%d", id);
180
181 client->buffer_message_end =
182 client->buffer_message_beg =
183 snprintf (client->buffer, BUFFER_SIZE, "<%s> ", client->nick);
184
185 client_id *entry = &clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE];
186 client->prev = 0;
187 client->next = *entry;
188 if (client->next)
189 clients.items[client->next - 1].prev = id + 1;
190 *entry = id + 1;
191
192 clients__server_printf_to (sock, "your nick is <%s>, "
193 "use '/nick <name>' to change it",
194 client->nick);
195
196 clients__server_printf_all ("client <%s> connected", client->nick);
197
198 client->socket_index = clients.socket_count++;
199 clients.socket_index_to_socket[client->socket_index] = sock;
200 clients.socket_to_id[sock] = id;
201
202 INFO ("added client <%s>", client->nick);
203
204 return true;
205}
206
207bool
208clients__accept_connection (void)
209{
210 ASSERT (listener != -1);
211
212 struct sockaddr_in addr;
213 socklen_t length = sizeof (addr);
214 int sock = accept (listener, (struct sockaddr *) &addr, &length);
215 if (sock == -1) {
216 if (errno == EWOULDBLOCK)
217 return false;
218 ERROR ("accept: %s", strerror (errno));
219 exit (EXIT_FAILURE);
220 }
221
222 INFO ("accepted connection: %hhu.%hhu.%hhu.%hhu:%hu",
223 ntohl (addr.sin_addr.s_addr) >> 3*8,
224 ntohl (addr.sin_addr.s_addr) >> 2*8,
225 ntohl (addr.sin_addr.s_addr) >> 1*8,
226 ntohl (addr.sin_addr.s_addr) >> 0*8,
227 ntohs (addr.sin_port));
228
229 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
230 ERROR ("fcntl: %s", strerror (errno));
231 if (close (sock) == -1)
232 ERROR ("close: %s", strerror (errno));
233 return true;
234 }
235
236 clients__add_client (sock);
237 return true;
238}
239
240bool
241clients__remove_client (int sock)
242{
243 ASSERT (sock < FD_SETSIZE);
244 ASSERT (FD_ISSET (sock, &active_fds));
245
246 FD_CLR (sock, &active_fds);
247 if (sock == max_fd) {
248 do max_fd -= 1;
249 while (!FD_ISSET (max_fd, &active_fds));
250 }
251
252 client_id id = clients.socket_to_id[sock];
253 struct client *client = &clients.items[id];
254
255 clients.socket_index_to_socket[client->socket_index] =
256 clients.socket_index_to_socket[--clients.socket_count];
257 if (close (sock) == -1)
258 ERROR ("close: %s", strerror (errno));
259
260 client->next = clients.free_list_head;
261 clients.free_list_head = id + 1;
262
263 if (client->next) clients.items[client->next - 1].prev = client->prev;
264 if (client->prev) clients.items[client->prev - 1].next = client->next;
265 else clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE] = client->next;
266
267 clients__server_printf_all ("client <%s> disconnected", client->nick);
268
269 INFO ("removed client <%s>", client->nick);
270
271 return true;
272}
273
274int
275clients__nick_to_socket (const char *nick_beg, const char *nick_end)
276{
277 ASSERT (nick_beg < nick_end);
278 ASSERT (nick_end - nick_beg <= MAX_NICK_LENGTH);
279
280 client_id recepient_id = clients.nick_index[HASHV (nick_beg, nick_end) % NICK_INDEX_SIZE];
281 while (recepient_id) {
282 const struct client *recepient = &clients.items[recepient_id - 1];
283 if (strlen (recepient->nick) == (size_t) (nick_end - nick_beg) &&
284 strncmp (recepient->nick, nick_beg, nick_end - nick_beg) == 0) {
285 return clients.socket_index_to_socket[recepient->socket_index];
286 }
287 recepient_id = recepient->next;
288 }
289
290 return -1;
291}
292
293bool
294clients__set_nick (int sock, const char *nick_beg, const char *nick_end)
295{
296 ASSERT (sock < FD_SETSIZE);
297 ASSERT (FD_ISSET (sock, &active_fds));
298
299 client_id id = clients.socket_to_id[sock];
300 struct client *client = &clients.items[id];
301
302 if (isalnum (*nick_end)) {
303 clients__server_printf_to (sock, "nick too long");
304 return false;
305 }
306
307 if (clients__nick_to_socket (nick_beg, nick_end) != -1) {
308 clients__server_printf_to (sock, "nick already occupied");
309 return false;
310 }
311
312 client_id *entry = &clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE];
313 if (*entry == id + 1)
314 *entry = client->next;
315
316 clients__server_printf_except (sock, "client <%s> changed it's nick to <%.*s>",
317 client->nick, (int) (nick_end - nick_beg),
318 nick_beg);
319
320 memcpy (client->nick, nick_beg, nick_end - nick_beg);
321 client->nick[nick_end - nick_beg] = '\0';
322 client->buffer_message_beg = sprintf (client->buffer, "<%.*s> ",
323 (int) (nick_end - nick_beg), nick_beg);
324
325 if (client->prev) clients.items[client->prev - 1].next = client->next;
326 if (client->next) clients.items[client->next - 1].prev = client->prev;
327 entry = &clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE];
328 client->prev = 0;
329 client->next = *entry;
330 if (client->next)
331 clients.items[client->next - 1].prev = id + 1;
332 *entry = id + 1;
333
334 clients__server_printf_to (sock, "your new nick is <%s>", client->nick);
335
336 return true;
337}
338
339bool
340clients__message_received (int sock, const char *message_end)
341{
342 ASSERT (sock < FD_SETSIZE);
343 ASSERT (FD_ISSET (sock, &active_fds));
344
345 client_id id = clients.socket_to_id[sock];
346 struct client *client = &clients.items[id];
347
348 char *message_beg = &client->buffer[client->buffer_message_beg];
349 if (*message_beg == '/') {
350 if (strncmp (message_beg + 1, "nick ", 5) == 0) {
351 char *nick_beg = message_beg + 6;
352 while (*nick_beg == ' ')
353 nick_beg += 1;
354 char *nick_end = nick_beg;
355 do {
356 *nick_end = tolower (*nick_end);
357 nick_end += 1;
358 } while (nick_end < nick_beg + MAX_NICK_LENGTH && isalnum (*nick_end));
359 clients__set_nick (sock, nick_beg, nick_end);
360 } else {
361 clients__server_printf_to (sock, "unsupported command");
362 }
363 } else if (*message_beg == '!') {
364 const char *nick_beg = message_beg + 1;
365 const char *nick_end = nick_beg;
366 do nick_end += 1;
367 while (nick_end < nick_beg + MAX_NICK_LENGTH && isalnum (*nick_end));
368 int recepient = clients__nick_to_socket (nick_beg, nick_end);
369 if (recepient == -1) {
370 clients__server_printf_to (sock, "nick not found: <%.*s>",
371 (int) (nick_end - nick_beg), nick_beg);
372 goto cleanup;
373 }
374 if (recepient == sock) {
375 clients__server_printf_to (sock, "you may not send message to yourself");
376 goto cleanup;
377 }
378
379 if (write (recepient, client->buffer, client->buffer_message_end) == -1) {
380 ERROR ("write: %s", strerror (errno));
381 goto cleanup;
382 }
383 } else {
384 for (client_id i = 0; i < clients.socket_count; ++i) {
385 int recepient = clients.socket_index_to_socket[i];
386 if (recepient == sock) continue;
387 if (write (recepient, client->buffer, client->buffer_message_end) == -1) {
388 ERROR ("write: %s", strerror (errno));
389 }
390 }
391 }
392
393 cleanup:
394 client->buffer_message_end = client->buffer_message_beg;
395 return true;
396}
397
398bool
399clients__read_from_client (int sock)
400{
401 ASSERT (sock < FD_SETSIZE);
402 ASSERT (FD_ISSET (sock, &active_fds));
403
404 client_id id = clients.socket_to_id[sock];
405 struct client *client = &clients.items[id];
406
407 ssize_t bytes_read = read (sock, &client->buffer[client->buffer_message_end],
408 BUFFER_SIZE - client->buffer_message_end);
409 if (bytes_read <= 0) {
410 if (bytes_read == -1)
411 ERROR ("read: %s", strerror (errno));
412 clients__remove_client (sock);
413 return false;
414 }
415
416 const char *head = &client->buffer[client->buffer_message_end];
417 client->buffer_message_end += bytes_read;
418 const char *end = &client->buffer[client->buffer_message_end];
419 while (head < end) {
420 if (*head == '\n')
421 return clients__message_received (sock, head);
422 head += 1;
423 }
424
425 return true;
426}
427
428int
429main (int argc, char *argv[])
430{
431 listener = socket (AF_INET, SOCK_STREAM, 0);
432 if (listener == -1)
433 DIE (EXIT_FAILURE, "socket: %s", strerror (errno));
434 max_fd = listener;
435
436 int reuseaddr = 1;
437 setsockopt (listener, SOL_SOCKET, SO_REUSEADDR,
438 &reuseaddr, sizeof (reuseaddr));
439
440 if (fcntl (listener, F_SETFL, O_NONBLOCK) == -1)
441 DIE (EXIT_FAILURE, "fcntl: %s", strerror (errno));
442
443 struct sockaddr_in addr = {
444 .sin_family = AF_INET,
445 .sin_port = htons (3422),
446 .sin_addr.s_addr = htonl (INADDR_ANY),
447 };
448
449 if (bind (listener, (struct sockaddr *) &addr, sizeof (addr)) == -1)
450 DIE (EXIT_FAILURE, "bind: %s", strerror (errno));
451 INFO ("listening on: %hhu.%hhu.%hhu.%hhu:%hu",
452 ntohl (addr.sin_addr.s_addr) >> 3*8,
453 ntohl (addr.sin_addr.s_addr) >> 2*8,
454 ntohl (addr.sin_addr.s_addr) >> 1*8,
455 ntohl (addr.sin_addr.s_addr) >> 0*8,
456 ntohs (addr.sin_port));
457
458 if (listen (listener, LISTEN_QUEUE))
459 DIE (EXIT_FAILURE, "listen: %s", strerror (errno));
460
461 FD_ZERO (&active_fds);
462 FD_SET (listener, &active_fds);
463
464 clients.items = malloc (INITIAL_CLIENT_CAPACITY*sizeof (*clients.items));
465 clients.capacity = INITIAL_CLIENT_CAPACITY;
466
467 for (;;) {
468 fd_set read_fds;
469 memcpy (&read_fds, &active_fds, sizeof (fd_set));
470
471 struct timeval timeout = { .tv_sec = 15 };
472 if (select (max_fd + 1, &read_fds, NULL, NULL, &timeout) == -1)
473 DIE (EXIT_FAILURE, "select: %s", strerror (errno));
474
475 if (FD_ISSET (listener, &read_fds))
476 while (clients__accept_connection ());
477
478 for (int i = 0; i < clients.socket_count; ++i) {
479 int sock = clients.socket_index_to_socket[i];
480 if (!FD_ISSET (sock, &read_fds)) continue;
481 if (!clients__read_from_client (sock))
482 sock -= 1;
483 }
484 }
485
486 return EXIT_SUCCESS;
487}