aboutsummaryrefslogtreecommitdiff
path: root/src/chat-server.c
blob: 79aee552676e03f21d2325afcff6199cfd83796b (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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <time.h>
#include <sys/select.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/resource.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "utils.h"

// TODO(cmmm): Could save some space by offseting, N first sockets
// won't be clients, but finding N is not trivial.
#define SOCKET_TO_CLIENT_ID(SOCK  ) (SOCK  )
#define CLIENT_ID_TO_SOCKET(CLIENT) (CLIENT)

#define MAX_CLIENT_COUNT SOCKET_TO_CLIENT_ID (FD_SETSIZE - 2)
#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 PROGRAM_ARGUMENTS                                                      \
  PROGRAM_ARGUMENT_BOOL   (help,      'h', "help",      "Show this help message"                                                   ) \
  PROGRAM_ARGUMENT_BOOL   (daemonize, 'd', "daemonize", "Daemonize process on startup"                                             ) \
  PROGRAM_ARGUMENT_UINT   (log_upto,  'l', "log-upto",  "Log up to this Syslog priority",        LOG_NOTICE                        ) \
  PROGRAM_ARGUMENT_STRING (archive,   'x', "archive",   "Filename of broadcast message archive", "/var/log/chat-server-archive.log") \
  PROGRAM_ARGUMENT_STRING (addr,      'a', "addr",      "IP address to listen on",               "0.0.0.0"                         ) \
  PROGRAM_ARGUMENT_UINT   (port,      'p', "port",      "Port to listen on",                     6666                              )
#include "program-arguments.h"

#define MOTD "Welcome, your nick is <%s>, "                     \
  "use `/nick NAME' to change it, use `/help' to show help", client->nick

#define COMMAND_HELP_OFFSET 20
#define COMMAND_FIGLET_MAX_MSG_LEN 23
#define COMMANDS                                                               \
  COMMAND (HELP,   "help",   "",       "Show this help message"               )  \
  COMMAND (NICK,   "nick",   "NAME",   "Set nickname to NAME"                 )  \
  COMMAND (USERS,  "users",  "",       "List users nicknames and ip addresses")  \
  COMMAND (UPTIME, "uptime", "",       "Show chat's age"                      )  \
  COMMAND (LALU,   "lalu",   "",       "Lalu's personal command"              )  \
  COMMAND (FIGLET, "figlet", "MSG...", "Send MSG... in large characters"      )

#define COMMAND(SYM, ...) COMMAND_##SYM,
enum command { COMMANDS COMMAND_COUNT };
#undef COMMAND

#define COMMAND(SYM, STR, ...) [COMMAND_##SYM] = STR,
const char *command_to_str[COMMAND_COUNT] = { COMMANDS };
#undef COMMAND

#define COMMAND(SYM, STR, ...) [COMMAND_##SYM] = (uint8_t) sizeof (STR) - 1,
uint8_t command_to_strlen[COMMAND_COUNT] = { COMMANDS };
#undef COMMAND

#define COMMAND(SYM, STR, ARGS, ...) [COMMAND_##SYM] = ARGS,
const char *command_to_args[COMMAND_COUNT] = { COMMANDS };
#undef COMMAND

#define COMMAND(SYM, STR, ARGS, HELP) [COMMAND_##SYM] = HELP,
const char *command_to_help[COMMAND_COUNT] = { COMMANDS };
#undef COMMAND

typedef uint16_t client_id;
typedef uint16_t buffer_index;

struct client {
  char nick[MAX_NICK_LENGTH + 1];
  client_id prev;               // prev in hash map bucket
  client_id next;               // next in hash map bucket
  client_id socket_index;
  uint8_t addr[4];
  uint16_t port;
  buffer_index buffer_message_beg;
  buffer_index buffer_message_end;
  char buffer[BUFFER_SIZE]; // only for reading from socket
} clients[MAX_CLIENT_COUNT];

client_id nick_index[NICK_INDEX_SIZE] = {0}; // hash map bucket heads
int client_sockets[MAX_CLIENT_COUNT];
int *client_sockets_end = client_sockets;
#define FOREACH_CLIENT_SOCKET(SOCK) \
  for (int *SOCK = client_sockets; SOCK < client_sockets_end; ++SOCK)

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

struct program_arguments pa;
volatile bool should_stop = false;
FILE *archive;
int   archive_fd;
time_t startup_time;
uint64_t accepted_messages;
uint64_t accepted_connections;

void
signal_handler (int sig)
{
  int serrno = errno;

  switch (sig) {
    case SIGINT:
      DEBUG ("Received SIGINT");
      should_stop = true;
      break;

    case SIGTERM:
      DEBUG ("Received SIGTERM");
      should_stop = true;
      break;

    default: DEBUG ("Received unhandled %s", strsignal (sig));
  }

  errno = serrno;
}

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) {
    DEBUG ("write: %s", strerror (errno));
    return false;
  }

  return true;
}

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

