aboutsummaryrefslogtreecommitdiff
path: root/src/chat-server-with-allocated-clients.c
blob: ab98c3df60803098f40a026d6b19148284212e53 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "utils.h"

#define ASSERT assert
// #define ASSERT

#define LISTEN_QUEUE 2
// #define MAX_CLIENT_COUNT (FD_SETSIZE - 5) // stdin, stdout, stderr, listener, reserved
#define MAX_CLIENT_COUNT 4
#define MAX_NICK_LENGTH 9
#define MAX_MESSAGE_SIZE 512
#define BUFFER_SIZE (1 + MAX_NICK_LENGTH + 2 + MAX_MESSAGE_SIZE) // "<nick> msg"
#define NICK_INDEX_SIZE FD_SETSIZE
#define HASH  djb2
#define HASHN djb2n
#define HASHV djb2v
#define INITIAL_CLIENT_CAPACITY 1

typedef uint16_t client_id;
typedef uint16_t buffer_index;

// arena with free list, socket luts and nick indexing
struct clients {
  struct client {
    char nick[MAX_NICK_LENGTH + 1];
    client_id prev;             // prev in hash map bucket
    client_id next;             // next in hash map bucket / free list
    client_id socket_index;
    buffer_index buffer_message_beg;
    buffer_index buffer_message_end;
    char buffer[BUFFER_SIZE];   // only for reading from socket
  } *items;
  client_id count;
  client_id capacity;
  client_id free_list_head;

  int       socket_count;
  int       socket_index_to_socket[MAX_CLIENT_COUNT];
  client_id socket_to_id          [FD_SETSIZE      ];

  client_id nick_index[NICK_INDEX_SIZE]; // hash map bucket heads
} clients = {0};

int max_fd = 0;
fd_set active_fds;
int listener = -1;

client_id
djb2 (const char *str)
{
  client_id hash = 5381;

  while (*str)
    hash = ((hash << 5) + hash) + *str++;

  return hash;
}

client_id
djb2n (const char *str, int n)
{
  client_id hash = 5381;

  while (n && *str) {
    hash = ((hash << 5) + hash) + *str++;
    n -= 1;
  }

  return hash;
}

client_id
djb2v (const char *str, const char *end)
{
  client_id hash = 5381;

  while (str < end && *str)
    hash = ((hash << 5) + hash) + *str++;

  return hash;
}

bool
clients__server_vprintf (int sock, const char *template, va_list ap)
{
  static char buffer[513];
  int len = 0;
  len +=  snprintf (buffer + len, 513 - len, "<server> ");
  len += vsnprintf (buffer + len, 513 - len, template, ap);
  len +=  snprintf (buffer + len, 513 - len, "\n");

  if (write (sock, buffer, len) == -1) {
    ERROR ("write: %s", strerror (errno));
    return false;
  }

  return true;
}

bool
clients__server_printf_to (int sock, const char *template, ...)
{
  va_list ap;
  va_start (ap, template);
  bool ret = clients__server_vprintf (sock, template, ap);
  va_end (ap);
  return ret;
}

bool
clients__server_printf_except (int except, const char *template, ...)
{
  va_list ap;
  bool ret = true;
  for (client_id i = 0; i < clients.socket_count; ++i) {
    int sock = clients.socket_index_to_socket[i];
    if (sock == except) continue;
    va_start (ap, template);
    if (!clients__server_vprintf (sock, template, ap))
      ret = false;
    va_end (ap);
  }
  return ret;
}

bool
clients__server_printf_all (const char *template, ...)
{
  va_list ap;
  bool ret = true;
  for (client_id i = 0; i < clients.socket_count; ++i) {
    int sock = clients.socket_index_to_socket[i];
    va_start (ap, template);
    if (!clients__server_vprintf (sock, template, ap))
      ret = false;
    va_end (ap);
  }
  return ret;
}

bool
clients__add_client (int sock)
{
  ASSERT (sock < FD_SETSIZE);
  ASSERT (!FD_ISSET (sock, &active_fds));

  FD_SET (sock, &active_fds);
  if (sock > max_fd)
    max_fd = sock;

  client_id id;
  if (clients.free_list_head) {
    id = clients.free_list_head - 1;
    clients.free_list_head = clients.items[id].next;
  } else {
    id = clients.count++;
    if (clients.count > clients.capacity) {
      if (clients.count == MAX_CLIENT_COUNT) {
        // TODO(cmmm): disconnect with error
      }

      clients.capacity *= 2;
      if (clients.capacity > MAX_CLIENT_COUNT)
        clients.capacity = MAX_CLIENT_COUNT;
      clients.items = realloc (clients.items, clients.capacity*sizeof (*clients.items));
    }
  }
  struct client *client = &clients.items[id];
  snprintf (client->nick, sizeof (client->nick), "guest%d", id);

  client->buffer_message_end =
    client->buffer_message_beg =
      snprintf (client->buffer, BUFFER_SIZE, "<%s> ", client->nick);

  client_id *entry = &clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE];
  client->prev = 0;
  client->next = *entry;
  if (client->next)
    clients.items[client->next - 1].prev = id + 1;
  *entry = id + 1;

  clients__server_printf_to (sock, "your nick is <%s>, "
                                   "use '/nick <name>' to change it",
                             client->nick);

  clients__server_printf_all ("client <%s> connected", client->nick);

  client->socket_index = clients.socket_count++;
  clients.socket_index_to_socket[client->socket_index] = sock;
  clients.socket_to_id[sock] = id;

  INFO ("added client <%s>", client->nick);

  return true;
}

