aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/chat-client.c23
-rw-r--r--src/chat-server-with-allocated-clients.c487
-rw-r--r--src/chat-server.c794
-rw-r--r--src/dynamic-array.h59
-rw-r--r--src/ncurses-test.c28
-rw-r--r--src/program-arguments.h89
-rw-r--r--src/utils.h53
7 files changed, 1533 insertions, 0 deletions
diff --git a/src/chat-client.c b/src/chat-client.c
new file mode 100644
index 0000000..bb4621c
--- /dev/null
+++ b/src/chat-client.c
@@ -0,0 +1,23 @@
1#include <stdlib.h>
2
3int
4main (int argc, char *argv[])
5{
6 int server = socket (AF_INET, SOCK_STREAM, 0);
7 if (server == -1)
8 DIE (EXIT_FAILURE, "socket: %s", strerror (errno));
9
10 if (fcntl (server, F_SETFL, O_NONBLOCK) == -1)
11 DIE (EXIT_FAILURE, "fcntl: %s", strerror (errno));
12
13 struct sockaddr_in addr = {
14 .sin_family = AF_INET,
15 .sin_port = htons (3422),
16 .sin_addr.s_addr = INADDR_LOOPBACK,
17 };
18
19 if (connect (server, (struct sockaddr *) &addr, sizeof (addr)) == -1)
20 DIE (EXIT_FAILURE, "connect: %s", strerror (errno));
21
22 return EXIT_SUCCESS;
23}
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}
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}
diff --git a/src/dynamic-array.h b/src/dynamic-array.h
new file mode 100644
index 0000000..726fcce
--- /dev/null
+++ b/src/dynamic-array.h
@@ -0,0 +1,59 @@
1#ifndef INCLUDED_DYNAMIC_ARRAY_H
2#define INCLUDED_DYNAMIC_ARRAY_H
3
4#include "utils.h"
5
6#ifndef DYNAMIC_ARRAY_INIT_CAP
7#define DYNAMIC_ARRAY_INIT_CAP 256
8#endif
9
10#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \
11 ({ \
12 if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \
13 if ((DYNAMIC_ARRAY).capacity == 0) \
14 (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \
15 while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \
16 (DYNAMIC_ARRAY).capacity *= 2; \
17 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
18 (DYNAMIC_ARRAY).capacity * \
19 sizeof (*(DYNAMIC_ARRAY).items)); \
20 ASSERT((DYNAMIC_ARRAY).items); \
21 } \
22 })
23
24#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \
25 ({ \
26 (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \
27 (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \
28 (DYNAMIC_ARRAY).capacity * \
29 sizeof (*(DYNAMIC_ARRAY).items)); \
30 ASSERT((DYNAMIC_ARRAY).items); \
31 \
32 })
33
34#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \
35 ({ \
36 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \
37 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \
38 })
39
40#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \
41 ({ \
42 DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \
43 memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \
44 (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \
45 (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \
46 })
47
48#define DYNAMIC_ARRAY_LAST(DYNAMIC_ARRAY) \
49 (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1]
50
51#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; })
52
53#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items)
54
55#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \
56 typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \
57 ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM)
58
59#endif
diff --git a/src/ncurses-test.c b/src/ncurses-test.c
new file mode 100644
index 0000000..a34f507
--- /dev/null
+++ b/src/ncurses-test.c
@@ -0,0 +1,28 @@
1#include <stdlib.h>
2#include <locale.h>
3#include <ncurses.h>
4
5int
6main (int argc, char *argv[])
7{
8 initscr ();
9 raw ();
10 noecho ();
11 keypad (stdscr, TRUE);
12
13 printw ("Type any character to see it in bold\n");
14 int ch = getch ();
15 if(ch == KEY_F (1)) printw ("F1 Key pressed");
16 else {
17 printw ("The pressed key is ");
18 attron (A_BOLD);
19 printw ("%c", ch);
20 attroff (A_BOLD);
21 }
22 refresh ();
23
24 getch ();
25 endwin ();
26
27 return EXIT_SUCCESS;
28}
diff --git a/src/program-arguments.h b/src/program-arguments.h
new file mode 100644
index 0000000..dc87f4b
--- /dev/null
+++ b/src/program-arguments.h
@@ -0,0 +1,89 @@
1#ifndef INCLUDED_PROGRAM_ARGUMENTS_H
2#define INCLUDED_PROGRAM_ARGUMENTS_H
3
4void
5print_help (const char *program_name)
6{
7 fprintf (stderr, "Usage: %s [OPTION...]\n", program_name);
8 fprintf (stderr, "\n");
9 fprintf (stderr, "Options:\n");
10#define PROGRAM_ARGUMENT_BOOL( sym, s, l, h, ...) fprintf (stderr, " -%c, --%s %*s\n", s, l, (int) (10 + sizeof (h) - sizeof (l)), h);
11#define PROGRAM_ARGUMENT_UINT( sym, s, l, h, d, ...) fprintf (stderr, " -%c, --%s <unsigned> %*s (default: %u)\n", s, l, (int) (10 + sizeof (h) - sizeof (l)), h, d);
12#define PROGRAM_ARGUMENT_STRING(sym, s, l, h, d, ...) fprintf (stderr, " -%c, --%s <string> %*s (default: %s)\n", s, l, (int) (10 + sizeof (h) - sizeof (l)), h, d);
13 PROGRAM_ARGUMENTS
14#undef PROGRAM_ARGUMENT_BOOL
15#undef PROGRAM_ARGUMENT_UINT
16#undef PROGRAM_ARGUMENT_STRING
17}
18
19#define PROGRAM_ARGUMENT_BOOL( sym, ...) bool sym;
20#define PROGRAM_ARGUMENT_UINT( sym, ...) unsigned int sym;
21#define PROGRAM_ARGUMENT_STRING(sym, ...) const char *sym;
22struct program_arguments {
23 const char *program_name;
24 PROGRAM_ARGUMENTS
25};
26#undef PROGRAM_ARGUMENT_BOOL
27#undef PROGRAM_ARGUMENT_UINT
28#undef PROGRAM_ARGUMENT_STRING
29
30struct program_arguments
31parse_program_arguments (int argc, char *argv[])
32{
33 UNUSED (argc);
34#define PROGRAM_ARGUMENT_BOOL(...)
35#define PROGRAM_ARGUMENT_UINT( sym, s, l, h, d, ...) .sym = d,
36#define PROGRAM_ARGUMENT_STRING(sym, s, l, h, d, ...) .sym = d,
37 struct program_arguments pa = {
38 .program_name = *argv++,
39 PROGRAM_ARGUMENTS
40 };
41#undef PROGRAM_ARGUMENT_BOOL
42#undef PROGRAM_ARGUMENT_UINT
43#undef PROGRAM_ARGUMENT_STRING
44
45#define PROGRAM_ARGUMENT_BOOL(sym, s, l, ...) MATCH (s, l) { \
46 pa.sym = true; \
47 continue; \
48 }
49#define PROGRAM_ARGUMENT_UINT(sym, s, l, ...) MATCH (s, l) { \
50 arg += 1; \
51 if (*arg == NULL) { \
52 fprintf (stderr, "error"); \
53 exit (EXIT_FAILURE); \
54 } \
55 if (sscanf (*arg, "%u", &pa.sym) == 0) { \
56 fprintf (stderr, "error: wrong format for %s\n", arg[-1]); \
57 exit (EXIT_FAILURE); \
58 } \
59 continue; \
60 }
61#define PROGRAM_ARGUMENT_STRING(sym, s, l, ...) MATCH (s, l) { \
62 arg += 1; \
63 pa.sym = *arg; \
64 continue; \
65 }
66 for (char **arg = argv; *arg; ++arg) {
67 if ((*arg)[0] == '-') {
68 if ((*arg)[1] == '-') {
69#define MATCH(s, l) if (!strcmp (*arg + 2, l))
70 PROGRAM_ARGUMENTS;
71 fprintf (stderr, "error: unknown option %s\n", *arg);
72 exit (EXIT_FAILURE);
73#undef MATCH
74 }
75#define MATCH(s, l) if ((*arg)[1] == s && (*arg)[2] == '\0')
76 PROGRAM_ARGUMENTS;
77 fprintf (stderr, "error: unknown option %s\n", *arg);
78 exit (EXIT_FAILURE);
79#undef MATCH
80 }
81 }
82#undef PROGRAM_ARGUMENT_BOOL
83#undef PROGRAM_ARGUMENT_UINT
84#undef PROGRAM_ARGUMENT_STRING
85
86 return pa;
87}
88
89#endif // INCLUDED_PROGRAM_ARGUMENTS_H
diff --git a/src/utils.h b/src/utils.h
new file mode 100644
index 0000000..706defa
--- /dev/null
+++ b/src/utils.h
@@ -0,0 +1,53 @@
1#ifndef INCLUDED_UTILS_H
2#define INCLUDED_UTILS_H
3
4#include <stdarg.h>
5#include <stdlib.h>
6#include <stdio.h>
7#include <assert.h>
8#include <syslog.h>
9
10#define STRINGIFY(ARG) #ARG
11#define TO_STRING(ARG) STRINGIFY (ARG)
12#define LOG(PRIORITY, FMT, ...) \
13 syslog (LOG_MAKEPRI (LOG_DAEMON, LOG_##PRIORITY), \
14 FMT __VA_OPT__ (,) __VA_ARGS__)
15#define DEBUG( FMT, ...) \
16 LOG (DEBUG, __FILE__ ":" TO_STRING (__LINE__) ": debug: %s: " FMT, __func__ __VA_OPT__ (,) __VA_ARGS__)
17#define EMERGENCY(FMT, ...) LOG (EMERG, "emergency: " FMT __VA_OPT__ (,) __VA_ARGS__)
18#define ALERT( FMT, ...) LOG (ALERT, "alert: " FMT __VA_OPT__ (,) __VA_ARGS__)
19#define CRITICAL( FMT, ...) LOG (CRIT, "critical: " FMT __VA_OPT__ (,) __VA_ARGS__)
20#define ERROR( FMT, ...) LOG (ERR, "error: " FMT __VA_OPT__ (,) __VA_ARGS__)
21#define WARNING( FMT, ...) LOG (WARNING, "warning: " FMT __VA_OPT__ (,) __VA_ARGS__)
22#define NOTICE( FMT, ...) LOG (NOTICE, "notice: " FMT __VA_OPT__ (,) __VA_ARGS__)
23#define INFO( FMT, ...) LOG (INFO, "info: " FMT __VA_OPT__ (,) __VA_ARGS__)
24
25#define UNUSED(X) ((void) (X))
26#define UNREACHABLE() ASSERT (!"reached the unreachable...")
27#define TODO(STR) fprintf (stderr, "%s:%d: warning: TODO "STR"\n", __FILE__, __LINE__)
28// #define TODO(...)
29#define REACHED(FMT, ...) fprintf (stderr, "%s:%d: info: %s: reached: "FMT"\n", __FILE__, __LINE__, __func__ __VA_OPT__(,) __VA_ARGS__)
30
31#define MALLOC malloc
32#define REALLOC realloc
33#define FREE free
34#define ASSERT assert
35
36#define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP)
37
38#define SOCKADDR_IN_FMT "%hhu.%hhu.%hhu.%hhu:%hu"
39#define SOCKADDR_IN_SPLIT(ADDR) \
40 ntohl ((ADDR).sin_addr.s_addr) >> 3*8, \
41 ntohl ((ADDR).sin_addr.s_addr) >> 2*8, \
42 ntohl ((ADDR).sin_addr.s_addr) >> 1*8, \
43 ntohl ((ADDR).sin_addr.s_addr) >> 0*8, \
44 ntohs ((ADDR).sin_port)
45
46inline uint8_t
47log10u8 (uint8_t n)
48{
49 return (n >= 100 ? 3 :
50 n >= 10 ? 2 : 1);
51}
52
53#endif