From 3b539f06811a181249d6a154a5fce54d95ce9693 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Tue, 10 Nov 2026 12:34:34 +0300 Subject: publish --- .gitignore | 2 + README.org | 22 + UNLICENSE | 24 + build.sh | 11 + doc/notes.org | 29 ++ src/chat-client.c | 23 + src/chat-server-with-allocated-clients.c | 487 +++++++++++++++++++ src/chat-server.c | 794 +++++++++++++++++++++++++++++++ src/dynamic-array.h | 59 +++ src/ncurses-test.c | 28 ++ src/program-arguments.h | 89 ++++ src/utils.h | 53 +++ 12 files changed, 1621 insertions(+) create mode 100644 .gitignore create mode 100644 README.org create mode 100644 UNLICENSE create mode 100755 build.sh create mode 100644 doc/notes.org create mode 100644 src/chat-client.c create mode 100644 src/chat-server-with-allocated-clients.c create mode 100644 src/chat-server.c create mode 100644 src/dynamic-array.h create mode 100644 src/ncurses-test.c create mode 100644 src/program-arguments.h create mode 100644 src/utils.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9ace4ec --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +*.html +/chat-server diff --git a/README.org b/README.org new file mode 100644 index 0000000..1d0d861 --- /dev/null +++ b/README.org @@ -0,0 +1,22 @@ +#+title: Netcat chat server +#+date: 2025H2 + +* Task +:PROPERTIES: +:CUSTOM_ID: task +:END: +Implement a network chat application. The server must use +non-blocking sockets as a way to process and transfer data to clients +in parallel. The network server must be implemented as a daemon, with +error monitoring and logging, either via syslog or in a log file. The +server must provide unicast and broadcast text messages to one or all +participants , respectively. Implement a network client to test the +server. A network client can be implemented without non-blocking +sockets, in the simplest version, you can take a ready-made one. +client: *netcat* or telnet. + +* Unlicense +:PROPERTIES: +:CUSTOM_ID: unlicense +:END: +#+include: UNLICENSE verse diff --git a/UNLICENSE b/UNLICENSE new file mode 100644 index 0000000..efb9808 --- /dev/null +++ b/UNLICENSE @@ -0,0 +1,24 @@ +This is free and unencumbered software released into the public domain. + +Anyone is free to copy, modify, publish, use, compile, sell, or +distribute this software, either in source code form or as a compiled +binary, for any purpose, commercial or non-commercial, and by any +means. + +In jurisdictions that recognize copyright laws, the author or authors +of this software dedicate any and all copyright interest in the +software to the public domain. We make this dedication for the benefit +of the public at large and to the detriment of our heirs and +successors. We intend this dedication to be an overt act of +relinquishment in perpetuity of all present and future rights to this +software under copyright law. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR +OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, +ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR +OTHER DEALINGS IN THE SOFTWARE. + +For more information, please refer to diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..3cb9189 --- /dev/null +++ b/build.sh @@ -0,0 +1,11 @@ +#!/bin/sh + +# gcc -Wl,-rpath,$HOME/.guix-profile/lib/ -lncurses -o ncurses-test src/ncurses-test.c +gcc -O3 -march=native \ + -std=gnu99 -D_GNU_SOURCE -ggdb3 \ + -Wall -Wextra \ + -Wno-unused-parameter -Wno-unused-variable \ + -Wno-format-truncation -Wno-restrict \ + -Wno-missing-braces -Wno-missing-field-initializers \ + -Isrc -o chat-server \ + src/chat-server.c diff --git a/doc/notes.org b/doc/notes.org new file mode 100644 index 0000000..bb1f786 --- /dev/null +++ b/doc/notes.org @@ -0,0 +1,29 @@ +* Задание +Реализовать приложение «сетевой чат». Сервер должен использовать +неблокирующие сокеты, как способ параллельной обработки и передачи +данных клиентам. Сетевой сервер должен быть реализован ввиде демона, +с контролем и журналированием ошибок, либо через syslog, либо в файл +журнала. Сервер должен обеспечивать одноадресную и широковещательную +отправку текстовых сообщений, одному или всем участникам +соответственно. Реализовать сетевой клиент для проверки +работоспособности сервера. Сетевой клиент может быть реализован без +неблокирующих сокетов, в самом простом варианте, можно взять готовый +клиент: netcat или telnet. + +* Заметки +Для определения конца сообщения использовать =\r\n= или просто =\n=. + +При передачи сообщения сохранять прочтённые байты в буфер, пока не +получен символ конца сообщения, только тогда его стоит обработать. +Таким образом, у сервера отдельный буфер для каждого клиента, но +пользователю достаточно одного буфера. + +Реализовать команды вроде =NICK = для установления имени, и =/msg += для отправки личного сообщения. + +Сервер добавляет перед сообщения ==, чтобы клиент видел от кого +какое сообщение. + +По умолчанию имя клиента может быть =guest%d=, с индексом из массива +клиентов. Но тогда точно придётся использовать free list для массива +клиентов. 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 @@ +#include + +int +main (int argc, char *argv[]) +{ + int server = socket (AF_INET, SOCK_STREAM, 0); + if (server == -1) + DIE (EXIT_FAILURE, "socket: %s", strerror (errno)); + + if (fcntl (server, F_SETFL, O_NONBLOCK) == -1) + DIE (EXIT_FAILURE, "fcntl: %s", strerror (errno)); + + struct sockaddr_in addr = { + .sin_family = AF_INET, + .sin_port = htons (3422), + .sin_addr.s_addr = INADDR_LOOPBACK, + }; + + if (connect (server, (struct sockaddr *) &addr, sizeof (addr)) == -1) + DIE (EXIT_FAILURE, "connect: %s", strerror (errno)); + + return EXIT_SUCCESS; +} 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 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "utils.h" + +#define ASSERT assert +// #define ASSERT + +#define LISTEN_QUEUE 2 +// #define MAX_CLIENT_COUNT (FD_SETSIZE - 5) // stdin, stdout, stderr, listener, reserved +#define MAX_CLIENT_COUNT 4 +#define MAX_NICK_LENGTH 9 +#define MAX_MESSAGE_SIZE 512 +#define BUFFER_SIZE (1 + MAX_NICK_LENGTH + 2 + MAX_MESSAGE_SIZE) // " msg" +#define NICK_INDEX_SIZE FD_SETSIZE +#define HASH djb2 +#define HASHN djb2n +#define HASHV djb2v +#define INITIAL_CLIENT_CAPACITY 1 + +typedef uint16_t client_id; +typedef uint16_t buffer_index; + +// arena with free list, socket luts and nick indexing +struct clients { + struct client { + char nick[MAX_NICK_LENGTH + 1]; + client_id prev; // prev in hash map bucket + client_id next; // next in hash map bucket / free list + client_id socket_index; + buffer_index buffer_message_beg; + buffer_index buffer_message_end; + char buffer[BUFFER_SIZE]; // only for reading from socket + } *items; + client_id count; + client_id capacity; + client_id free_list_head; + + int socket_count; + int socket_index_to_socket[MAX_CLIENT_COUNT]; + client_id socket_to_id [FD_SETSIZE ]; + + client_id nick_index[NICK_INDEX_SIZE]; // hash map bucket heads +} clients = {0}; + +int max_fd = 0; +fd_set active_fds; +int listener = -1; + +client_id +djb2 (const char *str) +{ + client_id hash = 5381; + + while (*str) + hash = ((hash << 5) + hash) + *str++; + + return hash; +} + +client_id +djb2n (const char *str, int n) +{ + client_id hash = 5381; + + while (n && *str) { + hash = ((hash << 5) + hash) + *str++; + n -= 1; + } + + return hash; +} + +client_id +djb2v (const char *str, const char *end) +{ + client_id hash = 5381; + + while (str < end && *str) + hash = ((hash << 5) + hash) + *str++; + + return hash; +} + +bool +clients__server_vprintf (int sock, const char *template, va_list ap) +{ + static char buffer[513]; + int len = 0; + len += snprintf (buffer + len, 513 - len, " "); + len += vsnprintf (buffer + len, 513 - len, template, ap); + len += snprintf (buffer + len, 513 - len, "\n"); + + if (write (sock, buffer, len) == -1) { + ERROR ("write: %s", strerror (errno)); + return false; + } + + return true; +} + +bool +clients__server_printf_to (int sock, const char *template, ...) +{ + va_list ap; + va_start (ap, template); + bool ret = clients__server_vprintf (sock, template, ap); + va_end (ap); + return ret; +} + +bool +clients__server_printf_except (int except, const char *template, ...) +{ + va_list ap; + bool ret = true; + for (client_id i = 0; i < clients.socket_count; ++i) { + int sock = clients.socket_index_to_socket[i]; + if (sock == except) continue; + va_start (ap, template); + if (!clients__server_vprintf (sock, template, ap)) + ret = false; + va_end (ap); + } + return ret; +} + +bool +clients__server_printf_all (const char *template, ...) +{ + va_list ap; + bool ret = true; + for (client_id i = 0; i < clients.socket_count; ++i) { + int sock = clients.socket_index_to_socket[i]; + va_start (ap, template); + if (!clients__server_vprintf (sock, template, ap)) + ret = false; + va_end (ap); + } + return ret; +} + +bool +clients__add_client (int sock) +{ + ASSERT (sock < FD_SETSIZE); + ASSERT (!FD_ISSET (sock, &active_fds)); + + FD_SET (sock, &active_fds); + if (sock > max_fd) + max_fd = sock; + + client_id id; + if (clients.free_list_head) { + id = clients.free_list_head - 1; + clients.free_list_head = clients.items[id].next; + } else { + id = clients.count++; + if (clients.count > clients.capacity) { + if (clients.count == MAX_CLIENT_COUNT) { + // TODO(cmmm): disconnect with error + } + + clients.capacity *= 2; + if (clients.capacity > MAX_CLIENT_COUNT) + clients.capacity = MAX_CLIENT_COUNT; + clients.items = realloc (clients.items, clients.capacity*sizeof (*clients.items)); + } + } + struct client *client = &clients.items[id]; + snprintf (client->nick, sizeof (client->nick), "guest%d", id); + + client->buffer_message_end = + client->buffer_message_beg = + snprintf (client->buffer, BUFFER_SIZE, "<%s> ", client->nick); + + client_id *entry = &clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE]; + client->prev = 0; + client->next = *entry; + if (client->next) + clients.items[client->next - 1].prev = id + 1; + *entry = id + 1; + + clients__server_printf_to (sock, "your nick is <%s>, " + "use '/nick ' to change it", + client->nick); + + clients__server_printf_all ("client <%s> connected", client->nick); + + client->socket_index = clients.socket_count++; + clients.socket_index_to_socket[client->socket_index] = sock; + clients.socket_to_id[sock] = id; + + INFO ("added client <%s>", client->nick); + + return true; +} + +bool +clients__accept_connection (void) +{ + ASSERT (listener != -1); + + struct sockaddr_in addr; + socklen_t length = sizeof (addr); + int sock = accept (listener, (struct sockaddr *) &addr, &length); + if (sock == -1) { + if (errno == EWOULDBLOCK) + return false; + ERROR ("accept: %s", strerror (errno)); + exit (EXIT_FAILURE); + } + + INFO ("accepted connection: %hhu.%hhu.%hhu.%hhu:%hu", + ntohl (addr.sin_addr.s_addr) >> 3*8, + ntohl (addr.sin_addr.s_addr) >> 2*8, + ntohl (addr.sin_addr.s_addr) >> 1*8, + ntohl (addr.sin_addr.s_addr) >> 0*8, + ntohs (addr.sin_port)); + + if (fcntl (sock, F_SETFL, O_NONBLOCK) == -1) { + ERROR ("fcntl: %s", strerror (errno)); + if (close (sock) == -1) + ERROR ("close: %s", strerror (errno)); + return true; + } + + clients__add_client (sock); + return true; +} + +bool +clients__remove_client (int sock) +{ + ASSERT (sock < FD_SETSIZE); + ASSERT (FD_ISSET (sock, &active_fds)); + + FD_CLR (sock, &active_fds); + if (sock == max_fd) { + do max_fd -= 1; + while (!FD_ISSET (max_fd, &active_fds)); + } + + client_id id = clients.socket_to_id[sock]; + struct client *client = &clients.items[id]; + + clients.socket_index_to_socket[client->socket_index] = + clients.socket_index_to_socket[--clients.socket_count]; + if (close (sock) == -1) + ERROR ("close: %s", strerror (errno)); + + client->next = clients.free_list_head; + clients.free_list_head = id + 1; + + if (client->next) clients.items[client->next - 1].prev = client->prev; + if (client->prev) clients.items[client->prev - 1].next = client->next; + else clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE] = client->next; + + clients__server_printf_all ("client <%s> disconnected", client->nick); + + INFO ("removed client <%s>", client->nick); + + return true; +} + +int +clients__nick_to_socket (const char *nick_beg, const char *nick_end) +{ + ASSERT (nick_beg < nick_end); + ASSERT (nick_end - nick_beg <= MAX_NICK_LENGTH); + + client_id recepient_id = clients.nick_index[HASHV (nick_beg, nick_end) % NICK_INDEX_SIZE]; + while (recepient_id) { + const struct client *recepient = &clients.items[recepient_id - 1]; + if (strlen (recepient->nick) == (size_t) (nick_end - nick_beg) && + strncmp (recepient->nick, nick_beg, nick_end - nick_beg) == 0) { + return clients.socket_index_to_socket[recepient->socket_index]; + } + recepient_id = recepient->next; + } + + return -1; +} + +bool +clients__set_nick (int sock, const char *nick_beg, const char *nick_end) +{ + ASSERT (sock < FD_SETSIZE); + ASSERT (FD_ISSET (sock, &active_fds)); + + client_id id = clients.socket_to_id[sock]; + struct client *client = &clients.items[id]; + + if (isalnum (*nick_end)) { + clients__server_printf_to (sock, "nick too long"); + return false; + } + + if (clients__nick_to_socket (nick_beg, nick_end) != -1) { + clients__server_printf_to (sock, "nick already occupied"); + return false; + } + + client_id *entry = &clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE]; + if (*entry == id + 1) + *entry = client->next; + + clients__server_printf_except (sock, "client <%s> changed it's nick to <%.*s>", + client->nick, (int) (nick_end - nick_beg), + nick_beg); + + memcpy (client->nick, nick_beg, nick_end - nick_beg); + client->nick[nick_end - nick_beg] = '\0'; + client->buffer_message_beg = sprintf (client->buffer, "<%.*s> ", + (int) (nick_end - nick_beg), nick_beg); + + if (client->prev) clients.items[client->prev - 1].next = client->next; + if (client->next) clients.items[client->next - 1].prev = client->prev; + entry = &clients.nick_index[HASH (client->nick) % NICK_INDEX_SIZE]; + client->prev = 0; + client->next = *entry; + if (client->next) + clients.items[client->next - 1].prev = id + 1; + *entry = id + 1; + + clients__server_printf_to (sock, "your new nick is <%s>", client->nick); + + return true; +} + +bool +clients__message_received (int sock, const char *message_end) +{ + ASSERT (sock < FD_SETSIZE); + ASSERT (FD_ISSET (sock, &active_fds)); + + client_id id = clients.socket_to_id[sock]; + struct client *client = &clients.items[id]; + + char *message_beg = &client->buffer[client->buffer_message_beg]; + if (*message_beg == '/') { + if (strncmp (message_beg + 1, "nick ", 5) == 0) { + char *nick_beg = message_beg + 6; + while (*nick_beg == ' ') + nick_beg += 1; + char *nick_end = nick_beg; + do { + *nick_end = tolower (*nick_end); + nick_end += 1; + } while (nick_end < nick_beg + MAX_NICK_LENGTH && isalnum (*nick_end)); + clients__set_nick (sock, nick_beg, nick_end); + } else { + clients__server_printf_to (sock, "unsupported command"); + } + } else if (*message_beg == '!') { + const char *nick_beg = message_beg + 1; + const char *nick_end = nick_beg; + do nick_end += 1; + while (nick_end < nick_beg + MAX_NICK_LENGTH && isalnum (*nick_end)); + int recepient = clients__nick_to_socket (nick_beg, nick_end); + if (recepient == -1) { + clients__server_printf_to (sock, "nick not found: <%.*s>", + (int) (nick_end - nick_beg), nick_beg); + goto cleanup; + } + if (recepient == sock) { + clients__server_printf_to (sock, "you may not send message to yourself"); + goto cleanup; + } + + if (write (recepient, client->buffer, client->buffer_message_end) == -1) { + ERROR ("write: %s", strerror (errno)); + goto cleanup; + } + } else { + for (client_id i = 0; i < clients.socket_count; ++i) { + int recepient = clients.socket_index_to_socket[i]; + if (recepient == sock) continue; + if (write (recepient, client->buffer, client->buffer_message_end) == -1) { + ERROR ("write: %s", strerror (errno)); + } + } + } + + cleanup: + client->buffer_message_end = client->buffer_message_beg; + return true; +} + +bool +clients__read_from_client (int sock) +{ + ASSERT (sock < FD_SETSIZE); + ASSERT (FD_ISSET (sock, &active_fds)); + + client_id id = clients.socket_to_id[sock]; + struct client *client = &clients.items[id]; + + ssize_t bytes_read = read (sock, &client->buffer[client->buffer_message_end], + BUFFER_SIZE - client->buffer_message_end); + if (bytes_read <= 0) { + if (bytes_read == -1) + ERROR ("read: %s", strerror (errno)); + clients__remove_client (sock); + return false; + } + + const char *head = &client->buffer[client->buffer_message_end]; + client->buffer_message_end += bytes_read; + const char *end = &client->buffer[client->buffer_message_end]; + while (head < end) { + if (*head == '\n') + return clients__message_received (sock, head); + head += 1; + } + + return true; +} + +int +main (int argc, char *argv[]) +{ + listener = socket (AF_INET, SOCK_STREAM, 0); + if (listener == -1) + DIE (EXIT_FAILURE, "socket: %s", strerror (errno)); + max_fd = listener; + + int reuseaddr = 1; + setsockopt (listener, SOL_SOCKET, SO_REUSEADDR, + &reuseaddr, sizeof (reuseaddr)); + + if (fcntl (listener, F_SETFL, O_NONBLOCK) == -1) + DIE (EXIT_FAILURE, "fcntl: %s", strerror (errno)); + + struct sockaddr_in addr = { + .sin_family = AF_INET, + .sin_port = htons (3422), + .sin_addr.s_addr = htonl (INADDR_ANY), + }; + + if (bind (listener, (struct sockaddr *) &addr, sizeof (addr)) == -1) + DIE (EXIT_FAILURE, "bind: %s", strerror (errno)); + INFO ("listening on: %hhu.%hhu.%hhu.%hhu:%hu", + ntohl (addr.sin_addr.s_addr) >> 3*8, + ntohl (addr.sin_addr.s_addr) >> 2*8, + ntohl (addr.sin_addr.s_addr) >> 1*8, + ntohl (addr.sin_addr.s_addr) >> 0*8, + ntohs (addr.sin_port)); + + if (listen (listener, LISTEN_QUEUE)) + DIE (EXIT_FAILURE, "listen: %s", strerror (errno)); + + FD_ZERO (&active_fds); + FD_SET (listener, &active_fds); + + clients.items = malloc (INITIAL_CLIENT_CAPACITY*sizeof (*clients.items)); + clients.capacity = INITIAL_CLIENT_CAPACITY; + + for (;;) { + fd_set read_fds; + memcpy (&read_fds, &active_fds, sizeof (fd_set)); + + struct timeval timeout = { .tv_sec = 15 }; + if (select (max_fd + 1, &read_fds, NULL, NULL, &timeout) == -1) + DIE (EXIT_FAILURE, "select: %s", strerror (errno)); + + if (FD_ISSET (listener, &read_fds)) + while (clients__accept_connection ()); + + for (int i = 0; i < clients.socket_count; ++i) { + int sock = clients.socket_index_to_socket[i]; + if (!FD_ISSET (sock, &read_fds)) continue; + if (!clients__read_from_client (sock)) + sock -= 1; + } + } + + return EXIT_SUCCESS; +} 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 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#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) // " 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, " "); + 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, " "); + 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, " "); + 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; +} 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 @@ +#ifndef INCLUDED_DYNAMIC_ARRAY_H +#define INCLUDED_DYNAMIC_ARRAY_H + +#include "utils.h" + +#ifndef DYNAMIC_ARRAY_INIT_CAP +#define DYNAMIC_ARRAY_INIT_CAP 256 +#endif + +#define DYNAMIC_ARRAY_ENSURE_CAPACITY(DYNAMIC_ARRAY, COUNT) \ + ({ \ + if ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) { \ + if ((DYNAMIC_ARRAY).capacity == 0) \ + (DYNAMIC_ARRAY).capacity = DYNAMIC_ARRAY_INIT_CAP; \ + while ((DYNAMIC_ARRAY).count + (COUNT) > (DYNAMIC_ARRAY).capacity) \ + (DYNAMIC_ARRAY).capacity *= 2; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + } \ + }) + +#define DYNAMIC_ARRAY_SHRINK(DYNAMIC_ARRAY) \ + ({ \ + (DYNAMIC_ARRAY).capacity = (DYNAMIC_ARRAY).count; \ + (DYNAMIC_ARRAY).items = REALLOC((DYNAMIC_ARRAY).items, \ + (DYNAMIC_ARRAY).capacity * \ + sizeof (*(DYNAMIC_ARRAY).items)); \ + ASSERT((DYNAMIC_ARRAY).items); \ + \ + }) + +#define DYNAMIC_ARRAY_APPEND(DYNAMIC_ARRAY, ITEM) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), 1); \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count++] = (ITEM); \ + }) + +#define DYNAMIC_ARRAY_APPEND_MANY(DYNAMIC_ARRAY, NEW_ITEMS, NEW_ITEMS_COUNT) \ + ({ \ + DYNAMIC_ARRAY_ENSURE_CAPACITY((DYNAMIC_ARRAY), (NEW_ITEMS_COUNT)); \ + memcpy ((DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count, (NEW_ITEMS), \ + (NEW_ITEMS_COUNT)*sizeof (*(DYNAMIC_ARRAY).items)); \ + (DYNAMIC_ARRAY).count += (NEW_ITEMS_COUNT); \ + }) + +#define DYNAMIC_ARRAY_LAST(DYNAMIC_ARRAY) \ + (DYNAMIC_ARRAY).items[(DYNAMIC_ARRAY).count - 1] + +#define DYNAMIC_ARRAY_RESET(DYNAMIC_ARRAY) ({ (DYNAMIC_ARRAY).count = 0; }) + +#define DYNAMIC_ARRAY_FREE(DYNAMIC_ARRAY) FREE((DYNAMIC_ARRAY).items) + +#define DYNAMIC_ARRAY_FOREACH(ITEM, DYNAMIC_ARRAY) for ( \ + typeof ((DYNAMIC_ARRAY).items) ITEM = (DYNAMIC_ARRAY).items; \ + ITEM < (DYNAMIC_ARRAY).items + (DYNAMIC_ARRAY).count; ++ITEM) + +#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 @@ +#include +#include +#include + +int +main (int argc, char *argv[]) +{ + initscr (); + raw (); + noecho (); + keypad (stdscr, TRUE); + + printw ("Type any character to see it in bold\n"); + int ch = getch (); + if(ch == KEY_F (1)) printw ("F1 Key pressed"); + else { + printw ("The pressed key is "); + attron (A_BOLD); + printw ("%c", ch); + attroff (A_BOLD); + } + refresh (); + + getch (); + endwin (); + + return EXIT_SUCCESS; +} 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 @@ +#ifndef INCLUDED_PROGRAM_ARGUMENTS_H +#define INCLUDED_PROGRAM_ARGUMENTS_H + +void +print_help (const char *program_name) +{ + fprintf (stderr, "Usage: %s [OPTION...]\n", program_name); + fprintf (stderr, "\n"); + fprintf (stderr, "Options:\n"); +#define PROGRAM_ARGUMENT_BOOL( sym, s, l, h, ...) fprintf (stderr, " -%c, --%s %*s\n", s, l, (int) (10 + sizeof (h) - sizeof (l)), h); +#define PROGRAM_ARGUMENT_UINT( sym, s, l, h, d, ...) fprintf (stderr, " -%c, --%s %*s (default: %u)\n", s, l, (int) (10 + sizeof (h) - sizeof (l)), h, d); +#define PROGRAM_ARGUMENT_STRING(sym, s, l, h, d, ...) fprintf (stderr, " -%c, --%s %*s (default: %s)\n", s, l, (int) (10 + sizeof (h) - sizeof (l)), h, d); + PROGRAM_ARGUMENTS +#undef PROGRAM_ARGUMENT_BOOL +#undef PROGRAM_ARGUMENT_UINT +#undef PROGRAM_ARGUMENT_STRING +} + +#define PROGRAM_ARGUMENT_BOOL( sym, ...) bool sym; +#define PROGRAM_ARGUMENT_UINT( sym, ...) unsigned int sym; +#define PROGRAM_ARGUMENT_STRING(sym, ...) const char *sym; +struct program_arguments { + const char *program_name; + PROGRAM_ARGUMENTS +}; +#undef PROGRAM_ARGUMENT_BOOL +#undef PROGRAM_ARGUMENT_UINT +#undef PROGRAM_ARGUMENT_STRING + +struct program_arguments +parse_program_arguments (int argc, char *argv[]) +{ + UNUSED (argc); +#define PROGRAM_ARGUMENT_BOOL(...) +#define PROGRAM_ARGUMENT_UINT( sym, s, l, h, d, ...) .sym = d, +#define PROGRAM_ARGUMENT_STRING(sym, s, l, h, d, ...) .sym = d, + struct program_arguments pa = { + .program_name = *argv++, + PROGRAM_ARGUMENTS + }; +#undef PROGRAM_ARGUMENT_BOOL +#undef PROGRAM_ARGUMENT_UINT +#undef PROGRAM_ARGUMENT_STRING + +#define PROGRAM_ARGUMENT_BOOL(sym, s, l, ...) MATCH (s, l) { \ + pa.sym = true; \ + continue; \ + } +#define PROGRAM_ARGUMENT_UINT(sym, s, l, ...) MATCH (s, l) { \ + arg += 1; \ + if (*arg == NULL) { \ + fprintf (stderr, "error"); \ + exit (EXIT_FAILURE); \ + } \ + if (sscanf (*arg, "%u", &pa.sym) == 0) { \ + fprintf (stderr, "error: wrong format for %s\n", arg[-1]); \ + exit (EXIT_FAILURE); \ + } \ + continue; \ + } +#define PROGRAM_ARGUMENT_STRING(sym, s, l, ...) MATCH (s, l) { \ + arg += 1; \ + pa.sym = *arg; \ + continue; \ + } + for (char **arg = argv; *arg; ++arg) { + if ((*arg)[0] == '-') { + if ((*arg)[1] == '-') { +#define MATCH(s, l) if (!strcmp (*arg + 2, l)) + PROGRAM_ARGUMENTS; + fprintf (stderr, "error: unknown option %s\n", *arg); + exit (EXIT_FAILURE); +#undef MATCH + } +#define MATCH(s, l) if ((*arg)[1] == s && (*arg)[2] == '\0') + PROGRAM_ARGUMENTS; + fprintf (stderr, "error: unknown option %s\n", *arg); + exit (EXIT_FAILURE); +#undef MATCH + } + } +#undef PROGRAM_ARGUMENT_BOOL +#undef PROGRAM_ARGUMENT_UINT +#undef PROGRAM_ARGUMENT_STRING + + return pa; +} + +#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 @@ +#ifndef INCLUDED_UTILS_H +#define INCLUDED_UTILS_H + +#include +#include +#include +#include +#include + +#define STRINGIFY(ARG) #ARG +#define TO_STRING(ARG) STRINGIFY (ARG) +#define LOG(PRIORITY, FMT, ...) \ + syslog (LOG_MAKEPRI (LOG_DAEMON, LOG_##PRIORITY), \ + FMT __VA_OPT__ (,) __VA_ARGS__) +#define DEBUG( FMT, ...) \ + LOG (DEBUG, __FILE__ ":" TO_STRING (__LINE__) ": debug: %s: " FMT, __func__ __VA_OPT__ (,) __VA_ARGS__) +#define EMERGENCY(FMT, ...) LOG (EMERG, "emergency: " FMT __VA_OPT__ (,) __VA_ARGS__) +#define ALERT( FMT, ...) LOG (ALERT, "alert: " FMT __VA_OPT__ (,) __VA_ARGS__) +#define CRITICAL( FMT, ...) LOG (CRIT, "critical: " FMT __VA_OPT__ (,) __VA_ARGS__) +#define ERROR( FMT, ...) LOG (ERR, "error: " FMT __VA_OPT__ (,) __VA_ARGS__) +#define WARNING( FMT, ...) LOG (WARNING, "warning: " FMT __VA_OPT__ (,) __VA_ARGS__) +#define NOTICE( FMT, ...) LOG (NOTICE, "notice: " FMT __VA_OPT__ (,) __VA_ARGS__) +#define INFO( FMT, ...) LOG (INFO, "info: " FMT __VA_OPT__ (,) __VA_ARGS__) + +#define UNUSED(X) ((void) (X)) +#define UNREACHABLE() ASSERT (!"reached the unreachable...") +#define TODO(STR) fprintf (stderr, "%s:%d: warning: TODO "STR"\n", __FILE__, __LINE__) +// #define TODO(...) +#define REACHED(FMT, ...) fprintf (stderr, "%s:%d: info: %s: reached: "FMT"\n", __FILE__, __LINE__, __func__ __VA_OPT__(,) __VA_ARGS__) + +#define MALLOC malloc +#define REALLOC realloc +#define FREE free +#define ASSERT assert + +#define PRINT_EXP(EXP, FMT) printf (#EXP" = "FMT"\n", EXP) + +#define SOCKADDR_IN_FMT "%hhu.%hhu.%hhu.%hhu:%hu" +#define SOCKADDR_IN_SPLIT(ADDR) \ + ntohl ((ADDR).sin_addr.s_addr) >> 3*8, \ + ntohl ((ADDR).sin_addr.s_addr) >> 2*8, \ + ntohl ((ADDR).sin_addr.s_addr) >> 1*8, \ + ntohl ((ADDR).sin_addr.s_addr) >> 0*8, \ + ntohs ((ADDR).sin_port) + +inline uint8_t +log10u8 (uint8_t n) +{ + return (n >= 100 ? 3 : + n >= 10 ? 2 : 1); +} + +#endif -- cgit v1.3.1