bool
clients__accept_connection (void)
{
  ASSERT (listener != -1);

  struct sockaddr_in addr;
  socklen_t length = sizeof (addr);
  int sock = accept (listener, (struct sockaddr *) &addr, &length);
  if (sock == -1) {
    if (errno == EWOULDBLOCK)
      return false;
    ERROR ("accept: %s", strerror (errno));
    exit (EXIT_FAILURE);
  }

  INFO ("accepted connection: %hhu.%hhu.%hhu.%hhu:%hu",
        ntohl (addr.sin_addr.s_addr) >> 3*8,
        ntohl (addr.sin_addr.s_addr) >> 2*8,
        ntohl (addr.sin_addr.s_addr) >> 1*8,
        ntohl (addr.sin_addr.s_addr) >> 0*8,
        ntohs (addr.sin_port));

  if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
    ERROR ("fcntl: %s", strerror (errno));
    if (close (sock) == -1)
      ERROR ("close: %s", strerror (errno));
    return true;
  }

  clients__add_client (sock);
  return true;
}

bool
clients__remove_client (int sock)
{
  ASSERT (sock < FD_SETSIZE);
  ASSERT (FD_ISSET (sock, &active_fds));

  FD_CLR (sock, &active_fds);
  if (sock == max_fd) {
    do max_fd -= 1;
    while (!FD_ISSET (max_fd, &active_fds));
  }

  client_id id = clients.socket_to_id[sock];
  struct client *client = &clients.items[id];

  clients.socket_index_to_socket[client->socket_index] =
    clients.socket_index_to_socket[--clients.socket_count];
  if (close (sock) == -1)
    ERROR ("close: %s", strerror (errno));

  client->next = clients.free_list_head;
  clients.free_list_head = id + 1;

  if (client->next) clients.items[client->next - 1].prev = client->prev;
  if (client->prev) clients.items[client->prev - 1].next = client->next;
  else clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE] = client->next;

  clients__server_printf_all ("client <%s> disconnected", client->nick);

  INFO ("removed client <%s>", client->nick);

  return true;
}

int
clients__nick_to_socket (const char *nick_beg, const char *nick_end)
{
  ASSERT (nick_beg < nick_end);
  ASSERT (nick_end - nick_beg <= MAX_NICK_LENGTH);

  client_id recepient_id = clients.nick_index[HASHV (nick_beg, nick_end) % NICK_INDEX_SIZE];
  while (recepient_id) {
    const struct client *recepient = &clients.items[recepient_id - 1];
    if (strlen (recepient->nick) == (size_t) (nick_end - nick_beg) &&
        strncmp (recepient->nick, nick_beg, nick_end - nick_beg) == 0) {
      return clients.socket_index_to_socket[recepient->socket_index];
    }
    recepient_id = recepient->next;
  }

  return -1;
}

bool
clients__set_nick (int sock, const char *nick_beg, const char *nick_end)
{
  ASSERT (sock < FD_SETSIZE);
  ASSERT (FD_ISSET (sock, &active_fds));

  client_id id = clients.socket_to_id[sock];
  struct client *client = &clients.items[id];

  if (isalnum (*nick_end)) {
    clients__server_printf_to (sock, "nick too long");
    return false;
  }

  if (clients__nick_to_socket (nick_beg, nick_end) != -1) {
    clients__server_printf_to (sock, "nick already occupied");
    return false;
  }

  client_id *entry = &clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE];
  if (*entry == id + 1)
    *entry = client->next;

  clients__server_printf_except (sock, "client <%s> changed it's nick to <%.*s>",
                                 client->nick, (int) (nick_end - nick_beg),
                                 nick_beg);

  memcpy (client->nick, nick_beg, nick_end - nick_beg);
  client->nick[nick_end - nick_beg] = '\0';
  client->buffer_message_beg = sprintf (client->buffer, "<%.*s> ",
                                        (int) (nick_end - nick_beg), nick_beg);

  if (client->prev) clients.items[client->prev - 1].next = client->next;
  if (client->next) clients.items[client->next - 1].prev = client->prev;
  entry = &clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE];
  client->prev = 0;
  client->next = *entry;
  if (client->next)
    clients.items[client->next - 1].prev = id + 1;
  *entry = id + 1;

  clients__server_printf_to (sock, "your new nick is <%s>", client->nick);

  return true;
}