bool
clients__server_printf_except (int except, const char *template, ...)
{
  va_list ap;
  va_start (ap, template);
   fprintf (archive, "<server> ");
  vfprintf (archive, template, ap);
   fprintf (archive, "\n");
  va_end (ap);
  fflush (archive);

  bool ret = true;
  FOREACH_CLIENT_SOCKET (recepient) {
    if (*recepient == except) continue;
    va_start (ap, template);
    if (!clients__server_vprintf (*recepient, template, ap))
      ret = false;
    va_end (ap);
  }
  return ret;
}

bool
clients__server_printf_all (const char *template, ...)
{
  va_list ap;
  va_start (ap, template);
   fprintf (archive, "<server> ");
  vfprintf (archive, template, ap);
   fprintf (archive, "\n");
  va_end (ap);
  fflush (archive);

  bool ret = true;
  FOREACH_CLIENT_SOCKET (recepient) {
    va_start (ap, template);
    if (!clients__server_vprintf (*recepient, template, ap))
      ret = false;
    va_end (ap);
  }
  return ret;
}

bool
clients__add_client (int sock, uint32_t addr, uint16_t port)
{
  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 = SOCKET_TO_CLIENT_ID (sock);
  struct client *client = &clients[id];
  snprintf (client->nick, sizeof (client->nick), "guest%d", id);

  *((uint32_t *) &client->addr) = addr;
  client->port = port;

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

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

  clients__server_printf_to (sock, MOTD);

  clients__server_printf_all ("Client <%s> connected from %hhu.%hhu.%hhu.%hhu",
                              client->nick,
                              client->addr[3],
                              client->addr[2],
                              client->addr[1],
                              client->addr[0]);

  client->socket_index = client_sockets_end - client_sockets;
  *client_sockets_end++ = sock;

  INFO ("Added client <%s> %hhu.%hhu.%hhu.%hhu:%hu", client->nick,
        client->addr[3],
        client->addr[2],
        client->addr[1],
        client->addr[0], client->port);

  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 ("Failed to accept connection: %s", strerror (errno));
    exit (EXIT_FAILURE);
  } NOTICE ("Accepted connection: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (addr));
  accepted_connections += 1;

  if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
    ERROR ("Failed to set nonblocking mode for client socket: %s",
           strerror (errno));
    if (close (sock) == -1)
      WARNING ("close: %s", strerror (errno));
    return true;
  }

  clients__add_client (sock, ntohl (addr.sin_addr.s_addr), ntohs (addr.sin_port));
  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));
  }

  if (close (sock) == -1)
    WARNING ("close: %s", strerror (errno));

  client_id id = SOCKET_TO_CLIENT_ID (sock);
  struct client *client = &clients[id];

  client_sockets_end -= 1;
  clients[SOCKET_TO_CLIENT_ID (*client_sockets_end)].socket_index =
    client->socket_index;
  client_sockets[client->socket_index] = *client_sockets_end;

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

  clients__server_printf_all ("Client <%s> from %hhu.%hhu.%hhu.%hhu disconnected",
                              client->nick,
                              client->addr[3],
                              client->addr[2],
                              client->addr[1],
                              client->addr[0]);

  INFO ("Removed client <%s> %hhu.%hhu.%hhu.%hhu:%hu", client->nick,
        client->addr[3],
        client->addr[2],
        client->addr[1],
        client->addr[0], client->port);

  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 = nick_index[HASHV (nick_beg, nick_end) % NICK_INDEX_SIZE];
  while (recepient_id) {
    const struct client *recepient = &clients[recepient_id - 1];
    if (strlen (recepient->nick) == (size_t) (nick_end - nick_beg) &&
        strncmp (recepient->nick, nick_beg, nick_end - nick_beg) == 0) {
      return CLIENT_ID_TO_SOCKET (recepient - clients);
    }
    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 = SOCKET_TO_CLIENT_ID (sock);
  struct client *client = &clients[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 = &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);

  INFO ("Client <%s> %hhu.%hhu.%hhu.%hhu:%hu changed it's nick to <%.*s>",
        client->nick,
        client->addr[3],
        client->addr[2],
        client->addr[1],
        client->addr[0], client->port, (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[client->prev - 1].next = client->next;
  if (client->next) clients[client->next - 1].prev = client->prev;
  entry = &nick_index[HASH (client->nick) % NICK_INDEX_SIZE];
  client->prev = 0;
  client->next = *entry;
  if (client->next)
    clients[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, char *message_end)
{
  ASSERT (sock < FD_SETSIZE);
  ASSERT (FD_ISSET (sock, &active_fds));

  accepted_messages += 1;

  client_id id = SOCKET_TO_CLIENT_ID (sock);
  struct client *client = &clients[id];

  char *message_beg = &client->buffer[client->buffer_message_beg];
  if (*message_beg == '/') {
    enum command command = COMMAND_COUNT;
    char *command_beg = message_beg + 1;
    char *command_end = command_beg;
    for (enum command c = 0; c < COMMAND_COUNT; ++c) {
      if (strncmp (command_beg, command_to_str[c], command_to_strlen[c]) == 0 &&
          strchr (" \t\n", command_beg[command_to_strlen[c]])) {
        command = c;
        command_end += command_to_strlen[c];
        break;
      }
    }

    switch (command) {
      case COMMAND_HELP: {
#define COMMAND(SYM, STR, ARGS, HELP) clients__server_printf_to (              \
          sock, "/"STR" %-*s"HELP, (int) (COMMAND_HELP_OFFSET - sizeof (STR)), ARGS);
        COMMANDS;
#undef COMMAND
      } goto cleanup;

      case COMMAND_NICK: {
        char *nick_beg = command_end;
        if (*nick_beg == '\n') {
          clients__server_printf_to (sock, "No nickname provided");
          goto cleanup;
        }
        while (nick_beg < message_end && strchr (" \t", *nick_beg))
          nick_beg += 1;
        if (*nick_beg == '\n') {
          clients__server_printf_to (sock, "No nickname provided");
          goto cleanup;
        }
        char *nick_end = nick_beg;
        while (nick_end < message_end &&
               nick_end < nick_beg + MAX_NICK_LENGTH &&
               isalnum (*nick_end)) {
          *nick_end = tolower (*nick_end);
          nick_end += 1;
        }
        if (nick_end - nick_beg == 0) {
          clients__server_printf_to (sock, "Invalid nickname");
          goto cleanup;
        }
        clients__set_nick (sock, nick_beg, nick_end);
      } goto cleanup;

      case COMMAND_USERS: {
        FOREACH_CLIENT_SOCKET (user_sock) {
          const struct client *user = &clients[SOCKET_TO_CLIENT_ID (*user_sock)];
          clients__server_printf_to (sock, "%*hhu.%hhu.%hhu.%hhu <%s>%s",
                                     4*3 -
                                     log10u8 (user->addr[3]) -
                                     log10u8 (user->addr[2]) -
                                     log10u8 (user->addr[1]) -
                                     log10u8 (user->addr[0]),
                                     user->addr[3],
                                     user->addr[2],
                                     user->addr[1],
                                     user->addr[0], user->nick,
                                     *user_sock == sock ? " (you)" : "");
        }
      } goto cleanup;

      case COMMAND_UPTIME: {
        double uptime = difftime (time (NULL), startup_time);
        uint8_t seconds = (uint8_t) (uptime      ) % 60;
        uint8_t minutes = (uint8_t) (uptime/60   ) % 60;
        uint8_t hours   = (uint8_t) (uptime/60/60) % 24;
        double  days    = uptime/60/60/24;
        struct rusage usage;
        getrusage (RUSAGE_SELF, &usage);
        clients__server_printf_to (sock, "Up %.0lf day%s %02hhu:%02hhu:%02hhu, "
                                         "accepted %lu connection%s and %lu message%s",
                                   days, 1 <= days && days < 2 ? "s" : "",
                                   hours, minutes, seconds,
                                   accepted_connections, accepted_connections != 1 ? "s" : "",
                                   accepted_messages,    accepted_messages    != 1 ? "s" : "");
      } goto cleanup;

      case COMMAND_LALU: {
        clients__server_printf_all ("Chaau from lu");
        clients__remove_client (sock);
      } goto cleanup;

      case COMMAND_FIGLET: {
        char line_buffer[6][72];
        char line_lengths[6] = {0};
        if (message_end - command_end > COMMAND_FIGLET_MAX_MSG_LEN)
          strcpy (command_end + COMMAND_FIGLET_MAX_MSG_LEN, " 2>/dev/null");
        else strcpy (message_end, " 2>/dev/null");
        INFO ("Running command %s", command_beg);
        FILE *figlet = popen (command_beg, "r");
        int c = getc (figlet);
        if (c == EOF) {
          pclose (figlet);
          clients__server_printf_to (sock, "Something went wrong");
          goto cleanup;
        } ungetc (c, figlet);
        for (int i = 0; i < 6; ++i) {
          char *head = &line_buffer[i][0];
          while (head < &line_buffer[i][0] + sizeof (line_buffer[i]) - 1) {
            int c = getc (figlet);
            if (c == EOF) {
              pclose (figlet);
              clients__server_printf_to (sock, "Something went wrong");
              goto cleanup;
            }
            *head++ = c;
            line_lengths[i] += 1;
            if (c == '\n') break;
          }
        }
        pclose (figlet);
        for (int i = 0; i < 6; ++i) {
          memcpy (client->buffer + client->buffer_message_beg, &line_buffer[i][0], line_lengths[i]);
          client->buffer_message_end = client->buffer_message_beg + line_lengths[i];
          if (write (archive_fd, client->buffer, client->buffer_message_end) == -1)
            DEBUG ("write: %s", strerror (errno));
          FOREACH_CLIENT_SOCKET (recepient) {
            if (write (*recepient, client->buffer, client->buffer_message_end) == -1) {
              DEBUG ("write: %s", strerror (errno));
              goto cleanup;
            }
          }
        }
      } goto cleanup;

      case COMMAND_COUNT: {
        clients__server_printf_to (sock, "Unknown command");
      } goto cleanup;

      default: {
        clients__server_printf_to (sock, "Sorry, command not implemented(");
      } goto cleanup;
    }
  } 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) {
      DEBUG ("write: %s", strerror (errno));
      goto cleanup;
    }
  } else {
    if (write (archive_fd, client->buffer, client->buffer_message_end) == -1)
      DEBUG ("write: %s", strerror (errno));
    FOREACH_CLIENT_SOCKET (recepient) {
      if (*recepient == sock) continue;
      if (write (*recepient, client->buffer, client->buffer_message_end) == -1)
        DEBUG ("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 = SOCKET_TO_CLIENT_ID (sock);
  struct client *client = &clients[id];

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

    char *head = &client->buffer[client->buffer_message_beg];
    char *end = &client->buffer[client->buffer_message_beg + bytes_read];
    while (head < end && *head != '\n')
      head += 1;

    if (head == end)
      return true;

    clients__server_printf_to (sock, "Message too long");

    head += 1;
    if (head == end) {
      client->buffer_message_end = client->buffer_message_beg;
      return true;
    }

    bytes_read = end - head;
    memmove (&client->buffer[client->buffer_message_beg], head, bytes_read);
    client->buffer_message_end = client->buffer_message_beg;
  } else {
    bytes_read = read (sock, &client->buffer[client->buffer_message_end],
                       BUFFER_SIZE - client->buffer_message_end);
    if (bytes_read < 1) {
      if (bytes_read == -1)
        DEBUG ("read: %s", strerror (errno));
      clients__remove_client (sock);
      return false;
    }
  }

  char *head = &client->buffer[client->buffer_message_end];
  client->buffer_message_end += bytes_read;
  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[])
{
  pa = parse_program_arguments (argc, argv);
  if (pa.help) {
    print_help (pa.program_name);
    exit (EXIT_SUCCESS);
  }

  setlogmask (LOG_UPTO (pa.log_upto));
  openlog (basename (pa.program_name),
           LOG_PID | (pa.daemonize ? 0 : LOG_PERROR), LOG_DAEMON);

  if (pa.daemonize) {
    close (STDIN_FILENO);
    close (STDOUT_FILENO);
    close (STDERR_FILENO);
    DEBUG ("Closed standard file descriptors");
  }

  archive = fopen (pa.archive, "a");
  if (!archive) {
    EMERGENCY ("Unable to open message archive `%s' for append access: %s",
               pa.archive, strerror (errno));
    exit (EXIT_FAILURE);
  } NOTICE ("Opened message archive `%s' for append access", pa.archive);
  archive_fd = fileno (archive);

  struct sigaction sa = { .sa_handler = signal_handler };
  sigaction (SIGINT,  &sa, NULL);
  sigaction (SIGTERM, &sa, NULL);
  DEBUG ("Registered signal handlers");

  if (pa.daemonize) {
    pid_t pid = fork ();
    if (pid == -1) {
      EMERGENCY ("Unable to fork: %s", strerror (errno));
      exit (EXIT_FAILURE);
    }

    if (pid > 0)
      exit (EXIT_SUCCESS);
    DEBUG ("Forked");

    pid_t sid = setsid ();
    if (sid == -1) {
      EMERGENCY ("Unable to set SID: %s", strerror (errno));
      exit (EXIT_FAILURE);
    } DEBUG ("Set sid to %d", sid);
  }

  umask (0);

  if (chdir ("/") == -1) {
    EMERGENCY ("Unable to chdir to /: %s", strerror (errno));
    exit (EXIT_FAILURE);
  } DEBUG ("Changed directory to /");

  listener = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
  if (listener == -1) {
    EMERGENCY ("Failed to create socket: %s", strerror (errno));
    exit (EXIT_FAILURE);
  } DEBUG ("Created socket");
  max_fd = listener;

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

  if (fcntl (listener, F_SETFL, O_NONBLOCK) == -1) {
    EMERGENCY ("Failed to set nonblocking mode for listener socket: %s",
               strerror (errno));
    exit (EXIT_FAILURE);
  } DEBUG ("Set nonblocking mode for listener socket");

  struct sockaddr_in addr = {
    .sin_family = AF_INET,
    .sin_port   = htons (pa.port),
  };
  if (!inet_aton (pa.addr, &addr.sin_addr)) {
    EMERGENCY ("Failed to convert address %s", pa.addr);
    exit (EXIT_FAILURE);
  } DEBUG ("Converted address %s: %s", pa.addr, inet_ntoa (addr.sin_addr));

  if (bind (listener, (struct sockaddr *) &addr, sizeof (addr)) == -1) {
    EMERGENCY ("Failed to bind address "SOCKADDR_IN_FMT" to listener socket: %s",
               SOCKADDR_IN_SPLIT (addr), strerror (errno));
    exit (EXIT_FAILURE);
  } DEBUG ("Bound address "SOCKADDR_IN_FMT" to listener socket",
           SOCKADDR_IN_SPLIT (addr));

  if (listen (listener, 2)) {
    EMERGENCY ("Failed to listen on "SOCKADDR_IN_FMT": %s",
               SOCKADDR_IN_SPLIT (addr), strerror (errno));
    exit (EXIT_FAILURE);
  } NOTICE ("Listening on: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (addr));

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

  NOTICE ("Server started");
  startup_time = time (NULL);
  while (!should_stop) {
    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) {
      DEBUG ("select: %s", strerror (errno));
      continue;
    }

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

    FOREACH_CLIENT_SOCKET (client) {
      if (!FD_ISSET (*client, &read_fds)) continue;
      if (!clients__read_from_client (*client))
        client -= 1;
    }
  } NOTICE ("Server stopped");

  return EXIT_SUCCESS;
}