+ if(read(pipefd[0], &signum, 1) != 1) {
+ return;
+ }
+
+ signal_t *sig = splay_search(&signal_tree, &((signal_t) {
+ .signum = signum
+ }));
+
+ if(sig) {
+ sig->cb(sig->data);
+ }
+}
+
+static void pipe_init(void) {
+ if(!pipe(pipefd)) {
+ io_add(&signalio, signalio_handler, NULL, pipefd[0], IO_READ);
+ }
+}
+
+void signal_add(signal_t *sig, signal_cb_t cb, void *data, int signum) {
+ if(sig->cb) {
+ return;
+ }
+
+ sig->cb = cb;
+ sig->data = data;
+ sig->signum = signum;
+ sig->node.data = sig;
+
+ if(pipefd[0] == -1) {
+ pipe_init();
+ }
+
+ signal(sig->signum, signal_handler);
+
+ if(!splay_insert_node(&signal_tree, &sig->node)) {
+ abort();
+ }
+}
+
+void signal_del(signal_t *sig) {
+ if(!sig->cb) {
+ return;
+ }
+
+ signal(sig->signum, SIG_DFL);
+
+ splay_unlink_node(&signal_tree, &sig->node);
+ sig->cb = NULL;
+}
+#endif
+
+static struct timeval *get_time_remaining(struct timeval *diff) {
+ gettimeofday(&now, NULL);
+ struct timeval *tv = NULL;
+
+ while(timeout_tree.head) {
+ timeout_t *timeout = timeout_tree.head->data;
+ timersub(&timeout->tv, &now, diff);
+
+ if(diff->tv_sec < 0) {
+ timeout->cb(timeout->data);
+
+ if(timercmp(&timeout->tv, &now, <)) {
+ timeout_del(timeout);
+ }
+ } else {
+ tv = diff;
+ break;
+ }
+ }
+
+ return tv;
+}
+
+bool event_loop(void) {
+ running = true;
+
+#ifndef HAVE_MINGW
+ fd_set readable;
+ fd_set writable;
+
+ while(running) {
+ struct timeval diff;
+ struct timeval *tv = get_time_remaining(&diff);
+ memcpy(&readable, &readfds, sizeof(readable));
+ memcpy(&writable, &writefds, sizeof(writable));
+
+ int fds = 0;
+
+ if(io_tree.tail) {
+ io_t *last = io_tree.tail->data;
+ fds = last->fd + 1;
+ }
+
+ int n = select(fds, &readable, &writable, NULL, tv);
+
+ if(n < 0) {
+ if(sockwouldblock(sockerrno)) {
+ continue;
+ } else {
+ return false;
+ }
+ }
+
+ if(!n) {
+ continue;
+ }
+
+ for splay_each(io_t, io, &io_tree) {
+ if(FD_ISSET(io->fd, &writable)) {
+ io->cb(io->data, IO_WRITE);
+ } else if(FD_ISSET(io->fd, &readable)) {
+ io->cb(io->data, IO_READ);
+ } else {
+ continue;
+ }
+
+ /*
+ There are scenarios in which the callback will remove another io_t from the tree
+ (e.g. closing a double connection). Since splay_each does not support that, we
+ need to exit the loop now. That's okay, since any remaining events will get picked
+ up by the next select() call.
+ */
+ break;