bool
clients__message_received (int sock, const char *message_end)
{
  ASSERT (sock < FD_SETSIZE);
  ASSERT (FD_ISSET (sock, &active_fds));

  client_id id = clients.socket_to_id[sock];
  struct client *client = &clients.items[id];

  char *message_beg = &client->buffer[client->buffer_message_beg];
  if (*message_beg == '/') {
    if (strncmp (message_beg + 1, "nick ", 5) == 0) {
      char *nick_beg = message_beg + 6;
      while (*nick_beg == ' ')
        nick_beg += 1;
      char *nick_end = nick_beg;
      do {
        *nick_end = tolower (*nick_end);
        nick_end += 1;
      } while (nick_end < nick_beg + MAX_NICK_LENGTH && isalnum (*nick_end));
      clients__set_nick (sock, nick_beg, nick_end);
    } else {
      clients__server_printf_to (sock, "unsupported command");
    }
  } else if (*message_beg == '!') {
    const char *nick_beg = message_beg + 1;
    const char *nick_end = nick_beg;
    do nick_end += 1;
    while (nick_end < nick_beg + MAX_NICK_LENGTH && isalnum (*nick_end));
    int recepient = clients__nick_to_socket (nick_beg, nick_end);
    if (recepient == -1) {
      clients__server_printf_to (sock, "nick not found: <%.*s>",
                                 (int) (nick_end - nick_beg), nick_beg);
      goto cleanup;
    }
    if (recepient == sock) {
      clients__server_printf_to (sock, "you may not send message to yourself");
      goto cleanup;
    }

    if (write (recepient, client->buffer, client->buffer_message_end) == -1) {
      ERROR ("write: %s", strerror (errno));
      goto cleanup;
    }
  } else {
    for (client_id i = 0; i < clients.socket_count; ++i) {
      int recepient = clients.socket_index_to_socket[i];
      if (recepient == sock) continue;
      if (write (recepient, client->buffer, client->buffer_message_end) == -1) {
        ERROR ("write: %s", strerror (errno));
      }
    }
  }

 cleanup:
  client->buffer_message_end = client->buffer_message_beg;
  return true;
}

bool
clients__read_from_client (int sock)
{
  ASSERT (sock < FD_SETSIZE);
  ASSERT (FD_ISSET (sock, &active_fds));

  client_id id = clients.socket_to_id[sock];
  struct client *client = &clients.items[id];

  ssize_t bytes_read = read (sock, &client->buffer[client->buffer_message_end],
                             BUFFER_SIZE - client->buffer_message_end);
  if (bytes_read <= 0) {
    if (bytes_read == -1)
      ERROR ("read: %s", strerror (errno));
    clients__remove_client (sock);
    return false;
  }

  const char *head = &client->buffer[client->buffer_message_end];
  client->buffer_message_end += bytes_read;
  const char *end = &client->buffer[client->buffer_message_end];
  while (head < end) {
    if (*head == '\n')
      return clients__message_received (sock, head);
    head += 1;
  }

  return true;
}

int
main (int argc, char *argv[])
{
  listener = socket (AF_INET, SOCK_STREAM, 0);
  if (listener == -1)
    DIE (EXIT_FAILURE, "socket: %s", strerror (errno));
  max_fd = listener;

  int reuseaddr = 1;
  setsockopt (listener, SOL_SOCKET, SO_REUSEADDR,
              &reuseaddr, sizeof (reuseaddr));

  if (fcntl (listener, F_SETFL, O_NONBLOCK) == -1)
    DIE (EXIT_FAILURE, "fcntl: %s", strerror (errno));

  struct sockaddr_in addr = {
    .sin_family      = AF_INET,
    .sin_port        = htons (3422),
    .sin_addr.s_addr = htonl (INADDR_ANY),
  };

  if (bind (listener, (struct sockaddr *) &addr, sizeof (addr)) == -1)
    DIE (EXIT_FAILURE, "bind: %s", strerror (errno));
  INFO ("listening on: %hhu.%hhu.%hhu.%hhu:%hu",
        ntohl (addr.sin_addr.s_addr) >> 3*8,
        ntohl (addr.sin_addr.s_addr) >> 2*8,
        ntohl (addr.sin_addr.s_addr) >> 1*8,
        ntohl (addr.sin_addr.s_addr) >> 0*8,
        ntohs (addr.sin_port));

  if (listen (listener, LISTEN_QUEUE))
    DIE (EXIT_FAILURE, "listen: %s", strerror (errno));

  FD_ZERO (&active_fds);
  FD_SET (listener, &active_fds);

  clients.items = malloc (INITIAL_CLIENT_CAPACITY*sizeof (*clients.items));
  clients.capacity = INITIAL_CLIENT_CAPACITY;

  for (;;) {
    fd_set read_fds;
    memcpy (&read_fds, &active_fds, sizeof (fd_set));

    struct timeval timeout = { .tv_sec = 15 };
    if (select (max_fd + 1, &read_fds, NULL, NULL, &timeout) == -1)
      DIE (EXIT_FAILURE, "select: %s", strerror (errno));

    if (FD_ISSET (listener, &read_fds))
      while (clients__accept_connection ());

    for (int i = 0; i < clients.socket_count; ++i) {
      int sock = clients.socket_index_to_socket[i];
      if (!FD_ISSET (sock, &read_fds)) continue;
      if (!clients__read_from_client (sock))
        sock -= 1;
    }
  }

  return EXIT_SUCCESS;
}