From 705c0e943eb157ba7d6de7c5670c877188f754cc Mon Sep 17 00:00:00 2001 From: Přemysl Janouch Date: Wed, 9 Jul 2014 01:54:50 +0200 Subject: WIP: add a stub IRC daemon named `kike' As it is going to share a great lot of functionality with ZyklonB, I have decided to extract the common parts into `common.c' and make the two subprojects include this file. The Single Compile Unit concept has proven valuable (sub-second compile times, dead code warnings, almost no need for function declarations, whole-program optimizations), and the sources aren't that long so far anyway. I am probably going to add CMake support later but so far it's not a priority. This project is meant to be portable and freely relocatable (ie. no hardcoded paths if I can avoid it). --- Makefile | 11 +- README | 11 + src/common.c | 1772 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/kike.c | 796 ++++++++++++++++++++++++++ src/zyklonb.c | 1677 +++-------------------------------------------------- 5 files changed, 2656 insertions(+), 1611 deletions(-) create mode 100644 src/common.c create mode 100644 src/kike.c diff --git a/Makefile b/Makefile index f47959a..db6d657 100644 --- a/Makefile +++ b/Makefile @@ -1,17 +1,20 @@ SHELL = /bin/sh CC = clang CFLAGS = -ggdb -Wall -Wextra -std=c99 -LDFLAGS = `pkg-config --libs libssl` +# -lpthread is only there for debugging (gdb & errno) +LDFLAGS = `pkg-config --libs libssl` -lpthread .PHONY: all clean -targets = zyklonb +targets = zyklonb kike all: $(targets) clean: rm -f $(targets) -zyklonb: src/zyklonb.c src/siphash.c - $(CC) $^ -o $@ $(CFLAGS) $(LDFLAGS) +zyklonb: src/zyklonb.c src/common.c src/siphash.c + $(CC) src/zyklonb.c src/siphash.c -o $@ $(CFLAGS) $(LDFLAGS) +kike: src/kike.c src/common.c src/siphash.c + $(CC) src/kike.c src/siphash.c -o $@ $(CFLAGS) $(LDFLAGS) diff --git a/README b/README index d00bd27..e036f87 100644 --- a/README +++ b/README @@ -10,6 +10,17 @@ While originally intended to be a simple C99 rewrite of the original bot, which was written in the GNU dialect of AWK, it fairly quickly became a playground where I added everything that seemed nice. +kike +---- +Also included is a simple IRC daemon that mostly follows the RFC's but is +limited to single-server networks, due to the protocol being incredibly ugly +and tricky to implement correctly. Even so, it took me a ridiculous amount of +time to write. (But it was a valuable exercise and I can reuse the code.) + +Disclaimer +---------- +I am not an antisemitist, I'm just being an offensive asshole with the naming. + License ------- `ZyklonB' is written by Přemysl Janouch . diff --git a/src/common.c b/src/common.c new file mode 100644 index 0000000..be523a9 --- /dev/null +++ b/src/common.c @@ -0,0 +1,1772 @@ +/* + * common.c: common functionality + * + * Copyright (c) 2014, Přemysl Janouch + * 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#ifndef NI_MAXHOST +#define NI_MAXHOST 1025 +#endif // ! NI_MAXHOST + +#ifndef NI_MAXSERV +#define NI_MAXSERV 32 +#endif // ! NI_MAXSERV + +#include +#include +#include +#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) + +// --- Utilities --------------------------------------------------------------- + +static void +print_message (FILE *stream, const char *type, const char *fmt, ...) + ATTRIBUTE_PRINTF (3, 4); + +static void +print_message (FILE *stream, const char *type, const char *fmt, ...) +{ + va_list ap; + + va_start (ap, fmt); + fprintf (stream, "%s ", type); + vfprintf (stream, fmt, ap); + fputs ("\n", stream); + va_end (ap); +} + +#define print_fatal(...) print_message (stderr, "fatal:", __VA_ARGS__) +#define print_error(...) print_message (stderr, "error:", __VA_ARGS__) +#define print_warning(...) print_message (stderr, "warning:", __VA_ARGS__) +#define print_status(...) print_message (stdout, "--", __VA_ARGS__) + +// --- 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) \ + print_message (stderr, "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) + { + print_fatal ("malloc: %s", strerror (errno)); + exit (EXIT_FAILURE); + } + return p; +} + +static void * +xcalloc (size_t n, size_t m) +{ + void *p = calloc (n, m); + if (!p && n && m) + { + print_fatal ("calloc: %s", strerror (errno)); + exit (EXIT_FAILURE); + } + return p; +} + +static void * +xrealloc (void *o, size_t n) +{ + void *p = realloc (o, n); + if (!p && n) + { + print_fatal ("realloc: %s", strerror (errno)); + exit (EXIT_FAILURE); + } + return p; +} + +static void * +xreallocarray (void *o, size_t n, size_t m) +{ + if (m && n > SIZE_MAX / m) + { + errno = ENOMEM; + print_fatal ("reallocarray: %s", strerror (errno)); + exit (EXIT_FAILURE); + } + 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 ---------------------------------------------- + +// The links of the list need to have the members `prev' and `next'. + +#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_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 +{ + size_t domain; ///< The domain of the error + int id; ///< The concrete error ID + char *message; ///< Textual description of the event +}; + +static size_t +error_resolve_domain (size_t *tag) +{ + // This method is fairly sensitive to the order in which resolution + // requests come in, does not provide a good way of decoding the number + // back to a meaningful identifier, and may not play all too well with + // dynamic libraries when a module is e.g. statically linked into multiple + // libraries, but it's fast, simple, and more than enough for our purposes. + static size_t domain_counter; + + if (!*tag) + *tag = ++domain_counter; + return *tag; +} + +static void +error_set (struct error **e, size_t domain, int id, + const char *message, ...) ATTRIBUTE_PRINTF (4, 5); + +static void +error_set (struct error **e, size_t domain, int id, + const char *message, ...) +{ + if (!e) + return; + + va_list ap; + va_start (ap, message); + int size = snprintf (NULL, 0, message, ap); + va_end (ap); + + hard_assert (size >= 0); + + struct error *tmp = xmalloc (sizeof *tmp); + tmp->domain = domain; + tmp->id = id; + tmp->message = xmalloc (size + 1); + + va_start (ap, message); + size = snprintf (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 map (or associative array). + +struct str_map_link +{ + struct str_map_link *next; ///< The next link in a chain + struct str_map_link *prev; ///< The previous link in a chain + + 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 +}; + +#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->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 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 (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 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_find (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, (char *) iter + sizeof *iter)) + return iter->data; + return NULL; +} + +// --- 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 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 (); + return timeout >= 0 ? timeout : 0; +} + +#ifdef __linux__ + +// I don't really need this, I've basically implemented this just because I can. + +#include + +struct poller_info +{ + int fd; ///< Our file descriptor + uint32_t events; ///< The events we registered + 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; + self->revents = xreallocarray + (self->revents, sizeof *self->revents, self->alloc); + self->info = xreallocarray + (self->info, sizeof *self->info, self->alloc); +} + +static int +poller_epoll_to_poll_events (int events) +{ + int 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 (uint32_t 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 int 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->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) + { + print_fatal ("%s: %s", "epoll", strerror (errno)); + exit (EXIT_FAILURE); + } + + 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 = poller_epoll_to_poll_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 int 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) + { + print_fatal ("%s: %s", "poll", strerror (errno)); + exit (EXIT_FAILURE); + } + + 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 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 size_t io_error_domain_tag; +#define IO_ERROR (error_resolve_domain (&io_error_domain_tag)) + +enum +{ + IO_ERROR_FAILED +}; + +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, IO_ERROR, IO_ERROR_FAILED, + "cannot create directory `%s': %s", + path, strerror (errno)); + return false; + } + } + else if (!S_ISDIR (st.st_mode)) + { + error_set (e, IO_ERROR, IO_ERROR_FAILED, + "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 void +regerror_to_str (int code, const regex_t *preg, struct str *out) +{ + size_t required = regerror (code, preg, NULL, 0); + str_ensure_space (out, required); + out->len += regerror (code, preg, + out->str + out->len, out->alloc - out->len) - 1; +} + +static size_t regex_error_domain_tag; +#define REGEX_ERROR (error_resolve_domain (®ex_error_domain_tag)) + +enum +{ + REGEX_ERROR_COMPILATION_FAILED +}; + +static bool +regex_match (const char *regex, const char *s, struct error **e) +{ + regex_t re; + int err = regcomp (&re, regex, REG_EXTENDED | REG_NOSUB); + if (err) + { + struct str desc; + + str_init (&desc); + regerror_to_str (err, &re, &desc); + error_set (e, REGEX_ERROR, REGEX_ERROR_COMPILATION_FAILED, + "failed to compile regular expression: %s", desc.str); + str_free (&desc); + return false; + } + + bool result = regexec (&re, s, 0, NULL, 0) != REG_NOMATCH; + regfree (&re); + return result; +} + +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; + } +} + +// --- IRC utilities ----------------------------------------------------------- + +struct irc_message +{ + char *prefix; + char *command; + struct str_vector params; +}; + +static void +irc_parse_message (struct irc_message *msg, const char *line) +{ + msg->prefix = NULL; + msg->command = NULL; + str_vector_init (&msg->params); + + // 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) +{ + 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 (char c) +{ + if (c == '[') return '{'; + if (c == ']') return '}'; + if (c == '\\') return '|'; + if (c == '~') return '^'; + return c >= 'A' && c <= 'Z' ? c + ('a' - 'A') : c; +} + +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; +} + +// --- Configuration ----------------------------------------------------------- + +// The keys are stripped of surrounding whitespace, the values are not. + +static size_t config_error_domain_tag; +#define CONFIG_ERROR (error_resolve_domain (&config_error_domain_tag)) + +enum +{ + CONFIG_ERROR_MALFORMED +}; + +struct config_item +{ + const char *key; + const char *default_value; + const char *description; +}; + +static FILE * +get_config_file (void) +{ + struct str_vector paths; + struct str config_home, file; + const char *xdg_config_dirs; + unsigned i; + FILE *fp = NULL; + + str_vector_init (&paths); + + str_init (&config_home); + get_xdg_home_dir (&config_home, "XDG_CONFIG_HOME", ".config"); + str_vector_add (&paths, config_home.str); + str_free (&config_home); + + if ((xdg_config_dirs = getenv ("XDG_CONFIG_DIRS"))) + split_str_ignore_empty (xdg_config_dirs, ':', &paths); + + str_init (&file); + for (i = 0; i < paths.len; i++) + { + // As per spec, relative paths are ignored + if (*paths.vector[i] != '/') + continue; + + str_reset (&file); + str_append (&file, paths.vector[i]); + str_append (&file, "/" PROGRAM_NAME "/" PROGRAM_NAME ".conf"); + + if ((fp = fopen (file.str, "r"))) + break; + } + + str_free (&file); + str_vector_free (&paths); + return fp; +} + +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) +{ + struct str line; + FILE *fp = get_config_file (); + unsigned line_no = 0; + bool errors = false; + + if (!fp) + return true; + + str_init (&line); + for (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) + { + if (*start) + { + error_set (e, CONFIG_ERROR, CONFIG_ERROR_MALFORMED, + "line %u in config: %s", line_no, "malformed input"); + errors = true; + break; + } + } + else + { + char *value = end + 1; + do + *end = '\0'; + while (isspace (*--end)); + + str_map_set (config, start, xstrdup (value)); + } + } + + str_free (&line); + fclose (fp); + + return !errors; +} + +static char * +write_default_config (const char *filename, 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, IO_ERROR, IO_ERROR_FAILED, + "could not open `%s' for writing: %s", path.str, strerror (errno)); + goto error; + } + + 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, IO_ERROR, IO_ERROR_FAILED, + "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; + +} diff --git a/src/kike.c b/src/kike.c new file mode 100644 index 0000000..bf13476 --- /dev/null +++ b/src/kike.c @@ -0,0 +1,796 @@ +/* + * kike.c: the experimental IRC daemon + * + * Copyright (c) 2014, Přemysl Janouch + * 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" + +// --- Configuration (application-specific) ------------------------------------ + +static struct config_item g_config_table[] = +{ + { "server_name", NULL, "Server name" }, + { "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)" }, + + { "max_connections", NULL, "Maximum client connections" }, + { 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) + { + print_fatal ("pipe: %s", strerror (errno)); + exit (EXIT_FAILURE); + } + + 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) + { + print_error ("sigaction: %s", strerror (errno)); + exit (EXIT_FAILURE); + } +} + +// --- Application data -------------------------------------------------------- + +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 connection +{ + struct connection *next; ///< The next link in a chain + struct connection *prev; ///< The previous link in a chain + + 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 + + unsigned initialized : 1; ///< Has any data been received yet? + unsigned ssl_rx_want_tx : 1; ///< SSL_read() wants to write + unsigned ssl_tx_want_rx : 1; ///< SSL_write() wants to read + + SSL_CTX *ssl_ctx; ///< SSL context + SSL *ssl; ///< SSL connection + + char *nickname; ///< IRC nickname (main identifier) + char *username; ///< IRC username + char *fullname; ///< IRC fullname (e-mail) + + char *hostname; ///< Hostname shown to the network + + unsigned mode; ///< User's mode + char *away_message; ///< Away message +}; + +static void +connection_init (struct connection *self) +{ + memset (self, 0, sizeof *self); + + self->socket_fd = -1; + str_init (&self->read_buffer); + str_init (&self->write_buffer); +} + +static void +connection_free (struct connection *self) +{ + if (!soft_assert (self->socket_fd == -1)) + xclose (self->socket_fd); + if (self->ssl_ctx) + SSL_CTX_free (self->ssl_ctx); + 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->fullname); + + free (self->hostname); + free (self->away_message); +} + +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_SECRET = (1 << 3), + IRC_CHAN_MODE_PRIVATE = (1 << 4), + IRC_CHAN_MODE_PROTECTED_TOPIC = (1 << 5), + IRC_CHAN_MODE_QUIET = (1 << 6) +}; + +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 + + struct str_vector ban_list; ///< Ban list + struct str_vector exception_list; ///< Exceptions from bans + struct str_vector invite_list; ///< Exceptions from +I +}; + +static void +channel_init (struct channel *self) +{ + memset (self, 0, sizeof *self); + + str_vector_init (&self->ban_list); + str_vector_init (&self->exception_list); + str_vector_init (&self->invite_list); +} + +static void +channel_free (struct channel *self) +{ + free (self->name); + free (self->key); + + str_vector_free (&self->ban_list); + str_vector_free (&self->exception_list); + str_vector_free (&self->invite_list); +} + +struct server_context +{ + struct str_map config; ///< Server configuration + + int listen_fd; ///< Listening socket FD + struct connection *clients; ///< Client connections + + struct str_map users; ///< Maps nicknames to connections + struct str_map channels; ///< Maps channel names to data + + struct poller poller; ///< Manages polled description + bool polling; ///< The event loop is running +}; + +static void +server_context_init (struct server_context *self) +{ + str_map_init (&self->config); + self->config.free = free; + load_config_defaults (&self->config, g_config_table); + + self->listen_fd = -1; + self->clients = NULL; + + str_map_init (&self->users); + // TODO: set channel_free() as the free function? + str_map_init (&self->channels); + + poller_init (&self->poller); + self->polling = false; +} + +static void +server_context_free (struct server_context *self) +{ + str_map_free (&self->config); + + if (self->listen_fd != -1) + xclose (self->listen_fd); + + // TODO: terminate the connections properly before this is called + struct connection *link, *tmp; + for (link = self->clients; link; link = tmp) + { + tmp = link->next; + connection_free (link); + free (link); + } + + str_map_free (&self->users); + str_map_free (&self->channels); + poller_free (&self->poller); +} + +// --- Main program ------------------------------------------------------------ + +static size_t network_error_domain_tag; +#define NETWORK_ERROR (error_resolve_domain (&network_error_domain_tag)) + +enum +{ + NETWORK_ERROR_INVALID_CONFIGURATION, + NETWORK_ERROR_FAILED +}; + +static bool +irc_autodetect_ssl (struct connection *conn) +{ + // 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 (conn->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 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 connection *conn) +{ + struct server_context *ctx = conn->ctx; + + conn->ssl_ctx = SSL_CTX_new (SSLv23_server_method ()); + if (!conn->ssl_ctx) + goto error_ssl_1; + SSL_CTX_set_verify (conn->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 + + conn->ssl = SSL_new (conn->ssl_ctx); + if (!conn->ssl) + goto error_ssl_2; + + const char *ssl_cert = str_map_find (&ctx->config, "ssl_cert"); + if (ssl_cert + && !SSL_CTX_use_certificate_chain_file (conn->ssl_ctx, ssl_cert)) + { + // XXX: perhaps we should read the file ourselves for better messages + print_error ("%s: %s", "setting the SSL client certificate failed", + ERR_error_string (ERR_get_error (), NULL)); + } + + const char *ssl_key = str_map_find (&ctx->config, "ssl_key"); + if (ssl_key + && !SSL_use_PrivateKey_file (conn->ssl, ssl_key, SSL_FILETYPE_PEM)) + { + // XXX: perhaps we should read the file ourselves for better messages + print_error ("%s: %s", "setting the SSL private key failed", + ERR_error_string (ERR_get_error (), NULL)); + } + + // TODO: SSL_check_private_key(conn->ssl)? It is has probably already been + // checked by SSL_use_PrivateKey_file() above. + + SSL_set_accept_state (conn->ssl); + if (!SSL_set_fd (conn->ssl, conn->socket_fd)) + goto error_ssl_3; + // 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_set_mode (conn->ssl, + SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE); + return true; + +error_ssl_3: + SSL_free (conn->ssl); + conn->ssl = NULL; +error_ssl_2: + SSL_CTX_free (conn->ssl_ctx); + conn->ssl_ctx = NULL; +error_ssl_1: + // XXX: these error strings are really nasty; also there could be + // multiple errors on the OpenSSL stack. + print_error ("%s: %s", "could not initialize SSL", + ERR_error_string (ERR_get_error (), NULL)); + return false; +} + +static void +connection_abort (struct connection *conn, const char *reason) +{ + // TODO: send a QUIT message with `reason' || "Client exited" + (void) reason; + + // TODO: do further cleanup if the client has successfully registered + + struct server_context *ctx = conn->ctx; + ssize_t i = poller_find_by_fd (&ctx->poller, conn->socket_fd); + if (i != -1) + poller_remove_at_index (&ctx->poller, i); + + xclose (conn->socket_fd); + conn->socket_fd = -1; + connection_free (conn); + LIST_UNLINK (ctx->clients, conn); + free (conn); +} + +static void +irc_process_message (const struct irc_message *msg, + const char *raw, void *user_data) +{ + struct connection *conn = user_data; + // TODO +} + +static bool +irc_try_read (struct connection *conn) +{ + // TODO + return false; +} + +static bool +irc_try_read_ssl (struct connection *conn) +{ + if (conn->ssl_tx_want_rx) + return true; + + struct str *buf = &conn->read_buffer; + conn->ssl_rx_want_tx = false; + while (true) + { + str_ensure_space (buf, 512); + int n_read = SSL_read (conn->ssl, buf->str + buf->len, + buf->alloc - buf->len - 1 /* null byte */); + + const char *error_info = NULL; + switch (xssl_get_error (conn->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, conn); + continue; + case SSL_ERROR_ZERO_RETURN: + connection_abort (conn, NULL); + return false; + case SSL_ERROR_WANT_READ: + return true; + case SSL_ERROR_WANT_WRITE: + conn->ssl_rx_want_tx = true; + return false; + case XSSL_ERROR_TRY_AGAIN: + continue; + default: + print_debug ("%s: %s: %s", __func__, "SSL_read", error_info); + connection_abort (conn, error_info); + return false; + } + } +} + +static bool +irc_try_write (struct connection *conn) +{ + // TODO + return false; +} + +static bool +irc_try_write_ssl (struct connection *conn) +{ + if (conn->ssl_rx_want_tx) + return true; + + struct str *buf = &conn->write_buffer; + conn->ssl_tx_want_rx = false; + while (buf->len) + { + int n_written = SSL_write (conn->ssl, buf->str, buf->len); + + const char *error_info = NULL; + switch (xssl_get_error (conn->ssl, n_written, &error_info)) + { + case SSL_ERROR_NONE: + str_remove_slice (buf, 0, n_written); + continue; + case SSL_ERROR_ZERO_RETURN: + connection_abort (conn, NULL); + return false; + case SSL_ERROR_WANT_WRITE: + return true; + case SSL_ERROR_WANT_READ: + conn->ssl_tx_want_rx = true; + return false; + case XSSL_ERROR_TRY_AGAIN: + continue; + default: + print_debug ("%s: %s: %s", __func__, "SSL_write", error_info); + connection_abort (conn, error_info); + return false; + } + } + return true; +} + +static void +on_irc_client_ready (const struct pollfd *pfd, void *user_data) +{ + // XXX: check/load `ssl_cert' and `ssl_key' earlier? + struct connection *conn = user_data; + if (!conn->initialized) + { + hard_assert (pfd->events == POLLIN); + // XXX: what with the error from irc_initialize_ssl()? + if (irc_autodetect_ssl (conn) && !irc_initialize_ssl (conn)) + { + connection_abort (conn, NULL); + return; + } + conn->initialized = true; + } + + // FIXME: aborting a connection inside try_read() will fuck things up + int new_events = 0; + if (conn->ssl) + { + // Reads may want to write, writes may want to read, poll() may + // return unexpected things in `revents'... let's try both + irc_try_read_ssl (conn) && irc_try_write_ssl (conn); + + new_events |= POLLIN; + if (conn->write_buffer.len || conn->ssl_rx_want_tx) + new_events |= POLLOUT; + + // While we're waiting for an opposite event, we ignore the original + if (conn->ssl_rx_want_tx) new_events &= ~POLLIN; + if (conn->ssl_tx_want_rx) new_events &= ~POLLOUT; + } + else + { + irc_try_read (conn) && irc_try_write (conn); + + new_events |= POLLIN; + if (conn->write_buffer.len) + new_events |= POLLOUT; + } + + hard_assert (new_events != 0); + if (pfd->events != new_events) + poller_set (&conn->ctx->poller, conn->socket_fd, new_events, + (poller_dispatcher_func) on_irc_client_ready, conn); +} + +static void +on_irc_connection_available (const struct pollfd *pfd, void *user_data) +{ + (void) pfd; + struct server_context *ctx = user_data; + + // TODO: stop accepting new connections when `max_connections' is reached + + 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 (ctx->listen_fd, (struct sockaddr *) &peer, &peer_len); + if (fd == -1) + { + if (errno == EAGAIN) + break; + if (errno == EINTR) + continue; + if (errno == ECONNABORTED) + continue; + + // TODO: handle resource exhaustion (EMFILE, ENFILE) specially + // (stop accepting new connections and wait until we close some). + print_fatal ("%s: %s", "accept", strerror (errno)); + + // FIXME: handle this better, bring the server down cleanly. + exit (EXIT_FAILURE); + } + + char host[NI_MAXHOST] = "unknown", port[NI_MAXSERV] = "unknown"; + int err = getnameinfo ((struct sockaddr *) &peer, peer_len, + host, sizeof host, port, sizeof port, AI_NUMERICSERV); + if (err) + print_debug ("%s: %s", "getnameinfo", gai_strerror (err)); + print_debug ("accepted connection from %s:%s", host, port); + + struct connection *conn = xmalloc (sizeof *conn); + connection_init (conn); + conn->socket_fd = fd; + conn->hostname = xstrdup (host); + LIST_PREPEND (ctx->clients, conn); + + // TODO: set a timeout on the socket, something like 3 minutes, then we + // should terminate the connection. + poller_set (&ctx->poller, conn->socket_fd, POLLIN, + (poller_dispatcher_func) on_irc_client_ready, conn); + } +} + +static bool +irc_listen (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, NETWORK_ERROR, NETWORK_ERROR_FAILED, "%s: %s: %s", + "network setup failed", "getaddrinfo", gai_strerror (err)); + return false; + } + + int sockfd; + char real_host[NI_MAXHOST], real_port[NI_MAXSERV]; + + 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); + soft_assert (setsockopt (sockfd, SOL_SOCKET, SO_REUSEADDR, + &yes, sizeof yes) != -1); + + real_host[0] = real_port[0] = '\0'; + 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 (sockfd, 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 (sockfd, 16 /* arbitrary number */)) + print_error ("listen() at %s:%s failed: %s", + real_host, real_port, strerror (errno)); + else + break; + + xclose (sockfd); + } + + freeaddrinfo (gai_result); + + if (!gai_iter) + { + error_set (e, NETWORK_ERROR, NETWORK_ERROR_FAILED, + "network setup failed"); + return false; + } + + ctx->listen_fd = sockfd; + poller_set (&ctx->poller, ctx->listen_fd, POLLIN, + (poller_dispatcher_func) on_irc_connection_available, ctx); + + print_status ("listening at %s:%s", real_host, real_port); + return true; +} + +static void +on_signal_pipe_readable (const struct pollfd *fd, struct server_context *ctx) +{ + char *dummy; + (void) read (fd->fd, &dummy, 1); + +#if 0 + // TODO + if (g_termination_requested && !ctx->quitting) + { + initiate_quit (ctx); + } +#endif +} + +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]; + + struct error *e = NULL; + 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': + { + char *filename = write_default_config (optarg, g_config_table, &e); + if (!filename) + { + print_fatal ("%s", e->message); + error_free (e); + exit (EXIT_FAILURE); + } + print_status ("configuration written to `%s'", filename); + free (filename); + exit (EXIT_SUCCESS); + } + default: + print_fatal ("error in 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); + + if (!read_config_file (&ctx.config, &e)) + { + print_fatal ("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_listen (&ctx, &e)) + { + print_error ("%s", e->message); + error_free (e); + exit (EXIT_FAILURE); + } + + // TODO: daemonize + + ctx.polling = true; + while (ctx.polling) + poller_run (&ctx.poller); + + server_context_free (&ctx); + return EXIT_SUCCESS; +} diff --git a/src/zyklonb.c b/src/zyklonb.c index a182d17..69c41c1 100644 --- a/src/zyklonb.c +++ b/src/zyklonb.c @@ -18,1464 +18,10 @@ * */ -#define _POSIX_C_SOURCE 199309L -#define _XOPEN_SOURCE 500 - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#ifndef NI_MAXHOST -#define NI_MAXHOST 1025 -#endif // ! NI_MAXHOST - -#include -#include -#include -#include "siphash.h" - -#define PROGRAM_NAME "ZyklonB" -#define PROGRAM_VERSION "alpha" - -extern char **environ; - -#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) - -// --- Utilities --------------------------------------------------------------- - -static void -print_message (FILE *stream, const char *type, const char *fmt, ...) - ATTRIBUTE_PRINTF (3, 4); - -static void -print_message (FILE *stream, const char *type, const char *fmt, ...) -{ - va_list ap; - - va_start (ap, fmt); - fprintf (stream, "%s ", type); - vfprintf (stream, fmt, ap); - fputs ("\n", stream); - va_end (ap); -} - -#define print_fatal(...) print_message (stderr, "fatal:", __VA_ARGS__) -#define print_error(...) print_message (stderr, "error:", __VA_ARGS__) -#define print_warning(...) print_message (stderr, "warning:", __VA_ARGS__) -#define print_status(...) print_message (stdout, "--", __VA_ARGS__) - -// --- 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) \ - print_message (stderr, "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) - { - print_fatal ("malloc: %s", strerror (errno)); - exit (EXIT_FAILURE); - } - return p; -} - -static void * -xcalloc (size_t n, size_t m) -{ - void *p = calloc (n, m); - if (!p && n && m) - { - print_fatal ("calloc: %s", strerror (errno)); - exit (EXIT_FAILURE); - } - return p; -} - -static void * -xrealloc (void *o, size_t n) -{ - void *p = realloc (o, n); - if (!p && n) - { - print_fatal ("realloc: %s", strerror (errno)); - exit (EXIT_FAILURE); - } - return p; -} - -static void * -xreallocarray (void *o, size_t n, size_t m) -{ - if (m && n > SIZE_MAX / m) - { - errno = ENOMEM; - print_fatal ("reallocarray: %s", strerror (errno)); - exit (EXIT_FAILURE); - } - 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 ---------------------------------------------- - -// The links of the list need to have the members `prev' and `next'. - -#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_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 -{ - size_t domain; ///< The domain of the error - int id; ///< The concrete error ID - char *message; ///< Textual description of the event -}; - -static size_t -error_resolve_domain (size_t *tag) -{ - // This method is fairly sensitive to the order in which resolution - // requests come in, does not provide a good way of decoding the number - // back to a meaningful identifier, and may not play all too well with - // dynamic libraries when a module is e.g. statically linked into multiple - // libraries, but it's fast, simple, and more than enough for our purposes. - static size_t domain_counter; - - if (!*tag) - *tag = ++domain_counter; - return *tag; -} - -static void -error_set (struct error **e, size_t domain, int id, - const char *message, ...) ATTRIBUTE_PRINTF (4, 5); - -static void -error_set (struct error **e, size_t domain, int id, - const char *message, ...) -{ - if (!e) - return; - - va_list ap; - va_start (ap, message); - int size = snprintf (NULL, 0, message, ap); - va_end (ap); - - hard_assert (size >= 0); - - struct error *tmp = xmalloc (sizeof *tmp); - tmp->domain = domain; - tmp->id = id; - tmp->message = xmalloc (size + 1); - - va_start (ap, message); - size = snprintf (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 map (or associative array). - -struct str_map_link -{ - struct str_map_link *next; ///< The next link in a chain - struct str_map_link *prev; ///< The previous link in a chain - - 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 -}; - -#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->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 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 (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 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_find (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, (char *) iter + sizeof *iter)) - return iter->data; - return NULL; -} - -// --- 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 *); - -#define POLLER_MIN_ALLOC 16 - -#ifdef __linux__ - -// I don't really need this, I've basically implemented this just because I can. - -#include - -struct poller_info -{ - int fd; ///< Our file descriptor - uint32_t events; ///< The events we registered - 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 - - /// Index of the element in `revents' that's currently being dispatched, - /// or -1 if we're not dispatching at the moment. - int dispatch_iterator; - - /// 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); - - self->dispatch_iterator = -1; - 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); - } - - 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; - self->revents = xreallocarray - (self->revents, sizeof *self->revents, self->alloc); - self->info = xreallocarray - (self->info, sizeof *self->info, self->alloc); -} - -static int -poller_epoll_to_poll_events (int events) -{ - int 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 (uint32_t 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 int 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->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_iterator == -1) - return; - - int i; - for (i = self->dispatch_iterator; 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]; - - // We've removed the element we're currently processing; go back one entry - // so that we don't skip the one we might have replaced it with. - if (i == self->dispatch_iterator) - self->dispatch_iterator--; -} - -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_iterator == -1); - - int n_fds; - do - n_fds = epoll_wait (self->epoll_fd, self->revents, self->len, -1); - while (n_fds == -1 && errno == EINTR); - - if (n_fds == -1) - { - print_fatal ("%s: %s", "epoll", strerror (errno)); - exit (EXIT_FAILURE); - } - - for (int i = 0; i < n_fds; i++) - { - struct epoll_event *revents = self->revents + i; - 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 = poller_epoll_to_poll_events (info->events); - - self->dispatch_iterator = i; - self->dispatch_total = n_fds; - - info->dispatcher (&pfd, info->user_data); - - i = self->dispatch_iterator; - n_fds = self->dispatch_total; - } - - self->dispatch_iterator = -1; - 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 - - int dispatch_index; ///< The currently 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); - self->dispatch_index = -1; -} - -static void -poller_free (struct poller *self) -{ - free (self->fds); - free (self->fds_info); -} - -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 int 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_index) - { - 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); - } - else - { - self->fds[index] = self->fds[self->len]; - self->fds_info[index] = self->fds_info[self->len]; - } - - if ((int) index <= self->dispatch_index) - self->dispatch_index--; -} - -static void -poller_run (struct poller *self) -{ - // Not reentrant - hard_assert (self->dispatch_index == -1); - - int result; - do - result = poll (self->fds, self->len, -1); - while (result == -1 && errno == EINTR); - - if (result == -1) - { - print_fatal ("%s: %s", "poll", strerror (errno)); - exit (EXIT_FAILURE); - } - - for (int i = 0; i < (int) self->len; i++) - { - struct pollfd pfd = self->fds[i]; - if (!pfd.revents) - continue; - - struct poller_info *info = self->fds_info + i; - self->dispatch_index = i; - info->dispatcher (&pfd, info->user_data); - i = self->dispatch_index; - } - - self->dispatch_index = -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 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 size_t io_error_domain_tag; -#define IO_ERROR (error_resolve_domain (&io_error_domain_tag)) - -enum -{ - IO_ERROR_FAILED -}; - -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, IO_ERROR, IO_ERROR_FAILED, - "cannot create directory `%s': %s", - path, strerror (errno)); - return false; - } - } - else if (!S_ISDIR (st.st_mode)) - { - error_set (e, IO_ERROR, IO_ERROR_FAILED, - "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 void -regerror_to_str (int code, const regex_t *preg, struct str *out) -{ - size_t required = regerror (code, preg, NULL, 0); - str_ensure_space (out, required); - out->len += regerror (code, preg, - out->str + out->len, out->alloc - out->len) - 1; -} - -static size_t regex_error_domain_tag; -#define REGEX_ERROR (error_resolve_domain (®ex_error_domain_tag)) - -enum -{ - REGEX_ERROR_COMPILATION_FAILED -}; - -static bool -regex_match (const char *regex, const char *s, struct error **e) -{ - regex_t re; - int err = regcomp (&re, regex, REG_EXTENDED | REG_NOSUB); - if (err) - { - struct str desc; - - str_init (&desc); - regerror_to_str (err, &re, &desc); - error_set (e, REGEX_ERROR, REGEX_ERROR_COMPILATION_FAILED, - "failed to compile regular expression: %s", desc.str); - str_free (&desc); - return false; - } - - bool result = regexec (&re, s, 0, NULL, 0) != REG_NOMATCH; - regfree (&re); - return result; -} - -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; -} - -// --- IRC utilities ----------------------------------------------------------- - -struct irc_message -{ - char *prefix; - char *command; - struct str_vector params; -}; - -static void -irc_parse_message (struct irc_message *msg, const char *line) -{ - msg->prefix = NULL; - msg->command = NULL; - str_vector_init (&msg->params); - - // 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) -{ - 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; - char *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; - } - - str_remove_slice (buf, 0, start - buf->str); -} - -// --- Configuration ----------------------------------------------------------- - -// The keys are stripped of surrounding whitespace, the values are not. - -static size_t config_error_domain_tag; -#define CONFIG_ERROR (error_resolve_domain (&config_error_domain_tag)) - -enum -{ - CONFIG_ERROR_MALFORMED -}; - -struct config_item -{ - const char *key; - const char *default_value; - const char *description; -}; - -static FILE * -get_config_file (void) -{ - struct str_vector paths; - struct str config_home, file; - const char *xdg_config_dirs; - unsigned i; - FILE *fp = NULL; - - str_vector_init (&paths); - - str_init (&config_home); - get_xdg_home_dir (&config_home, "XDG_CONFIG_HOME", ".config"); - str_vector_add (&paths, config_home.str); - str_free (&config_home); - - if ((xdg_config_dirs = getenv ("XDG_CONFIG_DIRS"))) - split_str_ignore_empty (xdg_config_dirs, ':', &paths); - - str_init (&file); - for (i = 0; i < paths.len; i++) - { - // As per spec, relative paths are ignored - if (*paths.vector[i] != '/') - continue; - - str_reset (&file); - str_append (&file, paths.vector[i]); - str_append (&file, "/" PROGRAM_NAME "/" PROGRAM_NAME ".conf"); - - if ((fp = fopen (file.str, "r"))) - break; - } - - str_free (&file); - str_vector_free (&paths); - return fp; -} - -static bool -read_config_file (struct str_map *config, struct error **e) -{ - struct str line; - FILE *fp = get_config_file (); - unsigned line_no = 0; - bool errors = false; - - if (!fp) - return true; - - str_init (&line); - for (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) - { - if (*start) - { - error_set (e, CONFIG_ERROR, CONFIG_ERROR_MALFORMED, - "line %u in config: %s", line_no, "malformed input"); - errors = true; - break; - } - } - else - { - char *value = end + 1; - do - *end = '\0'; - while (isspace (*--end)); - - str_map_set (config, start, xstrdup (value)); - } - } - - str_free (&line); - fclose (fp); +#define PROGRAM_NAME "ZyklonB" +#define PROGRAM_VERSION "alpha" - return !errors; -} +#include "common.c" // --- Configuration (application-specific) ------------------------------------ @@ -1498,18 +44,9 @@ static struct config_item g_config_table[] = { "plugins", NULL, "The plugins to load on startup" }, { "plugin_dir", NULL, "Where to search for plugins" }, { "recover", "on", "Whether to re-launch on crash" }, -}; -static void -load_config_defaults (struct str_map *config) -{ - for (size_t i = 0; i < N_ELEMENTS (g_config_table); i++) - { - const struct config_item *item = g_config_table + i; - if (item->default_value) - str_map_set (config, item->key, xstrdup (item->default_value)); - } -} + { NULL, NULL, NULL } +}; // --- Application data -------------------------------------------------------- @@ -1598,51 +135,51 @@ struct bot_context }; static void -bot_context_init (struct bot_context *ctx) +bot_context_init (struct bot_context *self) { - str_map_init (&ctx->config); - ctx->config.free = free; - load_config_defaults (&ctx->config); + str_map_init (&self->config); + self->config.free = free; + load_config_defaults (&self->config, g_config_table); - ctx->irc_fd = -1; - str_init (&ctx->read_buffer); - ctx->irc_ready = false; + self->irc_fd = -1; + str_init (&self->read_buffer); + self->irc_ready = false; - ctx->ssl = NULL; - ctx->ssl_ctx = NULL; + self->ssl = NULL; + self->ssl_ctx = NULL; - ctx->plugins = NULL; - str_map_init (&ctx->plugins_by_name); + self->plugins = NULL; + str_map_init (&self->plugins_by_name); - poller_init (&ctx->poller); - ctx->quitting = false; - ctx->polling = false; + poller_init (&self->poller); + self->quitting = false; + self->polling = false; } static void -bot_context_free (struct bot_context *ctx) +bot_context_free (struct bot_context *self) { - str_map_free (&ctx->config); - str_free (&ctx->read_buffer); + str_map_free (&self->config); + str_free (&self->read_buffer); // TODO: terminate the plugins properly before this is called struct plugin_data *link, *tmp; - for (link = ctx->plugins; link; link = tmp) + for (link = self->plugins; link; link = tmp) { tmp = link->next; plugin_data_free (link); free (link); } - if (ctx->irc_fd != -1) - xclose (ctx->irc_fd); - if (ctx->ssl) - SSL_free (ctx->ssl); - if (ctx->ssl_ctx) - SSL_CTX_free (ctx->ssl_ctx); + 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 (&ctx->plugins_by_name); - poller_free (&ctx->poller); + str_map_free (&self->plugins_by_name); + poller_free (&self->poller); } static void @@ -1690,7 +227,8 @@ irc_send (struct bot_context *ctx, const char *format, ...) fputs ("\"\n", stderr); } - soft_assert (ctx->irc_fd != -1); + if (!soft_assert (ctx->irc_fd != -1)) + return false; va_start (ap, format); struct str str; @@ -2143,10 +681,8 @@ on_plugin_writable (const struct pollfd *fd, struct plugin_data *plugin) struct str *buf = &plugin->write_buffer; size_t written_total = 0; - // TODO: see "Advanced Programming in the UNIX Environment" Figure C.19; - // check for any unexpected behaviour that might occur - if (fd->revents != POLLOUT) - print_debug ("poller fd %d: revents: %d", fd->fd, fd->revents); + if (fd->revents & ~(POLLOUT | POLLHUP | POLLERR)) + print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents); while (written_total != buf->len) { @@ -2157,15 +693,18 @@ on_plugin_writable (const struct pollfd *fd, struct plugin_data *plugin) { if (errno == EAGAIN) break; + if (errno == EINTR) + continue; - if (!soft_assert (errno == EINTR) && !plugin->is_zombie) - { - print_debug ("%s: %s", "recv", strerror (errno)); - print_error ("failure on writing to plugin `%s'," - " therefore I'm unloading it", plugin->name); - plugin_zombify (plugin); - break; - } + 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 @@ -2301,10 +840,8 @@ plugin_process_message (const struct irc_message *msg, static void on_plugin_readable (const struct pollfd *fd, struct plugin_data *plugin) { - // TODO: see "Advanced Programming in the UNIX Environment" Figure C.19; - // check for any unexpected behaviour that might occur - if (fd->revents != POLLIN) - print_debug ("poller fd %d: revents: %d", fd->fd, fd->revents); + 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; @@ -2818,11 +1355,11 @@ start: buf->alloc - buf->len - 1 /* null byte */); const char *error_info = NULL; - switch (SSL_get_error (ctx->ssl, n_read)) + switch (xssl_get_error (ctx->ssl, n_read, &error_info)) { case SSL_ERROR_NONE: buf->str[buf->len += n_read] = '\0'; - return IRC_READ_AGAIN; + return IRC_READ_OK; case SSL_ERROR_ZERO_RETURN: return IRC_READ_EOF; case SSL_ERROR_WANT_READ: @@ -2835,28 +1372,12 @@ start: soft_assert (poll (&pfd, 1, 0) > 0); goto start; } - case SSL_ERROR_SYSCALL: - { - int err; - if ((err = ERR_get_error ())) - error_info = ERR_error_string (err, NULL); - else if (n_read == 0) - return IRC_READ_EOF; - else - { - if (errno == EINTR) - goto start; - error_info = strerror (errno); - } - break; - } - case SSL_ERROR_SSL: + case XSSL_ERROR_TRY_AGAIN: + goto start; default: - error_info = ERR_error_string (ERR_get_error (), NULL); + print_debug ("%s: %s: %s", __func__, "SSL_read", error_info); + return IRC_READ_ERROR; } - - print_debug ("%s: %s: %s", __func__, "SSL_read", error_info); - return IRC_READ_ERROR; } static enum irc_read_result @@ -2975,8 +1496,8 @@ on_irc_disconnected (struct bot_context *ctx) static void on_irc_readable (const struct pollfd *fd, struct bot_context *ctx) { - if (fd->revents != POLLIN) - print_debug ("poller fd %d: revents: %d", fd->fd, fd->revents); + if (fd->revents & ~(POLLIN | POLLHUP | POLLERR)) + print_debug ("fd %d: unexpected revents: %d", fd->fd, fd->revents); (void) set_blocking (ctx->irc_fd, false); @@ -3143,75 +1664,6 @@ on_signal_pipe_readable (const struct pollfd *fd, struct bot_context *ctx) } } -static void -write_default_configuration (const char *filename) -{ - struct str path, base; - int status = EXIT_SUCCESS; - - 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"); - } - - struct error *e = NULL; - if (!mkdir_with_parents (path.str, &e)) - { - print_fatal ("%s", e->message); - status = EXIT_FAILURE; - goto out; - } - - str_append_c (&path, '/'); - str_append_str (&path, &base); - - FILE *fp = fopen (path.str, "w"); - if (!fp) - { - print_fatal ("could not open `%s' for writing: %s", - path.str, strerror (errno)); - status = EXIT_FAILURE; - goto out; - } - - errno = 0; - for (size_t i = 0; i < N_ELEMENTS (g_config_table); i++) - { - const struct config_item *item = g_config_table + i; - fprintf (fp, "# %s\n", item->description); - if (item->default_value) - fprintf (fp, "%s=%s\n", item->key, item->default_value); - else - fprintf (fp, "#%s=\n", item->key); - } - fclose (fp); - if (errno) - { - print_fatal ("writing to `%s' failed: %s", path.str, strerror (errno)); - status = EXIT_FAILURE; - goto out; - } - print_status ("configuration written to `%s'", path.str); - -out: - str_free (&path); - str_free (&base); - exit (status); -} - static void print_usage (const char *program_name) { @@ -3234,6 +1686,7 @@ main (int argc, char *argv[]) str_vector_init (&g_original_argv); str_vector_add_vector (&g_original_argv, argv); + struct error *e = NULL; static struct option opts[] = { { "debug", no_argument, NULL, 'd' }, @@ -3263,8 +1716,18 @@ main (int argc, char *argv[]) printf (PROGRAM_NAME " " PROGRAM_VERSION "\n"); exit (EXIT_SUCCESS); case 'w': - write_default_configuration (optarg); - abort (); + { + char *filename = write_default_config (optarg, g_config_table, &e); + if (!filename) + { + print_fatal ("%s", e->message); + error_free (e); + exit (EXIT_FAILURE); + } + print_status ("configuration written to `%s'", filename); + free (filename); + exit (EXIT_SUCCESS); + } default: print_fatal ("error in options"); exit (EXIT_FAILURE); @@ -3277,12 +1740,12 @@ main (int argc, char *argv[]) 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_fatal ("error loading configuration: %s", e->message); -- cgit v1.2.3-70-g09d2