aboutsummaryrefslogtreecommitdiff
path: root/src/chat-server.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.c
downloadlab-05-3b539f06811a181249d6a154a5fce54d95ce9693.tar.gz
publishHEADmaster
Diffstat (limited to 'src/chat-server.c')
-rw-r--r--src/chat-server.c794
1 files changed, 794 insertions, 0 deletions
diff --git a/src/chat-server.c b/src/chat-server.c
new file mode 100644
index 0000000..79aee55
--- /dev/null
+++ b/src/chat-server.c
@@ -0,0 +1,794 @@
1#include <stdio.h>
2#include <stdlib.h>
3#include <stdarg.h>
4#include <stdbool.h>
5#include <string.h>
6#include <ctype.h>
7#include <errno.h>
8#include <unistd.h>
9#include <fcntl.h>
10#include <signal.h>
11#include <time.h>
12#include <sys/select.h>
13#include <sys/socket.h>
14#include <sys/stat.h>
15#include <sys/resource.h>
16#include <netinet/in.h>
17#include <arpa/inet.h>
18#include "utils.h"
19
20// TODO(cmmm): Could save some space by offseting, N first sockets
21// won't be clients, but finding N is not trivial.
22#define SOCKET_TO_CLIENT_ID(SOCK ) (SOCK )
23#define CLIENT_ID_TO_SOCKET(CLIENT) (CLIENT)
24
25#define MAX_CLIENT_COUNT SOCKET_TO_CLIENT_ID (FD_SETSIZE - 2)
26#define MAX_NICK_LENGTH 9
27#define MAX_MESSAGE_SIZE 512
28#define BUFFER_SIZE (1 + MAX_NICK_LENGTH + 2 + MAX_MESSAGE_SIZE) // "<nick> msg"
29#define NICK_INDEX_SIZE FD_SETSIZE
30#define HASH djb2
31#define HASHN djb2n
32#define HASHV djb2v
33
34#define PROGRAM_ARGUMENTS \
35 PROGRAM_ARGUMENT_BOOL (help, 'h', "help", "Show this help message" ) \
36 PROGRAM_ARGUMENT_BOOL (daemonize, 'd', "daemonize", "Daemonize process on startup" ) \
37 PROGRAM_ARGUMENT_UINT (log_upto, 'l', "log-upto", "Log up to this Syslog priority", LOG_NOTICE ) \
38 PROGRAM_ARGUMENT_STRING (archive, 'x', "archive", "Filename of broadcast message archive", "/var/log/chat-server-archive.log") \
39 PROGRAM_ARGUMENT_STRING (addr, 'a', "addr", "IP address to listen on", "0.0.0.0" ) \
40 PROGRAM_ARGUMENT_UINT (port, 'p', "port", "Port to listen on", 6666 )
41#include "program-arguments.h"
42
43#define MOTD "Welcome, your nick is <%s>, " \
44 "use `/nick NAME' to change it, use `/help' to show help", client->nick
45
46#define COMMAND_HELP_OFFSET 20
47#define COMMAND_FIGLET_MAX_MSG_LEN 23
48#define COMMANDS \
49 COMMAND (HELP, "help", "", "Show this help message" ) \
50 COMMAND (NICK, "nick", "NAME", "Set nickname to NAME" ) \
51 COMMAND (USERS, "users", "", "List users nicknames and ip addresses") \
52 COMMAND (UPTIME, "uptime", "", "Show chat's age" ) \
53 COMMAND (LALU, "lalu", "", "Lalu's personal command" ) \
54 COMMAND (FIGLET, "figlet", "MSG...", "Send MSG... in large characters" )
55
56#define COMMAND(SYM, ...) COMMAND_##SYM,
57enum command { COMMANDS COMMAND_COUNT };
58#undef COMMAND
59
60#define COMMAND(SYM, STR, ...) [COMMAND_##SYM] = STR,
61const char *command_to_str[COMMAND_COUNT] = { COMMANDS };
62#undef COMMAND
63
64#define COMMAND(SYM, STR, ...) [COMMAND_##SYM] = (uint8_t) sizeof (STR) - 1,
65uint8_t command_to_strlen[COMMAND_COUNT] = { COMMANDS };
66#undef COMMAND
67
68#define COMMAND(SYM, STR, ARGS, ...) [COMMAND_##SYM] = ARGS,
69const char *command_to_args[COMMAND_COUNT] = { COMMANDS };
70#undef COMMAND
71
72#define COMMAND(SYM, STR, ARGS, HELP) [COMMAND_##SYM] = HELP,
73const char *command_to_help[COMMAND_COUNT] = { COMMANDS };
74#undef COMMAND
75
76typedef uint16_t client_id;
77typedef uint16_t buffer_index;
78
79struct client {
80 char nick[MAX_NICK_LENGTH + 1];
81 client_id prev; // prev in hash map bucket
82 client_id next; // next in hash map bucket
83 client_id socket_index;
84 uint8_t addr[4];
85 uint16_t port;
86 buffer_index buffer_message_beg;
87 buffer_index buffer_message_end;
88 char buffer[BUFFER_SIZE]; // only for reading from socket
89} clients[MAX_CLIENT_COUNT];
90
91client_id nick_index[NICK_INDEX_SIZE] = {0}; // hash map bucket heads
92int client_sockets[MAX_CLIENT_COUNT];
93int *client_sockets_end = client_sockets;
94#define FOREACH_CLIENT_SOCKET(SOCK) \
95 for (int *SOCK = client_sockets; SOCK < client_sockets_end; ++SOCK)
96
97int max_fd = 0;
98fd_set active_fds;
99int listener = -1;
100
101struct program_arguments pa;
102volatile bool should_stop = false;
103FILE *archive;
104int archive_fd;
105time_t startup_time;
106uint64_t accepted_messages;
107uint64_t accepted_connections;
108
109void
110signal_handler (int sig)
111{
112 int serrno = errno;
113
114 switch (sig) {
115 case SIGINT:
116 DEBUG ("Received SIGINT");
117 should_stop = true;
118 break;
119
120 case SIGTERM:
121 DEBUG ("Received SIGTERM");
122 should_stop = true;
123 break;
124
125 default: DEBUG ("Received unhandled %s", strsignal (sig));
126 }
127
128 errno = serrno;
129}
130
131client_id
132djb2 (const char *str)
133{
134 client_id hash = 5381;
135
136 while (*str)
137 hash = ((hash << 5) + hash) + *str++;
138
139 return hash;
140}
141
142client_id
143djb2n (const char *str, int n)
144{
145 client_id hash = 5381;
146
147 while (n && *str) {
148 hash = ((hash << 5) + hash) + *str++;
149 n -= 1;
150 }
151
152 return hash;
153}
154
155client_id
156djb2v (const char *str, const char *end)
157{
158 client_id hash = 5381;
159
160 while (str < end && *str)
161 hash = ((hash << 5) + hash) + *str++;
162
163 return hash;
164}
165
166bool
167clients__server_vprintf (int sock, const char *template, va_list ap)
168{
169 static char buffer[513];
170 int len = 0;
171 len += snprintf (buffer + len, 513 - len, "<server> ");
172 len += vsnprintf (buffer + len, 513 - len, template, ap);
173 len += snprintf (buffer + len, 513 - len, "\n");
174
175 if (write (sock, buffer, len) == -1) {
176 DEBUG ("write: %s", strerror (errno));
177 return false;
178 }
179
180 return true;
181}
182
183bool
184clients__server_printf_to (int recepient, const char *template, ...)
185{
186 va_list ap;
187 va_start (ap, template);
188 bool ret = clients__server_vprintf (recepient, template, ap);
189 va_end (ap);
190 return ret;
191}
192
193bool
194clients__server_printf_except (int except, const char *template, ...)
195{
196 va_list ap;
197 va_start (ap, template);
198 fprintf (archive, "<server> ");
199 vfprintf (archive, template, ap);
200 fprintf (archive, "\n");
201 va_end (ap);
202 fflush (archive);
203
204 bool ret = true;
205 FOREACH_CLIENT_SOCKET (recepient) {
206 if (*recepient == except) continue;
207 va_start (ap, template);
208 if (!clients__server_vprintf (*recepient, template, ap))
209 ret = false;
210 va_end (ap);
211 }
212 return ret;
213}
214
215bool
216clients__server_printf_all (const char *template, ...)
217{
218 va_list ap;
219 va_start (ap, template);
220 fprintf (archive, "<server> ");
221 vfprintf (archive, template, ap);
222 fprintf (archive, "\n");
223 va_end (ap);
224 fflush (archive);
225
226 bool ret = true;
227 FOREACH_CLIENT_SOCKET (recepient) {
228 va_start (ap, template);
229 if (!clients__server_vprintf (*recepient, template, ap))
230 ret = false;
231 va_end (ap);
232 }
233 return ret;
234}
235
236bool
237clients__add_client (int sock, uint32_t addr, uint16_t port)
238{
239 ASSERT (sock < FD_SETSIZE);
240 ASSERT (!FD_ISSET (sock, &active_fds));
241
242 FD_SET (sock, &active_fds);
243 if (sock > max_fd)
244 max_fd = sock;
245
246 client_id id = SOCKET_TO_CLIENT_ID (sock);
247 struct client *client = &clients[id];
248 snprintf (client->nick, sizeof (client->nick), "guest%d", id);
249
250 *((uint32_t *) &client->addr) = addr;
251 client->port = port;
252
253 client->buffer_message_end =
254 client->buffer_message_beg =
255 snprintf (client->buffer, BUFFER_SIZE, "<%s> ", client->nick);
256
257 client_id *entry = &nick_index[HASH (client->nick) % NICK_INDEX_SIZE];
258 client->prev = 0;
259 client->next = *entry;
260 if (client->next)
261 clients[client->next - 1].prev = id + 1;
262 *entry = id + 1;
263
264 clients__server_printf_to (sock, MOTD);
265
266 clients__server_printf_all ("Client <%s> connected from %hhu.%hhu.%hhu.%hhu",
267 client->nick,
268 client->addr[3],
269 client->addr[2],
270 client->addr[1],
271 client->addr[0]);
272
273 client->socket_index = client_sockets_end - client_sockets;
274 *client_sockets_end++ = sock;
275
276 INFO ("Added client <%s> %hhu.%hhu.%hhu.%hhu:%hu", client->nick,
277 client->addr[3],
278 client->addr[2],
279 client->addr[1],
280 client->addr[0], client->port);
281
282 return true;
283}
284
285bool
286clients__accept_connection (void)
287{
288 ASSERT (listener != -1);
289
290 struct sockaddr_in addr;
291 socklen_t length = sizeof (addr);
292 int sock = accept (listener, (struct sockaddr *) &addr, &length);
293 if (sock == -1) {
294 if (errno == EWOULDBLOCK)
295 return false;
296 ERROR ("Failed to accept connection: %s", strerror (errno));
297 exit (EXIT_FAILURE);
298 } NOTICE ("Accepted connection: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (addr));
299 accepted_connections += 1;
300
301 if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) {
302 ERROR ("Failed to set nonblocking mode for client socket: %s",
303 strerror (errno));
304 if (close (sock) == -1)
305 WARNING ("close: %s", strerror (errno));
306 return true;
307 }
308
309 clients__add_client (sock, ntohl (addr.sin_addr.s_addr), ntohs (addr.sin_port));
310 return true;
311}
312
313bool
314clients__remove_client (int sock)
315{
316 ASSERT (sock < FD_SETSIZE);
317 ASSERT (FD_ISSET (sock, &active_fds));
318
319 FD_CLR (sock, &active_fds);
320 if (sock == max_fd) {
321 do max_fd -= 1;
322 while (!FD_ISSET (max_fd, &active_fds));
323 }
324
325 if (close (sock) == -1)
326 WARNING ("close: %s", strerror (errno));
327
328 client_id id = SOCKET_TO_CLIENT_ID (sock);
329 struct client *client = &clients[id];
330
331 client_sockets_end -= 1;
332 clients[SOCKET_TO_CLIENT_ID (*client_sockets_end)].socket_index =
333 client->socket_index;
334 client_sockets[client->socket_index] = *client_sockets_end;
335
336 if (client->next) clients[client->next - 1].prev = client->prev;
337 if (client->prev) clients[client->prev - 1].next = client->next;
338 else nick_index[HASH (client->nick) % NICK_INDEX_SIZE] = client->next;
339
340 clients__server_printf_all ("Client <%s> from %hhu.%hhu.%hhu.%hhu disconnected",
341 client->nick,
342 client->addr[3],
343 client->addr[2],
344 client->addr[1],
345 client->addr[0]);
346
347 INFO ("Removed client <%s> %hhu.%hhu.%hhu.%hhu:%hu", client->nick,
348 client->addr[3],
349 client->addr[2],
350 client->addr[1],
351 client->addr[0], client->port);
352
353 return true;
354}
355
356int
357clients__nick_to_socket (const char *nick_beg, const char *nick_end)
358{
359 ASSERT (nick_beg < nick_end);
360 ASSERT (nick_end - nick_beg <= MAX_NICK_LENGTH);
361
362 client_id recepient_id = nick_index[HASHV (nick_beg, nick_end) % NICK_INDEX_SIZE];
363 while (recepient_id) {
364 const struct client *recepient = &clients[recepient_id - 1];
365 if (strlen (recepient->nick) == (size_t) (nick_end - nick_beg) &&
366 strncmp (recepient->nick, nick_beg, nick_end - nick_beg) == 0) {
367 return CLIENT_ID_TO_SOCKET (recepient - clients);
368 }
369 recepient_id = recepient->next;
370 }
371
372 return -1;
373}
374
375bool
376clients__set_nick (int sock, const char *nick_beg, const char *nick_end)
377{
378 ASSERT (sock < FD_SETSIZE);
379 ASSERT (FD_ISSET (sock, &active_fds));
380
381 client_id id = SOCKET_TO_CLIENT_ID (sock);
382 struct client *client = &clients[id];
383
384 if (isalnum (*nick_end)) {
385 clients__server_printf_to (sock, "Nick too long");
386 return false;
387 }
388
389 if (clients__nick_to_socket (nick_beg, nick_end) != -1) {
390 clients__server_printf_to (sock, "Nick already occupied");
391 return false;
392 }
393
394 client_id *entry = &nick_index[HASH (client->nick) % NICK_INDEX_SIZE];
395 if (*entry == id + 1)
396 *entry = client->next;
397
398 clients__server_printf_except (sock, "Client <%s> changed it's nick to <%.*s>",
399 client->nick,
400 (int) (nick_end - nick_beg), nick_beg);
401
402 INFO ("Client <%s> %hhu.%hhu.%hhu.%hhu:%hu changed it's nick to <%.*s>",
403 client->nick,
404 client->addr[3],
405 client->addr[2],
406 client->addr[1],
407 client->addr[0], client->port, (int) (nick_end - nick_beg), nick_beg);
408
409 memcpy (client->nick, nick_beg, nick_end - nick_beg);
410 client->nick[nick_end - nick_beg] = '\0';
411 client->buffer_message_beg = sprintf (client->buffer, "<%.*s> ",
412 (int) (nick_end - nick_beg), nick_beg);
413
414 if (client->prev) clients[client->prev - 1].next = client->next;
415 if (client->next) clients[client->next - 1].prev = client->prev;
416 entry = &nick_index[HASH (client->nick) % NICK_INDEX_SIZE];
417 client->prev = 0;
418 client->next = *entry;
419 if (client->next)
420 clients[client->next - 1].prev = id + 1;
421 *entry = id + 1;
422
423 clients__server_printf_to (sock, "Your new nick is <%s>", client->nick);
424
425 return true;
426}
427
428bool
429clients__message_received (int sock, char *message_end)
430{
431 ASSERT (sock < FD_SETSIZE);
432 ASSERT (FD_ISSET (sock, &active_fds));
433
434 accepted_messages += 1;
435
436 client_id id = SOCKET_TO_CLIENT_ID (sock);
437 struct client *client = &clients[id];
438
439 char *message_beg = &client->buffer[client->buffer_message_beg];
440 if (*message_beg == '/') {
441 enum command command = COMMAND_COUNT;
442 char *command_beg = message_beg + 1;
443 char *command_end = command_beg;
444 for (enum command c = 0; c < COMMAND_COUNT; ++c) {
445 if (strncmp (command_beg, command_to_str[c], command_to_strlen[c]) == 0 &&
446 strchr (" \t\n", command_beg[command_to_strlen[c]])) {
447 command = c;
448 command_end += command_to_strlen[c];
449 break;
450 }
451 }
452
453 switch (command) {
454 case COMMAND_HELP: {
455#define COMMAND(SYM, STR, ARGS, HELP) clients__server_printf_to ( \
456 sock, "/"STR" %-*s"HELP, (int) (COMMAND_HELP_OFFSET - sizeof (STR)), ARGS);
457 COMMANDS;
458#undef COMMAND
459 } goto cleanup;
460
461 case COMMAND_NICK: {
462 char *nick_beg = command_end;
463 if (*nick_beg == '\n') {
464 clients__server_printf_to (sock, "No nickname provided");
465 goto cleanup;
466 }
467 while (nick_beg < message_end && strchr (" \t", *nick_beg))
468 nick_beg += 1;
469 if (*nick_beg == '\n') {
470 clients__server_printf_to (sock, "No nickname provided");
471 goto cleanup;
472 }
473 char *nick_end = nick_beg;
474 while (nick_end < message_end &&
475 nick_end < nick_beg + MAX_NICK_LENGTH &&
476 isalnum (*nick_end)) {
477 *nick_end = tolower (*nick_end);
478 nick_end += 1;
479 }
480 if (nick_end - nick_beg == 0) {
481 clients__server_printf_to (sock, "Invalid nickname");
482 goto cleanup;
483 }
484 clients__set_nick (sock, nick_beg, nick_end);
485 } goto cleanup;
486
487 case COMMAND_USERS: {
488 FOREACH_CLIENT_SOCKET (user_sock) {
489 const struct client *user = &clients[SOCKET_TO_CLIENT_ID (*user_sock)];
490 clients__server_printf_to (sock, "%*hhu.%hhu.%hhu.%hhu <%s>%s",
491 4*3 -
492 log10u8 (user->addr[3]) -
493 log10u8 (user->addr[2]) -
494 log10u8 (user->addr[1]) -
495 log10u8 (user->addr[0]),
496 user->addr[3],
497 user->addr[2],
498 user->addr[1],
499 user->addr[0], user->nick,
500 *user_sock == sock ? " (you)" : "");
501 }
502 } goto cleanup;
503
504 case COMMAND_UPTIME: {
505 double uptime = difftime (time (NULL), startup_time);
506 uint8_t seconds = (uint8_t) (uptime ) % 60;
507 uint8_t minutes = (uint8_t) (uptime/60 ) % 60;
508 uint8_t hours = (uint8_t) (uptime/60/60) % 24;
509 double days = uptime/60/60/24;
510 struct rusage usage;
511 getrusage (RUSAGE_SELF, &usage);
512 clients__server_printf_to (sock, "Up %.0lf day%s %02hhu:%02hhu:%02hhu, "
513 "accepted %lu connection%s and %lu message%s",
514 days, 1 <= days && days < 2 ? "s" : "",
515 hours, minutes, seconds,
516 accepted_connections, accepted_connections != 1 ? "s" : "",
517 accepted_messages, accepted_messages != 1 ? "s" : "");
518 } goto cleanup;
519
520 case COMMAND_LALU: {
521 clients__server_printf_all ("Chaau from lu");
522 clients__remove_client (sock);
523 } goto cleanup;
524
525 case COMMAND_FIGLET: {
526 char line_buffer[6][72];
527 char line_lengths[6] = {0};
528 if (message_end - command_end > COMMAND_FIGLET_MAX_MSG_LEN)
529 strcpy (command_end + COMMAND_FIGLET_MAX_MSG_LEN, " 2>/dev/null");
530 else strcpy (message_end, " 2>/dev/null");
531 INFO ("Running command %s", command_beg);
532 FILE *figlet = popen (command_beg, "r");
533 int c = getc (figlet);
534 if (c == EOF) {
535 pclose (figlet);
536 clients__server_printf_to (sock, "Something went wrong");
537 goto cleanup;
538 } ungetc (c, figlet);
539 for (int i = 0; i < 6; ++i) {
540 char *head = &line_buffer[i][0];
541 while (head < &line_buffer[i][0] + sizeof (line_buffer[i]) - 1) {
542 int c = getc (figlet);
543 if (c == EOF) {
544 pclose (figlet);
545 clients__server_printf_to (sock, "Something went wrong");
546 goto cleanup;
547 }
548 *head++ = c;
549 line_lengths[i] += 1;
550 if (c == '\n') break;
551 }
552 }
553 pclose (figlet);
554 for (int i = 0; i < 6; ++i) {
555 memcpy (client->buffer + client->buffer_message_beg, &line_buffer[i][0], line_lengths[i]);
556 client->buffer_message_end = client->buffer_message_beg + line_lengths[i];
557 if (write (archive_fd, client->buffer, client->buffer_message_end) == -1)
558 DEBUG ("write: %s", strerror (errno));
559 FOREACH_CLIENT_SOCKET (recepient) {
560 if (write (*recepient, client->buffer, client->buffer_message_end) == -1) {
561 DEBUG ("write: %s", strerror (errno));
562 goto cleanup;
563 }
564 }
565 }
566 } goto cleanup;
567
568 case COMMAND_COUNT: {
569 clients__server_printf_to (sock, "Unknown command");
570 } goto cleanup;
571
572 default: {
573 clients__server_printf_to (sock, "Sorry, command not implemented(");
574 } goto cleanup;
575 }
576 } else if (*message_beg == '!') {
577 const char *nick_beg = message_beg + 1;
578 const char *nick_end = nick_beg;
579 do nick_end += 1;
580 while (nick_end < nick_beg + MAX_NICK_LENGTH && isalnum (*nick_end));
581 int recepient = clients__nick_to_socket (nick_beg, nick_end);
582 if (recepient == -1) {
583 clients__server_printf_to (sock, "Nick not found: <%.*s>",
584 (int) (nick_end - nick_beg), nick_beg);
585 goto cleanup;
586 }
587 if (recepient == sock) {
588 clients__server_printf_to (sock, "You may not send message to yourself");
589 goto cleanup;
590 }
591
592 if (write (recepient, client->buffer, client->buffer_message_end) == -1) {
593 DEBUG ("write: %s", strerror (errno));
594 goto cleanup;
595 }
596 } else {
597 if (write (archive_fd, client->buffer, client->buffer_message_end) == -1)
598 DEBUG ("write: %s", strerror (errno));
599 FOREACH_CLIENT_SOCKET (recepient) {
600 if (*recepient == sock) continue;
601 if (write (*recepient, client->buffer, client->buffer_message_end) == -1)
602 DEBUG ("write: %s", strerror (errno));
603 }
604 }
605
606 cleanup:
607 client->buffer_message_end = client->buffer_message_beg;
608 return true;
609}
610
611bool
612clients__read_from_client (int sock)
613{
614 ASSERT (sock < FD_SETSIZE);
615 ASSERT (FD_ISSET (sock, &active_fds));
616
617 client_id id = SOCKET_TO_CLIENT_ID (sock);
618 struct client *client = &clients[id];
619
620 ssize_t bytes_read;
621 if (client->buffer_message_end == BUFFER_SIZE) {
622 bytes_read = read (sock, &client->buffer[client->buffer_message_beg], BUFFER_SIZE);
623 if (bytes_read == -1) {
624 DEBUG ("read: %s", strerror (errno));
625 clients__remove_client (sock);
626 return false;
627 }
628
629 char *head = &client->buffer[client->buffer_message_beg];
630 char *end = &client->buffer[client->buffer_message_beg + bytes_read];
631 while (head < end && *head != '\n')
632 head += 1;
633
634 if (head == end)
635 return true;
636
637 clients__server_printf_to (sock, "Message too long");
638
639 head += 1;
640 if (head == end) {
641 client->buffer_message_end = client->buffer_message_beg;
642 return true;
643 }
644
645 bytes_read = end - head;
646 memmove (&client->buffer[client->buffer_message_beg], head, bytes_read);
647 client->buffer_message_end = client->buffer_message_beg;
648 } else {
649 bytes_read = read (sock, &client->buffer[client->buffer_message_end],
650 BUFFER_SIZE - client->buffer_message_end);
651 if (bytes_read < 1) {
652 if (bytes_read == -1)
653 DEBUG ("read: %s", strerror (errno));
654 clients__remove_client (sock);
655 return false;
656 }
657 }
658
659 char *head = &client->buffer[client->buffer_message_end];
660 client->buffer_message_end += bytes_read;
661 char *end = &client->buffer[client->buffer_message_end];
662 while (head < end) {
663 if (*head == '\n')
664 return clients__message_received (sock, head);
665 head += 1;
666 }
667
668 return true;
669}
670
671int
672main (int argc, char *argv[])
673{
674 pa = parse_program_arguments (argc, argv);
675 if (pa.help) {
676 print_help (pa.program_name);
677 exit (EXIT_SUCCESS);
678 }
679
680 setlogmask (LOG_UPTO (pa.log_upto));
681 openlog (basename (pa.program_name),
682 LOG_PID | (pa.daemonize ? 0 : LOG_PERROR), LOG_DAEMON);
683
684 if (pa.daemonize) {
685 close (STDIN_FILENO);
686 close (STDOUT_FILENO);
687 close (STDERR_FILENO);
688 DEBUG ("Closed standard file descriptors");
689 }
690
691 archive = fopen (pa.archive, "a");
692 if (!archive) {
693 EMERGENCY ("Unable to open message archive `%s' for append access: %s",
694 pa.archive, strerror (errno));
695 exit (EXIT_FAILURE);
696 } NOTICE ("Opened message archive `%s' for append access", pa.archive);
697 archive_fd = fileno (archive);
698
699 struct sigaction sa = { .sa_handler = signal_handler };
700 sigaction (SIGINT, &sa, NULL);
701 sigaction (SIGTERM, &sa, NULL);
702 DEBUG ("Registered signal handlers");
703
704 if (pa.daemonize) {
705 pid_t pid = fork ();
706 if (pid == -1) {
707 EMERGENCY ("Unable to fork: %s", strerror (errno));
708 exit (EXIT_FAILURE);
709 }
710
711 if (pid > 0)
712 exit (EXIT_SUCCESS);
713 DEBUG ("Forked");
714
715 pid_t sid = setsid ();
716 if (sid == -1) {
717 EMERGENCY ("Unable to set SID: %s", strerror (errno));
718 exit (EXIT_FAILURE);
719 } DEBUG ("Set sid to %d", sid);
720 }
721
722 umask (0);
723
724 if (chdir ("/") == -1) {
725 EMERGENCY ("Unable to chdir to /: %s", strerror (errno));
726 exit (EXIT_FAILURE);
727 } DEBUG ("Changed directory to /");
728
729 listener = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
730 if (listener == -1) {
731 EMERGENCY ("Failed to create socket: %s", strerror (errno));
732 exit (EXIT_FAILURE);
733 } DEBUG ("Created socket");
734 max_fd = listener;
735
736 int reuseaddr = 1;
737 setsockopt (listener, SOL_SOCKET, SO_REUSEADDR,
738 &reuseaddr, sizeof (reuseaddr));
739
740 if (fcntl (listener, F_SETFL, O_NONBLOCK) == -1) {
741 EMERGENCY ("Failed to set nonblocking mode for listener socket: %s",
742 strerror (errno));
743 exit (EXIT_FAILURE);
744 } DEBUG ("Set nonblocking mode for listener socket");
745
746 struct sockaddr_in addr = {
747 .sin_family = AF_INET,
748 .sin_port = htons (pa.port),
749 };
750 if (!inet_aton (pa.addr, &addr.sin_addr)) {
751 EMERGENCY ("Failed to convert address %s", pa.addr);
752 exit (EXIT_FAILURE);
753 } DEBUG ("Converted address %s: %s", pa.addr, inet_ntoa (addr.sin_addr));
754
755 if (bind (listener, (struct sockaddr *) &addr, sizeof (addr)) == -1) {
756 EMERGENCY ("Failed to bind address "SOCKADDR_IN_FMT" to listener socket: %s",
757 SOCKADDR_IN_SPLIT (addr), strerror (errno));
758 exit (EXIT_FAILURE);
759 } DEBUG ("Bound address "SOCKADDR_IN_FMT" to listener socket",
760 SOCKADDR_IN_SPLIT (addr));
761
762 if (listen (listener, 2)) {
763 EMERGENCY ("Failed to listen on "SOCKADDR_IN_FMT": %s",
764 SOCKADDR_IN_SPLIT (addr), strerror (errno));
765 exit (EXIT_FAILURE);
766 } NOTICE ("Listening on: "SOCKADDR_IN_FMT, SOCKADDR_IN_SPLIT (addr));
767
768 FD_ZERO (&active_fds);
769 FD_SET (listener, &active_fds);
770
771 NOTICE ("Server started");
772 startup_time = time (NULL);
773 while (!should_stop) {
774 fd_set read_fds;
775 memcpy (&read_fds, &active_fds, sizeof (fd_set));
776
777 struct timeval timeout = { .tv_sec = 15 };
778 if (select (max_fd + 1, &read_fds, NULL, NULL, &timeout) == -1) {
779 DEBUG ("select: %s", strerror (errno));
780 continue;
781 }
782
783 if (FD_ISSET (listener, &read_fds))
784 while (clients__accept_connection ());
785
786 FOREACH_CLIENT_SOCKET (client) {
787 if (!FD_ISSET (*client, &read_fds)) continue;
788 if (!clients__read_from_client (*client))
789 client -= 1;
790 }
791 } NOTICE ("Server stopped");
792
793 return EXIT_SUCCESS;
794}