diff options
author | Přemysl Janouch <p.janouch@gmail.com> | 2014-08-10 00:01:38 +0200 |
---|---|---|
committer | Přemysl Janouch <p.janouch@gmail.com> | 2014-08-10 00:01:38 +0200 |
commit | bd68e28b608fb74bb4823726b9f0bf6489ad94b5 (patch) | |
tree | ff082bd52d8dfde8cc8d2f223e2d9b3c63bcc770 /src | |
parent | 0da22a799a215f00ebc2be9e7cf5cc505db27148 (diff) | |
download | xK-bd68e28b608fb74bb4823726b9f0bf6489ad94b5.tar.gz xK-bd68e28b608fb74bb4823726b9f0bf6489ad94b5.tar.xz xK-bd68e28b608fb74bb4823726b9f0bf6489ad94b5.zip |
Remove the `src' directory
There are not that many files, and aren't going to be.
Diffstat (limited to 'src')
-rw-r--r-- | src/common.c | 1988 | ||||
-rw-r--r-- | src/kike.c | 3251 | ||||
-rw-r--r-- | src/siphash.c | 87 | ||||
-rw-r--r-- | src/siphash.h | 10 | ||||
-rw-r--r-- | src/zyklonb.c | 1769 |
5 files changed, 0 insertions, 7105 deletions
diff --git a/src/common.c b/src/common.c deleted file mode 100644 index 782572d..0000000 --- a/src/common.c +++ /dev/null @@ -1,1988 +0,0 @@ -/* - * common.c: common functionality - * - * Copyright (c) 2014, Přemysl Janouch <p.janouch@gmail.com> - * All rights reserved. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - */ - -#define _POSIX_C_SOURCE 199309L -#define _XOPEN_SOURCE 500 - -#include <stdio.h> -#include <stdlib.h> -#include <errno.h> -#include <string.h> -#include <stdarg.h> -#include <stdint.h> -#include <stdbool.h> -#include <ctype.h> -#include <time.h> -#include <limits.h> - -#include <unistd.h> -#include <sys/wait.h> -#include <sys/stat.h> -#include <sys/time.h> -#include <fcntl.h> -#include <poll.h> -#include <signal.h> -#include <strings.h> -#include <regex.h> -#include <libgen.h> -#include <syslog.h> -#include <fnmatch.h> - -#include <sys/socket.h> -#include <sys/types.h> -#include <netinet/in.h> -#include <netdb.h> - -#ifndef NI_MAXHOST -#define NI_MAXHOST 1025 -#endif // ! NI_MAXHOST - -#ifndef NI_MAXSERV -#define NI_MAXSERV 32 -#endif // ! NI_MAXSERV - -#include <getopt.h> -#include <openssl/ssl.h> -#include <openssl/err.h> -#include "siphash.h" - -extern char **environ; - -#ifdef _POSIX_MONOTONIC_CLOCK -#define CLOCK_BEST CLOCK_MONOTONIC -#else // ! _POSIX_MONOTIC_CLOCK -#define CLOCK_BEST CLOCK_REALTIME -#endif // ! _POSIX_MONOTONIC_CLOCK - -#if defined __GNUC__ -#define ATTRIBUTE_PRINTF(x, y) __attribute__ ((format (printf, x, y))) -#else // ! __GNUC__ -#define ATTRIBUTE_PRINTF(x, y) -#endif // ! __GNUC__ - -#if defined __GNUC__ && __GNUC__ >= 4 -#define ATTRIBUTE_SENTINEL __attribute__ ((sentinel)) -#else // ! __GNUC__ || __GNUC__ < 4 -#define ATTRIBUTE_SENTINEL -#endif // ! __GNUC__ || __GNUC__ < 4 - -#define N_ELEMENTS(a) (sizeof (a) / sizeof ((a)[0])) - -#define BLOCK_START do { -#define BLOCK_END } while (0) - -// --- Logging ----------------------------------------------------------------- - -static void -log_message_syslog (int prio, const char *quote, const char *fmt, va_list ap) -{ - va_list va; - va_copy (va, ap); - int size = vsnprintf (NULL, 0, fmt, va); - va_end (va); - if (size < 0) - return; - - char buf[size + 1]; - if (vsnprintf (buf, sizeof buf, fmt, ap) >= 0) - syslog (prio, "%s%s", quote, buf); -} - -static void -log_message_stdio (int prio, const char *quote, const char *fmt, va_list ap) -{ - (void) prio; - FILE *stream = stderr; - - fputs (quote, stream); - vfprintf (stream, fmt, ap); - fputs ("\n", stream); -} - -static void (*g_log_message_real) (int, const char *, const char *, va_list) - = log_message_stdio; - -static void -log_message (int priority, const char *quote, const char *fmt, ...) - ATTRIBUTE_PRINTF (3, 4); - -static void -log_message (int priority, const char *quote, const char *fmt, ...) -{ - va_list ap; - va_start (ap, fmt); - g_log_message_real (priority, quote, fmt, ap); - va_end (ap); -} - -// `fatal' is reserved for unexpected failures that would harm further operation - -#define print_fatal(...) log_message (LOG_ERR, "fatal: ", __VA_ARGS__) -#define print_error(...) log_message (LOG_ERR, "error: ", __VA_ARGS__) -#define print_warning(...) log_message (LOG_WARNING, "warning: ", __VA_ARGS__) -#define print_status(...) log_message (LOG_INFO, "-- ", __VA_ARGS__) - -#define exit_fatal(...) \ - BLOCK_START \ - print_fatal (__VA_ARGS__); \ - exit (EXIT_FAILURE); \ - BLOCK_END - -// --- Debugging and assertions ------------------------------------------------ - -// We should check everything that may possibly fail with at least a soft -// assertion, so that any causes for problems don't slip us by silently. -// -// `g_soft_asserts_are_deadly' may be useful while running inside a debugger. - -static bool g_debug_mode; ///< Debug messages are printed -static bool g_soft_asserts_are_deadly; ///< soft_assert() aborts as well - -#define print_debug(...) \ - BLOCK_START \ - if (g_debug_mode) \ - log_message (LOG_DEBUG, "debug: ", __VA_ARGS__); \ - BLOCK_END - -static void -assertion_failure_handler (bool is_fatal, const char *file, int line, - const char *function, const char *condition) -{ - if (is_fatal) - { - print_fatal ("assertion failed [%s:%d in function %s]: %s", - file, line, function, condition); - abort (); - } - else - print_debug ("assertion failed [%s:%d in function %s]: %s", - file, line, function, condition); -} - -#define soft_assert(condition) \ - ((condition) ? true : \ - (assertion_failure_handler (g_soft_asserts_are_deadly, \ - __FILE__, __LINE__, __func__, #condition), false)) - -#define hard_assert(condition) \ - ((condition) ? (void) 0 : \ - assertion_failure_handler (true, \ - __FILE__, __LINE__, __func__, #condition)) - -// --- Safe memory management -------------------------------------------------- - -// When a memory allocation fails and we need the memory, we're usually pretty -// much fucked. Use the non-prefixed versions when there's a legitimate -// worry that an unrealistic amount of memory may be requested for allocation. - -// XXX: it's not a good idea to use print_message() as it may want to allocate -// further memory for printf() and the output streams. That may fail. - -static void * -xmalloc (size_t n) -{ - void *p = malloc (n); - if (!p) - exit_fatal ("malloc: %s", strerror (errno)); - return p; -} - -static void * -xcalloc (size_t n, size_t m) -{ - void *p = calloc (n, m); - if (!p && n && m) - exit_fatal ("calloc: %s", strerror (errno)); - return p; -} - -static void * -xrealloc (void *o, size_t n) -{ - void *p = realloc (o, n); - if (!p && n) - exit_fatal ("realloc: %s", strerror (errno)); - return p; -} - -static void * -xreallocarray (void *o, size_t n, size_t m) -{ - if (m && n > SIZE_MAX / m) - { - errno = ENOMEM; - exit_fatal ("reallocarray: %s", strerror (errno)); - } - return xrealloc (o, n * m); -} - -static char * -xstrdup (const char *s) -{ - return strcpy (xmalloc (strlen (s) + 1), s); -} - -static char * -xstrndup (const char *s, size_t n) -{ - size_t size = strlen (s); - if (n > size) - n = size; - - char *copy = xmalloc (n + 1); - memcpy (copy, s, n); - copy[n] = '\0'; - return copy; -} - -// --- Double-linked list helpers ---------------------------------------------- - -#define LIST_HEADER(type) \ - struct type *next; \ - struct type *prev; - -#define LIST_PREPEND(head, link) \ - BLOCK_START \ - (link)->prev = NULL; \ - (link)->next = (head); \ - if ((link)->next) \ - (link)->next->prev = (link); \ - (head) = (link); \ - BLOCK_END - -#define LIST_UNLINK(head, link) \ - BLOCK_START \ - if ((link)->prev) \ - (link)->prev->next = (link)->next; \ - else \ - (head) = (link)->next; \ - if ((link)->next) \ - (link)->next->prev = (link)->prev; \ - BLOCK_END - -// --- Dynamically allocated string array -------------------------------------- - -struct str_vector -{ - char **vector; - size_t len; - size_t alloc; -}; - -static void -str_vector_init (struct str_vector *self) -{ - self->alloc = 4; - self->len = 0; - self->vector = xcalloc (sizeof *self->vector, self->alloc); -} - -static void -str_vector_free (struct str_vector *self) -{ - unsigned i; - for (i = 0; i < self->len; i++) - free (self->vector[i]); - - free (self->vector); - self->vector = NULL; -} - -static void -str_vector_reset (struct str_vector *self) -{ - str_vector_free (self); - str_vector_init (self); -} - -static void -str_vector_add_owned (struct str_vector *self, char *s) -{ - self->vector[self->len] = s; - if (++self->len >= self->alloc) - self->vector = xreallocarray (self->vector, - sizeof *self->vector, (self->alloc <<= 1)); - self->vector[self->len] = NULL; -} - -static void -str_vector_add (struct str_vector *self, const char *s) -{ - str_vector_add_owned (self, xstrdup (s)); -} - -static void -str_vector_add_args (struct str_vector *self, const char *s, ...) - ATTRIBUTE_SENTINEL; - -static void -str_vector_add_args (struct str_vector *self, const char *s, ...) -{ - va_list ap; - - va_start (ap, s); - while (s) - { - str_vector_add (self, s); - s = va_arg (ap, const char *); - } - va_end (ap); -} - -static void -str_vector_add_vector (struct str_vector *self, char **vector) -{ - while (*vector) - str_vector_add (self, *vector++); -} - -static void -str_vector_remove (struct str_vector *self, size_t i) -{ - hard_assert (i < self->len); - free (self->vector[i]); - memmove (self->vector + i, self->vector + i + 1, - (self->len-- - i) * sizeof *self->vector); -} - -// --- Dynamically allocated strings ------------------------------------------- - -// Basically a string builder to abstract away manual memory management. - -struct str -{ - char *str; ///< String data, null terminated - size_t alloc; ///< How many bytes are allocated - size_t len; ///< How long the string actually is -}; - -/// We don't care about allocations that are way too large for the content, as -/// long as the allocation is below the given threshold. (Trivial heuristics.) -#define STR_SHRINK_THRESHOLD (1 << 20) - -static void -str_init (struct str *self) -{ - self->alloc = 16; - self->len = 0; - self->str = strcpy (xmalloc (self->alloc), ""); -} - -static void -str_free (struct str *self) -{ - free (self->str); - self->str = NULL; - self->alloc = 0; - self->len = 0; -} - -static void -str_reset (struct str *self) -{ - str_free (self); - str_init (self); -} - -static char * -str_steal (struct str *self) -{ - char *str = self->str; - self->str = NULL; - str_free (self); - return str; -} - -static void -str_ensure_space (struct str *self, size_t n) -{ - // We allocate at least one more byte for the terminating null character - size_t new_alloc = self->alloc; - while (new_alloc <= self->len + n) - new_alloc <<= 1; - if (new_alloc != self->alloc) - self->str = xrealloc (self->str, (self->alloc = new_alloc)); -} - -static void -str_append_data (struct str *self, const char *data, size_t n) -{ - str_ensure_space (self, n); - memcpy (self->str + self->len, data, n); - self->len += n; - self->str[self->len] = '\0'; -} - -static void -str_append_c (struct str *self, char c) -{ - str_append_data (self, &c, 1); -} - -static void -str_append (struct str *self, const char *s) -{ - str_append_data (self, s, strlen (s)); -} - -static void -str_append_str (struct str *self, const struct str *another) -{ - str_append_data (self, another->str, another->len); -} - -static int -str_append_vprintf (struct str *self, const char *fmt, va_list va) -{ - va_list ap; - int size; - - va_copy (ap, va); - size = vsnprintf (NULL, 0, fmt, ap); - va_end (ap); - - if (size < 0) - return -1; - - va_copy (ap, va); - str_ensure_space (self, size); - size = vsnprintf (self->str + self->len, self->alloc - self->len, fmt, ap); - va_end (ap); - - if (size > 0) - self->len += size; - - return size; -} - -static int -str_append_printf (struct str *self, const char *fmt, ...) - ATTRIBUTE_PRINTF (2, 3); - -static int -str_append_printf (struct str *self, const char *fmt, ...) -{ - va_list ap; - - va_start (ap, fmt); - int size = str_append_vprintf (self, fmt, ap); - va_end (ap); - return size; -} - -static void -str_remove_slice (struct str *self, size_t start, size_t length) -{ - size_t end = start + length; - hard_assert (end <= self->len); - memmove (self->str + start, self->str + end, self->len - end); - self->str[self->len -= length] = '\0'; - - // Shrink the string if the allocation becomes way too large - if (self->alloc >= STR_SHRINK_THRESHOLD && self->len < (self->alloc >> 2)) - self->str = xrealloc (self->str, self->alloc >>= 2); -} - -// --- Errors ------------------------------------------------------------------ - -// Error reporting utilities. Inspired by GError, only much simpler. - -struct error -{ - char *message; ///< Textual description of the event -}; - -static void -error_set (struct error **e, const char *message, ...) ATTRIBUTE_PRINTF (2, 3); - -static void -error_set (struct error **e, const char *message, ...) -{ - if (!e) - return; - - va_list ap; - va_start (ap, message); - int size = vsnprintf (NULL, 0, message, ap); - va_end (ap); - - hard_assert (size >= 0); - - struct error *tmp = xmalloc (sizeof *tmp); - tmp->message = xmalloc (size + 1); - - va_start (ap, message); - size = vsnprintf (tmp->message, size + 1, message, ap); - va_end (ap); - - hard_assert (size >= 0); - - soft_assert (*e == NULL); - *e = tmp; -} - -static void -error_free (struct error *e) -{ - free (e->message); - free (e); -} - -static void -error_propagate (struct error **destination, struct error *source) -{ - if (!destination) - { - error_free (source); - return; - } - - soft_assert (*destination == NULL); - *destination = source; -} - -// --- String hash map --------------------------------------------------------- - -// The most basic <string, managed pointer> map (or associative array). - -struct str_map_link -{ - LIST_HEADER (str_map_link) - - void *data; ///< Payload - size_t key_length; ///< Length of the key without '\0' - char key[]; ///< The key for this link -}; - -struct str_map -{ - struct str_map_link **map; ///< The hash table data itself - size_t alloc; ///< Number of allocated entries - size_t len; ///< Number of entries in the table - void (*free) (void *); ///< Callback to destruct the payload - - /// Callback that transforms all key values for storage and comparison; - /// has to behave exactly like strxfrm(). - size_t (*key_xfrm) (char *dest, const char *src, size_t n); -}; - -// As long as you don't remove the current entry, you can modify the map. -// Use `link' directly to access the data. - -struct str_map_iter -{ - struct str_map *map; ///< The map we're iterating - size_t next_index; ///< Next table index to search - struct str_map_link *link; ///< Current link -}; - -#define STR_MAP_MIN_ALLOC 16 - -typedef void (*str_map_free_func) (void *); - -static void -str_map_init (struct str_map *self) -{ - self->alloc = STR_MAP_MIN_ALLOC; - self->len = 0; - self->free = NULL; - self->key_xfrm = NULL; - self->map = xcalloc (self->alloc, sizeof *self->map); -} - -static void -str_map_free (struct str_map *self) -{ - struct str_map_link **iter, **end = self->map + self->alloc; - struct str_map_link *link, *tmp; - - for (iter = self->map; iter < end; iter++) - for (link = *iter; link; link = tmp) - { - tmp = link->next; - if (self->free) - self->free (link->data); - free (link); - } - - free (self->map); - self->map = NULL; -} - -static void -str_map_iter_init (struct str_map_iter *self, struct str_map *map) -{ - self->map = map; - self->next_index = 0; - self->link = NULL; -} - -static void * -str_map_iter_next (struct str_map_iter *self) -{ - struct str_map *map = self->map; - if (self->link) - self->link = self->link->next; - while (!self->link) - { - if (self->next_index >= map->alloc) - return NULL; - self->link = map->map[self->next_index++]; - } - return self->link->data; -} - -static uint64_t -str_map_hash (const char *s, size_t len) -{ - static unsigned char key[16] = "SipHash 2-4 key!"; - return siphash (key, (const void *) s, len); -} - -static uint64_t -str_map_pos (struct str_map *self, const char *s) -{ - size_t mask = self->alloc - 1; - return str_map_hash (s, strlen (s)) & mask; -} - -static uint64_t -str_map_link_hash (struct str_map_link *self) -{ - return str_map_hash (self->key, self->key_length); -} - -static void -str_map_resize (struct str_map *self, size_t new_size) -{ - struct str_map_link **old_map = self->map; - size_t i, old_size = self->alloc; - - // Only powers of two, so that we don't need to compute the modulo - hard_assert ((new_size & (new_size - 1)) == 0); - size_t mask = new_size - 1; - - self->alloc = new_size; - self->map = xcalloc (self->alloc, sizeof *self->map); - for (i = 0; i < old_size; i++) - { - struct str_map_link *iter = old_map[i], *next_iter; - while (iter) - { - next_iter = iter->next; - uint64_t pos = str_map_link_hash (iter) & mask; - LIST_PREPEND (self->map[pos], iter); - iter = next_iter; - } - } - - free (old_map); -} - -static void -str_map_set_real (struct str_map *self, const char *key, void *value) -{ - uint64_t pos = str_map_pos (self, key); - struct str_map_link *iter = self->map[pos]; - for (; iter; iter = iter->next) - { - if (strcmp (key, iter->key)) - continue; - - // Storing the same data doesn't destroy it - if (self->free && value != iter->data) - self->free (iter->data); - - if (value) - { - iter->data = value; - return; - } - - LIST_UNLINK (self->map[pos], iter); - free (iter); - self->len--; - - // The array should be at least 1/4 full - if (self->alloc >= (STR_MAP_MIN_ALLOC << 2) - && self->len < (self->alloc >> 2)) - str_map_resize (self, self->alloc >> 2); - return; - } - - if (!value) - return; - - if (self->len >= self->alloc) - { - str_map_resize (self, self->alloc << 1); - pos = str_map_pos (self, key); - } - - // Link in a new element for the given <key, value> pair - size_t key_length = strlen (key); - struct str_map_link *link = xmalloc (sizeof *link + key_length + 1); - link->data = value; - link->key_length = key_length; - memcpy (link->key, key, key_length + 1); - - LIST_PREPEND (self->map[pos], link); - self->len++; -} - -static void -str_map_set (struct str_map *self, const char *key, void *value) -{ - if (!self->key_xfrm) - { - str_map_set_real (self, key, value); - return; - } - char tmp[self->key_xfrm (NULL, key, 0) + 1]; - self->key_xfrm (tmp, key, sizeof tmp); - str_map_set_real (self, tmp, value); -} - -static void * -str_map_find_real (struct str_map *self, const char *key) -{ - struct str_map_link *iter = self->map[str_map_pos (self, key)]; - for (; iter; iter = iter->next) - if (!strcmp (key, (const char *) iter + sizeof *iter)) - return iter->data; - return NULL; -} - -static void * -str_map_find (struct str_map *self, const char *key) -{ - if (!self->key_xfrm) - return str_map_find_real (self, key); - - char tmp[self->key_xfrm (NULL, key, 0) + 1]; - self->key_xfrm (tmp, key, sizeof tmp); - return str_map_find_real (self, tmp); -} - -// --- File descriptor utilities ----------------------------------------------- - -static void -set_cloexec (int fd) -{ - soft_assert (fcntl (fd, F_SETFD, fcntl (fd, F_GETFD) | FD_CLOEXEC) != -1); -} - -static bool -set_blocking (int fd, bool blocking) -{ - int flags = fcntl (fd, F_GETFL); - hard_assert (flags != -1); - - bool prev = !(flags & O_NONBLOCK); - if (blocking) - flags &= ~O_NONBLOCK; - else - flags |= O_NONBLOCK; - - hard_assert (fcntl (fd, F_SETFL, flags) != -1); - return prev; -} - -static void -xclose (int fd) -{ - while (close (fd) == -1) - if (!soft_assert (errno == EINTR)) - break; -} - -// --- Polling ----------------------------------------------------------------- - -// Basically the poor man's GMainLoop/libev/libuv. It might make some sense -// to instead use those tested and proven libraries but we don't need much -// and it's interesting to implement. - -// At the moment the FD's are stored in an unsorted array. This is not ideal -// complexity-wise but I don't think I have much of a choice with poll(), -// and neither with epoll for that matter. -// -// unsorted array sorted array -// search O(n) O(log n) [O(log log n)] -// insert by fd O(n) O(n) -// delete by fd O(n) O(n) -// -// Insertion in the unsorted array can be reduced to O(1) if I maintain a -// bitmap of present FD's but that's still not a huge win. -// -// I don't expect this to be much of an issue, as there are typically not going -// to be that many FD's to watch, and the linear approach is cache-friendly. - -typedef void (*poller_dispatcher_func) (const struct pollfd *, void *); -typedef void (*poller_timer_func) (void *); - -#define POLLER_MIN_ALLOC 16 - -struct poller_timer_info -{ - int64_t when; ///< When is the timer to expire - poller_timer_func dispatcher; ///< Event dispatcher - void *user_data; ///< User data -}; - -struct poller_timers -{ - struct poller_timer_info *info; ///< Min-heap of timers - size_t len; ///< Number of scheduled timers - size_t alloc; ///< Number of timers allocated -}; - -static void -poller_timers_init (struct poller_timers *self) -{ - self->alloc = POLLER_MIN_ALLOC; - self->len = 0; - self->info = xmalloc (self->alloc * sizeof *self->info); -} - -static void -poller_timers_free (struct poller_timers *self) -{ - free (self->info); -} - -static int64_t -poller_timers_get_current_time (void) -{ -#ifdef _POSIX_TIMERS - struct timespec tp; - hard_assert (clock_gettime (CLOCK_BEST, &tp) != -1); - return (int64_t) tp.tv_sec * 1000 + (int64_t) tp.tv_nsec / 1000000; -#else - struct timeval tp; - gettimeofday (&tp, NULL); - return (int64_t) tp.tv_sec * 1000 + (int64_t) tp.tv_usec / 1000; -#endif -} - -static void -poller_timers_heapify_down (struct poller_timers *self, size_t index) -{ - typedef struct poller_timer_info info_t; - info_t *end = self->info + self->len; - - while (true) - { - info_t *parent = self->info + index; - info_t *left = self->info + 2 * index + 1; - info_t *right = self->info + 2 * index + 2; - - info_t *largest = parent; - if (left < end && left->when > largest->when) - largest = left; - if (right < end && right->when > largest->when) - largest = right; - if (parent == largest) - break; - - info_t tmp = *parent; - *parent = *largest; - *largest = tmp; - - index = largest - self->info; - } -} - -static void -poller_timers_remove_at_index (struct poller_timers *self, size_t index) -{ - hard_assert (index < self->len); - if (index == --self->len) - return; - - self->info[index] = self->info[self->len]; - poller_timers_heapify_down (self, index); -} - -static void -poller_timers_dispatch (struct poller_timers *self) -{ - int64_t now = poller_timers_get_current_time (); - while (self->len && self->info->when <= now) - { - struct poller_timer_info info = *self->info; - poller_timers_remove_at_index (self, 0); - info.dispatcher (info.user_data); - } -} - -static void -poller_timers_heapify_up (struct poller_timers *self, size_t index) -{ - while (index != 0) - { - size_t parent = (index - 1) / 2; - if (self->info[parent].when <= self->info[index].when) - break; - - struct poller_timer_info tmp = self->info[parent]; - self->info[parent] = self->info[index]; - self->info[index] = tmp; - - index = parent; - } -} - -static ssize_t -poller_timers_find (struct poller_timers *self, - poller_timer_func dispatcher, void *data) -{ - // NOTE: there may be duplicates. - for (size_t i = 0; i < self->len; i++) - if (self->info[i].dispatcher == dispatcher - && self->info[i].user_data == data) - return i; - return -1; -} - -static ssize_t -poller_timers_find_by_data (struct poller_timers *self, void *data) -{ - for (size_t i = 0; i < self->len; i++) - if (self->info[i].user_data == data) - return i; - return -1; -} - -static void -poller_timers_add (struct poller_timers *self, - poller_timer_func dispatcher, void *data, int timeout_ms) -{ - if (self->len == self->alloc) - self->info = xreallocarray (self->info, - self->alloc <<= 1, sizeof *self->info); - - self->info[self->len] = (struct poller_timer_info) { - .when = poller_timers_get_current_time () + timeout_ms, - .dispatcher = dispatcher, .user_data = data }; - poller_timers_heapify_up (self, self->len++); -} - -static int -poller_timers_get_poll_timeout (struct poller_timers *self) -{ - if (!self->len) - return -1; - - int64_t timeout = self->info->when - poller_timers_get_current_time (); - if (timeout <= 0) - return 0; - if (timeout > INT_MAX) - return INT_MAX; - return timeout; -} - -#ifdef __linux__ - -// I don't really need this, I've basically implemented this just because I can. - -#include <sys/epoll.h> - -struct poller_info -{ - int fd; ///< Our file descriptor - short events; ///< The poll() events we registered for - poller_dispatcher_func dispatcher; ///< Event dispatcher - void *user_data; ///< User data -}; - -struct poller -{ - int epoll_fd; ///< The epoll FD - struct poller_info **info; ///< Information associated with each FD - struct epoll_event *revents; ///< Output array for epoll_wait() - size_t len; ///< Number of polled descriptors - size_t alloc; ///< Number of entries allocated - - struct poller_timers timers; ///< Timeouts - - /// Index of the element in `revents' that's about to be dispatched next. - int dispatch_next; - - /// The total number of entries stored in `revents' by epoll_wait(). - int dispatch_total; -}; - -static void -poller_init (struct poller *self) -{ - self->epoll_fd = epoll_create (POLLER_MIN_ALLOC); - hard_assert (self->epoll_fd != -1); - set_cloexec (self->epoll_fd); - - self->len = 0; - self->alloc = POLLER_MIN_ALLOC; - self->info = xcalloc (self->alloc, sizeof *self->info); - self->revents = xcalloc (self->alloc, sizeof *self->revents); - - poller_timers_init (&self->timers); - - self->dispatch_next = 0; - self->dispatch_total = 0; -} - -static void -poller_free (struct poller *self) -{ - for (size_t i = 0; i < self->len; i++) - { - struct poller_info *info = self->info[i]; - hard_assert (epoll_ctl (self->epoll_fd, - EPOLL_CTL_DEL, info->fd, (void *) "") != -1); - free (info); - } - - poller_timers_free (&self->timers); - - xclose (self->epoll_fd); - free (self->info); - free (self->revents); -} - -static ssize_t -poller_find_by_fd (struct poller *self, int fd) -{ - for (size_t i = 0; i < self->len; i++) - if (self->info[i]->fd == fd) - return i; - return -1; -} - -static void -poller_ensure_space (struct poller *self) -{ - if (self->len < self->alloc) - return; - - self->alloc <<= 1; - hard_assert (self->alloc != 0); - - self->revents = xreallocarray - (self->revents, sizeof *self->revents, self->alloc); - self->info = xreallocarray - (self->info, sizeof *self->info, self->alloc); -} - -static short -poller_epoll_to_poll_events (uint32_t events) -{ - short result = 0; - if (events & EPOLLIN) result |= POLLIN; - if (events & EPOLLOUT) result |= POLLOUT; - if (events & EPOLLERR) result |= POLLERR; - if (events & EPOLLHUP) result |= POLLHUP; - if (events & EPOLLPRI) result |= POLLPRI; - return result; -} - -static uint32_t -poller_poll_to_epoll_events (short events) -{ - uint32_t result = 0; - if (events & POLLIN) result |= EPOLLIN; - if (events & POLLOUT) result |= EPOLLOUT; - if (events & POLLERR) result |= EPOLLERR; - if (events & POLLHUP) result |= EPOLLHUP; - if (events & POLLPRI) result |= EPOLLPRI; - return result; -} - -static void -poller_set (struct poller *self, int fd, short events, - poller_dispatcher_func dispatcher, void *data) -{ - ssize_t index = poller_find_by_fd (self, fd); - bool modifying = true; - if (index == -1) - { - poller_ensure_space (self); - self->info[index = self->len++] = xcalloc (1, sizeof **self->info); - modifying = false; - } - - struct poller_info *info = self->info[index]; - info->fd = fd; - info->events = events; - info->dispatcher = dispatcher; - info->user_data = data; - - struct epoll_event event; - event.events = poller_poll_to_epoll_events (events); - event.data.ptr = info; - hard_assert (epoll_ctl (self->epoll_fd, - modifying ? EPOLL_CTL_MOD : EPOLL_CTL_ADD, fd, &event) != -1); -} - -static void -poller_remove_from_dispatch (struct poller *self, - const struct poller_info *info) -{ - if (!self->dispatch_total) - return; - - int i; - for (i = self->dispatch_next; i < self->dispatch_total; i++) - if (self->revents[i].data.ptr == info) - break; - if (i == self->dispatch_total) - return; - - if (i != --self->dispatch_total) - self->revents[i] = self->revents[self->dispatch_total]; -} - -static void -poller_remove_at_index (struct poller *self, size_t index) -{ - hard_assert (index < self->len); - struct poller_info *info = self->info[index]; - - poller_remove_from_dispatch (self, info); - hard_assert (epoll_ctl (self->epoll_fd, - EPOLL_CTL_DEL, info->fd, (void *) "") != -1); - - free (info); - if (index != --self->len) - self->info[index] = self->info[self->len]; -} - -static void -poller_run (struct poller *self) -{ - // Not reentrant - hard_assert (!self->dispatch_total); - - int n_fds; - do - n_fds = epoll_wait (self->epoll_fd, self->revents, self->len, - poller_timers_get_poll_timeout (&self->timers)); - while (n_fds == -1 && errno == EINTR); - - if (n_fds == -1) - exit_fatal ("%s: %s", "epoll", strerror (errno)); - - poller_timers_dispatch (&self->timers); - - self->dispatch_next = 0; - self->dispatch_total = n_fds; - - while (self->dispatch_next < self->dispatch_total) - { - struct epoll_event *revents = self->revents + self->dispatch_next; - struct poller_info *info = revents->data.ptr; - - struct pollfd pfd; - pfd.fd = info->fd; - pfd.revents = poller_epoll_to_poll_events (revents->events); - pfd.events = info->events; - - self->dispatch_next++; - info->dispatcher (&pfd, info->user_data); - } - - self->dispatch_next = 0; - self->dispatch_total = 0; -} - -#else // !__linux__ - -struct poller_info -{ - poller_dispatcher_func dispatcher; ///< Event dispatcher - void *user_data; ///< User data -}; - -struct poller -{ - struct pollfd *fds; ///< Polled descriptors - struct poller_info *fds_info; ///< Additional information for each FD - size_t len; ///< Number of polled descriptors - size_t alloc; ///< Number of entries allocated - - struct poller_timers timers; ///< Timers - int dispatch_next; ///< The next dispatched FD or -1 -}; - -static void -poller_init (struct poller *self) -{ - self->alloc = POLLER_MIN_ALLOC; - self->len = 0; - self->fds = xcalloc (self->alloc, sizeof *self->fds); - self->fds_info = xcalloc (self->alloc, sizeof *self->fds_info); - poller_timers_init (&self->timers); - self->dispatch_next = -1; -} - -static void -poller_free (struct poller *self) -{ - free (self->fds); - free (self->fds_info); - poller_timers_free (&self->timers); -} - -static ssize_t -poller_find_by_fd (struct poller *self, int fd) -{ - for (size_t i = 0; i < self->len; i++) - if (self->fds[i].fd == fd) - return i; - return -1; -} - -static void -poller_ensure_space (struct poller *self) -{ - if (self->len < self->alloc) - return; - - self->alloc <<= 1; - self->fds = xreallocarray (self->fds, sizeof *self->fds, self->alloc); - self->fds_info = xreallocarray - (self->fds_info, sizeof *self->fds_info, self->alloc); -} - -static void -poller_set (struct poller *self, int fd, short events, - poller_dispatcher_func dispatcher, void *data) -{ - ssize_t index = poller_find_by_fd (self, fd); - if (index == -1) - { - poller_ensure_space (self); - index = self->len++; - } - - struct pollfd *new_entry = self->fds + index; - memset (new_entry, 0, sizeof *new_entry); - new_entry->fd = fd; - new_entry->events = events; - - self->fds_info[self->len] = (struct poller_info) { dispatcher, data }; -} - -static void -poller_remove_at_index (struct poller *self, size_t index) -{ - hard_assert (index < self->len); - if (index == --self->len) - return; - - // Make sure that we don't disrupt the dispatch loop; kind of crude - if ((int) index < self->dispatch_next) - { - memmove (self->fds + index, self->fds + index + 1, - (self->len - index) * sizeof *self->fds); - memmove (self->fds_info + index, self->fds_info + index + 1, - (self->len - index) * sizeof *self->fds_info); - self->dispatch_next--; - } - else - { - self->fds[index] = self->fds[self->len]; - self->fds_info[index] = self->fds_info[self->len]; - } -} - -static void -poller_run (struct poller *self) -{ - // Not reentrant - hard_assert (self->dispatch_next == -1); - - int result; - do - result = poll (self->fds, self->len, - poller_timers_get_poll_timeout (&self->timers)); - while (result == -1 && errno == EINTR); - - if (result == -1) - exit_fatal ("%s: %s", "poll", strerror (errno)); - - poller_timers_dispatch (&self->timers); - - for (int i = 0; i < (int) self->len; ) - { - struct pollfd pfd = self->fds[i]; - if (!pfd.revents) - continue; - - struct poller_info *info = self->fds_info + i; - self->dispatch_next = ++i; - info->dispatcher (&pfd, info->user_data); - i = self->dispatch_next; - } - - self->dispatch_next = -1; -} - -#endif // !__linux__ - -// --- Utilities --------------------------------------------------------------- - -static void -split_str_ignore_empty (const char *s, char delimiter, struct str_vector *out) -{ - const char *begin = s, *end; - - while ((end = strchr (begin, delimiter))) - { - if (begin != end) - str_vector_add_owned (out, xstrndup (begin, end - begin)); - begin = ++end; - } - - if (*begin) - str_vector_add (out, begin); -} - -static char * -strip_str_in_place (char *s, const char *stripped_chars) -{ - char *end = s + strlen (s); - while (end > s && strchr (stripped_chars, end[-1])) - *--end = '\0'; - - char *start = s + strspn (s, stripped_chars); - if (start > s) - memmove (s, start, end - start + 1); - return s; -} - -static char * -join_str_vector (const struct str_vector *v, char delimiter) -{ - if (!v->len) - return xstrdup (""); - - struct str result; - str_init (&result); - str_append (&result, v->vector[0]); - for (size_t i = 1; i < v->len; i++) - str_append_printf (&result, "%c%s", delimiter, v->vector[i]); - return str_steal (&result); -} - -static char *xstrdup_printf (const char *, ...) ATTRIBUTE_PRINTF (1, 2); - -static char * -xstrdup_printf (const char *format, ...) -{ - va_list ap; - struct str tmp; - str_init (&tmp); - va_start (ap, format); - str_append_vprintf (&tmp, format, ap); - va_end (ap); - return str_steal (&tmp); -} - -static bool -str_append_env_path (struct str *output, const char *var, bool only_absolute) -{ - const char *value = getenv (var); - - if (!value || (only_absolute && *value != '/')) - return false; - - str_append (output, value); - return true; -} - -static void -get_xdg_home_dir (struct str *output, const char *var, const char *def) -{ - str_reset (output); - if (!str_append_env_path (output, var, true)) - { - str_append_env_path (output, "HOME", false); - str_append_c (output, '/'); - str_append (output, def); - } -} - -static void -get_xdg_config_dirs (struct str_vector *out) -{ - struct str config_home; - str_init (&config_home); - get_xdg_home_dir (&config_home, "XDG_CONFIG_HOME", ".config"); - str_vector_add (out, config_home.str); - str_free (&config_home); - - const char *xdg_config_dirs; - if ((xdg_config_dirs = getenv ("XDG_CONFIG_DIRS"))) - split_str_ignore_empty (xdg_config_dirs, ':', out); -} - -static char * -resolve_config_filename (const char *filename) -{ - // Absolute path is absolute - if (*filename == '/') - return xstrdup (filename); - - struct str_vector paths; - str_vector_init (&paths); - get_xdg_config_dirs (&paths); - - struct str file; - str_init (&file); - - char *result = NULL; - for (unsigned i = 0; i < paths.len; i++) - { - // As per spec, relative paths are ignored - if (*paths.vector[i] != '/') - continue; - - str_reset (&file); - str_append_printf (&file, "%s/" PROGRAM_NAME "/%s", - paths.vector[i], filename); - - struct stat st; - if (!stat (file.str, &st)) - { - result = str_steal (&file); - break; - } - } - - str_vector_free (&paths); - str_free (&file); - return result; -} - -static bool -ensure_directory_existence (const char *path, struct error **e) -{ - struct stat st; - - if (stat (path, &st)) - { - if (mkdir (path, S_IRWXU | S_IRWXG | S_IRWXO)) - { - error_set (e, "cannot create directory `%s': %s", - path, strerror (errno)); - return false; - } - } - else if (!S_ISDIR (st.st_mode)) - { - error_set (e, "cannot create directory `%s': %s", - path, "file exists but is not a directory"); - return false; - } - return true; -} - -static bool -mkdir_with_parents (char *path, struct error **e) -{ - char *p = path; - - // XXX: This is prone to the TOCTTOU problem. The solution would be to - // rewrite the function using the {mkdir,fstat}at() functions from - // POSIX.1-2008, ideally returning a file descriptor to the open - // directory, with the current code as a fallback. Or to use chdir(). - while ((p = strchr (p + 1, '/'))) - { - *p = '\0'; - bool success = ensure_directory_existence (path, e); - *p = '/'; - - if (!success) - return false; - } - - return ensure_directory_existence (path, e); -} - -static bool -set_boolean_if_valid (bool *out, const char *s) -{ - if (!strcasecmp (s, "yes")) *out = true; - else if (!strcasecmp (s, "no")) *out = false; - else if (!strcasecmp (s, "on")) *out = true; - else if (!strcasecmp (s, "off")) *out = false; - else if (!strcasecmp (s, "true")) *out = true; - else if (!strcasecmp (s, "false")) *out = false; - else return false; - - return true; -} - -static bool -xstrtoul (unsigned long *out, const char *s, int base) -{ - char *end; - errno = 0; - *out = strtoul (s, &end, base); - return errno == 0 && !*end && end != s; -} - -static bool -read_line (FILE *fp, struct str *s) -{ - int c; - bool at_end = true; - - str_reset (s); - while ((c = fgetc (fp)) != EOF) - { - at_end = false; - if (c == '\r') - continue; - if (c == '\n') - break; - str_append_c (s, c); - } - - return !at_end; -} - -#define XSSL_ERROR_TRY_AGAIN INT_MAX - -/// A small wrapper around SSL_get_error() to simplify further handling -static int -xssl_get_error (SSL *ssl, int result, const char **error_info) -{ - int error = SSL_get_error (ssl, result); - switch (error) - { - case SSL_ERROR_NONE: - case SSL_ERROR_ZERO_RETURN: - case SSL_ERROR_WANT_READ: - case SSL_ERROR_WANT_WRITE: - return error; - case SSL_ERROR_SYSCALL: - if ((error = ERR_get_error ())) - *error_info = ERR_error_string (error, NULL); - else if (result == 0) - // An EOF that's not according to the protocol is still an EOF - return SSL_ERROR_ZERO_RETURN; - else - { - if (errno == EINTR) - return XSSL_ERROR_TRY_AGAIN; - *error_info = strerror (errno); - } - return SSL_ERROR_SSL; - default: - if ((error = ERR_get_error ())) - *error_info = ERR_error_string (error, NULL); - else - *error_info = "Unknown error"; - return SSL_ERROR_SSL; - } -} - -// --- Regular expressions ----------------------------------------------------- - -static regex_t * -regex_compile (const char *regex, int flags, struct error **e) -{ - regex_t *re = xmalloc (sizeof *re); - int err = regcomp (re, regex, flags); - if (!err) - return re; - - char buf[regerror (err, re, NULL, 0)]; - regerror (err, re, buf, sizeof buf); - - free (re); - error_set (e, "%s: %s", "failed to compile regular expression", buf); - return NULL; -} - -static void -regex_free (void *regex) -{ - regfree (regex); - free (regex); -} - -// The cost of hashing a string is likely to be significantly smaller than that -// of compiling the whole regular expression anew, so here is a simple cache. -// Adding basic support for subgroups is easy: check `re_nsub' and output into -// a `struct str_vector' (if all we want is the substrings). - -static void -regex_cache_init (struct str_map *cache) -{ - str_map_init (cache); - cache->free = regex_free; -} - -static bool -regex_cache_match (struct str_map *cache, const char *regex, int flags, - const char *s, struct error **e) -{ - regex_t *re = str_map_find (cache, regex); - if (!re) - { - re = regex_compile (regex, flags, e); - if (!re) - return false; - str_map_set (cache, regex, re); - } - return regexec (re, s, 0, NULL, 0) != REG_NOMATCH; -} - -// --- IRC utilities ----------------------------------------------------------- - -struct irc_message -{ - struct str_map tags; ///< IRC 3.2 message tags - char *prefix; ///< Message prefix - char *command; ///< IRC command - struct str_vector params; ///< Command parameters -}; - -static void -irc_parse_message_tags (const char *tags, struct str_map *out) -{ - struct str_vector v; - str_vector_init (&v); - split_str_ignore_empty (tags, ';', &v); - - for (size_t i = 0; i < v.len; i++) - { - char *key = v.vector[i], *equal_sign = strchr (key, '='); - if (equal_sign) - { - *equal_sign = '\0'; - str_map_set (out, key, xstrdup (equal_sign + 1)); - } - else - str_map_set (out, key, xstrdup ("")); - } - - str_vector_free (&v); -} - -static void -irc_parse_message (struct irc_message *msg, const char *line) -{ - str_map_init (&msg->tags); - msg->tags.free = free; - - msg->prefix = NULL; - msg->command = NULL; - str_vector_init (&msg->params); - - // IRC 3.2 message tags - if (*line == '@') - { - size_t tags_len = strcspn (++line, " "); - char *tags = xstrndup (line, tags_len); - irc_parse_message_tags (tags, &msg->tags); - free (tags); - - line += tags_len; - while (*line == ' ') - line++; - } - - // Prefix - if (*line == ':') - { - size_t prefix_len = strcspn (++line, " "); - msg->prefix = xstrndup (line, prefix_len); - line += prefix_len; - } - - // Command name - { - while (*line == ' ') - line++; - - size_t cmd_len = strcspn (line, " "); - msg->command = xstrndup (line, cmd_len); - line += cmd_len; - } - - // Arguments - while (true) - { - while (*line == ' ') - line++; - - if (*line == ':') - { - str_vector_add (&msg->params, ++line); - break; - } - - size_t param_len = strcspn (line, " "); - if (!param_len) - break; - - str_vector_add_owned (&msg->params, xstrndup (line, param_len)); - line += param_len; - } -} - -static void -irc_free_message (struct irc_message *msg) -{ - str_map_free (&msg->tags); - free (msg->prefix); - free (msg->command); - str_vector_free (&msg->params); -} - -static void -irc_process_buffer (struct str *buf, - void (*callback)(const struct irc_message *, const char *, void *), - void *user_data) -{ - char *start = buf->str, *end = start + buf->len; - for (char *p = start; p + 1 < end; p++) - { - // Split the input on newlines - if (p[0] != '\r' || p[1] != '\n') - continue; - - *p = 0; - - struct irc_message msg; - irc_parse_message (&msg, start); - callback (&msg, start, user_data); - irc_free_message (&msg); - - start = p + 2; - } - - // XXX: we might want to just advance some kind of an offset to avoid - // moving memory around unnecessarily. - str_remove_slice (buf, 0, start - buf->str); -} - -static int -irc_tolower (int c) -{ - if (c == '[') return '{'; - if (c == ']') return '}'; - if (c == '\\') return '|'; - if (c == '~') return '^'; - return c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c; -} - -static size_t -irc_strxfrm (char *dest, const char *src, size_t n) -{ - size_t len = strlen (src); - while (n-- && (*dest++ = irc_tolower (*src++))) - ; - return len; -} - -static int -irc_strcmp (const char *a, const char *b) -{ - int x; - while (*a || *b) - if ((x = irc_tolower (*a++) - irc_tolower (*b++))) - return x; - return 0; -} - -static int -irc_fnmatch (const char *pattern, const char *string) -{ - size_t pattern_size = strlen (pattern) + 1; - size_t string_size = strlen (string) + 1; - char x_pattern[pattern_size], x_string[string_size]; - irc_strxfrm (x_pattern, pattern, pattern_size); - irc_strxfrm (x_string, string, string_size); - return fnmatch (x_pattern, x_string, 0); -} - -// --- Configuration ----------------------------------------------------------- - -// The keys are stripped of surrounding whitespace, the values are not. - -struct config_item -{ - const char *key; - const char *default_value; - const char *description; -}; - -static void -load_config_defaults (struct str_map *config, const struct config_item *table) -{ - for (; table->key != NULL; table++) - if (table->default_value) - str_map_set (config, table->key, xstrdup (table->default_value)); - else - str_map_set (config, table->key, NULL); -} - -static bool -read_config_file (struct str_map *config, struct error **e) -{ - char *filename = resolve_config_filename (PROGRAM_NAME ".conf"); - if (!filename) - return true; - - FILE *fp = fopen (filename, "r"); - if (!fp) - { - error_set (e, "could not open `%s' for reading: %s", - filename, strerror (errno)); - return false; - } - - struct str line; - str_init (&line); - - bool errors = false; - for (unsigned line_no = 1; read_line (fp, &line); line_no++) - { - char *start = line.str; - if (*start == '#') - continue; - - while (isspace (*start)) - start++; - - char *end = strchr (start, '='); - if (end) - { - char *value = end + 1; - do - *end = '\0'; - while (isspace (*--end)); - - str_map_set (config, start, xstrdup (value)); - } - else if (*start) - { - error_set (e, "line %u in config: %s", line_no, "malformed input"); - errors = true; - break; - } - } - - str_free (&line); - fclose (fp); - return !errors; -} - -static char * -write_default_config (const char *filename, const char *prolog, - const struct config_item *table, struct error **e) -{ - struct str path, base; - - str_init (&path); - str_init (&base); - - if (filename) - { - char *tmp = xstrdup (filename); - str_append (&path, dirname (tmp)); - strcpy (tmp, filename); - str_append (&base, basename (tmp)); - free (tmp); - } - else - { - get_xdg_home_dir (&path, "XDG_CONFIG_HOME", ".config"); - str_append (&path, "/" PROGRAM_NAME); - str_append (&base, PROGRAM_NAME ".conf"); - } - - if (!mkdir_with_parents (path.str, e)) - goto error; - - str_append_c (&path, '/'); - str_append_str (&path, &base); - - FILE *fp = fopen (path.str, "w"); - if (!fp) - { - error_set (e, "could not open `%s' for writing: %s", - path.str, strerror (errno)); - goto error; - } - - if (prolog) - fputs (prolog, fp); - - errno = 0; - for (; table->key != NULL; table++) - { - fprintf (fp, "# %s\n", table->description); - if (table->default_value) - fprintf (fp, "%s=%s\n", table->key, table->default_value); - else - fprintf (fp, "#%s=\n", table->key); - } - fclose (fp); - if (errno) - { - error_set (e, "writing to `%s' failed: %s", path.str, strerror (errno)); - goto error; - } - - str_free (&base); - return str_steal (&path); - -error: - str_free (&base); - str_free (&path); - return NULL; - -} - -static void -call_write_default_config (const char *hint, const struct config_item *table) -{ - static const char *prolog = - "# " PROGRAM_NAME " " PROGRAM_VERSION " configuration file\n" - "#\n" - "# Relative paths are searched for in ${XDG_CONFIG_HOME:-~/.config}\n" - "# /" PROGRAM_NAME " as well as in $XDG_CONFIG_DIRS/" PROGRAM_NAME "\n" - "\n"; - - struct error *e = NULL; - char *filename = write_default_config (hint, prolog, table, &e); - if (!filename) - { - print_error ("%s", e->message); - error_free (e); - exit (EXIT_FAILURE); - } - print_status ("configuration written to `%s'", filename); - free (filename); -} diff --git a/src/kike.c b/src/kike.c deleted file mode 100644 index f3c4f17..0000000 --- a/src/kike.c +++ /dev/null @@ -1,3251 +0,0 @@ -/* - * kike.c: the experimental IRC daemon - * - * Copyright (c) 2014, Přemysl Janouch <p.janouch@gmail.com> - * All rights reserved. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - */ - -#define PROGRAM_NAME "kike" -#define PROGRAM_VERSION "alpha" - -#include "common.c" -#include <nl_types.h> - -// --- Configuration (application-specific) ------------------------------------ - -static struct config_item g_config_table[] = -{ - { "server_name", NULL, "Server name" }, - { "server_info", "My server", "Brief server description" }, - { "motd", NULL, "MOTD filename" }, - { "catalog", NULL, "catgets localization catalog" }, - - { "bind_host", NULL, "Address of the IRC server" }, - { "bind_port", "6667", "Port of the IRC server" }, - { "ssl_cert", NULL, "Server SSL certificate (PEM)" }, - { "ssl_key", NULL, "Server SSL private key (PEM)" }, - - { "operators", NULL, "IRCop SSL cert. fingerprints" }, - - { "max_connections", "0", "Global connection limit" }, - { "ping_interval", "180", "Interval between PING's (sec)" }, - { NULL, NULL, NULL } -}; - -// --- Signals ----------------------------------------------------------------- - -static int g_signal_pipe[2]; ///< A pipe used to signal... signals - -/// Program termination has been requested by a signal -static volatile sig_atomic_t g_termination_requested; - -static void -sigterm_handler (int signum) -{ - (void) signum; - - g_termination_requested = true; - - int original_errno = errno; - if (write (g_signal_pipe[1], "t", 1) == -1) - soft_assert (errno == EAGAIN); - errno = original_errno; -} - -static void -setup_signal_handlers (void) -{ - if (pipe (g_signal_pipe) == -1) - exit_fatal ("%s: %s", "pipe", strerror (errno)); - - set_cloexec (g_signal_pipe[0]); - set_cloexec (g_signal_pipe[1]); - - // So that the pipe cannot overflow; it would make write() block within - // the signal handler, which is something we really don't want to happen. - // The same holds true for read(). - set_blocking (g_signal_pipe[0], false); - set_blocking (g_signal_pipe[1], false); - - signal (SIGPIPE, SIG_IGN); - - struct sigaction sa; - sa.sa_flags = SA_RESTART; - sigemptyset (&sa.sa_mask); - sa.sa_handler = sigterm_handler; - if (sigaction (SIGINT, &sa, NULL) == -1 - || sigaction (SIGTERM, &sa, NULL) == -1) - exit_fatal ("%s: %s", "sigaction", strerror (errno)); -} - -// --- IRC token validation ---------------------------------------------------- - -// Use the enum only if applicable and a simple boolean isn't sufficient. - -enum validation_result -{ - VALIDATION_OK, - VALIDATION_ERROR_EMPTY, - VALIDATION_ERROR_TOO_LONG, - VALIDATION_ERROR_INVALID -}; - -// Everything as per RFC 2812 -#define IRC_MAX_NICKNAME 9 -#define IRC_MAX_HOSTNAME 63 -#define IRC_MAX_CHANNEL_NAME 50 -#define IRC_MAX_MESSAGE_LENGTH 510 - -static bool -irc_regex_match (const char *regex, const char *s) -{ - static struct str_map cache; - static bool initialized; - - if (!initialized) - { - regex_cache_init (&cache); - initialized = true; - } - - struct error *e = NULL; - bool result = regex_cache_match (&cache, regex, - REG_EXTENDED | REG_NOSUB, s, &e); - hard_assert (!e); - return result; -} - -static const char * -irc_validate_to_str (enum validation_result result) -{ - switch (result) - { - case VALIDATION_OK: return "success"; - case VALIDATION_ERROR_EMPTY: return "the value is empty"; - case VALIDATION_ERROR_INVALID: return "invalid format"; - case VALIDATION_ERROR_TOO_LONG: return "the value is too long"; - default: abort (); - } -} - -// Anything to keep it as short as possible -#define SN "[0-9A-Za-z][-0-9A-Za-z]*[0-9A-Za-z]*" -#define N4 "[0-9]{1,3}" -#define N6 "[0-9ABCDEFabcdef]{1,}" - -#define LE "A-Za-z" -#define SP "][\\\\`_^{|}" - -static enum validation_result -irc_validate_hostname (const char *hostname) -{ - if (!*hostname) - return VALIDATION_ERROR_EMPTY; - if (!irc_regex_match ("^" SN "(\\." SN ")*$", hostname)) - return VALIDATION_ERROR_INVALID; - if (strlen (hostname) > IRC_MAX_HOSTNAME) - return VALIDATION_ERROR_TOO_LONG; - return VALIDATION_OK; -} - -static bool -irc_is_valid_hostaddr (const char *hostaddr) -{ - if (irc_regex_match ("^" N4 "\\." N4 "\\." N4 "\\." N4 "$", hostaddr) - || irc_regex_match ("^" N6 ":" N6 ":" N6 ":" N6 ":" - N6 ":" N6 ":" N6 ":" N6 "$", hostaddr) - || irc_regex_match ("^0:0:0:0:0:(0|[Ff]{4}):" - N4 "\\." N4 "\\." N4 "\\." N4 "$", hostaddr)) - return true; - return false; -} - -static bool -irc_is_valid_host (const char *host) -{ - return irc_validate_hostname (host) == VALIDATION_OK - || irc_is_valid_hostaddr (host); -} - -static bool -irc_is_valid_user (const char *user) -{ - return irc_regex_match ("^[^\r\n @]+$", user); -} - -static bool -irc_validate_nickname (const char *nickname) -{ - if (!*nickname) - return VALIDATION_ERROR_EMPTY; - if (!irc_regex_match ("^[" SP LE "][" SP LE "0-9-]*$", nickname)) - return VALIDATION_ERROR_INVALID; - if (strlen (nickname) > IRC_MAX_NICKNAME) - return VALIDATION_ERROR_TOO_LONG; - return VALIDATION_OK; -} - -static enum validation_result -irc_validate_channel_name (const char *channel_name) -{ - if (!*channel_name) - return VALIDATION_ERROR_EMPTY; - if (*channel_name != '#' || strpbrk (channel_name, "\7\r\n ,:")) - return VALIDATION_ERROR_INVALID; - if (strlen (channel_name) > IRC_MAX_CHANNEL_NAME) - return VALIDATION_ERROR_TOO_LONG; - return VALIDATION_OK; -} - -static bool -irc_is_valid_key (const char *key) -{ - // XXX: should be 7-bit as well but whatever - return irc_regex_match ("^[^\r\n\f\t\v ]{1,23}$", key); -} - -#undef SN -#undef N4 -#undef N6 - -#undef LE -#undef SP - -static bool -irc_is_valid_user_mask (const char *mask) -{ - return irc_regex_match ("^[^!@]+![^!@]+@[^@!]+$", mask); -} - -static bool -irc_is_valid_fingerprint (const char *fp) -{ - return irc_regex_match ("^[a-fA-F0-9]{2}(:[a-fA-F0-9]{2}){19}$", fp); -} - -// --- Clients (equals users) -------------------------------------------------- - -#define IRC_SUPPORTED_USER_MODES "aiwros" - -enum -{ - IRC_USER_MODE_INVISIBLE = (1 << 0), - IRC_USER_MODE_RX_WALLOPS = (1 << 1), - IRC_USER_MODE_RESTRICTED = (1 << 2), - IRC_USER_MODE_OPERATOR = (1 << 3), - IRC_USER_MODE_RX_SERVER_NOTICES = (1 << 4) -}; - -struct client -{ - LIST_HEADER (client) - struct server_context *ctx; ///< Server context - - int socket_fd; ///< The TCP socket - struct str read_buffer; ///< Unprocessed input - struct str write_buffer; ///< Output yet to be sent out - - bool initialized; ///< Has any data been received yet? - bool registered; ///< The user has registered - bool closing_link; ///< Closing link - - bool ssl_rx_want_tx; ///< SSL_read() wants to write - bool ssl_tx_want_rx; ///< SSL_write() wants to read - SSL *ssl; ///< SSL connection - char *ssl_cert_fingerprint; ///< Client certificate fingerprint - - char *nickname; ///< IRC nickname (main identifier) - char *username; ///< IRC username - char *realname; ///< IRC realname (e-mail) - - char *hostname; ///< Hostname shown to the network - - unsigned mode; ///< User's mode - char *away_message; ///< Away message - time_t last_active; ///< Last PRIVMSG, to get idle time -}; - -static void -client_init (struct client *self) -{ - memset (self, 0, sizeof *self); - - self->socket_fd = -1; - str_init (&self->read_buffer); - str_init (&self->write_buffer); -} - -static void -client_free (struct client *self) -{ - if (!soft_assert (self->socket_fd == -1)) - xclose (self->socket_fd); - if (self->ssl) - SSL_free (self->ssl); - - str_free (&self->read_buffer); - str_free (&self->write_buffer); - - free (self->nickname); - free (self->username); - free (self->realname); - - free (self->hostname); - free (self->away_message); -} - -static void client_close_link (struct client *, const char *); -static void client_send (struct client *, const char *, ...) - ATTRIBUTE_PRINTF (2, 3); -static void client_cancel_timers (struct client *); -static void client_set_kill_timer (struct client *); -static void client_update_poller (struct client *, const struct pollfd *); - -// --- Channels ---------------------------------------------------------------- - -#define IRC_SUPPORTED_CHAN_MODES "ov" "beI" "imnqpst" "kl" - -enum -{ - IRC_CHAN_MODE_INVITE_ONLY = (1 << 0), - IRC_CHAN_MODE_MODERATED = (1 << 1), - IRC_CHAN_MODE_NO_OUTSIDE_MSGS = (1 << 2), - IRC_CHAN_MODE_QUIET = (1 << 3), - IRC_CHAN_MODE_PRIVATE = (1 << 4), - IRC_CHAN_MODE_SECRET = (1 << 5), - IRC_CHAN_MODE_PROTECTED_TOPIC = (1 << 6), - - IRC_CHAN_MODE_OPERATOR = (1 << 7), - IRC_CHAN_MODE_VOICE = (1 << 8) -}; - -struct channel_user -{ - LIST_HEADER (channel_user) - - unsigned modes; - struct client *c; -}; - -struct channel -{ - struct server_context *ctx; ///< Server context - - char *name; ///< Channel name - unsigned modes; ///< Channel modes - char *key; ///< Channel key - long user_limit; ///< User limit or -1 - - char *topic; ///< Channel topic - - struct channel_user *users; ///< Channel users - - struct str_vector ban_list; ///< Ban list - struct str_vector exception_list; ///< Exceptions from bans - struct str_vector invite_list; ///< Exceptions from +I -}; - -static struct channel * -channel_new (void) -{ - struct channel *self = xcalloc (1, sizeof *self); - - self->user_limit = -1; - self->topic = xstrdup (""); - - str_vector_init (&self->ban_list); - str_vector_init (&self->exception_list); - str_vector_init (&self->invite_list); - return self; -} - -static void -channel_delete (struct channel *self) -{ - free (self->name); - free (self->key); - free (self->topic); - - struct channel_user *link, *tmp; - for (link = self->users; link; link = tmp) - { - tmp = link->next; - free (link); - } - - str_vector_free (&self->ban_list); - str_vector_free (&self->exception_list); - str_vector_free (&self->invite_list); - - free (self); -} - -static char * -channel_get_mode (struct channel *self, bool disclose_secrets) -{ - struct str mode; - str_init (&mode); - - unsigned m = self->modes; - if (m & IRC_CHAN_MODE_INVITE_ONLY) str_append_c (&mode, 'i'); - if (m & IRC_CHAN_MODE_MODERATED) str_append_c (&mode, 'm'); - if (m & IRC_CHAN_MODE_NO_OUTSIDE_MSGS) str_append_c (&mode, 'n'); - if (m & IRC_CHAN_MODE_QUIET) str_append_c (&mode, 'q'); - if (m & IRC_CHAN_MODE_PRIVATE) str_append_c (&mode, 'p'); - if (m & IRC_CHAN_MODE_SECRET) str_append_c (&mode, 's'); - if (m & IRC_CHAN_MODE_PROTECTED_TOPIC) str_append_c (&mode, 't'); - - if (self->user_limit != -1) str_append_c (&mode, 'l'); - if (self->key) str_append_c (&mode, 'k'); - - // XXX: is it correct to split it? Try it on an existing implementation. - if (disclose_secrets) - { - if (self->user_limit != -1) - str_append_printf (&mode, " %ld", self->user_limit); - if (self->key) - str_append_printf (&mode, " %s", self->key); - } - return str_steal (&mode); -} - -static struct channel_user * -channel_get_user (const struct channel *chan, const struct client *c) -{ - for (struct channel_user *iter = chan->users; iter; iter = iter->next) - if (iter->c == c) - return iter; - return NULL; -} - -static struct channel_user * -channel_add_user (struct channel *chan, struct client *c) -{ - struct channel_user *link = xcalloc (1, sizeof *link); - link->c = c; - LIST_PREPEND (chan->users, link); - return link; -} - -static void -channel_remove_user (struct channel *chan, struct channel_user *user) -{ - LIST_UNLINK (chan->users, user); - free (user); -} - -static size_t -channel_user_count (const struct channel *chan) -{ - size_t result = 0; - for (struct channel_user *iter = chan->users; iter; iter = iter->next) - result++; - return result; -} - -// --- IRC server context ------------------------------------------------------ - -struct server_context -{ - int listen_fds[1]; ///< Listening socket FD's - size_t n_listen_fds; ///< Number of listening sockets - - struct client *clients; ///< Clients - SSL_CTX *ssl_ctx; ///< SSL context - unsigned n_clients; ///< Current number of connections - - struct str_map users; ///< Maps nicknames to clients - struct str_map channels; ///< Maps channel names to data - struct str_map handlers; ///< Message handlers - - struct poller poller; ///< Manages polled description - bool quitting; ///< User requested quitting - bool polling; ///< The event loop is running - - struct str_map config; ///< Server configuration - char *server_name; ///< Our server name - unsigned ping_interval; ///< Ping interval in seconds - unsigned max_connections; ///< Max. connections allowed or 0 - struct str_vector motd; ///< MOTD (none if empty) - nl_catd catalog; ///< Message catalog for server msgs - struct str_map operators; ///< SSL cert. fingerprints for IRCops -}; - -static void -server_context_init (struct server_context *self) -{ - self->n_listen_fds = 0; - self->clients = NULL; - self->n_clients = 0; - - str_map_init (&self->users); - self->users.key_xfrm = irc_strxfrm; - str_map_init (&self->channels); - self->channels.key_xfrm = irc_strxfrm; - self->channels.free = (void (*) (void *)) channel_delete; - str_map_init (&self->handlers); - self->handlers.key_xfrm = irc_strxfrm; - - poller_init (&self->poller); - self->quitting = false; - self->polling = false; - - str_map_init (&self->config); - self->config.free = free; - load_config_defaults (&self->config, g_config_table); - - self->server_name = NULL; - self->ping_interval = 0; - self->max_connections = 0; - str_vector_init (&self->motd); - self->catalog = (nl_catd) -1; - str_map_init (&self->operators); - // The regular irc_strxfrm() is sufficient for fingerprints - self->operators.key_xfrm = irc_strxfrm; -} - -static void -server_context_free (struct server_context *self) -{ - str_map_free (&self->config); - - for (size_t i = 0; i < self->n_listen_fds; i++) - xclose (self->listen_fds[i]); - if (self->ssl_ctx) - SSL_CTX_free (self->ssl_ctx); - - struct client *link, *tmp; - for (link = self->clients; link; link = tmp) - { - tmp = link->next; - client_free (link); - free (link); - } - - free (self->server_name); - str_map_free (&self->users); - str_map_free (&self->channels); - str_map_free (&self->handlers); - poller_free (&self->poller); - - str_vector_free (&self->motd); - if (self->catalog != (nl_catd) -1) - catclose (self->catalog); - str_map_free (&self->operators); -} - -static const char * -irc_get_text (struct server_context *ctx, int id, const char *def) -{ - if (!soft_assert (def != NULL)) - def = ""; - if (ctx->catalog == (nl_catd) -1) - return def; - return catgets (ctx->catalog, 1, id, def); -} - -static void -irc_try_finish_quit (struct server_context *ctx) -{ - if (!ctx->n_clients && ctx->quitting) - ctx->polling = false; -} - -static void -irc_initiate_quit (struct server_context *ctx) -{ - print_status ("shutting down"); - - for (struct client *iter = ctx->clients; iter; iter = iter->next) - if (!iter->closing_link) - client_close_link (iter, "Shutting down"); - - for (size_t i = 0; i < ctx->n_listen_fds; i++) - { - ssize_t index = poller_find_by_fd (&ctx->poller, ctx->listen_fds[i]); - if (soft_assert (index != -1)) - poller_remove_at_index (&ctx->poller, index); - xclose (ctx->listen_fds[i]); - } - ctx->n_listen_fds = 0; - - ctx->quitting = true; - irc_try_finish_quit (ctx); -} - -static struct channel * -irc_channel_create (struct server_context *ctx, const char *name) -{ - struct channel *chan = channel_new (); - chan->ctx = ctx; - chan->name = xstrdup (name); - str_map_set (&ctx->channels, name, chan); - return chan; -} - -static void -irc_channel_destroy_if_empty (struct server_context *ctx, struct channel *chan) -{ - if (!chan->users) - str_map_set (&ctx->channels, chan->name, NULL); -} - -static void -irc_send_to_roommates (struct client *c, const char *message) -{ - struct str_map targets; - str_map_init (&targets); - targets.key_xfrm = irc_strxfrm; - - struct str_map_iter iter; - str_map_iter_init (&iter, &c->ctx->channels); - struct channel *chan; - while ((chan = str_map_iter_next (&iter))) - { - if (chan->modes & IRC_CHAN_MODE_QUIET - || !channel_get_user (chan, c)) - continue; - - // When we're unregistering, the str_map_find() will return zero, - // which will prevent sending the QUIT message to ourselves. - for (struct channel_user *iter = chan->users; iter; iter = iter->next) - str_map_set (&targets, iter->c->nickname, - str_map_find (&c->ctx->users, iter->c->nickname)); - } - - str_map_iter_init (&iter, &targets); - struct client *target; - while ((target = str_map_iter_next (&iter))) - client_send (target, "%s", message); -} - -// --- Clients (continued) ----------------------------------------------------- - -static void -client_mode_to_str (unsigned m, struct str *out) -{ - if (m & IRC_USER_MODE_INVISIBLE) str_append_c (out, 'i'); - if (m & IRC_USER_MODE_RX_WALLOPS) str_append_c (out, 'w'); - if (m & IRC_USER_MODE_RESTRICTED) str_append_c (out, 'r'); - if (m & IRC_USER_MODE_OPERATOR) str_append_c (out, 'o'); - if (m & IRC_USER_MODE_RX_SERVER_NOTICES) str_append_c (out, 's'); -} - -static char * -client_get_mode (struct client *self) -{ - struct str mode; - str_init (&mode); - if (self->away_message) - str_append_c (&mode, 'a'); - client_mode_to_str (self->mode, &mode); - return str_steal (&mode); -} - -static void -client_send_str (struct client *c, const struct str *s) -{ - hard_assert (c->initialized && !c->closing_link); - - // TODO: kill the connection above some "SendQ" threshold (careful!) - str_append_data (&c->write_buffer, s->str, - s->len > IRC_MAX_MESSAGE_LENGTH ? IRC_MAX_MESSAGE_LENGTH : s->len); - str_append (&c->write_buffer, "\r\n"); - // XXX: we might want to move this elsewhere, so that it doesn't get called - // as often; it's going to cause a lot of syscalls with epoll. - client_update_poller (c, NULL); -} - -static void -client_send (struct client *c, const char *format, ...) -{ - struct str tmp; - str_init (&tmp); - - va_list ap; - va_start (ap, format); - str_append_vprintf (&tmp, format, ap); - va_end (ap); - - client_send_str (c, &tmp); - str_free (&tmp); -} - -static void -client_unregister (struct client *c, const char *reason) -{ - if (!c->registered) - return; - - // Make the user effectively non-existent - str_map_set (&c->ctx->users, c->nickname, NULL); - - char *message = xstrdup_printf (":%s!%s@%s QUIT :%s", - c->nickname, c->username, c->hostname, reason); - irc_send_to_roommates (c, message); - free (message); - - struct str_map_iter iter; - str_map_iter_init (&iter, &c->ctx->channels); - struct channel *chan, *next = str_map_iter_next (&iter); - for (chan = next; chan; chan = next) - { - next = str_map_iter_next (&iter); - struct channel_user *user; - if (!(user = channel_get_user (chan, c))) - continue; - channel_remove_user (chan, user); - irc_channel_destroy_if_empty (c->ctx, chan); - } - - free (c->nickname); - c->nickname = NULL; - c->registered = false; -} - -static void -client_kill (struct client *c, const char *reason) -{ - client_unregister (c, reason ? reason : "Client exited"); - - struct server_context *ctx = c->ctx; - ssize_t i = poller_find_by_fd (&ctx->poller, c->socket_fd); - if (i != -1) - poller_remove_at_index (&ctx->poller, i); - client_cancel_timers (c); - - if (c->ssl) - (void) SSL_shutdown (c->ssl); - xclose (c->socket_fd); - c->socket_fd = -1; - client_free (c); - LIST_UNLINK (ctx->clients, c); - ctx->n_clients--; - free (c); - - irc_try_finish_quit (ctx); -} - -static void -client_close_link (struct client *c, const char *reason) -{ - if (!soft_assert (!c->closing_link)) - return; - - // We push an `ERROR' message to the write buffer and let the poller send - // it, with some arbitrary timeout. The `closing_link' state makes sure - // that a/ we ignore any successive messages, and b/ that the connection - // is killed after the write buffer is transferred and emptied. - client_send (c, "ERROR :Closing Link: %s[%s] (%s)", c->nickname, - c->hostname /* TODO host IP? */, reason); - c->closing_link = true; - - client_unregister (c, reason); - client_set_kill_timer (c); -} - -static bool -client_in_mask_list (const struct client *c, const struct str_vector *mask) -{ - char *client = xstrdup_printf ("%s!%s@%s", - c->nickname, c->username, c->hostname); - bool result = false; - for (size_t i = 0; i < mask->len; i++) - if (!irc_fnmatch (mask->vector[i], client)) - { - result = true; - break; - } - free (client); - return result; -} - -static char * -client_get_ssl_cert_fingerprint (struct client *c) -{ - if (!c->ssl) - return NULL; - - X509 *peer_cert = SSL_get_peer_certificate (c->ssl); - if (!peer_cert) - return NULL; - - int cert_len = i2d_X509 (peer_cert, NULL); - if (cert_len < 0) - return NULL; - - unsigned char cert[cert_len], *p = cert; - if (i2d_X509 (peer_cert, &p) < 0) - return NULL; - - unsigned char hash[SHA_DIGEST_LENGTH]; - SHA1 (cert, cert_len, hash); - - struct str fingerprint; - str_init (&fingerprint); - str_append_printf (&fingerprint, "%02X", hash[0]); - for (size_t i = 1; i < sizeof hash; i++) - str_append_printf (&fingerprint, ":%02X", hash[i]); - return str_steal (&fingerprint); -} - -// --- Timers ------------------------------------------------------------------ - -static void -client_cancel_timers (struct client *c) -{ - ssize_t i; - struct poller_timers *timers = &c->ctx->poller.timers; - while ((i = poller_timers_find_by_data (timers, c)) != -1) - poller_timers_remove_at_index (timers, i); -} - -static void -client_set_timer (struct client *c, poller_timer_func fn, unsigned interval) -{ - client_cancel_timers (c); - poller_timers_add (&c->ctx->poller.timers, fn, c, interval * 1000); -} - -static void -on_client_kill_timer (void *user_data) -{ - struct client *c = user_data; - hard_assert (!c->initialized || c->closing_link); - client_kill (c, NULL); -} - -static void -client_set_kill_timer (struct client *c) -{ - client_set_timer (c, on_client_kill_timer, c->ctx->ping_interval); -} - -static void -on_client_timeout_timer (void *user_data) -{ - struct client *c = user_data; - char *reason = xstrdup_printf - ("Ping timeout: >%u seconds", c->ctx->ping_interval); - client_close_link (c, reason); - free (reason); -} - -static void -on_client_ping_timer (void *user_data) -{ - struct client *c = user_data; - hard_assert (!c->closing_link); - client_send (c, "PING :%s", c->ctx->server_name); - client_set_timer (c, on_client_timeout_timer, c->ctx->ping_interval); -} - -static void -client_set_ping_timer (struct client *c) -{ - client_set_timer (c, on_client_ping_timer, c->ctx->ping_interval); -} - -// --- IRC command handling ---------------------------------------------------- - -enum -{ - IRC_RPL_WELCOME = 1, - IRC_RPL_YOURHOST = 2, - IRC_RPL_CREATED = 3, - IRC_RPL_MYINFO = 4, - - IRC_RPL_UMODEIS = 221, - IRC_RPL_LUSERCLIENT = 251, - IRC_RPL_LUSEROP = 252, - IRC_RPL_LUSERUNKNOWN = 253, - IRC_RPL_LUSERCHANNELS = 254, - IRC_RPL_LUSERME = 255, - - IRC_RPL_AWAY = 301, - IRC_RPL_USERHOST = 302, - IRC_RPL_ISON = 303, - IRC_RPL_UNAWAY = 305, - IRC_RPL_NOWAWAY = 306, - IRC_RPL_WHOISUSER = 311, - IRC_RPL_WHOISSERVER = 312, - IRC_RPL_WHOISOPERATOR = 313, - IRC_RPL_ENDOFWHO = 315, - IRC_RPL_WHOISIDLE = 317, - IRC_RPL_ENDOFWHOIS = 318, - IRC_RPL_WHOISCHANNELS = 319, - IRC_RPL_LIST = 322, - IRC_RPL_LISTEND = 323, - IRC_RPL_CHANNELMODEIS = 324, - IRC_RPL_NOTOPIC = 331, - IRC_RPL_TOPIC = 332, - IRC_RPL_INVITELIST = 346, - IRC_RPL_ENDOFINVITELIST = 347, - IRC_RPL_EXCEPTLIST = 348, - IRC_RPL_ENDOFEXCEPTLIST = 349, - IRC_RPL_VERSION = 351, - IRC_RPL_WHOREPLY = 352, - IRC_RPL_NAMREPLY = 353, - IRC_RPL_ENDOFNAMES = 366, - IRC_RPL_BANLIST = 367, - IRC_RPL_ENDOFBANLIST = 368, - IRC_RPL_MOTD = 372, - IRC_RPL_MOTDSTART = 375, - IRC_RPL_ENDOFMOTD = 376, - IRC_RPL_TIME = 391, - - IRC_ERR_NOSUCHNICK = 401, - IRC_ERR_NOSUCHSERVER = 402, - IRC_ERR_NOSUCHCHANNEL = 403, - IRC_ERR_CANNOTSENDTOCHAN = 404, - IRC_ERR_NOORIGIN = 409, - IRC_ERR_NORECIPIENT = 411, - IRC_ERR_NOTEXTTOSEND = 412, - IRC_ERR_UNKNOWNCOMMAND = 421, - IRC_ERR_NOMOTD = 422, - IRC_ERR_NOADMININFO = 423, - IRC_ERR_NONICKNAMEGIVEN = 431, - IRC_ERR_ERRONEOUSNICKNAME = 432, - IRC_ERR_NICKNAMEINUSE = 433, - IRC_ERR_USERNOTINCHANNEL = 441, - IRC_ERR_NOTONCHANNEL = 442, - IRC_ERR_SUMMONDISABLED = 445, - IRC_ERR_USERSDISABLED = 446, - IRC_ERR_NOTREGISTERED = 451, - IRC_ERR_NEEDMOREPARAMS = 461, - IRC_ERR_ALREADYREGISTERED = 462, - IRC_ERR_KEYSET = 467, - IRC_ERR_CHANNELISFULL = 471, - IRC_ERR_UNKNOWNMODE = 472, - IRC_ERR_INVITEONLYCHAN = 473, - IRC_ERR_BANNEDFROMCHAN = 474, - IRC_ERR_BADCHANNELKEY = 475, - IRC_ERR_BADCHANMASK = 476, - IRC_ERR_NOPRIVILEGES = 481, - IRC_ERR_CHANOPRIVSNEEDED = 482, - - IRC_ERR_UMODEUNKNOWNFLAG = 501, - IRC_ERR_USERSDONTMATCH = 502 -}; - -static const char *g_default_replies[] = -{ - [IRC_RPL_WELCOME] = ":Welcome to the Internet Relay Network %s!%s@%s", - [IRC_RPL_YOURHOST] = ":Your host is %s, running version %s", - [IRC_RPL_CREATED] = ":This server was created %s", - [IRC_RPL_MYINFO] = "%s %s %s %s", - - [IRC_RPL_UMODEIS] = "+%s", - [IRC_RPL_LUSERCLIENT] = ":There are %d users and %d services on %d servers", - [IRC_RPL_LUSEROP] = "%d :operator(s) online", - [IRC_RPL_LUSERUNKNOWN] = "%d :unknown connection(s)", - [IRC_RPL_LUSERCHANNELS] = "%d :channels formed", - [IRC_RPL_LUSERME] = ":I have %d clients and %d servers", - - [IRC_RPL_AWAY] = "%s :%s", - [IRC_RPL_USERHOST] = ":%s", - [IRC_RPL_ISON] = ":%s", - [IRC_RPL_UNAWAY] = ":You are no longer marked as being away", - [IRC_RPL_NOWAWAY] = ":You have been marked as being away", - [IRC_RPL_WHOISUSER] = "%s %s %s * :%s", - [IRC_RPL_WHOISSERVER] = "%s %s :%s", - [IRC_RPL_WHOISOPERATOR] = "%s :is an IRC operator", - [IRC_RPL_ENDOFWHO] = "%s :End of WHO list", - [IRC_RPL_WHOISIDLE] = "%s %d :seconds idle", - [IRC_RPL_ENDOFWHOIS] = "%s :End of WHOIS list", - [IRC_RPL_WHOISCHANNELS] = "%s :%s", - [IRC_RPL_LIST] = "%s %d :%s", - [IRC_RPL_LISTEND] = ":End of LIST", - [IRC_RPL_CHANNELMODEIS] = "%s +%s", - [IRC_RPL_NOTOPIC] = "%s :No topic is set", - [IRC_RPL_TOPIC] = "%s :%s", - [IRC_RPL_INVITELIST] = "%s %s", - [IRC_RPL_ENDOFINVITELIST] = "%s :End of channel invite list", - [IRC_RPL_EXCEPTLIST] = "%s %s", - [IRC_RPL_ENDOFEXCEPTLIST] = "%s :End of channel exception list", - [IRC_RPL_VERSION] = "%s.%d %s :%s", - [IRC_RPL_WHOREPLY] = "%s %s %s %s %s %s :%d %s", - [IRC_RPL_NAMREPLY] = "%c %s :%s", - [IRC_RPL_ENDOFNAMES] = "%s :End of NAMES list", - [IRC_RPL_BANLIST] = "%s %s", - [IRC_RPL_ENDOFBANLIST] = "%s :End of channel ban list", - [IRC_RPL_MOTD] = ":- %s", - [IRC_RPL_MOTDSTART] = ":- %s Message of the day - ", - [IRC_RPL_ENDOFMOTD] = ":End of MOTD command", - [IRC_RPL_TIME] = "%s :%s", - - [IRC_ERR_NOSUCHNICK] = "%s :No such nick/channel", - [IRC_ERR_NOSUCHSERVER] = "%s :No such server", - [IRC_ERR_NOSUCHCHANNEL] = "%s :No such channel", - [IRC_ERR_CANNOTSENDTOCHAN] = "%s :Cannot send to channel", - [IRC_ERR_NOORIGIN] = ":No origin specified", - [IRC_ERR_NORECIPIENT] = ":No recipient given (%s)", - [IRC_ERR_NOTEXTTOSEND] = ":No text to send", - [IRC_ERR_UNKNOWNCOMMAND] = "%s: Unknown command", - [IRC_ERR_NOMOTD] = ":MOTD File is missing", - [IRC_ERR_NOADMININFO] = "%s :No administrative info available", - [IRC_ERR_NONICKNAMEGIVEN] = ":No nickname given", - [IRC_ERR_ERRONEOUSNICKNAME] = "%s :Erroneous nickname", - [IRC_ERR_NICKNAMEINUSE] = "%s :Nickname is already in use", - [IRC_ERR_USERNOTINCHANNEL] = "%s %s :They aren't on that channel", - [IRC_ERR_NOTONCHANNEL] = "%s :You're not on that channel", - [IRC_ERR_SUMMONDISABLED] = ":SUMMON has been disabled", - [IRC_ERR_USERSDISABLED] = ":USERS has been disabled", - [IRC_ERR_NOTREGISTERED] = ":You have not registered", - [IRC_ERR_NEEDMOREPARAMS] = "%s :Not enough parameters", - [IRC_ERR_ALREADYREGISTERED] = ":Unauthorized command (already registered)", - [IRC_ERR_KEYSET] = "%s :Channel key already set", - [IRC_ERR_CHANNELISFULL] = "%s :Cannot join channel (+l)", - [IRC_ERR_UNKNOWNMODE] = "%c :is unknown mode char to me for %s", - [IRC_ERR_INVITEONLYCHAN] = "%s :Cannot join channel (+i)", - [IRC_ERR_BANNEDFROMCHAN] = "%s :Cannot join channel (+b)", - [IRC_ERR_BADCHANNELKEY] = "%s :Cannot join channel (+k)", - [IRC_ERR_BADCHANMASK] = "%s :Bad Channel Mask", - [IRC_ERR_NOPRIVILEGES] = ":Permission Denied- You're not an IRC operator", - [IRC_ERR_CHANOPRIVSNEEDED] = "%s :You're not channel operator", - - [IRC_ERR_UMODEUNKNOWNFLAG] = ":Unknown MODE flag", - [IRC_ERR_USERSDONTMATCH] = ":Cannot change mode for other users", -}; - -// XXX: this way we cannot typecheck the arguments, so we must be careful -static void -irc_send_reply (struct client *c, int id, ...) -{ - struct str tmp; - str_init (&tmp); - - va_list ap; - va_start (ap, id); - str_append_printf (&tmp, ":%s %03d %s ", - c->ctx->server_name, id, c->nickname ? c->nickname : ""); - str_append_vprintf (&tmp, - irc_get_text (c->ctx, id, g_default_replies[id]), ap); - va_end (ap); - - client_send_str (c, &tmp); - str_free (&tmp); -} - -#define RETURN_WITH_REPLY(c, ...) \ - BLOCK_START \ - irc_send_reply ((c), __VA_ARGS__); \ - return; \ - BLOCK_END - -static void -irc_send_motd (struct client *c) -{ - struct server_context *ctx = c->ctx; - if (!ctx->motd.len) - RETURN_WITH_REPLY (c, IRC_ERR_NOMOTD); - - irc_send_reply (c, IRC_RPL_MOTDSTART, ctx->server_name); - for (size_t i = 0; i < ctx->motd.len; i++) - irc_send_reply (c, IRC_RPL_MOTD, ctx->motd.vector[i]); - irc_send_reply (c, IRC_RPL_ENDOFMOTD); -} - -static void -irc_send_lusers (struct client *c) -{ - int n_users = 0, n_services = 0, n_opers = 0, n_unknown = 0; - for (struct client *link = c->ctx->clients; link; link = link->next) - { - if (link->registered) - n_users++; - else - n_unknown++; - if (link->mode & IRC_USER_MODE_OPERATOR) - n_opers++; - } - - int n_channels = 0; - struct str_map_iter iter; - str_map_iter_init (&iter, &c->ctx->channels); - struct channel *chan; - while ((chan = str_map_iter_next (&iter))) - if (!(chan->modes & IRC_CHAN_MODE_SECRET) - || channel_get_user (chan, c)) - n_channels++; - - irc_send_reply (c, IRC_RPL_LUSERCLIENT, - n_users, n_services, 1 /* servers total */); - if (n_opers) - irc_send_reply (c, IRC_RPL_LUSEROP, n_opers); - if (n_unknown) - irc_send_reply (c, IRC_RPL_LUSERUNKNOWN, n_unknown); - if (n_channels) - irc_send_reply (c, IRC_RPL_LUSERCHANNELS, n_channels); - irc_send_reply (c, IRC_RPL_LUSERME, - n_users + n_services + n_unknown, 0 /* peer servers */); -} - -static bool -irc_is_this_me (struct server_context *ctx, const char *target) -{ - // Target servers can also be matched by their users - return !irc_fnmatch (target, ctx->server_name) - || str_map_find (&ctx->users, target); -} - -static void -irc_try_finish_registration (struct client *c) -{ - struct server_context *ctx = c->ctx; - if (!c->nickname || !c->username || !c->realname) - return; - - c->registered = true; - irc_send_reply (c, IRC_RPL_WELCOME, c->nickname, c->username, c->hostname); - - irc_send_reply (c, IRC_RPL_YOURHOST, ctx->server_name, PROGRAM_VERSION); - // The purpose of this message eludes me - irc_send_reply (c, IRC_RPL_CREATED, __DATE__); - irc_send_reply (c, IRC_RPL_MYINFO, ctx->server_name, PROGRAM_VERSION, - IRC_SUPPORTED_USER_MODES, IRC_SUPPORTED_CHAN_MODES); - - irc_send_lusers (c); - irc_send_motd (c); - - char *mode = client_get_mode (c); - if (*mode) - client_send (c, ":%s MODE %s :+%s", c->nickname, c->nickname, mode); - free (mode); - - hard_assert (c->ssl_cert_fingerprint == NULL); - if ((c->ssl_cert_fingerprint = client_get_ssl_cert_fingerprint (c))) - client_send (c, ":%s NOTICE %s :" - "Your SSL client certificate fingerprint is %s", - ctx->server_name, c->nickname, c->ssl_cert_fingerprint); -} - -static void -irc_handle_pass (const struct irc_message *msg, struct client *c) -{ - if (c->registered) - irc_send_reply (c, IRC_ERR_ALREADYREGISTERED); - else if (msg->params.len < 1) - irc_send_reply (c, IRC_ERR_NEEDMOREPARAMS, msg->command); - - // We have SSL client certificates for this purpose; ignoring -} - -static void -irc_handle_nick (const struct irc_message *msg, struct client *c) -{ - struct server_context *ctx = c->ctx; - - if (msg->params.len < 1) - RETURN_WITH_REPLY (c, IRC_ERR_NONICKNAMEGIVEN); - - const char *nickname = msg->params.vector[0]; - if (irc_validate_nickname (nickname) != VALIDATION_OK) - RETURN_WITH_REPLY (c, IRC_ERR_ERRONEOUSNICKNAME, nickname); - - struct client *client = str_map_find (&ctx->users, nickname); - if (client && client != c) - RETURN_WITH_REPLY (c, IRC_ERR_NICKNAMEINUSE, nickname); - - if (c->registered) - { - char *message = xstrdup_printf (":%s!%s@%s NICK :%s", - c->nickname, c->username, c->hostname, nickname); - irc_send_to_roommates (c, message); - free (message); - } - - // Release the old nickname and allocate a new one - if (c->nickname) - { - str_map_set (&ctx->users, c->nickname, NULL); - free (c->nickname); - } - c->nickname = xstrdup (nickname); - str_map_set (&ctx->users, nickname, c); - - if (!c->registered) - irc_try_finish_registration (c); -} - -static void -irc_handle_user (const struct irc_message *msg, struct client *c) -{ - if (c->registered) - RETURN_WITH_REPLY (c, IRC_ERR_ALREADYREGISTERED); - if (msg->params.len < 4) - RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command); - - const char *username = msg->params.vector[0]; - const char *mode = msg->params.vector[1]; - const char *realname = msg->params.vector[3]; - - // Unfortunately the protocol doesn't give us any means of rejecting it - if (!irc_is_valid_user (username)) - username = "xxx"; - - free (c->username); - c->username = xstrdup (username); - free (c->realname); - c->realname = xstrdup (realname); - - unsigned long m; - if (xstrtoul (&m, mode, 10)) - { - if (m & 4) c->mode |= IRC_USER_MODE_RX_WALLOPS; - if (m & 8) c->mode |= IRC_USER_MODE_INVISIBLE; - } - - irc_try_finish_registration (c); -} - -static void -irc_handle_userhost (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len < 1) - RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command); - - struct str reply; - str_init (&reply); - for (size_t i = 0; i < 5 && i < msg->params.len; i++) - { - const char *nick = msg->params.vector[i]; - struct client *target = str_map_find (&c->ctx->users, nick); - if (!target) - continue; - - if (i) - str_append_c (&reply, ' '); - str_append (&reply, nick); - if (target->mode & IRC_USER_MODE_OPERATOR) - str_append_c (&reply, '*'); - str_append_printf (&reply, "=%c%s@%s", - target->away_message ? '-' : '+', - target->username, target->hostname); - } - irc_send_reply (c, IRC_RPL_USERHOST, reply.str); - str_free (&reply); -} - -static void -irc_handle_lusers (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1])) - irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]); - else - irc_send_lusers (c); -} - -static void -irc_handle_motd (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0])) - irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]); - else - irc_send_motd (c); -} - -static void -irc_handle_ping (const struct irc_message *msg, struct client *c) -{ - // XXX: the RFC is pretty incomprehensible about the exact usage - if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1])) - irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]); - else if (msg->params.len < 1) - irc_send_reply (c, IRC_ERR_NOORIGIN); - else - client_send (c, ":%s PONG :%s", - c->ctx->server_name, msg->params.vector[0]); -} - -static void -irc_handle_pong (const struct irc_message *msg, struct client *c) -{ - // We are the only server, so we don't have to care too much - if (msg->params.len < 1) - irc_send_reply (c, IRC_ERR_NOORIGIN); - else - // Set a new timer to send another PING - client_set_ping_timer (c); -} - -static void -irc_handle_quit (const struct irc_message *msg, struct client *c) -{ - char *reason = xstrdup_printf ("Quit: %s", - msg->params.len > 0 ? msg->params.vector[0] : c->nickname); - client_close_link (c, reason); - free (reason); -} - -static void -irc_handle_time (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0])) - RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]); - - char buf[32]; - time_t now = time (NULL); - struct tm tm; - strftime (buf, sizeof buf, "%a %b %d %Y %T", localtime_r (&now, &tm)); - irc_send_reply (c, IRC_RPL_TIME, c->ctx->server_name, buf); -} - -static void -irc_handle_version (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0])) - irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]); - else - irc_send_reply (c, IRC_RPL_VERSION, PROGRAM_VERSION, g_debug_mode, - c->ctx->server_name, PROGRAM_NAME " " PROGRAM_VERSION); -} - -static void -irc_channel_multicast (struct channel *chan, const char *message, - struct client *except) -{ - for (struct channel_user *iter = chan->users; iter; iter = iter->next) - { - if (iter->c != except) - client_send (iter->c, "%s", message); - } -} - -static bool -irc_modify_mode (unsigned *mask, unsigned mode, bool add) -{ - unsigned orig = *mask; - if (add) - *mask |= mode; - else - *mask &= ~mode; - return *mask != orig; -} - -static void -irc_update_user_mode (struct client *c, unsigned new_mode) -{ - unsigned old_mode = c->mode; - c->mode = new_mode; - - unsigned added = new_mode & ~old_mode; - unsigned removed = old_mode & ~new_mode; - - struct str diff; - str_init (&diff); - - if (added) - { - str_append_c (&diff, '+'); - client_mode_to_str (added, &diff); - } - if (removed) - { - str_append_c (&diff, '-'); - client_mode_to_str (removed, &diff); - } - - if (diff.len) - client_send (c, ":%s MODE %s :%s", - c->nickname, c->nickname, diff.str); - str_free (&diff); -} - -static void -irc_handle_user_mode_change (struct client *c, const char *mode_string) -{ - unsigned new_mode = c->mode; - bool adding = true; - - while (*mode_string) - switch (*mode_string++) - { - case '+': adding = true; break; - case '-': adding = false; break; - - case 'a': - // Ignore, the client should use AWAY - break; - case 'i': - irc_modify_mode (&new_mode, IRC_USER_MODE_INVISIBLE, adding); - break; - case 'w': - irc_modify_mode (&new_mode, IRC_USER_MODE_RX_WALLOPS, adding); - break; - case 'r': - // It's not possible to un-restrict yourself - if (adding) - new_mode |= IRC_USER_MODE_RESTRICTED; - break; - case 'o': - if (!adding) - new_mode &= ~IRC_USER_MODE_OPERATOR; - else if (c->ssl_cert_fingerprint - && str_map_find (&c->ctx->operators, c->ssl_cert_fingerprint)) - new_mode |= IRC_USER_MODE_OPERATOR; - else - client_send (c, ":%s NOTICE %s :Either you're not using an SSL" - " client certificate, or the fingerprint doesn't match", - c->ctx->server_name, c->nickname); - break; - case 's': - irc_modify_mode (&new_mode, IRC_USER_MODE_RX_SERVER_NOTICES, adding); - break; - default: - RETURN_WITH_REPLY (c, IRC_ERR_UMODEUNKNOWNFLAG); - } - irc_update_user_mode (c, new_mode); -} - -static void -irc_send_channel_list (struct client *c, const char *channel_name, - const struct str_vector *list, int reply, int end_reply) -{ - for (size_t i = 0; i < list->len; i++) - irc_send_reply (c, reply, channel_name, list->vector[i]); - irc_send_reply (c, end_reply); -} - -static char * -irc_check_expand_user_mask (const char *mask) -{ - struct str result; - str_init (&result); - str_append (&result, mask); - - // Make sure it is a complete mask - if (!strchr (result.str, '!')) - str_append (&result, "!*"); - if (!strchr (result.str, '@')) - str_append (&result, "@*"); - - // And validate whatever the result is - if (!irc_is_valid_user_mask (result.str)) - { - str_free (&result); - return NULL; - } - return str_steal (&result); -} - -static void -irc_handle_chan_mode_change (struct client *c, - struct channel *chan, char *params[]) -{ - struct channel_user *user = channel_get_user (chan, c); - - // This is by far the worst command to implement from the whole RFC; - // don't blame me if it doesn't work exactly as expected. - - struct str added; struct str_vector added_params; - struct str removed; struct str_vector removed_params; - - str_init (&added); str_vector_init (&added_params); - str_init (&removed); str_vector_init (&removed_params); - -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TODO: try to convert this madness into functions; that will most - // likely require creating a special parser class -#define NEEDS_OPER \ - if (!user || (!(user->modes & IRC_CHAN_MODE_OPERATOR) \ - && !(c->mode & IRC_USER_MODE_OPERATOR))) \ - { \ - irc_send_reply (c, IRC_ERR_CHANOPRIVSNEEDED, chan->name); \ - continue; \ - } - -#define HANDLE_USER(mode) \ - if (!(target = *params)) \ - continue; \ - params++; \ - NEEDS_OPER \ - if (!(client = str_map_find (&c->ctx->users, target))) \ - irc_send_reply (c, IRC_ERR_NOSUCHNICK, target); \ - else if (!(target_user = channel_get_user (chan, client))) \ - irc_send_reply (c, IRC_ERR_USERNOTINCHANNEL, \ - target, chan->name); \ - else if (irc_modify_mode (&target_user->modes, (mode), adding)) \ - { \ - str_append_c (output, mode_char); \ - str_vector_add (output_params, client->nickname); \ - } - -#define HANDLE_LIST(list, list_msg, end_msg) \ -{ \ - if (!(target = *params)) \ - { \ - if (adding) \ - irc_send_channel_list (c, chan->name, list, list_msg, end_msg); \ - continue; \ - } \ - params++; \ - NEEDS_OPER \ - char *mask = irc_check_expand_user_mask (target); \ - if (!mask) \ - continue; \ - size_t i; \ - for (i = 0; i < (list)->len; i++) \ - if (!irc_strcmp ((list)->vector[i], mask)) \ - break; \ - if (!((i != (list)->len) ^ adding)) \ - { \ - free (mask); \ - continue; \ - } \ - if (adding) \ - str_vector_add ((list), mask); \ - else \ - str_vector_remove ((list), i); \ - str_append_c (output, mode_char); \ - str_vector_add (output_params, mask); \ - free (mask); \ -} - -#define HANDLE_MODE(mode) \ - NEEDS_OPER \ - if (irc_modify_mode (&chan->modes, (mode), adding)) \ - str_append_c (output, mode_char); - -#define REMOVE_MODE(removed_mode, removed_char) \ - if (adding && irc_modify_mode (&chan->modes, (removed_mode), false)) \ - str_append_c (&removed, (removed_char)); - -// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - const char *mode_string; - while ((mode_string = *params++)) - { - bool adding = true; - struct str *output = &added; - struct str_vector *output_params = &added_params; - - const char *target; - struct channel_user *target_user; - struct client *client; - - char mode_char; - while (*mode_string) - switch ((mode_char = *mode_string++)) - { - case '+': - adding = true; - output = &added; - output_params = &added_params; - break; - case '-': - adding = false; - output = &removed; - output_params = &removed_params; - break; - - case 'o': HANDLE_USER (IRC_CHAN_MODE_OPERATOR) break; - case 'v': HANDLE_USER (IRC_CHAN_MODE_VOICE) break; - - case 'i': HANDLE_MODE (IRC_CHAN_MODE_INVITE_ONLY) break; - case 'm': HANDLE_MODE (IRC_CHAN_MODE_MODERATED) break; - case 'n': HANDLE_MODE (IRC_CHAN_MODE_NO_OUTSIDE_MSGS) break; - case 'q': HANDLE_MODE (IRC_CHAN_MODE_QUIET) break; - case 't': HANDLE_MODE (IRC_CHAN_MODE_PROTECTED_TOPIC) break; - - case 'p': - HANDLE_MODE (IRC_CHAN_MODE_PRIVATE) - REMOVE_MODE (IRC_CHAN_MODE_SECRET, 's') - break; - case 's': - HANDLE_MODE (IRC_CHAN_MODE_SECRET) - REMOVE_MODE (IRC_CHAN_MODE_PRIVATE, 'p') - break; - - case 'b': - HANDLE_LIST (&chan->ban_list, - IRC_RPL_BANLIST, IRC_RPL_ENDOFBANLIST) - break; - case 'e': - HANDLE_LIST (&chan->exception_list, - IRC_RPL_EXCEPTLIST, IRC_RPL_ENDOFEXCEPTLIST) - break; - case 'I': - HANDLE_LIST (&chan->invite_list, - IRC_RPL_INVITELIST, IRC_RPL_ENDOFINVITELIST) - break; - - case 'k': - NEEDS_OPER - if (!adding) - { - if (!(target = *params)) - continue; - params++; - if (!chan->key || irc_strcmp (target, chan->key)) - continue; - - str_append_c (&removed, mode_char); - str_vector_add (&removed_params, chan->key); - free (chan->key); - chan->key = NULL; - } - else if (!(target = *params)) - continue; - else - { - params++; - if (chan->key) - irc_send_reply (c, IRC_ERR_KEYSET, chan->name); - else - { - chan->key = xstrdup (target); - str_append_c (&added, mode_char); - str_vector_add (&added_params, chan->key); - } - } - break; - case 'l': - NEEDS_OPER - if (!adding) - { - if (chan->user_limit == -1) - continue; - - chan->user_limit = -1; - str_append_c (&removed, mode_char); - } - else if (!(target = *params)) - continue; - else - { - params++; - unsigned long x; - if (xstrtoul (&x, target, 10) && x > 0 && x <= LONG_MAX) - { - chan->user_limit = x; - str_append_c (&added, mode_char); - str_vector_add (&added_params, target); - } - } - break; - - default: - RETURN_WITH_REPLY (c, IRC_ERR_UNKNOWNMODE); - } - } - -#undef NEEDS_OPER -#undef HANDLE_USER -#undef HANDLE_LIST -#undef HANDLE_MODE -#undef REMOVE_MODE - - if (added.len || removed.len) - { - struct str message; - str_init (&message); - str_append_printf (&message, ":%s!%s@%s MODE %s ", - c->nickname, c->username, c->hostname, chan->name); - if (added.len) - str_append_printf (&message, "+%s", added.str); - if (removed.len) - str_append_printf (&message, "-%s", removed.str); - for (size_t i = 0; i < added_params.len; i++) - str_append_printf (&message, " %s", added_params.vector[i]); - for (size_t i = 0; i < removed_params.len; i++) - str_append_printf (&message, " %s", removed_params.vector[i]); - irc_channel_multicast (chan, message.str, NULL); - str_free (&message); - } - - str_free (&added); str_vector_free (&added_params); - str_free (&removed); str_vector_free (&removed_params); -} - -static void -irc_handle_mode (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len < 1) - RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command); - - const char *target = msg->params.vector[0]; - struct client *client = str_map_find (&c->ctx->users, target); - if (client) - { - if (irc_strcmp (target, c->nickname)) - RETURN_WITH_REPLY (c, IRC_ERR_USERSDONTMATCH); - - if (msg->params.len < 2) - { - char *mode = client_get_mode (client); - irc_send_reply (c, IRC_RPL_UMODEIS, mode); - free (mode); - } - else - irc_handle_user_mode_change (c, msg->params.vector[1]); - return; - } - - struct channel *chan = str_map_find (&c->ctx->channels, target); - if (chan) - { - if (msg->params.len < 2) - { - char *mode = channel_get_mode (chan, channel_get_user (chan, c)); - irc_send_reply (c, IRC_RPL_CHANNELMODEIS, target, mode); - free (mode); - } - else - irc_handle_chan_mode_change (c, chan, &msg->params.vector[1]); - return; - } - - irc_send_reply (c, IRC_ERR_NOSUCHNICK, target); -} - -static void -irc_handle_user_message (const struct irc_message *msg, struct client *c, - const char *command, bool allow_away_reply) -{ - if (msg->params.len < 1) - RETURN_WITH_REPLY (c, IRC_ERR_NORECIPIENT, msg->command); - if (msg->params.len < 2 || !*msg->params.vector[1]) - RETURN_WITH_REPLY (c, IRC_ERR_NOTEXTTOSEND); - - const char *target = msg->params.vector[0]; - const char *text = msg->params.vector[1]; - struct client *client = str_map_find (&c->ctx->users, target); - if (client) - { - client_send (client, ":%s!%s@%s %s %s :%s", - c->nickname, c->username, c->hostname, command, target, text); - if (allow_away_reply && client->away_message) - irc_send_reply (c, IRC_RPL_AWAY, target, client->away_message); - return; - } - - struct channel *chan = str_map_find (&c->ctx->channels, target); - if (chan) - { - struct channel_user *user = channel_get_user (chan, c); - if ((chan->modes & IRC_CHAN_MODE_NO_OUTSIDE_MSGS) && !user) - RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target); - if ((chan->modes & IRC_CHAN_MODE_MODERATED) && (!user || - !(user->modes & (IRC_CHAN_MODE_VOICE | IRC_CHAN_MODE_OPERATOR)))) - RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target); - if (client_in_mask_list (c, &chan->ban_list) - && !client_in_mask_list (c, &chan->exception_list)) - RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target); - - char *message = xstrdup_printf (":%s!%s@%s %s %s :%s", - c->nickname, c->username, c->hostname, command, target, text); - irc_channel_multicast (chan, message, c); - free (message); - return; - } - - irc_send_reply (c, IRC_ERR_NOSUCHNICK, target); -} - -static void -irc_handle_privmsg (const struct irc_message *msg, struct client *c) -{ - irc_handle_user_message (msg, c, "PRIVMSG", true); - // Let's not care too much about success or failure - c->last_active = time (NULL); -} - -static void -irc_handle_notice (const struct irc_message *msg, struct client *c) -{ - irc_handle_user_message (msg, c, "NOTICE", false); -} - -static void -irc_send_rpl_list (struct client *c, const struct channel *chan) -{ - int visible = 0; - for (struct channel_user *user = chan->users; - user; user = user->next) - visible++; - - irc_send_reply (c, IRC_RPL_LIST, chan->name, visible, chan->topic); -} - -static void -irc_handle_list (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1])) - RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]); - - struct channel *chan; - if (msg->params.len == 0) - { - struct str_map_iter iter; - str_map_iter_init (&iter, &c->ctx->channels); - while ((chan = str_map_iter_next (&iter))) - if (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET)) - || channel_get_user (chan, c)) - irc_send_rpl_list (c, chan); - } - else - { - struct str_vector channels; - str_vector_init (&channels); - split_str_ignore_empty (msg->params.vector[0], ',', &channels); - for (size_t i = 0; i < channels.len; i++) - if ((chan = str_map_find (&c->ctx->channels, channels.vector[i])) - && (!(chan->modes & IRC_CHAN_MODE_SECRET) - || channel_get_user (chan, c))) - irc_send_rpl_list (c, chan); - str_vector_free (&channels); - } - irc_send_reply (c, IRC_RPL_LISTEND); -} - -static void -irc_send_rpl_namreply (struct client *c, const struct channel *chan) -{ - struct str_vector nicks; - str_vector_init (&nicks); - - char type = '='; - if (chan->modes & IRC_CHAN_MODE_SECRET) - type = '@'; - else if (chan->modes & IRC_CHAN_MODE_PRIVATE) - type = '*'; - - bool on_channel = channel_get_user (chan, c); - for (struct channel_user *iter = chan->users; iter; iter = iter->next) - { - if (!on_channel && (iter->c->mode & IRC_USER_MODE_INVISIBLE)) - continue; - - struct str result; - str_init (&result); - if (iter->modes & IRC_CHAN_MODE_OPERATOR) - str_append_c (&result, '@'); - else if (iter->modes & IRC_CHAN_MODE_VOICE) - str_append_c (&result, '+'); - str_append (&result, iter->c->nickname); - str_vector_add_owned (&nicks, str_steal (&result)); - } - - if (nicks.len) - { - // FIXME: split it into multiple messages if it's too long - char *reply = join_str_vector (&nicks, ' '); - irc_send_reply (c, IRC_RPL_NAMREPLY, type, chan->name, reply); - free (reply); - } - str_vector_free (&nicks); -} - -static void -irc_handle_names (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1])) - RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]); - - struct channel *chan; - if (msg->params.len == 0) - { - struct str_map_iter iter; - str_map_iter_init (&iter, &c->ctx->channels); - while ((chan = str_map_iter_next (&iter))) - if (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET)) - || channel_get_user (chan, c)) - irc_send_rpl_namreply (c, chan); - - // TODO - // If no <channel> parameter is given, a list of all channels and their - // occupants is returned. At the end of this list, a list of users who - // are visible but either not on any channel or not on a visible channel - // are listed as being on `channel' "*". - irc_send_reply (c, IRC_RPL_ENDOFNAMES, "*"); - } - else - { - struct str_vector channels; - str_vector_init (&channels); - split_str_ignore_empty (msg->params.vector[0], ',', &channels); - for (size_t i = 0; i < channels.len; i++) - if ((chan = str_map_find (&c->ctx->channels, channels.vector[i])) - && (!(chan->modes & IRC_CHAN_MODE_SECRET) - || channel_get_user (chan, c))) - { - irc_send_rpl_namreply (c, chan); - irc_send_reply (c, IRC_RPL_ENDOFNAMES, channels.vector[i]); - } - str_vector_free (&channels); - } -} - -static void -irc_send_rpl_whoreply (struct client *c, const struct channel *chan, - const struct client *target) -{ - struct str chars; - str_init (&chars); - - str_append_c (&chars, target->away_message ? 'G' : 'H'); - if (target->mode & IRC_USER_MODE_OPERATOR) - str_append_c (&chars, '*'); - - struct channel_user *user; - if (chan && (user = channel_get_user (chan, target))) - { - if (user->modes & IRC_CHAN_MODE_OPERATOR) - str_append_c (&chars, '@'); - else if (user->modes & IRC_CHAN_MODE_VOICE) - str_append_c (&chars, '+'); - } - - irc_send_reply (c, IRC_RPL_WHOREPLY, chan ? chan->name : "*", - target->username, target->hostname, target->ctx->server_name, - target->nickname, chars.str, 0 /* hop count */, target->realname); - str_free (&chars); -} - -static void -irc_match_send_rpl_whoreply (struct client *c, struct client *target, - const char *mask) -{ - bool is_roommate = false; - struct str_map_iter iter; - str_map_iter_init (&iter, &c->ctx->channels); - struct channel *chan; - while ((chan = str_map_iter_next (&iter))) - if (channel_get_user (chan, target) && channel_get_user (chan, c)) - { - is_roommate = true; - break; - } - if ((target->mode & IRC_USER_MODE_INVISIBLE) && !is_roommate) - return; - - if (irc_fnmatch (mask, target->hostname) - && irc_fnmatch (mask, target->nickname) - && irc_fnmatch (mask, target->realname) - && irc_fnmatch (mask, c->ctx->server_name)) - return; - - // Try to find a channel they're on that's visible to us - struct channel *user_chan = NULL; - str_map_iter_init (&iter, &c->ctx->channels); - while ((chan = str_map_iter_next (&iter))) - if (channel_get_user (chan, target) - && (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET)) - || channel_get_user (chan, c))) - { - user_chan = chan; - break; - } - irc_send_rpl_whoreply (c, user_chan, target); -} - -static void -irc_handle_who (const struct irc_message *msg, struct client *c) -{ - bool only_ops = msg->params.len > 1 && !strcmp (msg->params.vector[1], "o"); - - const char *shown_mask = msg->params.vector[0], *used_mask; - if (!shown_mask) - used_mask = shown_mask = "*"; - else if (!strcmp (shown_mask, "0")) - used_mask = "*"; - else - used_mask = shown_mask; - - struct channel *chan; - if ((chan = str_map_find (&c->ctx->channels, used_mask))) - { - bool on_chan = !!channel_get_user (chan, c); - if (on_chan || !(chan->modes & IRC_CHAN_MODE_SECRET)) - for (struct channel_user *iter = chan->users; - iter; iter = iter->next) - { - if ((on_chan || !(iter->c->mode & IRC_USER_MODE_INVISIBLE)) - && (!only_ops || (iter->c->mode & IRC_USER_MODE_OPERATOR))) - irc_send_rpl_whoreply (c, chan, iter->c); - } - } - else - { - struct str_map_iter iter; - str_map_iter_init (&iter, &c->ctx->users); - struct client *target; - while ((target = str_map_iter_next (&iter))) - if (!only_ops || (target->mode & IRC_USER_MODE_OPERATOR)) - irc_match_send_rpl_whoreply (c, target, used_mask); - } - irc_send_reply (c, IRC_RPL_ENDOFWHO, shown_mask); -} - -static void -irc_send_whois_reply (struct client *c, const struct client *target) -{ - const char *nick = target->nickname; - irc_send_reply (c, IRC_RPL_WHOISUSER, nick, target->username, - target->hostname, target->realname); - irc_send_reply (c, IRC_RPL_WHOISSERVER, nick, target->ctx->server_name, - str_map_find (&c->ctx->config, "server_info")); - if (target->mode & IRC_USER_MODE_OPERATOR) - irc_send_reply (c, IRC_RPL_WHOISOPERATOR, nick); - irc_send_reply (c, IRC_RPL_WHOISIDLE, nick, - (int) (time (NULL) - target->last_active)); - - struct str_map_iter iter; - str_map_iter_init (&iter, &c->ctx->channels); - struct channel *chan; - struct channel_user *channel_user; - while ((chan = str_map_iter_next (&iter))) - if ((channel_user = channel_get_user (chan, target)) - && (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET)) - || channel_get_user (chan, c))) - { - struct str item; - str_init (&item); - if (channel_user->modes & IRC_CHAN_MODE_OPERATOR) - str_append_c (&item, '@'); - else if (channel_user->modes & IRC_CHAN_MODE_VOICE) - str_append_c (&item, '+'); - str_append (&item, chan->name); - str_append_c (&item, ' '); - - // TODO: try to merge the results into as few messages as possible - irc_send_reply (c, IRC_RPL_WHOISCHANNELS, nick, item.str); - - str_free (&item); - } - - irc_send_reply (c, IRC_RPL_ENDOFWHOIS, nick); -} - -static void -irc_handle_whois (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len < 1) - RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command); - if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[0])) - RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]); - - struct str_vector masks; - str_vector_init (&masks); - const char *masks_str = msg->params.vector[msg->params.len > 1]; - split_str_ignore_empty (masks_str, ',', &masks); - for (size_t i = 0; i < masks.len; i++) - { - const char *mask = masks.vector[i]; - struct client *target; - if (!strpbrk (mask, "*?")) - { - if (!(target = str_map_find (&c->ctx->users, mask))) - irc_send_reply (c, IRC_ERR_NOSUCHNICK, mask); - else - irc_send_whois_reply (c, target); - } - else - { - struct str_map_iter iter; - str_map_iter_init (&iter, &c->ctx->users); - bool found = false; - while ((target = str_map_iter_next (&iter)) - && !irc_fnmatch (mask, target->nickname)) - { - irc_send_whois_reply (c, target); - found = true; - } - if (!found) - irc_send_reply (c, IRC_ERR_NOSUCHNICK, mask); - } - } - str_vector_free (&masks); -} - -static void -irc_send_rpl_topic (struct client *c, struct channel *chan) -{ - if (!*chan->topic) - irc_send_reply (c, IRC_RPL_NOTOPIC, chan->name); - else - irc_send_reply (c, IRC_RPL_TOPIC, chan->name, chan->topic); -} - -static void -irc_handle_topic (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len < 1) - RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command); - - const char *target = msg->params.vector[0]; - struct channel *chan = str_map_find (&c->ctx->channels, target); - if (!chan) - RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, target); - - if (msg->params.len < 2) - { - irc_send_rpl_topic (c, chan); - return; - } - - struct channel_user *user = channel_get_user (chan, c); - if (!user) - RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, target); - - if ((chan->modes & IRC_CHAN_MODE_PROTECTED_TOPIC) - && !(user->modes & IRC_CHAN_MODE_OPERATOR)) - RETURN_WITH_REPLY (c, IRC_ERR_CHANOPRIVSNEEDED, target); - - free (chan->topic); - chan->topic = xstrdup (msg->params.vector[1]); - - char *message = xstrdup_printf (":%s!%s@%s TOPIC %s :%s", - c->nickname, c->username, c->hostname, target, chan->topic); - irc_channel_multicast (chan, message, NULL); - free (message); -} - -static void -irc_try_part (struct client *c, const char *channel_name, const char *reason) -{ - if (!reason) - reason = c->nickname; - - struct channel *chan; - if (!(chan = str_map_find (&c->ctx->channels, channel_name))) - RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, channel_name); - - struct channel_user *user; - if (!(user = channel_get_user (chan, c))) - RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, channel_name); - - char *message = xstrdup_printf (":%s!%s@%s PART %s :%s", - c->nickname, c->username, c->hostname, channel_name, reason); - if (!(chan->modes & IRC_CHAN_MODE_QUIET)) - irc_channel_multicast (chan, message, NULL); - else - client_send (c, "%s", message); - free (message); - - channel_remove_user (chan, user); - irc_channel_destroy_if_empty (c->ctx, chan); -} - -static void -irc_part_all_channels (struct client *c) -{ - struct str_map_iter iter; - str_map_iter_init (&iter, &c->ctx->channels); - struct channel *chan = str_map_iter_next (&iter), *next; - while (chan) - { - // We have to be careful here, the channel might get destroyed - next = str_map_iter_next (&iter); - if (channel_get_user (chan, c)) - irc_try_part (c, chan->name, NULL); - chan = next; - } -} - -static void -irc_handle_part (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len < 1) - RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command); - - const char *reason = msg->params.len > 1 ? msg->params.vector[1] : NULL; - struct str_vector channels; - str_vector_init (&channels); - split_str_ignore_empty (msg->params.vector[0], ',', &channels); - for (size_t i = 0; i < channels.len; i++) - irc_try_part (c, channels.vector[i], reason); - str_vector_free (&channels); -} - -static void -irc_try_kick (struct client *c, const char *channel_name, const char *nick, - const char *reason) -{ - struct channel *chan; - if (!(chan = str_map_find (&c->ctx->channels, channel_name))) - RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, channel_name); - - struct channel_user *user; - if (!(user = channel_get_user (chan, c))) - RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, channel_name); - if (!(user->modes & IRC_CHAN_MODE_OPERATOR)) - RETURN_WITH_REPLY (c, IRC_ERR_CHANOPRIVSNEEDED, channel_name); - - struct client *client; - if (!(client = str_map_find (&c->ctx->users, nick)) - || !(user = channel_get_user (chan, client))) - RETURN_WITH_REPLY (c, IRC_ERR_USERNOTINCHANNEL, nick, channel_name); - - char *message = xstrdup_printf (":%s!%s@%s KICK %s %s :%s", - c->nickname, c->username, c->hostname, channel_name, nick, reason); - if (!(chan->modes & IRC_CHAN_MODE_QUIET)) - irc_channel_multicast (chan, message, NULL); - else - client_send (c, "%s", message); - free (message); - - channel_remove_user (chan, user); - irc_channel_destroy_if_empty (c->ctx, chan); -} - -static void -irc_handle_kick (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len < 2) - RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command); - - const char *reason = c->nickname; - if (msg->params.len > 2) - reason = msg->params.vector[2]; - - struct str_vector channels; - struct str_vector users; - str_vector_init (&channels); - str_vector_init (&users); - split_str_ignore_empty (msg->params.vector[0], ',', &channels); - split_str_ignore_empty (msg->params.vector[1], ',', &users); - - if (channels.len == 1) - for (size_t i = 0; i < users.len; i++) - irc_try_kick (c, channels.vector[0], users.vector[i], reason); - else - for (size_t i = 0; i < channels.len && i < users.len; i++) - irc_try_kick (c, channels.vector[i], users.vector[i], reason); - - str_vector_free (&channels); - str_vector_free (&users); -} - -static void -irc_try_join (struct client *c, const char *channel_name, const char *key) -{ - struct channel *chan = str_map_find (&c->ctx->channels, channel_name); - unsigned user_mode = 0; - if (!chan) - { - if (irc_validate_channel_name (channel_name) != VALIDATION_OK) - RETURN_WITH_REPLY (c, IRC_ERR_BADCHANMASK, channel_name); - chan = irc_channel_create (c->ctx, channel_name); - user_mode = IRC_CHAN_MODE_OPERATOR; - } - else if (channel_get_user (chan, c)) - return; - - if ((chan->modes & IRC_CHAN_MODE_INVITE_ONLY) - && !client_in_mask_list (c, &chan->invite_list)) - // TODO: exceptions caused by INVITE - RETURN_WITH_REPLY (c, IRC_ERR_INVITEONLYCHAN, channel_name); - if (chan->key && (!key || strcmp (key, chan->key))) - RETURN_WITH_REPLY (c, IRC_ERR_BADCHANNELKEY, channel_name); - if (chan->user_limit != -1 - && channel_user_count (chan) >= (size_t) chan->user_limit) - RETURN_WITH_REPLY (c, IRC_ERR_CHANNELISFULL, channel_name); - if (client_in_mask_list (c, &chan->ban_list) - && !client_in_mask_list (c, &chan->exception_list)) - RETURN_WITH_REPLY (c, IRC_ERR_BANNEDFROMCHAN, channel_name); - - channel_add_user (chan, c)->modes = user_mode; - - char *message = xstrdup_printf (":%s!%s@%s JOIN %s", - c->nickname, c->username, c->hostname, channel_name); - if (!(chan->modes & IRC_CHAN_MODE_QUIET)) - irc_channel_multicast (chan, message, NULL); - else - client_send (c, "%s", message); - free (message); - - irc_send_rpl_topic (c, chan); - irc_send_rpl_namreply (c, chan); - irc_send_reply (c, IRC_RPL_ENDOFNAMES, chan->name); -} - -static void -irc_handle_join (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len < 1) - RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command); - - if (!strcmp (msg->params.vector[0], "0")) - { - irc_part_all_channels (c); - return; - } - - struct str_vector channels; - struct str_vector keys; - str_vector_init (&channels); - str_vector_init (&keys); - split_str_ignore_empty (msg->params.vector[0], ',', &channels); - if (msg->params.len > 1) - split_str_ignore_empty (msg->params.vector[1], ',', &keys); - - for (size_t i = 0; i < channels.len; i++) - irc_try_join (c, channels.vector[i], - i < keys.len ? keys.vector[i] : NULL); - - str_vector_free (&channels); - str_vector_free (&keys); -} - -static void -irc_handle_summon (const struct irc_message *msg, struct client *c) -{ - (void) msg; - irc_send_reply (c, IRC_ERR_SUMMONDISABLED); -} - -static void -irc_handle_users (const struct irc_message *msg, struct client *c) -{ - (void) msg; - irc_send_reply (c, IRC_ERR_USERSDISABLED); -} - -static void -irc_handle_away (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len < 1) - { - free (c->away_message); - c->away_message = NULL; - irc_send_reply (c, IRC_RPL_UNAWAY); - } - else - { - free (c->away_message); - c->away_message = xstrdup (msg->params.vector[0]); - irc_send_reply (c, IRC_RPL_NOWAWAY); - } -} - -static void -irc_handle_ison (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len < 1) - RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command); - - struct str result; - str_init (&result); - - const char *nick; - if (str_map_find (&c->ctx->users, (nick = msg->params.vector[0]))) - str_append (&result, nick); - for (size_t i = 1; i < msg->params.len; i++) - if (str_map_find (&c->ctx->users, (nick = msg->params.vector[i]))) - str_append_printf (&result, " %s", nick); - - irc_send_reply (c, IRC_RPL_ISON, result.str); - str_free (&result); -} - -static void -irc_handle_admin (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0])) - RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]); - irc_send_reply (c, IRC_ERR_NOADMININFO, c->ctx->server_name); -} - -static void -irc_handle_kill (const struct irc_message *msg, struct client *c) -{ - if (msg->params.len < 2) - RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command); - if (!(c->mode & IRC_USER_MODE_OPERATOR)) - RETURN_WITH_REPLY (c, IRC_ERR_NOPRIVILEGES); - - struct client *target; - if (!(target = str_map_find (&c->ctx->users, msg->params.vector[0]))) - RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHNICK, msg->params.vector[0]); - char *reason = xstrdup_printf ("Killed by %s: %s", - c->nickname, msg->params.vector[1]); - client_close_link (target, reason); - free (reason); -} - -static void -irc_handle_die (const struct irc_message *msg, struct client *c) -{ - (void) msg; - - if (!(c->mode & IRC_USER_MODE_OPERATOR)) - RETURN_WITH_REPLY (c, IRC_ERR_NOPRIVILEGES); - if (!c->ctx->quitting) - irc_initiate_quit (c->ctx); -} - -// ----------------------------------------------------------------------------- - -struct irc_command -{ - const char *name; - bool requires_registration; - void (*handler) (const struct irc_message *, struct client *); -}; - -static void -irc_register_handlers (struct server_context *ctx) -{ - // TODO: add an index for IRC_ERR_NOSUCHSERVER validation? - // TODO: add a minimal parameter count? - // TODO: add a field for oper-only commands? - static const struct irc_command message_handlers[] = - { - { "PASS", false, irc_handle_pass }, - { "NICK", false, irc_handle_nick }, - { "USER", false, irc_handle_user }, - - { "USERHOST", true, irc_handle_userhost }, - { "LUSERS", true, irc_handle_lusers }, - { "MOTD", true, irc_handle_motd }, - { "PING", true, irc_handle_ping }, - { "PONG", false, irc_handle_pong }, - { "QUIT", false, irc_handle_quit }, - { "TIME", true, irc_handle_time }, - { "VERSION", true, irc_handle_version }, - { "USERS", true, irc_handle_users }, - { "SUMMON", true, irc_handle_summon }, - { "AWAY", true, irc_handle_away }, - { "ADMIN", true, irc_handle_admin }, - - { "MODE", true, irc_handle_mode }, - { "PRIVMSG", true, irc_handle_privmsg }, - { "NOTICE", true, irc_handle_notice }, - { "JOIN", true, irc_handle_join }, - { "PART", true, irc_handle_part }, - { "KICK", true, irc_handle_kick }, - { "TOPIC", true, irc_handle_topic }, - { "LIST", true, irc_handle_list }, - { "NAMES", true, irc_handle_names }, - { "WHO", true, irc_handle_who }, - { "WHOIS", true, irc_handle_whois }, - { "ISON", true, irc_handle_ison }, - - { "KILL", true, irc_handle_kill }, - { "DIE", true, irc_handle_die }, - }; - - for (size_t i = 0; i < N_ELEMENTS (message_handlers); i++) - { - const struct irc_command *cmd = &message_handlers[i]; - str_map_set (&ctx->handlers, cmd->name, (void *) cmd); - } -} - -static void -irc_process_message (const struct irc_message *msg, - const char *raw, void *user_data) -{ - (void) raw; - - struct client *c = user_data; - if (c->closing_link) - return; - - struct irc_command *cmd = str_map_find (&c->ctx->handlers, msg->command); - if (!cmd) - irc_send_reply (c, IRC_ERR_UNKNOWNCOMMAND, msg->command); - else if (cmd->requires_registration && !c->registered) - irc_send_reply (c, IRC_ERR_NOTREGISTERED); - else - cmd->handler (msg, c); -} - -// --- Network I/O ------------------------------------------------------------- - -static bool -irc_try_read (struct client *c) -{ - struct str *buf = &c->read_buffer; - ssize_t n_read; - - while (true) - { - str_ensure_space (buf, 512); - n_read = recv (c->socket_fd, buf->str + buf->len, - buf->alloc - buf->len - 1 /* null byte */, 0); - - if (n_read > 0) - { - buf->str[buf->len += n_read] = '\0'; - // TODO: discard characters above the 512 character limit - irc_process_buffer (buf, irc_process_message, c); - continue; - } - if (n_read == 0) - { - client_kill (c, NULL); - return false; - } - - if (errno == EAGAIN) - return true; - if (errno == EINTR) - continue; - - print_debug ("%s: %s: %s", __func__, "recv", strerror (errno)); - client_kill (c, strerror (errno)); - return false; - } -} - -static bool -irc_try_read_ssl (struct client *c) -{ - if (c->ssl_tx_want_rx) - return true; - - struct str *buf = &c->read_buffer; - c->ssl_rx_want_tx = false; - while (true) - { - str_ensure_space (buf, 512); - int n_read = SSL_read (c->ssl, buf->str + buf->len, - buf->alloc - buf->len - 1 /* null byte */); - - const char *error_info = NULL; - switch (xssl_get_error (c->ssl, n_read, &error_info)) - { - case SSL_ERROR_NONE: - buf->str[buf->len += n_read] = '\0'; - // TODO: discard characters above the 512 character limit - irc_process_buffer (buf, irc_process_message, c); - continue; - case SSL_ERROR_ZERO_RETURN: - client_kill (c, NULL); - return false; - case SSL_ERROR_WANT_READ: - return true; - case SSL_ERROR_WANT_WRITE: - c->ssl_rx_want_tx = true; - return true; - case XSSL_ERROR_TRY_AGAIN: - continue; - default: - print_debug ("%s: %s: %s", __func__, "SSL_read", error_info); - client_kill (c, error_info); - return false; - } - } -} - -static bool -irc_try_write (struct client *c) -{ - struct str *buf = &c->write_buffer; - ssize_t n_written; - - while (buf->len) - { - n_written = send (c->socket_fd, buf->str, buf->len, 0); - if (n_written >= 0) - { - str_remove_slice (buf, 0, n_written); - continue; - } - - if (errno == EAGAIN) - return true; - if (errno == EINTR) - continue; - - print_debug ("%s: %s: %s", __func__, "send", strerror (errno)); - client_kill (c, strerror (errno)); - return false; - } - return true; -} - -static bool -irc_try_write_ssl (struct client *c) -{ - if (c->ssl_rx_want_tx) - return true; - - struct str *buf = &c->write_buffer; - c->ssl_tx_want_rx = false; - while (buf->len) - { - int n_written = SSL_write (c->ssl, buf->str, buf->len); - - const char *error_info = NULL; - switch (xssl_get_error (c->ssl, n_written, &error_info)) - { - case SSL_ERROR_NONE: - str_remove_slice (buf, 0, n_written); - continue; - case SSL_ERROR_ZERO_RETURN: - client_kill (c, NULL); - return false; - case SSL_ERROR_WANT_WRITE: - return true; - case SSL_ERROR_WANT_READ: - c->ssl_tx_want_rx = true; - return true; - case XSSL_ERROR_TRY_AGAIN: - continue; - default: - print_debug ("%s: %s: %s", __func__, "SSL_write", error_info); - client_kill (c, error_info); - return false; - } - } - return true; -} - -static bool -irc_autodetect_ssl (struct client *c) -{ - // Trivial SSL/TLS autodetection. The first block of data returned by - // recv() must be at least three bytes long for this to work reliably, - // but that should not pose a problem in practice. - // - // SSL2: 1xxx xxxx | xxxx xxxx | <1> - // (message length) (client hello) - // SSL3/TLS: <22> | <3> | xxxx xxxx - // (handshake)| (protocol version) - // - // Such byte sequences should never occur at the beginning of regular IRC - // communication, which usually begins with USER/NICK/PASS/SERVICE. - - char buf[3]; -start: - switch (recv (c->socket_fd, buf, sizeof buf, MSG_PEEK)) - { - case 3: - if ((buf[0] & 0x80) && buf[2] == 1) - return true; - case 2: - if (buf[0] == 22 && buf[1] == 3) - return true; - break; - case 1: - if (buf[0] == 22) - return true; - break; - case 0: - break; - default: - if (errno == EINTR) - goto start; - } - return false; -} - -static bool -client_initialize_ssl (struct client *c) -{ - // SSL support not enabled - if (!c->ctx->ssl_ctx) - return false; - - c->ssl = SSL_new (c->ctx->ssl_ctx); - if (!c->ssl) - goto error_ssl_1; - - if (!SSL_set_fd (c->ssl, c->socket_fd)) - goto error_ssl_2; - SSL_set_accept_state (c->ssl); - return true; - -error_ssl_2: - SSL_free (c->ssl); - c->ssl = NULL; -error_ssl_1: - // XXX: these error strings are really nasty; also there could be - // multiple errors on the OpenSSL stack. - print_debug ("%s: %s: %s", "could not initialize SSL", - c->hostname, ERR_error_string (ERR_get_error (), NULL)); - return false; -} - -static void -on_client_ready (const struct pollfd *pfd, void *user_data) -{ - struct client *c = user_data; - if (!c->initialized) - { - hard_assert (pfd->events == POLLIN); - if (irc_autodetect_ssl (c) && !client_initialize_ssl (c)) - { - client_kill (c, NULL); - return; - } - c->initialized = true; - client_set_ping_timer (c); - } - - if (c->ssl) - { - // Reads may want to write, writes may want to read, poll() may - // return unexpected things in `revents'... let's try both - if (!irc_try_read_ssl (c) || !irc_try_write_ssl (c)) - return; - } - else if (!irc_try_read (c) || !irc_try_write (c)) - return; - - client_update_poller (c, pfd); - - // The purpose of the `closing_link' state is to transfer the `ERROR' - if (c->closing_link && !c->write_buffer.len) - client_kill (c, NULL); -} - -static void -client_update_poller (struct client *c, const struct pollfd *pfd) -{ - int new_events = POLLIN; - if (c->ssl) - { - if (c->write_buffer.len || c->ssl_rx_want_tx) - new_events |= POLLOUT; - - // While we're waiting for an opposite event, we ignore the original - if (c->ssl_rx_want_tx) new_events &= ~POLLIN; - if (c->ssl_tx_want_rx) new_events &= ~POLLOUT; - } - else if (c->write_buffer.len) - new_events |= POLLOUT; - - hard_assert (new_events != 0); - if (!pfd || pfd->events != new_events) - poller_set (&c->ctx->poller, c->socket_fd, new_events, - (poller_dispatcher_func) on_client_ready, c); -} - -static void -on_irc_client_available (const struct pollfd *pfd, void *user_data) -{ - (void) pfd; - struct server_context *ctx = user_data; - - while (true) - { - // XXX: `struct sockaddr_storage' is not the most portable thing - struct sockaddr_storage peer; - socklen_t peer_len = sizeof peer; - - int fd = accept (pfd->fd, (struct sockaddr *) &peer, &peer_len); - if (fd == -1) - { - if (errno == EAGAIN) - break; - if (errno == EINTR - || errno == ECONNABORTED) - continue; - - // TODO: handle resource exhaustion (EMFILE, ENFILE) specially - // (stop accepting new connections and wait until we close some). - // FIXME: handle this better, bring the server down cleanly. - exit_fatal ("%s: %s", "accept", strerror (errno)); - } - - if (ctx->max_connections != 0 && ctx->n_clients >= ctx->max_connections) - { - print_debug ("connection limit reached, refusing connection"); - close (fd); - continue; - } - - char host[NI_MAXHOST] = "unknown", port[NI_MAXSERV] = "unknown"; - int err = getnameinfo ((struct sockaddr *) &peer, peer_len, - host, sizeof host, port, sizeof port, NI_NUMERICSERV); - if (err) - print_debug ("%s: %s", "getnameinfo", gai_strerror (err)); - print_debug ("accepted connection from %s:%s", host, port); - - struct client *c = xmalloc (sizeof *c); - client_init (c); - c->ctx = ctx; - c->socket_fd = fd; - c->hostname = xstrdup (host); - c->last_active = time (NULL); - LIST_PREPEND (ctx->clients, c); - ctx->n_clients++; - - set_blocking (fd, false); - client_update_poller (c, NULL); - client_set_kill_timer (c); - } -} - -// --- Application setup ------------------------------------------------------- - -static int -irc_ssl_verify_callback (int verify_ok, X509_STORE_CTX *ctx) -{ - (void) verify_ok; - (void) ctx; - - // We only want to provide additional privileges based on the client's - // certificate, so let's not terminate the connection because of a failure. - return 1; -} - -static bool -irc_initialize_ssl (struct server_context *ctx, struct error **e) -{ - const char *ssl_cert = str_map_find (&ctx->config, "ssl_cert"); - const char *ssl_key = str_map_find (&ctx->config, "ssl_key"); - - // Only try to enable SSL support if the user configures it; it is not - // a failure if no one has requested it. - if (!ssl_cert && !ssl_key) - return true; - - if (!ssl_cert) - error_set (e, "no SSL certificate set"); - else if (!ssl_key) - error_set (e, "no SSL private key set"); - if (!ssl_cert || !ssl_key) - return false; - - char *cert_path = resolve_config_filename (ssl_cert); - char *key_path = resolve_config_filename (ssl_key); - if (!cert_path) - error_set (e, "%s: %s", "cannot open file", ssl_cert); - else if (!key_path) - error_set (e, "%s: %s", "cannot open file", ssl_key); - if (!cert_path || !key_path) - return false; - - ctx->ssl_ctx = SSL_CTX_new (SSLv23_server_method ()); - if (!ctx->ssl_ctx) - { - // XXX: these error strings are really nasty; also there could be - // multiple errors on the OpenSSL stack. - error_set (e, "%s: %s", "could not initialize SSL", - ERR_error_string (ERR_get_error (), NULL)); - goto error_ssl_1; - } - SSL_CTX_set_verify (ctx->ssl_ctx, - SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, irc_ssl_verify_callback); - // XXX: maybe we should call SSL_CTX_set_options() for some workarounds - - const unsigned char session_id_context[SSL_MAX_SSL_SESSION_ID_LENGTH] - = PROGRAM_NAME; - (void) SSL_CTX_set_session_id_context (ctx->ssl_ctx, - session_id_context, sizeof session_id_context); - - // XXX: perhaps we should read the files ourselves for better messages - if (!SSL_CTX_use_certificate_chain_file (ctx->ssl_ctx, cert_path)) - { - error_set (e, "%s: %s", "setting the SSL client certificate failed", - ERR_error_string (ERR_get_error (), NULL)); - goto error_ssl_2; - } - if (!SSL_CTX_use_PrivateKey_file (ctx->ssl_ctx, key_path, SSL_FILETYPE_PEM)) - { - error_set (e, "%s: %s", "setting the SSL private key failed", - ERR_error_string (ERR_get_error (), NULL)); - goto error_ssl_2; - } - - // TODO: SSL_CTX_check_private_key()? It has probably already been checked - // by SSL_CTX_use_PrivateKey_file() above. - - // Gah, spare me your awkward semantics, I just want to push data! - // XXX: do we want SSL_MODE_AUTO_RETRY as well? I guess not. - SSL_CTX_set_mode (ctx->ssl_ctx, - SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE); - return true; - -error_ssl_2: - SSL_CTX_free (ctx->ssl_ctx); - ctx->ssl_ctx = NULL; -error_ssl_1: - return false; -} - -static bool -irc_initialize_catalog (struct server_context *ctx, struct error **e) -{ - hard_assert (ctx->catalog == (nl_catd) -1); - const char *catalog = str_map_find (&ctx->config, "catalog"); - if (!catalog) - return true; - - char *path = resolve_config_filename (catalog); - if (!path) - { - error_set (e, "%s: %s", "cannot open file", catalog); - return false; - } - ctx->catalog = catopen (path, NL_CAT_LOCALE); - free (path); - - if (ctx->catalog == (nl_catd) -1) - { - error_set (e, "%s: %s", - "failed reading the message catalog file", strerror (errno)); - return false; - } - return true; -} - -static bool -irc_initialize_motd (struct server_context *ctx, struct error **e) -{ - hard_assert (ctx->motd.len == 0); - const char *motd = str_map_find (&ctx->config, "motd"); - if (!motd) - return true; - - char *path = resolve_config_filename (motd); - if (!path) - { - error_set (e, "%s: %s", "cannot open file", motd); - return false; - } - FILE *fp = fopen (path, "r"); - free (path); - - if (!fp) - { - error_set (e, "%s: %s", - "failed reading the MOTD file", strerror (errno)); - return false; - } - - struct str line; - str_init (&line); - while (read_line (fp, &line)) - str_vector_add_owned (&ctx->motd, str_steal (&line)); - str_free (&line); - - fclose (fp); - return true; -} - -/// This function handles values that require validation before their first use, -/// or some kind of a transformation (such as conversion to an integer) needs -/// to be done before they can be used directly. -static bool -irc_parse_config (struct server_context *ctx, struct error **e) -{ - unsigned long ul; -#define PARSE_UNSIGNED(name, min, max) \ - const char *name = str_map_find (&ctx->config, #name); \ - hard_assert (name != NULL); \ - if (!xstrtoul (&ul, name, 10) || ul > max || ul < min) \ - { \ - error_set (e, "invalid configuration value for `%s': %s", \ - #name, "the number is invalid or out of range"); \ - return false; \ - } \ - ctx->name = ul - - PARSE_UNSIGNED (ping_interval, 1, UINT_MAX); - PARSE_UNSIGNED (max_connections, 0, UINT_MAX); - - bool result = true; - struct str_vector fingerprints; - str_vector_init (&fingerprints); - const char *operators = str_map_find (&ctx->config, "operators"); - if (operators) - split_str_ignore_empty (operators, ',', &fingerprints); - for (size_t i = 0; i < fingerprints.len; i++) - { - const char *key = fingerprints.vector[i]; - if (!irc_is_valid_fingerprint (key)) - { - error_set (e, "invalid configuration value for `%s': %s", - "operators", "invalid fingerprint value"); - result = false; - break; - } - str_map_set (&ctx->operators, key, (void *) 1); - } - str_vector_free (&fingerprints); - return result; -} - -static bool -irc_initialize_server_name (struct server_context *ctx, struct error **e) -{ - enum validation_result res; - const char *server_name = str_map_find (&ctx->config, "server_name"); - if (server_name) - { - res = irc_validate_hostname (server_name); - if (res != VALIDATION_OK) - { - error_set (e, "invalid configuration value for `%s': %s", - "server_name", irc_validate_to_str (res)); - return false; - } - ctx->server_name = xstrdup (server_name); - } - else - { - char hostname[HOST_NAME_MAX]; - if (gethostname (hostname, sizeof hostname)) - { - error_set (e, "%s: %s", - "getting the hostname failed", strerror (errno)); - return false; - } - res = irc_validate_hostname (hostname); - if (res != VALIDATION_OK) - { - error_set (e, - "`%s' is not set and the hostname (`%s') cannot be used: %s", - "server_name", hostname, irc_validate_to_str (res)); - return false; - } - ctx->server_name = xstrdup (hostname); - } - return true; -} - -static int -irc_listen (struct addrinfo *gai_iter) -{ - int fd = socket (gai_iter->ai_family, - gai_iter->ai_socktype, gai_iter->ai_protocol); - if (fd == -1) - return -1; - set_cloexec (fd); - - int yes = 1; - soft_assert (setsockopt (fd, SOL_SOCKET, SO_KEEPALIVE, - &yes, sizeof yes) != -1); - soft_assert (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, - &yes, sizeof yes) != -1); - - char real_host[NI_MAXHOST], real_port[NI_MAXSERV]; - real_host[0] = real_port[0] = '\0'; - int err = getnameinfo (gai_iter->ai_addr, gai_iter->ai_addrlen, - real_host, sizeof real_host, real_port, sizeof real_port, - NI_NUMERICHOST | NI_NUMERICSERV); - if (err) - print_debug ("%s: %s", "getnameinfo", gai_strerror (err)); - - if (bind (fd, gai_iter->ai_addr, gai_iter->ai_addrlen)) - print_error ("bind to %s:%s failed: %s", - real_host, real_port, strerror (errno)); - else if (listen (fd, 16 /* arbitrary number */)) - print_error ("listen at %s:%s failed: %s", - real_host, real_port, strerror (errno)); - else - { - print_status ("listening at %s:%s", real_host, real_port); - return fd; - } - - xclose (fd); - return -1; -} - -static bool -irc_setup_listen_fds (struct server_context *ctx, struct error **e) -{ - const char *bind_host = str_map_find (&ctx->config, "bind_host"); - const char *bind_port = str_map_find (&ctx->config, "bind_port"); - hard_assert (bind_port != NULL); // We have a default value for this - - struct addrinfo gai_hints, *gai_result, *gai_iter; - memset (&gai_hints, 0, sizeof gai_hints); - - gai_hints.ai_socktype = SOCK_STREAM; - gai_hints.ai_flags = AI_PASSIVE; - - int err = getaddrinfo (bind_host, bind_port, &gai_hints, &gai_result); - if (err) - { - error_set (e, "%s: %s: %s", - "network setup failed", "getaddrinfo", gai_strerror (err)); - return false; - } - - int fd; - for (gai_iter = gai_result; gai_iter; gai_iter = gai_iter->ai_next) - { - if (ctx->n_listen_fds >= N_ELEMENTS (ctx->listen_fds)) - break; - if ((fd = irc_listen (gai_iter)) == -1) - continue; - - ctx->listen_fds[ctx->n_listen_fds++] = fd; - set_blocking (fd, false); - poller_set (&ctx->poller, fd, POLLIN, - (poller_dispatcher_func) on_irc_client_available, ctx); - break; - } - freeaddrinfo (gai_result); - - if (!ctx->n_listen_fds) - { - error_set (e, "network setup failed"); - return false; - } - return true; -} - -// --- Main -------------------------------------------------------------------- - -static void -on_signal_pipe_readable (const struct pollfd *fd, struct server_context *ctx) -{ - char *dummy; - (void) read (fd->fd, &dummy, 1); - - if (g_termination_requested && !ctx->quitting) - irc_initiate_quit (ctx); -} - -static void -daemonize (void) -{ - // TODO: create and lock a PID file? - print_status ("daemonizing..."); - - if (chdir ("/")) - exit_fatal ("%s: %s", "chdir", strerror (errno)); - - pid_t pid; - if ((pid = fork ()) < 0) - exit_fatal ("%s: %s", "fork", strerror (errno)); - else if (pid) - exit (EXIT_SUCCESS); - - setsid (); - signal (SIGHUP, SIG_IGN); - - if ((pid = fork ()) < 0) - exit_fatal ("%s: %s", "fork", strerror (errno)); - else if (pid) - exit (EXIT_SUCCESS); - - openlog (PROGRAM_NAME, LOG_NDELAY | LOG_NOWAIT | LOG_PID, 0); - g_log_message_real = log_message_syslog; - - // XXX: we may close our own descriptors this way, crippling ourselves - for (int i = 0; i < 3; i++) - xclose (i); - - int tty = open ("/dev/null", O_RDWR); - if (tty != 0 || dup (0) != 1 || dup (0) != 2) - exit_fatal ("failed to reopen FD's: %s", strerror (errno)); -} - -static void -print_usage (const char *program_name) -{ - fprintf (stderr, - "Usage: %s [OPTION]...\n" - "Experimental IRC server.\n" - "\n" - " -d, --debug run in debug mode (do not daemonize)\n" - " -h, --help display this help and exit\n" - " -V, --version output version information and exit\n" - " --write-default-cfg [filename]\n" - " write a default configuration file and exit\n", - program_name); -} - -int -main (int argc, char *argv[]) -{ - const char *invocation_name = argv[0]; - - static struct option opts[] = - { - { "debug", no_argument, NULL, 'd' }, - { "help", no_argument, NULL, 'h' }, - { "version", no_argument, NULL, 'V' }, - { "write-default-cfg", optional_argument, NULL, 'w' }, - { NULL, 0, NULL, 0 } - }; - - while (1) - { - int c, opt_index; - - c = getopt_long (argc, argv, "dhV", opts, &opt_index); - if (c == -1) - break; - - switch (c) - { - case 'd': - g_debug_mode = true; - break; - case 'h': - print_usage (invocation_name); - exit (EXIT_SUCCESS); - case 'V': - printf (PROGRAM_NAME " " PROGRAM_VERSION "\n"); - exit (EXIT_SUCCESS); - case 'w': - call_write_default_config (optarg, g_config_table); - exit (EXIT_SUCCESS); - default: - print_error ("wrong options"); - exit (EXIT_FAILURE); - } - } - - print_status (PROGRAM_NAME " " PROGRAM_VERSION " starting"); - setup_signal_handlers (); - - SSL_library_init (); - atexit (EVP_cleanup); - SSL_load_error_strings (); - // XXX: ERR_load_BIO_strings()? Anything else? - atexit (ERR_free_strings); - - struct server_context ctx; - server_context_init (&ctx); - irc_register_handlers (&ctx); - - struct error *e = NULL; - if (!read_config_file (&ctx.config, &e)) - { - print_error ("error loading configuration: %s", e->message); - error_free (e); - exit (EXIT_FAILURE); - } - - poller_set (&ctx.poller, g_signal_pipe[0], POLLIN, - (poller_dispatcher_func) on_signal_pipe_readable, &ctx); - - if (!irc_initialize_ssl (&ctx, &e) - || !irc_initialize_server_name (&ctx, &e) - || !irc_initialize_motd (&ctx, &e) - || !irc_initialize_catalog (&ctx, &e) - || !irc_parse_config (&ctx, &e) - || !irc_setup_listen_fds (&ctx, &e)) - { - print_error ("%s", e->message); - error_free (e); - exit (EXIT_FAILURE); - } - - if (!g_debug_mode) - daemonize (); - - ctx.polling = true; - while (ctx.polling) - poller_run (&ctx.poller); - - server_context_free (&ctx); - return EXIT_SUCCESS; -} diff --git a/src/siphash.c b/src/siphash.c deleted file mode 100644 index 7a5c8d4..0000000 --- a/src/siphash.c +++ /dev/null @@ -1,87 +0,0 @@ -// Code taken from https://github.com/floodyberry/siphash with some edits. -// -// To the extent possible under law, the author(s) have dedicated all copyright -// and related and neighboring rights to this software to the public domain -// worldwide. This software is distributed without any warranty. -// -// You should have received a copy of the CC0 Public Domain Dedication along -// with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. - -#include "siphash.h" - -inline static uint64_t -u8to64_le (const unsigned char *p) -{ - return - (uint64_t) p[0] | - (uint64_t) p[1] << 8 | - (uint64_t) p[2] << 16 | - (uint64_t) p[3] << 24 | - (uint64_t) p[4] << 32 | - (uint64_t) p[5] << 40 | - (uint64_t) p[6] << 48 | - (uint64_t) p[7] << 56 ; -} - -uint64_t -siphash (const unsigned char key[16], const unsigned char *m, size_t len) -{ - uint64_t v0, v1, v2, v3; - uint64_t mi, k0, k1; - uint64_t last7; - size_t i, blocks; - - k0 = u8to64_le (key + 0); - k1 = u8to64_le (key + 8); - v0 = k0 ^ 0x736f6d6570736575ull; - v1 = k1 ^ 0x646f72616e646f6dull; - v2 = k0 ^ 0x6c7967656e657261ull; - v3 = k1 ^ 0x7465646279746573ull; - - last7 = (uint64_t) (len & 0xff) << 56; - -#define ROTL64(a,b) (((a)<<(b))|((a)>>(64-b))) - -#define COMPRESS \ - v0 += v1; v2 += v3; \ - v1 = ROTL64 (v1,13); v3 = ROTL64 (v3,16); \ - v1 ^= v0; v3 ^= v2; \ - v0 = ROTL64 (v0,32); \ - v2 += v1; v0 += v3; \ - v1 = ROTL64 (v1,17); v3 = ROTL64 (v3,21); \ - v1 ^= v2; v3 ^= v0; \ - v2 = ROTL64(v2,32); - - for (i = 0, blocks = (len & ~(size_t) 7); i < blocks; i += 8) - { - mi = u8to64_le (m + i); - v3 ^= mi; - COMPRESS - COMPRESS - v0 ^= mi; - } - - switch (len - blocks) - { - case 7: last7 |= (uint64_t) m[i + 6] << 48; - case 6: last7 |= (uint64_t) m[i + 5] << 40; - case 5: last7 |= (uint64_t) m[i + 4] << 32; - case 4: last7 |= (uint64_t) m[i + 3] << 24; - case 3: last7 |= (uint64_t) m[i + 2] << 16; - case 2: last7 |= (uint64_t) m[i + 1] << 8; - case 1: last7 |= (uint64_t) m[i + 0] ; - default:; - }; - v3 ^= last7; - COMPRESS - COMPRESS - v0 ^= last7; - v2 ^= 0xff; - COMPRESS - COMPRESS - COMPRESS - COMPRESS - - return v0 ^ v1 ^ v2 ^ v3; -} - diff --git a/src/siphash.h b/src/siphash.h deleted file mode 100644 index dca7c42..0000000 --- a/src/siphash.h +++ /dev/null @@ -1,10 +0,0 @@ -#ifndef SIPHASH_H -#define SIPHASH_H - -#include <stdint.h> -#include <stdlib.h> - -uint64_t siphash (const unsigned char key[16], - const unsigned char *m, size_t len); - -#endif // SIPHASH_H diff --git a/src/zyklonb.c b/src/zyklonb.c deleted file mode 100644 index c99b141..0000000 --- a/src/zyklonb.c +++ /dev/null @@ -1,1769 +0,0 @@ -/* - * zyklonb.c: the experimental IRC bot - * - * Copyright (c) 2014, Přemysl Janouch <p.janouch@gmail.com> - * All rights reserved. - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY - * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION - * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN - * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - * - */ - -#define PROGRAM_NAME "ZyklonB" -#define PROGRAM_VERSION "alpha" - -#include "common.c" - -// --- Configuration (application-specific) ------------------------------------ - -static struct config_item g_config_table[] = -{ - { "nickname", "ZyklonB", "IRC nickname" }, - { "username", "bot", "IRC user name" }, - { "realname", "ZyklonB IRC bot", "IRC real name/e-mail" }, - - { "irc_host", NULL, "Address of the IRC server" }, - { "irc_port", "6667", "Port of the IRC server" }, - { "ssl_use", "off", "Whether to use SSL" }, - { "ssl_cert", NULL, "Client SSL certificate (PEM)" }, - { "autojoin", NULL, "Channels to join on start" }, - { "reconnect", "on", "Whether to reconnect on error" }, - { "reconnect_delay", "5", "Time between reconnecting" }, - - { "prefix", ":", "The prefix for bot commands" }, - { "admin", NULL, "Host mask for administrators" }, - { "plugins", NULL, "The plugins to load on startup" }, - { "plugin_dir", NULL, "Where to search for plugins" }, - { "recover", "on", "Whether to re-launch on crash" }, - - { NULL, NULL, NULL } -}; - -// --- Application data -------------------------------------------------------- - -struct plugin_data -{ - LIST_HEADER (plugin_data) - struct bot_context *ctx; ///< Parent context - - char *name; ///< Plugin identifier - pid_t pid; ///< PID of the plugin process - - bool is_zombie; ///< Whether the child is a zombie - bool initialized; ///< Ready to exchange IRC messages - struct str queued_output; ///< Output queued up until initialized - - // Since we're doing non-blocking I/O, we need to queue up data so that - // we don't stall on plugins unnecessarily. - - int read_fd; ///< The read end of the comm. pipe - int write_fd; ///< The write end of the comm. pipe - - struct str read_buffer; ///< Unprocessed input - struct str write_buffer; ///< Output yet to be sent out -}; - -static void -plugin_data_init (struct plugin_data *self) -{ - memset (self, 0, sizeof *self); - - self->pid = -1; - str_init (&self->queued_output); - - self->read_fd = -1; - str_init (&self->read_buffer); - self->write_fd = -1; - str_init (&self->write_buffer); -} - -static void -plugin_data_free (struct plugin_data *self) -{ - soft_assert (self->pid == -1); - free (self->name); - - str_free (&self->read_buffer); - if (!soft_assert (self->read_fd == -1)) - xclose (self->read_fd); - - str_free (&self->write_buffer); - if (!soft_assert (self->write_fd == -1)) - xclose (self->write_fd); - - if (!self->initialized) - str_free (&self->queued_output); -} - -struct bot_context -{ - struct str_map config; ///< User configuration - regex_t *admin_re; ///< Regex to match our administrator - - int irc_fd; ///< Socket FD of the server - struct str read_buffer; ///< Input yet to be processed - bool irc_ready; ///< Whether we may send messages now - - SSL_CTX *ssl_ctx; ///< SSL context - SSL *ssl; ///< SSL connection - - struct plugin_data *plugins; ///< Linked list of plugins - struct str_map plugins_by_name; ///< Indexes @em plugins by their name - - struct poller poller; ///< Manages polled descriptors - bool quitting; ///< User requested quitting - bool polling; ///< The event loop is running -}; - -static void -bot_context_init (struct bot_context *self) -{ - str_map_init (&self->config); - self->config.free = free; - load_config_defaults (&self->config, g_config_table); - self->admin_re = NULL; - - self->irc_fd = -1; - str_init (&self->read_buffer); - self->irc_ready = false; - - self->ssl = NULL; - self->ssl_ctx = NULL; - - self->plugins = NULL; - str_map_init (&self->plugins_by_name); - - poller_init (&self->poller); - self->quitting = false; - self->polling = false; -} - -static void -bot_context_free (struct bot_context *self) -{ - str_map_free (&self->config); - if (self->admin_re) - regex_free (self->admin_re); - str_free (&self->read_buffer); - - // TODO: terminate the plugins properly before this is called - struct plugin_data *link, *tmp; - for (link = self->plugins; link; link = tmp) - { - tmp = link->next; - plugin_data_free (link); - free (link); - } - - if (self->irc_fd != -1) - xclose (self->irc_fd); - if (self->ssl) - SSL_free (self->ssl); - if (self->ssl_ctx) - SSL_CTX_free (self->ssl_ctx); - - str_map_free (&self->plugins_by_name); - poller_free (&self->poller); -} - -static void -irc_shutdown (struct bot_context *ctx) -{ - // Generally non-critical - if (ctx->ssl) - soft_assert (SSL_shutdown (ctx->ssl) != -1); - else - soft_assert (shutdown (ctx->irc_fd, SHUT_WR) == 0); -} - -static void -initiate_quit (struct bot_context *ctx) -{ - irc_shutdown (ctx); - ctx->quitting = true; -} - -static void -try_finish_quit (struct bot_context *ctx) -{ - if (!ctx->quitting) - return; - if (ctx->irc_fd == -1 && !ctx->plugins) - ctx->polling = false; -} - -static bool irc_send (struct bot_context *ctx, - const char *format, ...) ATTRIBUTE_PRINTF (2, 3); - -// XXX: is it okay to just ignore the return value and wait until we receive -// it in on_irc_readable()? -static bool -irc_send (struct bot_context *ctx, const char *format, ...) -{ - va_list ap; - - if (g_debug_mode) - { - fputs ("[IRC] <== \"", stderr); - va_start (ap, format); - vfprintf (stderr, format, ap); - va_end (ap); - fputs ("\"\n", stderr); - } - - if (!soft_assert (ctx->irc_fd != -1)) - return false; - - va_start (ap, format); - struct str str; - str_init (&str); - str_append_vprintf (&str, format, ap); - str_append (&str, "\r\n"); - va_end (ap); - - bool result = true; - if (ctx->ssl) - { - // TODO: call SSL_get_error() to detect if a clean shutdown has occured - if (SSL_write (ctx->ssl, str.str, str.len) != (int) str.len) - { - print_debug ("%s: %s: %s", __func__, "SSL_write", - ERR_error_string (ERR_get_error (), NULL)); - result = false; - } - } - else if (write (ctx->irc_fd, str.str, str.len) != (ssize_t) str.len) - { - print_debug ("%s: %s: %s", __func__, "write", strerror (errno)); - result = false; - } - - str_free (&str); - return result; -} - -static bool -irc_initialize_ssl (struct bot_context *ctx, struct error **e) -{ - ctx->ssl_ctx = SSL_CTX_new (SSLv23_client_method ()); - if (!ctx->ssl_ctx) - goto error_ssl_1; - // We don't care; some encryption is always better than no encryption - SSL_CTX_set_verify (ctx->ssl_ctx, SSL_VERIFY_NONE, NULL); - // XXX: maybe we should call SSL_CTX_set_options() for some workarounds - - ctx->ssl = SSL_new (ctx->ssl_ctx); - if (!ctx->ssl) - goto error_ssl_2; - - const char *ssl_cert = str_map_find (&ctx->config, "ssl_cert"); - if (ssl_cert) - { - char *path = resolve_config_filename (ssl_cert); - if (!path) - print_error ("%s: %s", "cannot open file", ssl_cert); - // XXX: perhaps we should read the file ourselves for better messages - else if (!SSL_use_certificate_file (ctx->ssl, path, SSL_FILETYPE_PEM)) - print_error ("%s: %s", "setting the SSL client certificate failed", - ERR_error_string (ERR_get_error (), NULL)); - free (path); - } - - SSL_set_connect_state (ctx->ssl); - if (!SSL_set_fd (ctx->ssl, ctx->irc_fd)) - goto error_ssl_3; - // Avoid SSL_write() returning SSL_ERROR_WANT_READ - SSL_set_mode (ctx->ssl, SSL_MODE_AUTO_RETRY); - if (SSL_connect (ctx->ssl) > 0) - return true; - -error_ssl_3: - SSL_free (ctx->ssl); - ctx->ssl = NULL; -error_ssl_2: - SSL_CTX_free (ctx->ssl_ctx); - ctx->ssl_ctx = NULL; -error_ssl_1: - // XXX: these error strings are really nasty; also there could be - // multiple errors on the OpenSSL stack. - error_set (e, "%s: %s", "could not initialize SSL", - ERR_error_string (ERR_get_error (), NULL)); - return false; -} - -static bool -irc_establish_connection (struct bot_context *ctx, - const char *host, const char *port, bool use_ssl, struct error **e) -{ - struct addrinfo gai_hints, *gai_result, *gai_iter; - memset (&gai_hints, 0, sizeof gai_hints); - - // We definitely want TCP. - gai_hints.ai_socktype = SOCK_STREAM; - - int err = getaddrinfo (host, port, &gai_hints, &gai_result); - if (err) - { - error_set (e, "%s: %s: %s", - "connection failed", "getaddrinfo", gai_strerror (err)); - return false; - } - - int sockfd; - for (gai_iter = gai_result; gai_iter; gai_iter = gai_iter->ai_next) - { - sockfd = socket (gai_iter->ai_family, - gai_iter->ai_socktype, gai_iter->ai_protocol); - if (sockfd == -1) - continue; - set_cloexec (sockfd); - - int yes = 1; - soft_assert (setsockopt (sockfd, SOL_SOCKET, SO_KEEPALIVE, - &yes, sizeof yes) != -1); - - const char *real_host = host; - - // Let's try to resolve the address back into a real hostname; - // we don't really need this, so we can let it quietly fail - char buf[NI_MAXHOST]; - err = getnameinfo (gai_iter->ai_addr, gai_iter->ai_addrlen, - buf, sizeof buf, NULL, 0, 0); - if (err) - print_debug ("%s: %s", "getnameinfo", gai_strerror (err)); - else - real_host = buf; - - // XXX: we shouldn't mix these statuses with `struct error'; choose 1! - print_status ("connecting to `%s:%s'...", real_host, port); - if (!connect (sockfd, gai_iter->ai_addr, gai_iter->ai_addrlen)) - break; - - xclose (sockfd); - } - - freeaddrinfo (gai_result); - - if (!gai_iter) - { - error_set (e, "connection failed"); - return false; - } - - ctx->irc_fd = sockfd; - if (use_ssl && !irc_initialize_ssl (ctx, e)) - { - xclose (ctx->irc_fd); - ctx->irc_fd = -1; - return false; - } - - print_status ("connection established"); - return true; -} - -// --- Signals ----------------------------------------------------------------- - -static int g_signal_pipe[2]; ///< A pipe used to signal... signals - -static struct str_vector - g_original_argv, ///< Original program arguments - g_recovery_env; ///< Environment for re-exec recovery - -/// Program termination has been requested by a signal -static volatile sig_atomic_t g_termination_requested; - -/// Points to startup reason location within `g_recovery_environment' -static char **g_startup_reason_location; -/// The environment variable used to pass the startup reason when re-executing -static const char g_startup_reason_str[] = "STARTUP_REASON"; - -static void -sigchld_handler (int signum) -{ - (void) signum; - - int original_errno = errno; - // Just so that the read end of the pipe wakes up the poller. - // NOTE: Linux has signalfd() and eventfd(), and the BSD's have kqueue. - // All of them are better than this approach, although platform-specific. - if (write (g_signal_pipe[1], "c", 1) == -1) - soft_assert (errno == EAGAIN); - errno = original_errno; -} - -static void -sigterm_handler (int signum) -{ - (void) signum; - - g_termination_requested = true; - - int original_errno = errno; - if (write (g_signal_pipe[1], "t", 1) == -1) - soft_assert (errno == EAGAIN); - errno = original_errno; -} - -static void -setup_signal_handlers (void) -{ - if (pipe (g_signal_pipe) == -1) - exit_fatal ("%s: %s", "pipe", strerror (errno)); - - set_cloexec (g_signal_pipe[0]); - set_cloexec (g_signal_pipe[1]); - - // So that the pipe cannot overflow; it would make write() block within - // the signal handler, which is something we really don't want to happen. - // The same holds true for read(). - set_blocking (g_signal_pipe[0], false); - set_blocking (g_signal_pipe[1], false); - - struct sigaction sa; - sa.sa_flags = SA_RESTART; - sa.sa_handler = sigchld_handler; - sigemptyset (&sa.sa_mask); - - if (sigaction (SIGCHLD, &sa, NULL) == -1) - exit_fatal ("sigaction: %s", strerror (errno)); - - signal (SIGPIPE, SIG_IGN); - - sa.sa_handler = sigterm_handler; - if (sigaction (SIGINT, &sa, NULL) == -1 - || sigaction (SIGTERM, &sa, NULL) == -1) - exit_fatal ("sigaction: %s", strerror (errno)); -} - -static void -translate_signal_info (int no, const char **name, int code, const char **reason) -{ - if (code == SI_USER) *reason = "signal sent by kill()"; - if (code == SI_QUEUE) *reason = "signal sent by sigqueue()"; - - switch (no) - { - case SIGILL: - *name = "SIGILL"; - if (code == ILL_ILLOPC) *reason = "illegal opcode"; - if (code == ILL_ILLOPN) *reason = "illegal operand"; - if (code == ILL_ILLADR) *reason = "illegal addressing mode"; - if (code == ILL_ILLTRP) *reason = "illegal trap"; - if (code == ILL_PRVOPC) *reason = "privileged opcode"; - if (code == ILL_PRVREG) *reason = "privileged register"; - if (code == ILL_COPROC) *reason = "coprocessor error"; - if (code == ILL_BADSTK) *reason = "internal stack error"; - break; - case SIGFPE: - *name = "SIGFPE"; - if (code == FPE_INTDIV) *reason = "integer divide by zero"; - if (code == FPE_INTOVF) *reason = "integer overflow"; - if (code == FPE_FLTDIV) *reason = "floating-point divide by zero"; - if (code == FPE_FLTOVF) *reason = "floating-point overflow"; - if (code == FPE_FLTUND) *reason = "floating-point underflow"; - if (code == FPE_FLTRES) *reason = "floating-point inexact result"; - if (code == FPE_FLTINV) *reason = "invalid floating-point operation"; - if (code == FPE_FLTSUB) *reason = "subscript out of range"; - break; - case SIGSEGV: - *name = "SIGSEGV"; - if (code == SEGV_MAPERR) - *reason = "address not mapped to object"; - if (code == SEGV_ACCERR) - *reason = "invalid permissions for mapped object"; - break; - case SIGBUS: - *name = "SIGBUS"; - if (code == BUS_ADRALN) *reason = "invalid address alignment"; - if (code == BUS_ADRERR) *reason = "nonexistent physical address"; - if (code == BUS_OBJERR) *reason = "object-specific hardware error"; - break; - default: - *name = NULL; - } -} - -static void -recovery_handler (int signum, siginfo_t *info, void *context) -{ - (void) context; - - // TODO: maybe try to force a core dump like this: if (fork() == 0) return; - // TODO: maybe we could even send "\r\nQUIT :reason\r\n" to the server. >_> - // As long as we're not connected via TLS, that is. - - const char *signal_name = NULL, *reason = NULL; - translate_signal_info (signum, &signal_name, info->si_code, &reason); - - char buf[128], numbuf[8]; - if (!signal_name) - { - snprintf (numbuf, sizeof numbuf, "%d", signum); - signal_name = numbuf; - } - - if (reason) - snprintf (buf, sizeof buf, "%s=%s: %s: %s", g_startup_reason_str, - "signal received", signal_name, reason); - else - snprintf (buf, sizeof buf, "%s=%s: %s", g_startup_reason_str, - "signal received", signal_name); - *g_startup_reason_location = buf; - - // TODO: maybe pregenerate the path, see the following for some other ways - // that would be illegal to do from within a signal handler: - // http://stackoverflow.com/a/1024937 - // http://stackoverflow.com/q/799679 - // Especially if we change the current working directory in the program. - // - // Note that I can just overwrite g_orig_argv[0]. - - // NOTE: our children will read EOF on the read ends of their pipes as a - // a result of O_CLOEXEC. That should be enough to make them terminate. - - char **argv = g_original_argv.vector, **argp = g_recovery_env.vector; - execve ("/proc/self/exe", argv, argp); // Linux - execve ("/proc/curproc/file", argv, argp); // BSD - execve ("/proc/curproc/exe", argv, argp); // BSD - execve ("/proc/self/path/a.out", argv, argp); // Solaris - execve (argv[0], argv, argp); // unreliable fallback - - // Let's just crash - perror ("execve"); - signal (signum, SIG_DFL); - raise (signum); -} - -static void -prepare_recovery_environment (void) -{ - str_vector_init (&g_recovery_env); - str_vector_add_vector (&g_recovery_env, environ); - - // Prepare a location within the environment where we will put the startup - // (or maybe rather restart) reason in case of an irrecoverable error. - char **iter; - for (iter = g_recovery_env.vector; *iter; iter++) - { - const size_t len = sizeof g_startup_reason_str - 1; - if (!strncmp (*iter, g_startup_reason_str, len) && (*iter)[len] == '=') - break; - } - - if (iter) - g_startup_reason_location = iter; - else - { - str_vector_add (&g_recovery_env, ""); - g_startup_reason_location = - g_recovery_env.vector + g_recovery_env.len - 1; - } -} - -static void -setup_recovery_handler (struct bot_context *ctx) -{ - const char *recover_str = str_map_find (&ctx->config, "recover"); - hard_assert (recover_str != NULL); // We have a default value for this - - bool recover; - if (!set_boolean_if_valid (&recover, recover_str)) - { - print_error ("invalid configuration value for `%s'", "recover"); - exit (EXIT_FAILURE); - } - if (!recover) - return; - - // Make sure these signals aren't blocked, otherwise we would be unable - // to handle them, making the critical conditions fatal. - sigset_t mask; - sigemptyset (&mask); - sigaddset (&mask, SIGSEGV); - sigaddset (&mask, SIGBUS); - sigaddset (&mask, SIGFPE); - sigaddset (&mask, SIGILL); - sigprocmask (SIG_UNBLOCK, &mask, NULL); - - struct sigaction sa; - sa.sa_flags = SA_SIGINFO; - sa.sa_sigaction = recovery_handler; - sigemptyset (&sa.sa_mask); - - prepare_recovery_environment (); - - // TODO: also handle SIGABRT... or avoid doing abort() in the first place? - if (sigaction (SIGSEGV, &sa, NULL) == -1 - || sigaction (SIGBUS, &sa, NULL) == -1 - || sigaction (SIGFPE, &sa, NULL) == -1 - || sigaction (SIGILL, &sa, NULL) == -1) - print_error ("sigaction: %s", strerror (errno)); -} - -// --- Plugins ----------------------------------------------------------------- - -/// The name of the special IRC command for interprocess communication -static const char *plugin_ipc_command = "ZYKLONB"; - -static struct plugin_data * -plugin_find_by_pid (struct bot_context *ctx, pid_t pid) -{ - struct plugin_data *iter; - for (iter = ctx->plugins; iter; iter = iter->next) - if (iter->pid == pid) - return iter; - return NULL; -} - -static bool -plugin_zombify (struct plugin_data *plugin) -{ - if (plugin->is_zombie) - return false; - - // FIXME: make sure that we don't remove entries from the poller while we - // still may have stuff to read; maybe just check that the read pipe is - // empty before closing it... and then on EOF check if `pid == -1' and - // only then dispose of it (it'd be best to simulate that both of these - // cases may happen). - ssize_t poller_idx = - poller_find_by_fd (&plugin->ctx->poller, plugin->write_fd); - if (poller_idx != -1) - poller_remove_at_index (&plugin->ctx->poller, poller_idx); - - // TODO: try to flush the write buffer (non-blocking)? - - // The plugin should terminate itself after it receives EOF. - xclose (plugin->write_fd); - plugin->write_fd = -1; - - // Make it a pseudo-anonymous zombie. In this state we process any - // remaining commands it attempts to send to us before it finally dies. - str_map_set (&plugin->ctx->plugins_by_name, plugin->name, NULL); - plugin->is_zombie = true; - return true; -} - -static void -on_plugin_writable (const struct pollfd *fd, struct plugin_data *plugin) -{ - struct bot_context *ctx = plugin->ctx; - struct str *buf = &plugin->write_buffer; - size_t written_total = 0; - - if (fd->revents & ~(POLLOUT | POLLHUP | POLLERR)) - print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents); - - while (written_total != buf->len) - { - ssize_t n_written = write (fd->fd, buf->str + written_total, - buf->len - written_total); - - if (n_written < 0) - { - if (errno == EAGAIN) - break; - if (errno == EINTR) - continue; - - soft_assert (errno == EPIPE); - // Zombies shouldn't get dispatched for writability - hard_assert (!plugin->is_zombie); - - print_debug ("%s: %s", "write", strerror (errno)); - print_error ("failure on writing to plugin `%s'," - " therefore I'm unloading it", plugin->name); - plugin_zombify (plugin); - break; - } - - // This may be equivalent to EAGAIN on some implementations - if (n_written == 0) - break; - - written_total += n_written; - } - - if (written_total != 0) - str_remove_slice (buf, 0, written_total); - - if (buf->len == 0) - { - // Everything has been written, there's no need to end up in here again - ssize_t index = poller_find_by_fd (&ctx->poller, fd->fd); - if (index != -1) - poller_remove_at_index (&ctx->poller, index); - } -} - -static void -plugin_queue_write (struct plugin_data *plugin) -{ - if (plugin->is_zombie) - return; - - // Don't let the write buffer grow infinitely. If there's a ton of data - // waiting to be processed by the plugin, it usually means there's something - // wrong with it (such as someone stopping the process). - if (plugin->write_buffer.len >= (1 << 20)) - { - print_warning ("plugin `%s' does not seem to process messages fast" - " enough, I'm unloading it", plugin->name); - plugin_zombify (plugin); - return; - } - - poller_set (&plugin->ctx->poller, plugin->write_fd, POLLOUT, - (poller_dispatcher_func) on_plugin_writable, plugin); -} - -static void -plugin_send (struct plugin_data *plugin, const char *format, ...) - ATTRIBUTE_PRINTF (2, 3); - -static void -plugin_send (struct plugin_data *plugin, const char *format, ...) -{ - va_list ap; - - if (g_debug_mode) - { - fprintf (stderr, "[%s] <-- \"", plugin->name); - va_start (ap, format); - vfprintf (stderr, format, ap); - va_end (ap); - fputs ("\"\n", stderr); - } - - va_start (ap, format); - str_append_vprintf (&plugin->write_buffer, format, ap); - va_end (ap); - str_append (&plugin->write_buffer, "\r\n"); - - plugin_queue_write (plugin); -} - -static void -plugin_process_message (const struct irc_message *msg, - const char *raw, void *user_data) -{ - struct plugin_data *plugin = user_data; - struct bot_context *ctx = plugin->ctx; - - if (g_debug_mode) - fprintf (stderr, "[%s] --> \"%s\"\n", plugin->name, raw); - - if (!strcasecmp (msg->command, plugin_ipc_command)) - { - // Replies are sent in the order in which they came in, so there's - // no need to attach a special identifier to them. It might be - // desirable in some cases, though. - - if (msg->params.len < 1) - return; - - const char *command = msg->params.vector[0]; - if (!plugin->initialized && !strcasecmp (command, "register")) - { - // Register for relaying of IRC traffic - plugin->initialized = true; - - // Flush any queued up traffic here. The point of queuing it in - // the first place is so that we don't have to wait for plugin - // initialization during startup. - // - // Note that if we start filtering data coming to the plugins e.g. - // based on what it tells us upon registration, we might need to - // filter `queued_output' as well. - str_append_str (&plugin->write_buffer, &plugin->queued_output); - str_free (&plugin->queued_output); - - // NOTE: this may trigger the buffer length check - plugin_queue_write (plugin); - } - else if (!strcasecmp (command, "get_config")) - { - if (msg->params.len < 2) - return; - - const char *value = - str_map_find (&ctx->config, msg->params.vector[1]); - // TODO: escape the value (although there's no need to ATM) - plugin_send (plugin, "%s :%s", - plugin_ipc_command, value ? value : ""); - } - else if (!strcasecmp (command, "print")) - { - if (msg->params.len < 2) - return; - - printf ("%s\n", msg->params.vector[1]); - } - } - else if (plugin->initialized && ctx->irc_ready) - { - // Pass everything else through to the IRC server - // XXX: when the server isn't ready yet, these messages get silently - // discarded, which shouldn't pose a problem most of the time. - // Perhaps we could send a "connected" notification on `register' - // if `irc_ready' is true, or after it becomes true later, so that - // plugins know when to start sending unprovoked IRC messages. - // XXX: another case is when the connection gets interrupted and the - // plugin tries to send something back while we're reconnecting. - // For that we might set up a global buffer that gets flushed out - // after `irc_ready' becomes true. Note that there is always some - // chance of messages getting lost without us even noticing it. - irc_send (ctx, "%s", raw); - } -} - -static void -on_plugin_readable (const struct pollfd *fd, struct plugin_data *plugin) -{ - if (fd->revents & ~(POLLIN | POLLHUP | POLLERR)) - print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents); - - // TODO: see if I can reuse irc_fill_read_buffer() - struct str *buf = &plugin->read_buffer; - while (true) - { - str_ensure_space (buf, 512 + 1); - ssize_t n_read = read (fd->fd, buf->str + buf->len, - buf->alloc - buf->len - 1); - - if (n_read < 0) - { - if (errno == EAGAIN) - break; - if (soft_assert (errno == EINTR)) - continue; - - if (!plugin->is_zombie) - { - print_error ("failure on reading from plugin `%s'," - " therefore I'm unloading it", plugin->name); - plugin_zombify (plugin); - } - return; - } - - // EOF; hopefully it will die soon (maybe it already has) - if (n_read == 0) - break; - - buf->str[buf->len += n_read] = '\0'; - if (buf->len >= (1 << 20)) - { - // XXX: this isn't really the best flood prevention mechanism, - // but it wasn't even supposed to be one. - if (plugin->is_zombie) - { - print_error ("a zombie of plugin `%s' is trying to flood us," - " therefore I'm killing it", plugin->name); - kill (plugin->pid, SIGKILL); - } - else - { - print_error ("plugin `%s' seems to spew out data frantically," - " therefore I'm unloading it", plugin->name); - plugin_zombify (plugin); - } - return; - } - } - - irc_process_buffer (buf, plugin_process_message, plugin); -} - -static bool -is_valid_plugin_name (const char *name) -{ - if (!*name) - return false; - for (const char *p = name; *p; p++) - if (!isgraph (*p) || *p == '/') - return false; - return true; -} - -static bool -plugin_load (struct bot_context *ctx, const char *name, struct error **e) -{ - const char *plugin_dir = str_map_find (&ctx->config, "plugin_dir"); - if (!plugin_dir) - { - error_set (e, "plugin directory not set"); - return false; - } - - if (!is_valid_plugin_name (name)) - { - error_set (e, "invalid plugin name"); - return false; - } - - if (str_map_find (&ctx->plugins_by_name, name)) - { - error_set (e, "the plugin has already been loaded"); - return false; - } - - int stdin_pipe[2]; - if (pipe (stdin_pipe) == -1) - { - error_set (e, "%s: %s: %s", - "failed to load the plugin", "pipe", strerror (errno)); - goto fail_1; - } - - int stdout_pipe[2]; - if (pipe (stdout_pipe) == -1) - { - error_set (e, "%s: %s: %s", - "failed to load the plugin", "pipe", strerror (errno)); - goto fail_2; - } - - set_cloexec (stdin_pipe[1]); - set_cloexec (stdout_pipe[0]); - - pid_t pid = fork (); - if (pid == -1) - { - error_set (e, "%s: %s: %s", - "failed to load the plugin", "fork", strerror (errno)); - goto fail_3; - } - - if (pid == 0) - { - // Redirect the child's stdin and stdout to the pipes - hard_assert (dup2 (stdin_pipe[0], STDIN_FILENO) != -1); - hard_assert (dup2 (stdout_pipe[1], STDOUT_FILENO) != -1); - - xclose (stdin_pipe[0]); - xclose (stdout_pipe[1]); - - struct str pathname; - str_init (&pathname); - str_append (&pathname, plugin_dir); - str_append_c (&pathname, '/'); - str_append (&pathname, name); - - // Restore some of the signal handling - signal (SIGPIPE, SIG_DFL); - - char *const argv[] = { pathname.str, NULL }; - execve (argv[0], argv, environ); - - // We will collect the failure later via SIGCHLD - print_error ("%s: %s: %s", - "failed to load the plugin", "exec", strerror (errno)); - _exit (EXIT_FAILURE); - } - - xclose (stdin_pipe[0]); - xclose (stdout_pipe[1]); - - set_blocking (stdout_pipe[0], false); - set_blocking (stdin_pipe[1], false); - - struct plugin_data *plugin = xmalloc (sizeof *plugin); - plugin_data_init (plugin); - plugin->ctx = ctx; - plugin->pid = pid; - plugin->name = xstrdup (name); - plugin->read_fd = stdout_pipe[0]; - plugin->write_fd = stdin_pipe[1]; - - LIST_PREPEND (ctx->plugins, plugin); - str_map_set (&ctx->plugins_by_name, name, plugin); - - poller_set (&ctx->poller, stdout_pipe[0], POLLIN, - (poller_dispatcher_func) on_plugin_readable, plugin); - return true; - -fail_3: - xclose (stdout_pipe[0]); - xclose (stdout_pipe[1]); -fail_2: - xclose (stdin_pipe[0]); - xclose (stdin_pipe[1]); -fail_1: - return false; -} - -static bool -plugin_unload (struct bot_context *ctx, const char *name, struct error **e) -{ - struct plugin_data *plugin = str_map_find (&ctx->plugins_by_name, name); - - if (!plugin) - { - error_set (e, "no such plugin is loaded"); - return false; - } - - plugin_zombify (plugin); - - // TODO: add a `kill zombies' command to forcefully get rid of processes - // that do not understand the request. - // TODO: set a timeout before we go for a kill automatically (and if this - // was a reload request, try to bring the plugin back up) - return true; -} - -static void -plugin_load_all_from_config (struct bot_context *ctx) -{ - const char *plugin_list = str_map_find (&ctx->config, "plugins"); - if (!plugin_list) - return; - - struct str_vector plugins; - str_vector_init (&plugins); - - split_str_ignore_empty (plugin_list, ',', &plugins); - for (size_t i = 0; i < plugins.len; i++) - { - char *name = strip_str_in_place (plugins.vector[i], " "); - - struct error *e = NULL; - if (!plugin_load (ctx, name, &e)) - { - print_error ("plugin `%s' failed to load: %s", name, e->message); - error_free (e); - } - } - - str_vector_free (&plugins); -} - -// --- Main program ------------------------------------------------------------ - -static bool -parse_bot_command (const char *s, const char *command, const char **following) -{ - size_t command_len = strlen (command); - if (strncasecmp (s, command, command_len)) - return false; - s += command_len; - - // Expect a word boundary, so that we don't respond to invalid things - if (isalnum (*s)) - return false; - - // Ignore any initial spaces; the rest is the command's argument - while (isblank (*s)) - s++; - *following = s; - return true; -} - -static void -split_bot_command_argument_list (const char *arguments, struct str_vector *out) -{ - split_str_ignore_empty (arguments, ',', out); - for (size_t i = 0; i < out->len; ) - { - if (!*strip_str_in_place (out->vector[i], " \t")) - str_vector_remove (out, i); - else - i++; - } -} - -static bool -is_private_message (const struct irc_message *msg) -{ - hard_assert (msg->params.len); - return !strchr ("#&+!", *msg->params.vector[0]); -} - -static bool -is_sent_by_admin (struct bot_context *ctx, const struct irc_message *msg) -{ - // No administrator set -> everyone is an administrator - if (!ctx->admin_re) - return true; - return regexec (ctx->admin_re, msg->prefix, 0, NULL, 0) != REG_NOMATCH; -} - -static void respond_to_user (struct bot_context *ctx, const struct - irc_message *msg, const char *format, ...) ATTRIBUTE_PRINTF (3, 4); - -static void -respond_to_user (struct bot_context *ctx, const struct irc_message *msg, - const char *format, ...) -{ - if (!soft_assert (msg->prefix && msg->params.len)) - return; - - char nick[strcspn (msg->prefix, "!") + 1]; - strncpy (nick, msg->prefix, sizeof nick - 1); - nick[sizeof nick - 1] = '\0'; - - struct str text; - va_list ap; - - str_init (&text); - va_start (ap, format); - str_append_vprintf (&text, format, ap); - va_end (ap); - - if (is_private_message (msg)) - irc_send (ctx, "PRIVMSG %s :%s", nick, text.str); - else - irc_send (ctx, "PRIVMSG %s :%s: %s", - msg->params.vector[0], nick, text.str); - - str_free (&text); -} - -static void -process_plugin_load (struct bot_context *ctx, - const struct irc_message *msg, const char *name) -{ - struct error *e = NULL; - if (plugin_load (ctx, name, &e)) - respond_to_user (ctx, msg, "plugin `%s' queued for loading", name); - else - { - respond_to_user (ctx, msg, "plugin `%s' could not be loaded: %s", - name, e->message); - error_free (e); - } -} - -static void -process_plugin_unload (struct bot_context *ctx, - const struct irc_message *msg, const char *name) -{ - struct error *e = NULL; - if (plugin_unload (ctx, name, &e)) - respond_to_user (ctx, msg, "plugin `%s' unloaded", name); - else - { - respond_to_user (ctx, msg, "plugin `%s' could not be unloaded: %s", - name, e->message); - error_free (e); - } -} - -static void -process_plugin_reload (struct bot_context *ctx, - const struct irc_message *msg, const char *name) -{ - // So far the only error that can occur is that the plugin hasn't been - // loaded, which in this case doesn't really matter. - plugin_unload (ctx, name, NULL); - - process_plugin_load (ctx, msg, name); -} - -static void -process_privmsg (struct bot_context *ctx, const struct irc_message *msg) -{ - if (!is_sent_by_admin (ctx, msg)) - return; - if (msg->params.len < 2) - return; - - const char *prefix = str_map_find (&ctx->config, "prefix"); - hard_assert (prefix != NULL); // We have a default value for this - - // For us to recognize the command, it has to start with the prefix, - // with the exception of PM's sent directly to us. - const char *text = msg->params.vector[1]; - if (!strncmp (text, prefix, strlen (prefix))) - text += strlen (prefix); - else if (!is_private_message (msg)) - return; - - const char *following; - struct str_vector list; - str_vector_init (&list); - - if (parse_bot_command (text, "quote", &following)) - // This seems to replace tons of random stupid commands - irc_send (ctx, "%s", following); - else if (parse_bot_command (text, "quit", &following)) - { - // We actually need this command (instead of just `quote') because we - // could try to reconnect to the server automatically otherwise. - if (*following) - irc_send (ctx, "QUIT :%s", following); - else - irc_send (ctx, "QUIT"); - initiate_quit (ctx); - } - else if (parse_bot_command (text, "status", &following)) - { - struct str report; - str_init (&report); - - const char *reason = getenv (g_startup_reason_str); - if (!reason) - reason = "launched normally"; - str_append_printf (&report, "\x02startup reason:\x0f %s, ", reason); - - str_append (&report, "\x02plugins:\x0f "); - size_t zombies = 0; - for (struct plugin_data *plugin = ctx->plugins; - plugin; plugin = plugin->next) - { - if (plugin->is_zombie) - zombies++; - else - str_append_printf (&report, "%s, ", plugin->name); - } - if (!ctx->plugins) - str_append (&report, "\x02none\x0f, "); - str_append_printf (&report, "\x02zombies:\x0f %zu", zombies); - - respond_to_user (ctx, msg, "%s", report.str); - str_free (&report); - } - else if (parse_bot_command (text, "load", &following)) - { - split_bot_command_argument_list (following, &list); - for (size_t i = 0; i < list.len; i++) - process_plugin_load (ctx, msg, list.vector[i]); - } - else if (parse_bot_command (text, "reload", &following)) - { - split_bot_command_argument_list (following, &list); - for (size_t i = 0; i < list.len; i++) - process_plugin_reload (ctx, msg, list.vector[i]); - } - else if (parse_bot_command (text, "unload", &following)) - { - split_bot_command_argument_list (following, &list); - for (size_t i = 0; i < list.len; i++) - process_plugin_unload (ctx, msg, list.vector[i]); - } - - str_vector_free (&list); -} - -static void -irc_forward_message_to_plugins (struct bot_context *ctx, const char *raw) -{ - // For consistency with plugin_process_message() - if (!ctx->irc_ready) - return; - - for (struct plugin_data *plugin = ctx->plugins; - plugin; plugin = plugin->next) - { - if (plugin->is_zombie) - continue; - - if (plugin->initialized) - plugin_send (plugin, "%s", raw); - else - // TODO: make sure that this buffer doesn't get too large either - str_append_printf (&plugin->queued_output, "%s\r\n", raw); - } -} - -static void -irc_process_message (const struct irc_message *msg, - const char *raw, void *user_data) -{ - struct bot_context *ctx = user_data; - if (g_debug_mode) - fprintf (stderr, "[%s] ==> \"%s\"\n", "IRC", raw); - - // This should be as minimal as possible, I don't want to have the whole bot - // written in C, especially when I have this overengineered plugin system. - // Therefore the very basic functionality only. - // - // I should probably even rip out the autojoin... - - irc_forward_message_to_plugins (ctx, raw); - - if (!strcasecmp (msg->command, "PING")) - { - if (msg->params.len) - irc_send (ctx, "PONG :%s", msg->params.vector[0]); - else - irc_send (ctx, "PONG"); - } - else if (!ctx->irc_ready && (!strcasecmp (msg->command, "MODE") - || !strcasecmp (msg->command, "376") // RPL_ENDOFMOTD - || !strcasecmp (msg->command, "422"))) // ERR_NOMOTD - { - print_status ("successfully connected"); - ctx->irc_ready = true; - - const char *autojoin = str_map_find (&ctx->config, "autojoin"); - if (autojoin) - irc_send (ctx, "JOIN :%s", autojoin); - } - else if (!strcasecmp (msg->command, "PRIVMSG")) - process_privmsg (ctx, msg); -} - -enum irc_read_result -{ - IRC_READ_OK, ///< Some data were read successfully - IRC_READ_EOF, ///< The server has closed connection - IRC_READ_AGAIN, ///< No more data at the moment - IRC_READ_ERROR ///< General connection failure -}; - -static enum irc_read_result -irc_fill_read_buffer_ssl (struct bot_context *ctx, struct str *buf) -{ - int n_read; -start: - n_read = SSL_read (ctx->ssl, buf->str + buf->len, - buf->alloc - buf->len - 1 /* null byte */); - - const char *error_info = NULL; - switch (xssl_get_error (ctx->ssl, n_read, &error_info)) - { - case SSL_ERROR_NONE: - buf->str[buf->len += n_read] = '\0'; - return IRC_READ_OK; - case SSL_ERROR_ZERO_RETURN: - return IRC_READ_EOF; - case SSL_ERROR_WANT_READ: - return IRC_READ_AGAIN; - case SSL_ERROR_WANT_WRITE: - { - // Let it finish the handshake as we don't poll for writability; - // any errors are to be collected by SSL_read() in the next iteration - struct pollfd pfd = { .fd = ctx->irc_fd, .events = POLLOUT }; - soft_assert (poll (&pfd, 1, 0) > 0); - goto start; - } - case XSSL_ERROR_TRY_AGAIN: - goto start; - default: - print_debug ("%s: %s: %s", __func__, "SSL_read", error_info); - return IRC_READ_ERROR; - } -} - -static enum irc_read_result -irc_fill_read_buffer (struct bot_context *ctx, struct str *buf) -{ - ssize_t n_read; -start: - n_read = recv (ctx->irc_fd, buf->str + buf->len, - buf->alloc - buf->len - 1 /* null byte */, 0); - - if (n_read > 0) - { - buf->str[buf->len += n_read] = '\0'; - return IRC_READ_OK; - } - if (n_read == 0) - return IRC_READ_EOF; - - if (errno == EAGAIN) - return IRC_READ_AGAIN; - if (errno == EINTR) - goto start; - - print_debug ("%s: %s: %s", __func__, "recv", strerror (errno)); - return IRC_READ_ERROR; -} - -static bool irc_connect (struct bot_context *ctx, struct error **e); - -static void -irc_try_reconnect (struct bot_context *ctx) -{ - if (!soft_assert (ctx->irc_fd == -1)) - return; - - const char *reconnect_str = str_map_find (&ctx->config, "reconnect"); - hard_assert (reconnect_str != NULL); // We have a default value for this - - bool reconnect; - if (!set_boolean_if_valid (&reconnect, reconnect_str)) - { - print_fatal ("invalid configuration value for `%s'", "recover"); - try_finish_quit (ctx); - return; - } - if (!reconnect) - return; - - const char *delay_str = str_map_find (&ctx->config, "reconnect_delay"); - hard_assert (delay_str != NULL); // We have a default value for this - - unsigned long delay; - if (!xstrtoul (&delay, delay_str, 10)) - { - print_error ("invalid configuration value for `%s'", - "reconnect_delay"); - delay = 0; - } - - while (true) - { - // TODO: this would be better suited by a timeout event; - // remember to update try_finish_quit() etc. to reflect this - print_status ("trying to reconnect in %ld seconds...", delay); - sleep (delay); - - struct error *e = NULL; - if (irc_connect (ctx, &e)) - break; - - print_error ("%s", e->message); - error_free (e); - } - - // TODO: inform plugins about the new connection -} - -static void -on_irc_disconnected (struct bot_context *ctx) -{ - // Get rid of the dead socket etc. - if (ctx->ssl) - { - SSL_free (ctx->ssl); - ctx->ssl = NULL; - SSL_CTX_free (ctx->ssl_ctx); - ctx->ssl_ctx = NULL; - } - - ssize_t i = poller_find_by_fd (&ctx->poller, ctx->irc_fd); - if (i != -1) - poller_remove_at_index (&ctx->poller, i); - - xclose (ctx->irc_fd); - ctx->irc_fd = -1; - ctx->irc_ready = false; - - // TODO: inform plugins about the disconnect event - - if (ctx->quitting) - { - // Unload all plugins - // TODO: wait for a few seconds and then send SIGKILL to all plugins - for (struct plugin_data *plugin = ctx->plugins; - plugin; plugin = plugin->next) - plugin_zombify (plugin); - - try_finish_quit (ctx); - return; - } - - irc_try_reconnect (ctx); -} - -static void -on_irc_readable (const struct pollfd *fd, struct bot_context *ctx) -{ - if (fd->revents & ~(POLLIN | POLLHUP | POLLERR)) - print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents); - - (void) set_blocking (ctx->irc_fd, false); - - struct str *buf = &ctx->read_buffer; - enum irc_read_result (*fill_buffer)(struct bot_context *, struct str *) - = ctx->ssl - ? irc_fill_read_buffer_ssl - : irc_fill_read_buffer; - bool disconnected = false; - while (true) - { - str_ensure_space (buf, 512); - switch (fill_buffer (ctx, buf)) - { - case IRC_READ_AGAIN: - goto end; - case IRC_READ_ERROR: - print_error ("reading from the IRC server failed"); - disconnected = true; - goto end; - case IRC_READ_EOF: - print_status ("the IRC server closed the connection"); - disconnected = true; - goto end; - case IRC_READ_OK: - break; - } - - if (buf->len >= (1 << 20)) - { - print_error ("the IRC server seems to spew out data frantically"); - irc_shutdown (ctx); - goto end; - } - } -end: - (void) set_blocking (ctx->irc_fd, true); - irc_process_buffer (buf, irc_process_message, ctx); - - if (disconnected) - on_irc_disconnected (ctx); -} - -static bool -irc_connect (struct bot_context *ctx, struct error **e) -{ - const char *irc_host = str_map_find (&ctx->config, "irc_host"); - const char *irc_port = str_map_find (&ctx->config, "irc_port"); - const char *ssl_use_str = str_map_find (&ctx->config, "ssl_use"); - - const char *nickname = str_map_find (&ctx->config, "nickname"); - const char *username = str_map_find (&ctx->config, "username"); - const char *realname = str_map_find (&ctx->config, "realname"); - - // We have a default value for these - hard_assert (irc_port && ssl_use_str); - hard_assert (nickname && username && realname); - - // TODO: again, get rid of `struct error' in here. The question is: how - // do we tell our caller that he should not try to reconnect? - if (!irc_host) - { - error_set (e, "no hostname specified in configuration"); - return false; - } - - bool use_ssl; - if (!set_boolean_if_valid (&use_ssl, ssl_use_str)) - { - error_set (e, "invalid configuration value for `%s'", "use_ssl"); - return false; - } - - if (!irc_establish_connection (ctx, irc_host, irc_port, use_ssl, e)) - return false; - - // TODO: set a timeout on the socket, something like 30 minutes, then we - // should ideally send a PING... or just forcefully reconnect. - // - // TODO: in exec try: 1/ set blocking, 2/ setsockopt() SO_LINGER, - // (struct linger) { .l_onoff = true; .l_linger = 1 /* 1s should do */; } - // 3/ /* O_CLOEXEC */ But only if the QUIT message proves unreliable. - poller_set (&ctx->poller, ctx->irc_fd, POLLIN, - (poller_dispatcher_func) on_irc_readable, ctx); - - // TODO: probably check for errors from these calls as well - irc_send (ctx, "NICK %s", nickname); - irc_send (ctx, "USER %s 8 * :%s", username, realname); - return true; -} - -static bool -load_admin_regex (struct bot_context *ctx) -{ - hard_assert (!ctx->admin_re); - const char *admin = str_map_find (&ctx->config, "admin"); - - if (!admin) - return true; - - struct error *e = NULL; - ctx->admin_re = regex_compile (admin, REG_EXTENDED | REG_NOSUB, &e); - if (!e) - return true; - - print_error ("invalid configuration value for `%s': %s", - "admin", e->message); - error_free (e); - return false; -} - -static void -on_signal_pipe_readable (const struct pollfd *fd, struct bot_context *ctx) -{ - char *dummy; - (void) read (fd->fd, &dummy, 1); - - // XXX: do we need to check if we have a connection? - if (g_termination_requested && !ctx->quitting) - { - irc_send (ctx, "QUIT :Terminated by signal"); - initiate_quit (ctx); - } - - // Reap all dead children (since the pipe may overflow, we ask waitpid() - // to return all the zombies it knows about). - while (true) - { - int status; - pid_t zombie = waitpid (-1, &status, WNOHANG); - - if (zombie == -1) - { - // No children to wait on - if (errno == ECHILD) - break; - - hard_assert (errno == EINTR); - continue; - } - - if (zombie == 0) - break; - - struct plugin_data *plugin = plugin_find_by_pid (ctx, zombie); - // Something has died but we don't recognize it (re-exec?) - if (!soft_assert (plugin != NULL)) - continue; - - // TODO: callbacks on children death, so that we may tell the user - // "plugin `name' died like a dirty jewish pig"; use `status' - if (!plugin->is_zombie && WIFSIGNALED (status)) - { - const char *notes = ""; -#ifdef WCOREDUMP - if (WCOREDUMP (status)) - notes = " (core dumped)"; -#endif - print_warning ("Plugin `%s' died from signal %d%s", - plugin->name, WTERMSIG (status), notes); - } - - // Let's go through the zombie state to simplify things a bit - // TODO: might not be a completely bad idea to restart the plugin - plugin_zombify (plugin); - - plugin->pid = -1; - - ssize_t poller_idx = poller_find_by_fd (&ctx->poller, plugin->read_fd); - if (poller_idx != -1) - poller_remove_at_index (&ctx->poller, poller_idx); - - xclose (plugin->read_fd); - plugin->read_fd = -1; - - LIST_UNLINK (ctx->plugins, plugin); - plugin_data_free (plugin); - free (plugin); - - // Living child processes block us from quitting - try_finish_quit (ctx); - } -} - -static void -print_usage (const char *program_name) -{ - fprintf (stderr, - "Usage: %s [OPTION]...\n" - "Experimental IRC bot.\n" - "\n" - " -d, --debug run in debug mode\n" - " -h, --help display this help and exit\n" - " -V, --version output version information and exit\n" - " --write-default-cfg [filename]\n" - " write a default configuration file and exit\n", - program_name); -} - -int -main (int argc, char *argv[]) -{ - const char *invocation_name = argv[0]; - str_vector_init (&g_original_argv); - str_vector_add_vector (&g_original_argv, argv); - - static struct option opts[] = - { - { "debug", no_argument, NULL, 'd' }, - { "help", no_argument, NULL, 'h' }, - { "version", no_argument, NULL, 'V' }, - { "write-default-cfg", optional_argument, NULL, 'w' }, - { NULL, 0, NULL, 0 } - }; - - while (1) - { - int c, opt_index; - - c = getopt_long (argc, argv, "dhV", opts, &opt_index); - if (c == -1) - break; - - switch (c) - { - case 'd': - g_debug_mode = true; - break; - case 'h': - print_usage (invocation_name); - exit (EXIT_SUCCESS); - case 'V': - printf (PROGRAM_NAME " " PROGRAM_VERSION "\n"); - exit (EXIT_SUCCESS); - case 'w': - call_write_default_config (optarg, g_config_table); - exit (EXIT_SUCCESS); - default: - print_error ("wrong options"); - exit (EXIT_FAILURE); - } - } - - print_status (PROGRAM_NAME " " PROGRAM_VERSION " starting"); - setup_signal_handlers (); - - SSL_library_init (); - atexit (EVP_cleanup); - SSL_load_error_strings (); - // XXX: ERR_load_BIO_strings()? Anything else? - atexit (ERR_free_strings); - - struct bot_context ctx; - bot_context_init (&ctx); - - struct error *e = NULL; - if (!read_config_file (&ctx.config, &e)) - { - print_error ("error loading configuration: %s", e->message); - error_free (e); - exit (EXIT_FAILURE); - } - - setup_recovery_handler (&ctx); - poller_set (&ctx.poller, g_signal_pipe[0], POLLIN, - (poller_dispatcher_func) on_signal_pipe_readable, &ctx); - - plugin_load_all_from_config (&ctx); - if (!load_admin_regex (&ctx)) - exit (EXIT_FAILURE); - if (!irc_connect (&ctx, &e)) - { - print_error ("%s", e->message); - error_free (e); - exit (EXIT_FAILURE); - } - - // TODO: clean re-exec support; to save the state I can either use argv, - // argp, or I can create a temporary file, unlink it and use the FD - // (mkstemp() on a `struct str' constructed from XDG_RUNTIME_DIR, TMPDIR - // or /tmp as a last resort + PROGRAM_NAME + ".XXXXXX" -> unlink(); - // remember to use O_CREAT | O_EXCL). The state needs to be versioned. - // Unfortunately I cannot de/serialize SSL state. - - ctx.polling = true; - while (ctx.polling) - poller_run (&ctx.poller); - - bot_context_free (&ctx); - str_vector_free (&g_original_argv); - return EXIT_SUCCESS; -} - |